﻿
// alert("caller is " + arguments.callee.caller.toString());


// vbasepath:   points to http://www.vbaseworks.com/V163/ or localhost.. version always included
//              or, in the case of a domain pointer, http://dirtybirty.com/V163
//
// vbaseroot:   same without the version
//
// vbasedomain: the caller: http://localhost/vbase/vbasemain.asp or http://vmediaworks.tv

//[attribute^=value]	Matches elements that have the specified attribute and it starts with a certain value.;
//[attribute$=value]	Matches elements that have the specified attribute and it ends with a certain value.;
//[attribute*=value]	Matches elements that have the specified attribute and it contains a certain value.;

// common subroutines, for LayoutManager and vbase;

var panes = ["content", "top", "left", "right", "bottom", "modal"];
var simpleCartCartHeaders;
var useAssets = false;
var timer = new Date();
var rounding = [];
var styleIndex = [];  //index for a style in theRules of stylesheet. this is 3x faster then cycling through the rules

var imgArray = [];
var lab_message = "";
var saveScrollTop;
var lastTarget;
var psSrc;  // source of productshowmanager;

var mouseIsDown = false;

var tagsloggedin = false;
var tagsuserid = "";
var tagsusername = "";

var blogsloggedin = false;
var blogsuserid = "";
var blogsusername = "";

var tinyBrowserWrapperRef = false;
var adminWrapperRef = false;

var imageBrowser = false;

var docIsLoaded = false;
var guestbookTarget;
var windowW;
var windowH;
var styleScrollbars;
var bodyHeight;
var bodyWidth;
var pageHeight;
var pageWidth;
var leftHeight;
var rightHeight;
var middleHeight;
var contentHeight;
var contentWidth;
var topHeight;
var bottomHeight;
var topWidth;

var searchTarget = "";
var haveProducts = false;

var md5Hash = "";
var site_key;
var start = false;
var username = "";
var password = "";
var passwordPassed = false;
var docLoc = "";
var haveScrollbar = false;
var lastId;
var editId;
var editPane;
var changeState = false;
var keyIsDown = false;

var shiftkeydown;
var controlkeydown;
var returnkeydown;
var vkeydown;
var bkeydown;
var ekeydown;


var doPoll = false;

var forceRemote = false;  // set to true if using local scripts with remote database;

var toolBoxPosition = "";

document.onkeydown = storeKey;
document.onkeyup = clearKey;
var restoreNode;

var canceled = false; // to cancel any callback;

var availablePanes = ""; // panes that may be edited;

var lastNodeShowed = false;
var onVBPageLoad = false;
var beforeVBPageLoad = false;

var ajaxTarget = "";

var mayEdit = false;
var mayLayout = false;
var mayPages = false;
var maySlides = false;
var mayUsers = false;
var mayAccess = false;
var mayFileupload = false;
var mayImageupload = false;
var mayProducts = false;

var disableNavClick = false; // to temporary block the onclick handler for nav;

var anchor = [];
anchor.top = "";
anchor.left = "";
anchor.right = "";
anchor.bottom = "";
anchor.content = "";
anchor.modal = "";

var navObjects = "navholder|chapter|link|sublink_container|sublink|chapter_first|link_first|chapter_last|link_last".split("|");

var right100 = "";
var left100 = "";

var menuOpener = "";
var alwaysOpen;
var fixedHeight;

var theRules = "";

var currentStyle;

var state = "";  // either empty, , _hover or _clicked;

var navPos;
var navAnchor;

var animation; // if true then do accordion menu;

var nChapters;  // total amout of chapters;

var jumpToAnchor = "";

var lastPage = "00";

var lastLinkId; // id of the the last main link.;

var firstTime = true; // asp loads the content already;

var sameDomain = false;

// here some often used JQuery arrays

var JQlink;
var JQsublink;
var JQsublink_container;
var JQchapter;

//=======================================================;
String.prototype.find = function (what) {
    return (this.indexOf(what) >= 0 ? true : false);
};

var hulp;

//=======================================================;
function init() {

    hulp = document.createElement("div");
    document.body.appendChild(hulp);   // otherwise css3pie doesn't work

    hulp.style.behavior = "url('PIE.htc')";

    document.documentElement.scrollTop = 0;

    readStyles();
    
    if ((vbaseroot === vbasedomain) || (vbasedomain.indexOf("localhost") !== -1)) {
        sameDomain = true;
    }

    gebi("pusername").value = getCookie("username");
    gebi("ppassword").value = getCookie("password");

    var pane;
    for (pane in panes) {
        $(gebi(panes[pane])).bind("dblclick", function() { doubleclicked(this); });
        $(gebi(panes[pane])).bind("click", function() { doubleclicked(this); });
    }

    var i;
    for (i = 1; i < 11; i++) {
        $(gebi("aux" + i)).bind("dblclick", function() { doubleclicked(this); });
        $(gebi("aux" + i)).bind("click", function() { doubleclicked(this); });
    }

    if (product_id !== "") {
        var data = initData();
        var extra = "";
        if (forceRemote) { extra = extra + "&forceremote=1"; }

        data[4] = "productshow.asp?site_key=" + site_key + "&p_id=" + product_id + extra + "&startdate=" + startdate;
        data[2] = "modal";
        showNodeCallBack(data,"init");
    }

    // at last load the navigation;
    navCallBack(navdata);


}

//=====================================;
function initData() {
    var data = [],i;
    for (i = 0; i < 10; i++) {
        data[i] = "";
    }
    return data;

}

var nNavFields = 7; // amount of fields retrieved by the query;


// ======================================================================	;
function getNumParagraphs(chapter, data) {

    var numparagraph = 0,j,k;
    for ( j = 0; j < data.length; j = j + nNavFields) {
        var thispage = data[j + 2];
        if ((thispage === chapter) && (j < data.length - 2)) {
            for (k = j + nNavFields; k < data.length; k = k + nNavFields) {
                thispage = data[k + 2];
                if (thispage.indexOf("_") !== -1) {
                    numparagraph++;
                }
                else {
                    return numparagraph;
                }
            }
        }
    }
    return numparagraph;
}



// ======================================================================	;
function getchapter(pointer, data) {
    //returns index of the array data;
    var anindex = 0,ic;
    for (ic = 0; ic < data.length; ic = ic + nNavFields) {

        var pageno = data[ic + 2];
        if (pageno.indexOf("_") === -1) {
            if (pointer === anindex) { return ic; }
            anindex++;
        }
    }
    alert("chapter not found:" + pointer);
}

//===================================================================================================;
function removeAuxClickedStates(who) {

    var i;
    $("[id^=aux][class^=aux]").each(function () {
        var alist = this.className.split(" ");
        for (i = 0; i < alist.length; i++) {
            if (alist[i].find("_clicked")) {
                $(this).removeClass(alist[i]);
            }
        }
    });
}

//===================================================================================================;
function removeClickedStates(what, includeAux, who) {
    if (includeAux) { removeAuxClickedStates("removeClicked"); }
    var i;
    if ((what == "all") || (what === "link")) {
        //            $('a.acheader[@class*=_clicked]').each(function(){
        $("a.acheader[class*='_clicked']").each(function () {

            list = this.className.split(" ");
            for (i = 0; i < list.length; i++) {
                if (list[i].indexOf("_clicked") !== -1) {

                    $(this).removeClass(list[i]);

                }
            }
        });
    }

    if ((what == "all") || (what === "sublink")) {
        $("#navholder .sublink[class*='_clicked']").each(function () {
            list = this.className.split(" ");
            for (i = 0; i < list.length; i++) {
                if (list[i].indexOf("_clicked") !== -1) {
                    $(this).removeClass(list[i]);

                }
            }
        });
    }
}

//===================================================================================================;
function accordion(who) {
    if (!animation) { return; }
    JQchapter.unbind("mouseenter").unbind("mouseleave");

    if ((menuOpener === "mouseover") && (!alwaysOpen)) {
        JQsublink_container.hide();

        JQchapter.each(function () {
            if (gebi("sublink_container" + this.getAttribute("pageno") * 1)) {
                $(this).bind("mouseenter", function () {
                    $(gebi("sublink_container" + this.getAttribute("pageno") * 1)).slideDown(300);
                });
                $(this).bind("mouseleave", function () {
                    $(gebi("sublink_container" + this.getAttribute("pageno") * 1)).slideUp(0);
                });
            }
        });
        return;
    }

    JQsublink_container.show();

    $(gebi("navholder")).accordion({
        header: "a.acheader",

        event: menuOpener,
        alwaysOpen: alwaysOpen,
        autoHeight: fixedHeight
    });
}

//=======================================================;
function getPseudoStyle(name, adefault) {
    name = name.toLowerCase();
    if (pstyles[name]) {
        return pstyles[name];
    }
    return adefault;
}

//=======================================================;
String.prototype.toCamel = function () {
    // background-color --> backgroundColor
    return this.replace(/(\-[a-z])/g, function ($1) { return $1.toUpperCase().replace('-', ''); });
};

//=======================================================;
String.prototype.toDash = function () {
    // backgroundColor --> background-color
    return this.replace(/([A-Z])/g, function ($1) { return "-" + $1.toLowerCase(); });
};


//=======================================================;
function setScroll(something) {

    var atop = $("html").scrollTop();  // for IE...

    //document.body.scrollTop = 0;
    if (something === "content") {
        setStyle("body", 'overflowY', 'hidden');
        document.body.style.overflowY = "hidden";

        haveScrollbar = true;
    }
    else {

        setStyle("body", 'overflow', 'auto');
        setStyle("body", 'overflowY', 'auto');
        setStyle("body", 'overflowX', 'hidden');

        document.body.style.overflow = "auto";
        document.body.style.overflowY = "auto";
        document.body.style.overflowX = "hidden";
        haveScrollbar = false;
    }
    $("html").scrollTop(atop);  // for IE...
    
}

//=======================================================;
function rgb2hex(value) {
    var hex = "", v, h, i;
    var regexp = /([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)/;
    h = regexp.exec(value);
    for (i = 1; i < 4; i++) {
        v = parseInt(h[i], 10).toString(16);
        if (v.length == 1) { hex += "0" + v; }
        else { hex += v; }
    }
    return ("#" + hex);
}

//=======================================================;
function getStyleName(aname,who) {
    if (typeof aname !== "string") {alert("here: " + who + " " + aname); }
    if (typeof aname == "undefined") {alert("here undefined: " + who + " " + aname); }
    if (taglist.find(";" + aname.toLowerCase() + ";")) { return aname; }
    return ("." + aname + state).toLowerCase();
}

//=======================================================;
function getRules(which) {

    
    theRules = [];
    if (document.styleSheets[which].cssRules) {
        return document.styleSheets[which].cssRules;
    }
    else if (document.styleSheets[which].rules) {
        return document.styleSheets[which].rules;
    }
    alert("rules not supported in this browser");
}

//=======================================================;
function report(stylename, returnString) {
    var sep;
    if (returnString) {
        sep = "<br>";
    }
    else {
        sep = "\n";
    }
    var s = stylename + sep;
    s = s + "=============== Heights ==================\n";
    s = s + "style: " + gebi(stylename).style.height + sep;
    s = s + "getStyle: " + getStyle(stylename, "height") + sep;
    s = s + "offsetHeight: " + gebi(stylename).offsetHeight + sep;
    s = s + "clientHeight: " + gebi(stylename).clientHeight + sep;
    s = s + "scrollHeight: " + gebi(stylename).scrollHeight + sep;
    s = s + "getStyleNH: " + getStyleNH(stylename, "height") + sep;
    //s = s + "textHeight: " + textHeight(stylename,"report") + sep;

    s = s + "=============== Width ==================\n";
    s = s + "style: " + gebi(stylename).style.width + sep;
    s = s + "getStyle: " + getStyle(stylename, "width") + sep;
    s = s + "offsetWidth: " + gebi(stylename).offsetWidth + sep;
    s = s + "clientWidth: " + gebi(stylename).clientWidth + sep;
    s = s + "scrollWidth: " + gebi(stylename).scrollWidth + sep;
    s = s + "getStyleNH: " + getStyleNH(stylename, "width") + sep;

    s = s + "=============== other =============\n";
    s = s + "display getStyle: " + getStyle(stylename, "display") + sep;
    s = s + "display style: " + gebi(stylename).style.display + sep;
    s = s + "overflow getStyle: " + getStyle(stylename, "overflow") + sep;
    s = s + "overflow style: " + gebi(stylename).style.overflow + sep;
    s = s + "overflowX getStyle: " + getStyle(stylename, "overflowX") + sep;
    s = s + "overflowX style: " + gebi(stylename).style.overflowX + sep;
    s = s + "overflowY getStyle: " + getStyle(stylename, "overflowY") + sep;
    s = s + "overflowY style: " + gebi(stylename).style.overflowY + sep;
    s = s + "padding style: " + gebi(stylename).style.padding + sep;
    s = s + "padding getStyle: " + getStyle(stylename, "padding") + sep;
    if (returnString) { return s; }
    alert(s);


}


//=======================================================;
function getStyleNH(name, prop) {
    // get dimensions if objetc is not hidden;

    var d = gebi(name).style[prop];

    if (d === "") {
        d = noPx(getStyle(name, prop));
    }

    if (gebi(name).style.display === "none") { d = 0; }
    if (getStyle(name, "display") === "none") { d = 0; }
    return noPx(d);
}
//=======================================================;
function getStyleNH2(name, prop) {
    // get dimensions if objetc is not hidden;

    var d = noPx(getStyle(name, prop));
    if (gebi(name).style.display === "none") { d = 0; }
    if (gebi(name).parentNode.style.display === "none") { d = 0; }
    if (gebi(name).parentNode.parentNode.style.display === "none") { d = 0; }
    if (getStyle(name, "display") === "none") { d = 0; }

    if ((name === "top") && (getStyle("top_holder", "display") === "none")) { d = 0; }
    if ((name === "bottom") && (getStyle("bottom_holder", "display") === "none")) { d = 0; }

    return noPx(d);
}





var currentWindowW = 0;
var currentWindowH = 0;
var resizeHandle;
//=======================================================;
function windowresize() {
    // IE fires multiple times;
    windowH = noPx(getWindowSize("h"));
    windowW = noPx(getWindowSize("w"));
    if (isIE()) {document.documentElement.scrollTop = 0; }
    if ((windowW !== currentWindowW) || (windowH !== currentWindowH)) {
        clearTimeout(resizeHandle);
        resizeHandle = setTimeout(function () {
            setVsize("all", "windowresize");
            if (onVBPageLoad) { onVBPageLoad(-1,"windowResize"); }
            currentWindowW = windowW;
            currentWindowH = windowH;
            //setTimeout(function () { textHeight("content","windowresize"); }, 300);
        }, 500);
    }
    else {
    }
}

//=======================================================;
function hasScroll(elem) {
    if (elem.clientHeight < elem.scrollHeight) {
        return true;
    }
    return false;
}

//===================================================================================================;
function min(a, b) {
    if (a < b) { return a; } else { return b; }
}

//===================================================================================================;
function max(a, b) {
    if (a > b) { return a; } else { return b; }
}
// ======================================================================	;
function getStyleProp(x, prop) {
    if (x.currentStyle) {
        return x.currentStyle[prop];
    }
    if (document.defaultView.getComputedStyle) {
        return document.defaultView.getComputedStyle(x, '')[prop];
    }

    return (null);
}





// ======================================================================	;

function navpos(pane) {
    var i;
    if (pane === "top") {
        $("#navcontenttable .chapter").css("display", "inline-block");

        for (i = 0; i < nChapters - 1; i++) {
            if (i === nChapters - 2) {
                aname = "chapter_last";
            }
            else {
                cid = i + 1;
                if (cid < 10) { cid = "0" + cid; }
                aname = "chapter_" + cid;
            }
            gebi("row" + (i + 1)).appendChild(gebi(aname));
        }
        navPos = "top";

    }
    else {
        $("#navcontenttable .chapter").css("display", "block");

        for (i = 0; i < nChapters - 1; i++) {
            if (i === nChapters - 2) {
                aname = "chapter_last";
            }
            else {
                cid = i + 1;
                if (cid < 10) { cid = "0" + cid; }

                aname = "chapter_" + cid;
            }

            gebi("row0").appendChild(gebi(aname));
        }
        navPos = "left";
    }
    reaccordion("navpos");
}

//=======================================================;
function log(text, pane) {
    if (!pane) { pane = "content"; }
    gebi(pane).innerHTML = gebi(pane).innerHTML + "<br>" + text;
}


//=============================================================;
function fixIEBlur(target) {

    // when 'content' has no backgroundcolor and ClearType is enabled, then text get blurred in IE after fading in;
    // so call this in the callback event of animate opacity;
    
    if (isIE()) {
        $("#" + target).css("filter", "");
    }
}




//=============================================================;
function getPageAsJSON(url, acallback) {
    url = replace(url, "?", "&");
    if (acallback) {
        src = vbasepath + "getpageasjson.asp?url=" + url + "&callback=" + acallback;
    }
    else {
        src = url + "?1=1";
    }
    request = new JSONscriptRequest(src, "js");
    request.buildScriptTag();
    request.addScriptTag();
}

var instance = 0;
var tinyZindex = 11002;
var tinyType = "";
var tinyAction = "";

// ======================================================================	;

function showTinyB(atype,action,nameOfFunction) {

    tinyZindex = tinyZindex + 10;
    var caption = "vBase " + atype + " browser";

    if (action==="upload") {
        src = vbasepath + "tinybrowser/upload.php?type=" + atype +  "&function="+nameOfFunction+ "&site_key=" + site_key + "&id=" + md5Hash + "&vbasepath=" + vbasepath + "#docloc=" + encodeURIComponent(document.location);
    }
    else {
        src = vbasepath + "tinybrowser/tinybrowser.php?type=" + atype + "&function=" + nameOfFunction + "&site_key=" + site_key + "&id=" + md5Hash + "&vbasepath=" + vbasepath + "#docloc=" + encodeURIComponent(document.location);
    }

    if ((document.location + " ").find("admin.asp")) {startAdmin("vBase Admin", 800, true); }


    if ((tinyBrowserWrapperRef) && (atype===tinyType) && (action===tinyAction)) {
        tinyBrowserWrapperRef.show();
        gebi("tinyBrowserWrapper").style.zIndex = tinyZindex;
        setTimeout(function() { tinyBrowserWrapperRef.moveTo("middle", "middle"); }, 500);

        tinyBrowserWrapperRef.onclose = function() {
            if ((document.location + " ").find("admin.asp")) {
                startAdmin("vBase Admin"); // shrink the admindow a bit
            }

            tinyBrowserWrapperRef = false;
            return true;
        };
    }

    else {
        tinyType = atype;
        tinyAction = action;

        instance++;
        windowH = noPx(getWindowSize("h"));
        if (tinyBrowserWrapperRef) { // we already have a window open, but for the wrong type


        }
        tinyBrowserWrapperRef = dhtmlwindow.open(tinyZindex, "tinyBrowserWrapper", "iframe", src, caption, "width=700px,height=" + (windowH - 50) + "px,resize=1,scrolling=1,center=1");
        a = window.frames["_iframe-tinyBrowserWrapper"].document.body;
        a.innerHTML = "<br><br>Loading page..&nbsp;&nbsp;<img src='" + vbasepath + "images/wait.gif' />";
        setTimeout(function() { tinyBrowserWrapperRef.moveTo("middle", "middle"); }, 500);
        tinyBrowserWrapperRef.onclose = function() {
            if ((document.location + " ").find("admin.asp")) {
                startAdmin("vBase Admin"); // shrink the admindow a bit
            }

            tinyBrowserWrapperRef.hide();

            return false;
        };
    }
}



// ======================================================================	;
function showEditStuff() {

    if (passwordPassed) {
        gebi('loginspan').style.display = 'none';
        gebi('adminspan').style.display = '';
        gebi('logoutspan').style.display = '';
        gebi('helpspan').style.display = "";
    }

    if (mayEdit) {
        gebi("editspan").style.display = "";
    }
    if (!passwordPassed) {
        gebi("editspan").style.display = "none";
        gebi("adminspan").style.display = "none";
        gebi('loginspan').style.display = '';
        gebi('logoutspan').style.display = 'none';
        gebi('helpspan').style.display = 'none';
    }
    gebi("searchspan").style.display = "";
}

var linkId = 0;

// ======================================================================	;
function linkstuff(target, overrule) {

    // replace protocol vbase:// by a javascript func jumpto in the whole document;
    // so:     <a href="vbase://vLinks#test2">test2</a>;
    // becomes <span class=vbaselink onclick="xxx('vLinks','test2')">test2</span>;

    // overrule: just to pass on to jumto. needed to jump anyway to the page, even if the page is lastPage (needed for search);
    var alist = gebi(target).getElementsByTagName("a");

    var listLength = alist.length;
    var product_id,i;
    for (i = 0; i < listLength; i++) {
        var a = alist[i];
        if ((a.href !== "") && (a.href !== "http://vbaseworks.com") && (a.id !== "vbaselink") && (!a.className.find("simpleCart")) ) {
            if ((a.className !== "imagelink") && (a.className !== "linkleft") && (a.className !== "linkright") && (a.className !== "linktop") && (a.className !== "linkbottom") && (a.className !== "linkcontent") && (a.className !== "linkmodal")) {

                // href can be:;
                // http://www.google.com/weather.htm;
                // vbase://E0726013-AAA4-4081-8524-A93E28584051#charly;
                // mailto:info@whatever.com;

                var linkInnerIsImage = false;
                var linkTargetIsImage = false;

                if (a.getElementsByTagName("img").length !== 0) { linkInnerIsImage = true; }
                if ((a.href.toLowerCase().indexOf("picapic.asp") !== -1) || (a.href.toLowerCase().indexOf(".jpg") !== -1) || (a.href.toLowerCase().indexOf(".jpeg") !== -1) || (a.href.toLowerCase().indexOf(".gif") !== -1) || (a.href.toLowerCase().indexOf(".png") !== -1)) { linkTargetIsImage = true; }

                var ananchor = "";
                linkId++;

                if (!linkInnerIsImage) {
                    a.className = "link" + target;
                    $(a).hover(function () { $(this).addClass("link" + target + "_hover"); }, function () { $(this).removeClass("link" + target + "_hover"); });
                }
                else {
                    a.className = "imagelink";
                    $(a).find("img").css("border", "0px");

                }

                a.style.position = "relative";
                var caption = a.name;

                if (a.href.substring(0, 8).toLowerCase() === "vbase://") {

                    if (a.href.indexOf("www.") !== -1) { a.href = replace(a.href, "vbase:", "http:"); }
                    if (a.href.indexOf(".com") !== -1) { a.href = replace(a.href, "vbase:", "http:"); }
                    if (a.href.indexOf(".net") !== -1) { a.href = replace(a.href, "vbase:", "http:"); }
                    if (a.href.indexOf(".tv") !== -1) { a.href = replace(a.href, "vbase:", "http:"); }
                }

                if (a.href.substring(0, 8).toLowerCase() === "vbase://") {


                    var rest = a.href.substring(8);

                    var content_key = rest.split("#")[0];
                    content_key = replace(content_key, "/", ""); // ie reports the href with an ending slash before the hash;
                    if (rest.split("#")[1]) { ananchor = rest.split("#")[1]; }
                    var linktarget = "";
                    if (rest.split("#")[2]) {
                        linktarget = rest.split("#")[2];
                        a.id = "linkid" + linkId + "|" + content_key + "|" + ananchor + "|" + linktarget;
                    }
                    else {
                        a.id = "linkid" + linkId + "|" + content_key + "|" + ananchor;
                    }

                    a.onclick = function() {

                        var thisId = this.id;

                        // Safari issue;

                        thisId = replace(thisId, "%23", "|");

                        var ananchor = thisId.split("|")[2];
                        var content_key = thisId.split("|")[1].toUpperCase();
                        if (thisId.split("|")[3]) {
                            ltarget = thisId.split("|")[3];
                        }
                        else {
                            ltarget = '';
                        }

                        var showcart = false;
                        var showproduct = false;
                        if (content_key.indexOf("VBASEPRODUCT:") !== -1) {

                            product_id = content_key.split(":")[1];
                            if (product_id === "0") {
                                showcart = true;
                            }
                            else {
                                showproduct = true;
                            }
                        }

                        var data = initData();

                        var pageno = getPageNo(content_key);
                        if (pageno !== -1) {  // if -1 then the page is not part of the navigation;
                            setNav(content_key, "linkstuff");
                        }
                        if (showcart) {  // not very usefull with mini cart 
                            if ($(".itemContainer").length === 0) {
                                alert(lab_cart_empty);
                            }
                            else {
                                showVBCart();
                            }
                        }
                        else if (showproduct) {
                            if (ltarget === "") { ltarget = "modal2"; }
                            showWait(ltarget);

                            var extra = "&target=" + ltarget;
                            data[4] = "productshow.asp?site_key=" + site_key + "&p_id=" + product_id;
                            data[2] = ltarget;

                            saveScrollTop = document.documentElement.scrollTop;
                            showNodeCallBack(data, "linkstuff showproduct");
                        }

                        else {
                            showNode('linkstuff', content_key, ltarget, ananchor);
                        }
                    };

                    if (!isIE()) {
                        a.href = "javascript:void(0)";
                    }
                    else {
                        a.href = "#";   //IE leaves relicts of cssRound if used like above
                    }
                }
                else {

                    a.id = linkId + "|" + (a.href);
                    a.id = replace(a.id, "%20", " ");
                    if (a.href.indexOf("mailto:") !== -1) {
                        a.onclick = function () {
                            var win = window.open(this.id.split("|")[1]);
                            if (win && win.open && !win.closed) { win.close(); }
                        };
                    }
                    if (a.href.indexOf("javascript") !== -1) {
                        a.onclick = function () {
                            eval(this.id.split("|")[1]);
                        };
                    }
                    else if (linkTargetIsImage) {
                        // make sure we open it with showpic()

                        var prevsrc = "";
                        var nextsrc = "";
                        var imgid = "";
                        var tagable = "";
                        if (a.id.find("vbslide|")) {
                            prevsrc = a.id.split("|")[1];
                            nextsrc = a.id.split("|")[2];
                            imgid = a.id.split("|")[3];
                            tagable = a.id.split("|")[4];  // flag to indicate if image is publicaly tagable;
                            if (prevsrc !== "") { prevsrc = (linkId - 1) + "|" + prevsrc; }
                            if (nextsrc !== "") { nextsrc = (linkId + 1) + "|" + nextsrc; }
                        }
                        a.link = a.href;
                        a.prev = prevsrc;
                        a.next = nextsrc;
                        a.imgid = imgid;
                        a.tagable = tagable;
                        a.caption = caption;
                        isSlideFromSlideshow = false;
                        if (a.id.find("vbslide|")) { isSlideFromSlideshow = true; }
                        a.isSlideFromSlideshow = isSlideFromSlideshow;
                        a.onclick = function () { showpic(this.link, this.caption, this.prev, this.next, this.imgid, this.id, this.isSlideFromSlideshow, this.tagable); };

                    }
                    else {
                        // a normal link of foreign website, then open in new window. if switching to other language, open in same window;

                        if ((a.href.find("?lan=")) || (a.href.find("&lan="))) {
                            a.onclick = function () {
                                faderIn(2);
                                showWait("screen");
                                document.location = this.id.split("|")[1];
                            };
                        }
                        else if (a.href.find("noaction")) {
                        }
                        else {
                            a.onclick = function () { window.open(this.id.split("|")[1]); };
                        }

                    }

                    if (!isIE()) {
                        a.href = "javascript:void(0)";
                    }
                    else {
                        a.href = "#";   //IE leaves relicts of cssRound if used like above
                    }

                }
            }
        }


        $(a).bind("click", function() {
            $(".link" + target).each(function() {
                $(this).removeClass("link" + target + "_clicked");
            });
            $(this).addClass("link" + target + "_clicked");

        });

    }


    $("#vbaselink").removeClass("linkbottom");




}




// ======================================================================	;
function goToAnchor(atarget) {
    // jumpt to an anchor if jumpToAnchor is not empty;
    if (atarget === "") { atarget = "content"; }

    if (anchor[atarget] !== "") {


        ananchor = anchor[atarget];
        if (typeof ananchor !== "undefined") { ananchor = replace(ananchor, "%20", " "); }
        
        if (atarget === "content") {
            newtarget = "content_scroller";
        }
        else {
            newtarget = atarget + "_scroller";
        }

        alist = gebi(atarget).getElementsByTagName("a");
        var i;
        for (i = 0; i < alist.length; i++) {
            if (alist[i].name.toLowerCase() === ananchor.toLowerCase()) {
                if (!haveScrollbar) {
                    apos = findPosY(alist[i]);
                    $(document.documentElement).animate({ scrollTop: apos }, 500);
                }
                else {
                    apos = findPosY(alist[i]) - findPosY(gebi(newtarget)) - 10;
                    $("#" + newtarget).animate({ scrollTop: apos }, 500);
                }
            }
        }
        anchor[atarget] = '';
    }
}

//=======================================================;
function reaccordion(who) {
    if ($(gebi("navholder")).accordion()) { JQsublink_container.show(); $(gebi("navholder")).accordion("destroy"); }
    if (animation) { accordion("reaccordion"); }
    gebi("navdragger").style.width = "";
    gebi("navdragger").style.height = "";
}




//=======================================================;
function closepic() {
    if (picInProgress) { return; }


    removeAllTags();
    if (gebi("currentpic")) { gebi("currentpic").onload = ""; }
    hideWait(); // just in case the picture didn't load;

    $("#picture_holder").stop().fadeOut(500, function () {  });
    gebi("loginpane").style.display = "";
    $("#thumb_holder,#prevbutton,#nextbutton,#closebutton,#ntags").css("display", "none");  // for IE
    gebi("thumb_holder").innerHTML = "";
    setStyle("thumb_holder", "display", "none");
    setStyle("prevbutton", "display", "none");
    setStyle("nextbutton", "display", "none");
    setStyle("closebutton", "display", "none");
    setStyle("caption_holder", "display", "none");
    setStyle("ntags", "display", "none");
    $("#thumb_holder,#prevbutton,#nextbutton,#closebutton,#ntags,#caption_holder").css("display", "");  // for IE

    document.body.appendChild(gebi("editCaption"));   // was attached to the caption div
    gebi("editCaption").style.display="none";   // was attached to the caption div



    if (vbaseParent !== "") {
        window.parent.location = vbaseParent + "#done";
    }


    faderOut(3);
    if (gebi("dragme")) { cancel_tag(); }

}

//=======================================================;
function noPx(aval) {
    if (aval === "") { return 0; }
    return parseInt(aval, 10);
}




//=======================================================;
function getStyleText(aname, ignoreState) {
    if (conflict) { alert("conflict"); return; }

    var styleName;
    if (ignoreState) {
        styleName = "." + aname;
    }
    else {
        styleName = getStyleName(aname,"getStyleText");
    }

    apos = styleIndex[styleName];
    if ((apos) || (apos === 0)) {

        //try {
            return theRules[apos].style.cssText;
        //}
       // catch (err) {
       //      return ""
        //}
    }
    else {
        return "";
    }

}




//=============================================================;
function getWidthStuff(styleName, leftOnly) {
    pl = noPx(getStyle(styleName, "paddingLeft"));
    pr = noPx(getStyle(styleName, "paddingRight"));
    bl = noPx(getStyle(styleName, "borderLeftWidth"));
    br = noPx(getStyle(styleName, "borderRightWidth"));
    if (getStyle(styleName, "borderRightStyle") === "none") { br = 0; }
    if (getStyle(styleName, "borderRightStyle") === "") { br = 0; }
    if (getStyle(styleName, "borderLeftStyle") === "none") { bl = 0; }
    if (getStyle(styleName, "borderLeftStyle") === "") { bl = 0; }
    ml = noPx(getStyle(styleName, "marginLeft"));
    mr = noPx(getStyle(styleName, "marginRight"));
    ml = 0;
    mr = 0;
    if (leftOnly) { return bl; }
    return pl + pr + bl + br + ml + mr;
}

//=============================================================;
function getHeightStuff(styleName, topOnly) {
    pt = noPx(getStyle(styleName, "paddingTop"));
    pb = noPx(getStyle(styleName, "paddingBottom"));
    bt = noPx(getStyle(styleName, "borderTopWidth"));
    bb = noPx(getStyle(styleName, "borderBottomWidth"));
    if (getStyle(styleName, "borderTopStyle") === "none") { bt = 0; }
    if (getStyle(styleName, "borderTopStyle") === "") { bt = 0; }
    if (getStyle(styleName, "borderBottomStyle") === "none") { bb = 0; }
    if (getStyle(styleName, "borderBottomStyle") === "") { bb = 0; }
    mt = noPx(getStyle(styleName, "marginTop"));
    mb = noPx(getStyle(styleName, "marginBottom"));
    mt = 0;
    mb = 0;
    if (topOnly) { return (bt); }
    return (pt + pb + bt + bb + mt + mb);
} //=============================================================;


var divcounter = 0;

var rotorId = 0;  // to attach to the id of a rotor image, in case two rotors point to the same show;

var imgID = 0;
// ======================================================================	;
function imagestuff(target, isproducttext) {

    // replace source of all images with the image resizer and put the image in a div;
    var alist,i;
    if (isproducttext) {
        valist = $(".producttext img");
    }
    else {
        alist = gebi(target).getElementsByTagName("img");
    }
    for (i = 0; i < alist.length; i++) {

        var img = alist[i];

        if ((!img.src.find("image.php")) && (!img.className.find("noimagestuff"))) {  // like productshow which already changes the image source to image.php

        var w = "";
        var h = "";
        var cr = "";

        var width = "";
        var height = "";
        if (findAttribute(img, "height")) { height = findAttribute(img, "height"); }
        if (findAttribute(img, "width")) { width = findAttribute(img, "width"); }

        if (width !== "") { width = parseInt(width, 10); }
        if (height !== "") { height = parseInt(height, 10); }
        if (width !== "") { w = "&width=" + width; }
        if (height !== "") { h = "&height=" + height; }

        if ((width !== "") && (height !== "")) { cr = "&cropratio=" + width + ":" + height; }
        asrc = findAttribute(img, "origsrc");

        if ((!asrc) || (asrc === "")) {
            asrc = decodeURIComponent(img.src);
        }
        else {
            asrc = replace(asrc, "&amp;", "&");
        }
        if (asrc.indexOf("picapic.asp") === -1) {
        
            if ((w !== "") || (h !== "")) { // need resizer;
                if ((asrc.indexOf("noresize") === -1) && (img.className.indexOf("noresize") === -1)) {
                    var newsrc = remotePath + "image.php?image=" + encodeURIComponent(asrc) + w + h + cr;
                    img.src = newsrc;
                    img.id = "img_" + imgID;
                    imgID++;
                    //$(img).addClass("rotator")
                }
            }
            else {
                img.src = asrc;
            }
        }
        else {
            if (localimg) { asrc = asrc + "&localimg=1"; }

            img.src = asrc;
            img.id = img.src + "&rotorId=" + rotorId;
            $(img).addClass("rotator")
            
            
            rotorId++;
        }
        if (img.src.indexOf("print_friendly") === -1) {

            var aspan = document.createElement("span");
            var margindiv=document.createElement("span");   // added for PIE, doesn't do well with margins
            img.parentNode.insertBefore(aspan, img);
            aspan.parentNode.insertBefore(margindiv, aspan);
            img.style.display = "block";
            aspan.appendChild(img);
            margindiv.appendChild(aspan);

            margindiv.style.border = "0px solid #ff0000";
            margindiv.style.display = "inline-block";
            margindiv.style.position = "relative";

            aspan.style.position = "relative"; // in ie, we get a weird mousover effect and the image will move
            
            if (img.hspace === -1) { img.hspace = ""; }
            if (img.vspace === -1) { img.vspace = ""; }

            margindiv.style.paddingLeft = img.hspace + "px";
            margindiv.style.paddingRight = img.hspace + "px";
            margindiv.style.paddingTop = img.vspace + "px";
            margindiv.style.paddingBottom = img.vspace + "px";

            img.vspace = "";
            img.hspace = "";

            if (img.style.marginLeft !== "") { margindiv.style.paddingLeft = img.style.marginLeft; }
            if (img.style.marginRight !== "") { margindiv.style.paddingRight = img.style.marginRight; }
            if (img.style.marginTop !== "") { margindiv.style.paddingTop = img.style.marginTop; }
            if (img.style.marginBottom !== "") { margindiv.style.paddingBottom = img.style.marginBottom; }

            if (isIE()) {
                margindiv.style.styleFloat = img.style.styleFloat;
                img.style.styleFloat = "";
            }
            else {
                margindiv.style.cssFloat = img.style.cssFloat;
                img.style.cssFloat = "";
            }
            
            img.style.margin = 0;

            aspan.style.display = "inline-block";
            //margindiv.style.visibility = "hidden"

            if ((img.align === "left") || (img.align === "right")) {
                if (isIE()) {
                    margindiv.style.styleFloat = img.align;
                }
                else {

                    margindiv.style.cssFloat = img.align;
                }
            }
            img.align = "";

            aspan.className = aspan.className + " " + "image" + target;
        }

    }
    }

}




//=======================================================;
function isSwapped(id) {
    if (trim(gebi(id + "_holder").innerHTML) === "") { return true; }
    return false;
}




//  =============================================================================;
function getJson(type, callback, content_key, target, panchor, assets_site) {
    // type should be 'nav','content' or 'panes';

    callback = 'JFgetdata(' + callback + ')';
    extra = "";
    if (content_key !== "") {
        extra = "&content_key=" + content_key;
    }
    if (target !== "") {
        extra = extra + "&target=" + target;
    }
    if (panchor !== "") {
        extra = extra + "&anchor=" + panchor;
    }
    extra = extra + "&id=" + md5Hash;
    //alert(forceRemote)
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    extra = extra + "&lan="+language;
    if ((type === "slideshows") || (type === "products")) {
        src = vbasepath + "getjson.asp?r=" + Math.random() + "&site_key=" + assets_site + "&type=" + type + "&callback=" + callback + extra;
    }
    else {
        src = vbasepath + "getjson.asp?r=" + Math.random() + "&site_key=" + site_key + "&type=" + type + "&callback=" + callback + extra;
    }
    request = new JSONscriptRequest(src, "js");
    request.buildScriptTag();
    request.addScriptTag();
}

// ======================================================================	;
function JFgetdata(callback, jsonstuff) {

    var j = 0;
    var myarray = [],i;
    for (i = 0; i < jsonstuff.items.length; i++) {
        var rec = jsonstuff.items[i],n;
        for (n in rec) {
            fieldname = n;
            myarray[j] = rec[fieldname];
            j++;
        }
    }
    callback(myarray);
}


//==============================JSON Class=======================;

function JSONscriptRequest(fullUrl, type) {
    this.fullUrl = fullUrl;
    this.type = type;
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

JSONscriptRequest.scriptCounter = 1;

JSONscriptRequest.prototype.buildScriptTag = function () {

    if (this.type === "js") {
        this.scriptObj = document.createElement("script");
        this.scriptObj.setAttribute("type", "text/javascript");
        this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
        this.scriptObj.setAttribute("id", this.scriptId);

    }
    else {
        this.scriptObj = document.createElement("style");
        this.scriptObj.setAttribute("type", "text/css");
        this.scriptObj.setAttribute("id", this.scriptId);
        this.scriptObj.innerHTML = this.fullUrl;

    }
};

JSONscriptRequest.prototype.removeScriptTag = function () {
    if (this.scriptObj) {
        this.headLoc.removeChild(this.scriptObj);
        this.scriptObj = null;
    }
};

JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
};


//  =============================================================================;
function findAttribute(obj, attr) {

    if (!isIE()) {
        return obj.getAttribute(attr);
    }
    else {
        var str = obj.outerHTML;

        str = str.toLowerCase();
        str = replace(str, "  ", " ");
        str = replace(str, "  ", " ");
        str = replace(str, "  ", " ");
        str = replace(str, " =", "=");
        str = replace(str, "= ", "=");
        str = replace(str, ">", " ");

        tofind = " " + attr + "=";
        ipos = str.indexOf(tofind);
        if (ipos === -1) { return ""; }
        delim = str.substr(ipos + tofind.length, 1);

        if ((delim !== "'") && (delim !== "\"")) { delim = " "; }
        if (delim === " ") { str = str.substr(ipos + tofind.length); }
        else { str = str.substr(ipos + tofind.length + 1); }

        ipos = str.indexOf(delim);

        return str.substr(0, ipos);

    }
}





// ======================================================================	;
function showNode(who, id, atarget, ananchor, doNotCheckPiggyBack) {
    id = id.toUpperCase();
    gebi("myselect").style.display = "none";
    if ((atarget !== "modal") && (atarget !== "modal2")) { closeModal(1, true); }
    if (atarget !== "modal2") { closeModal(2, true); }

    lastId = id;
    lastTarget = atarget;
    var i;
    for (i = 1; i < 11; i++) {
        if (gebi("aux" + i).shownode === id) {
            removeAuxClickedStates("shownode");
        }
    }

    lastNodeShowed = id;
    
    saveScrollTop = document.documentElement.scrollTop;


    // normaly target is defined for a record in the database. if target is specified, then show it in the specified pane;

    // show node 'id' in pane 'target';
    //store the id, needed for editing;

    if ((ananchor !== "") && (atarget === "") && (id === contentIds.content)) { setNav(id); anchor.content = ananchor; goToAnchor("content"); return; }
    if ((ananchor !== "") && (id === contentIds[atarget])) { setNav(id); anchor[atarget] = ananchor; goToAnchor(atarget); return; }

    if (atarget === "") { anchor.content = ananchor; } else {anchor[atarget] = ananchor; }
    // id of the last page loaded in main content pane;

    if (!doNotCheckPiggyBack) {getPiggies(id);}

    // check if the page is already loaded, if so, skip;
    var skip = false;
    
    if (!contentIds[atarget]) {contentIds[atarget] = "-1"; }
    if (id.toUpperCase() === contentIds[atarget].toUpperCase()) { skip = true; }
    if (atarget.find("modal")) {skip = false;}

    if (!skip) {

        showWait("screen");


        //gets the content of the page when clicked on a nav div;

        if ((standalone) && (pi[id][3] === "")) {
            extern = id + ".htm";
            $.get(extern, function (data) {  standaloneFinished(data, atarget, id,false); },"html");
            return;
        }

        if ((pi[id][3] !== '') && (vbaseExternal(pi[id][3]))) { // external page. no need to go to the database to get the external address, as we already have it
            // not true. the page might still have some headers. o yes, unless it's one of our own pages, which take care of writing the header
                    var data = initData(pi[id][3]);
                    data[3] = id;
                    data[4] = pi[id][3];
                    if (data[2] === "") {atarget = pi[id][2]; } // if target not sepecified use the default
                    data[2] = atarget;
                    data[5] = ananchor;
                    getPiggies(id);
                    showNodeCallBack(data, "shownode");
                    
            
        }
        else {
            getJson("content", "showNodeCallBack", id, atarget, ananchor);
        }
    }
    
}

// ======================================================================	;
function standaloneFinished(data, atarget, id) {
    var newdata = initData();
    //   0        1       2       3;
    // content,page_no,target, content_key,external,original_page;
    newdata[0] = data;
    newdata[2] = atarget;
    newdata[3] = id;
    showNodeCallBack(newdata, "standaloneFinished");

}

// ======================================================================	;
function getPiggies(id) {
    if (pi[id][0] !== '') {
        var alist = pi[id][0].split("|");
        var atargetlist = pi[id][1].split("|"),i;
        for (i = 0; i < alist.length; i++) {
            if (alist[i] !== '') {
                if (typeof pi[alist[i]] !== 'undefined') {
                    showNode('getpiggies', alist[i], atargetlist[i], "", true);
                } // do not check for piggybacks on piggybacks;
            }

        }
    }

    else {

        //getJson("piggyback", "piggybackCallback", id, "", "");
    }
}        


// ======================================================================	;
function piggybackCallback(pdata) {
    var original_page = pdata[5];
    var ic;
    for (ic = 0; ic < pdata.length; ic = ic + 7) {
        if (pdata[ic + 3] !== '') { // can be empty if no piggybacks;

            var newdata = [];
            //   0        1       2       3;
            // content,page_no,target, content_key,external,original_page;
            newdata[0] = pdata[ic];
            newdata[1] = pdata[ic + 1];
            newdata[2] = pdata[ic + 2];

            newdata[3] = pdata[ic + 3];
            newdata[4] = pdata[ic + 4];
            newdata[5] = ''; // anchor, not implemented;
            newdata[6] = pdata[ic + 6]; // modified
            original_page = pdata[ic + 5];
            showNodeCallBack(newdata,"piggyback");
        }
    }

}

// ========================================================================;
function showNodeCallBack(data,who) {
    gebi("myselect").style.display = "none";
    if (beforeVBPageLoad) { beforeVBPageLoad(); }
    //data contains: content,page_no,target, content_key , external,anchor;
    var myhtml = data[0];

    var target = data[2];
    var id = data[3];
    var extern = data[4];
    //extern=pi[id][3]
    var ananchor = data[5];
    var modified = data[6];
    anchor[target] = ananchor;

    if (extern === "") {
        if (contentIds[target] === id) {
            hideWait();
            return; }
    }

    contentIds[target] = id; 
    if ((target !== "modal") && (target!=="modal2")) { closeModal(1, true); }
    if (target !== "modal2") { closeModal(2, true); }

    $("#" + target).stop();
    stopRotators(target);

    gebi("left_holder").style.display = "";
    gebi("right_holder").style.display = "";
    gebi("navdragger").style.display = "";
    gebi("top_holder").style.display = "";


    if (target === "") {
        showWait("content");
    }
    else if (target.find("modal")) {
        showWait("screen");
    }
    else {
        showWait(target);
    }

    externalAddress = false;  // http of an iframe source

    var doit = false;
    if (extern !== "") {

        if (extern.indexOf("vbaseoption=full") !== -1) {  //use just as a link. opens in same window (IELTS)
            document.location = extern;
            return;
        }
        //isExternal[target] = extern;
        if (extern.indexOf("calendar.asp") !== -1) {

            //calendar.asp?site_key=6D70FE2D-7895-47F8-87BC-6C288A679E4C
            extern = replace(extern, "calendar.asp", "http://v-cal.com");
            extern = extern + "&noheader=1";
            if (forceRemote) { extern = extern + "&forceremote=1"; }
            if (md5Hash !== "") { extern = extern + "&id=" + md5Hash; }

        }
        if (vbaseExternal(extern)) {  // one of the vbase external pages
            if (extern.find("guestbook.asp")) { guestbookTarget = target; }
            
            // extern:  slideshow.asp?site_key=123&ss_id=abc;

            extern = replace(extern, "slideshow.asp?", vbasedomain + "?relay=slideshow.asp&usermd5=" + gbmd5_tags + "&");
            extern = replace(extern, "guestbook.asp?", vbasedomain + "?relay=guestbook.asp&usermd5=" + gbmd5_blogs + "&");
            extern = replace(extern, "productshow.asp?", vbaseroot + "?relay=productshow.asp&");
            extern = replace(extern, "emailform.asp?", vbaseroot + "?relay=emailform.asp&");
            extern = replace(extern, "emaillist.asp?", vbaseroot + "?relay=emaillist.asp&");

            extern = extern + "&page_c=" + id;
            if (extern.indexOf("http://") == -1) { extern = vbasepath + extern; }
            if (forceRemote) { extern = extern + "&forceremote=1"; }
            if (localimg) { extern = extern + "&localimg=1"; }
            extern = extern + version;
            if (md5Hash !== "") { extern = extern + "&id=" + md5Hash; }
            if (!standalone) {
                extern = extern + "&rnd=" + Math.random();
            }
            if (extern.find("productshow.asp")) {
                extern = extern + "&mal_server=" + mal_server + "&merchant_id=" + merchant_id + "&target=" + target;
                extern = extern + "&vbcur=" + vbase_currency;
                extern = extern + "&malcur=" + mal_currency;
                extern = extern + "&dec=" + decimals;
                extern = extern + "&mallan=" + mal_language;

            }
            if ((extern.indexOf("slideshow.asp") !== -1) && (!tagsloggedin)) { extern = extern + "&taglogout=1"; }
            extern = extern + "&lan=" + language;
            // external page, however we need to inject the HTML in the main body, as opposed to using a iframe.;
            // the iframe cannot communicate with vBase when used cross-domain, like embropatch.com;
            
            ajaxTarget = target;

            if ((sameDomain) || (standalone)) {
                //alert("here")
                if (standalone) {
                    extern = hex_md5(extern.toUpperCase()).toUpperCase() + ".htm";
                    $.get(extern, function (data) { ajaxCallback(target, data); }, "html");
                    
                }
                else {

                    // http//support.microsoft.com/default.aspx?scid=kb;en-us;Q316451;
                    $.get(extern, function(data) { ajaxCallback(target, data); }, "html");
                }
            }
            else {
                getPageAsJSON(extern, "ajaxCallback('"+target+"')");
            }

            return;  // done, the rest will be done after the callback

        }
        else {
            externalAddress = extern;
            myhtml = myhtml + "<iframe  name=extif  class=extif id=extif scrolling='auto'  frameborder='0' src='javascript:void(0)' style='display:none;background-color:#ffffff; padding: 0px;'></iframe>";
        }
    }


    if ((target === "modal") && (gebi("modal_holder").style.display !== "block")) {
        showModal(1, myhtml, false, true, externalAddress); 
    }
    else if ((target === "modal2") && (gebi("modal2_holder").style.display !== "block")) {
        showModal(2, myhtml, false, true, externalAddress);
    }
    else {

        if (getStyleText("printfriendly") !== "") {
            if (modified.indexOf("(") > 0) {
                modified = modified.substr(0, modified.indexOf("(") - 1);
            }
            if (target === "content") {
                myhtml = myhtml + "<br><p   align=right onclick=\"printNode('" + contentIds.content + "')\"><span class=printfriendly style='cursor:pointer;cursor:hand'>print-friendly&nbsp;<img class=noresize align=absmiddle src=" + vbasepath + "images/print_friendly.png></span><br>";
                myhtml = myhtml + "<span class=modified >this page was last modified on " + modified + "</span></p>";
            }
        }


        setTimeout(function () { pageFinished(myhtml, target, id, externalAddress); }, 0);


    }

}

//=============================================================;
function vbaseExternal(extern) {
    var vbe = false;
    if ((extern.indexOf("guestbook.asp") !== -1) || (extern.indexOf("slideshow.asp") !== -1) || (extern.indexOf("productshow.asp") !== -1) || (extern.indexOf("emailform.asp") !== -1) || (extern.indexOf("emaillist.asp") !== -1) || (extern.indexOf("email.asp") !== -1) || (extern.indexOf("emaillist.asp") !== -1)) { vbe = true; }
    return vbe;
}    


//=============================================================;

function pageFinished(html, target, page_id, externalAddress) {
    // called when the pageHTMl is finished loading

    if (localimg) {
        html = replace(html, "www.vbaseworks.com", "localhost/vbase");
        html = replace(html, "vbaseworks.com", "localhost/vbase");
        html = replace(html, "/V161/", "/V203/");
        html = replace(html, "/V162/", "/V203/");
        html = replace(html, "/V163/", "/V203/");
        html = replace(html, "/V164/", "/V203/");
        html = replace(html, "/V165/", "/V203/");
        html = replace(html, "/V166/", "/V203/");
        html = replace(html, "/V167/", "/V203/");
    }

    if (isIE()) {
        $("#" + target).css("opacity", 1);
    }
    else {
        $("#" + target).css("opacity",0);
    }

    gebi(target).innerHTML = "";
    //obj.style.overflow = "hidden";   // needed for Safari
    var adiv = document.createElement("div");
    adiv.id = target + "_scroller";
    adiv.className = target + "_scroller";
    adiv.style.position = "relative";
        
    gebi(target).appendChild(adiv);
    adiv.innerHTML = html;
    fix(target);   // ie loses inheritance


    if ($("#" + target + " .slideholder")[0]) {
        aholder = $("#" + target + " .slideholder")[0];
        newh = noPx(aholder.style.height) + noPx(getStyle("slide", "paddingTop")) + noPx(getStyle("slide", "paddingBottom")) - getHeightStuff("slideholder");
        neww = noPx(aholder.style.width) + noPx(getStyle("slide", "paddingLeft")) + noPx(getStyle("slide", "paddingRight")) - getWidthStuff("slideholder");

        if (1==1) {
            newh = noPx(aholder.style.height) + getHeightStuff("slideholder") + getHeightStuff("slide");
            neww = noPx(aholder.style.width) + getWidthStuff("slideholder") + getWidthStuff("slide");
        }
        $(".slideholder").css("height", newh);
        $(".slideholder").css("width", neww);
    }

    fixIEBlur(target);
    fixIEBlur(target + "_scroller");

    imagestuff(target);

    linkstuff(target);

    JFormaramaStuff(target);
    jCDBIStuff(target);

    startRotators(target);

    if (onVBPageLoad) { onVBPageLoad(page_id,"pagefinished"); }    
    if (!target.find("modal")) {document.documentElement.scrollTop = 0; }
    if (!gebi("editorIframe")) {setIframeSize(target, externalAddress); }

    if (haveScrollbar || target.find("modal")) {
        setVsize(target, "pagefinished 1");
            //alert(3)
    }
    else {
        setVsize("all", "pagefinished 2");
            //alert(5)
    }

    //setVsize("all")
    goToAnchor(target);

    $(".popper").hover(function() {
        var atext = this.getAttribute('helptext');
        this.title = "";  // by setting a title, ie supresses the tooltip, which is annoying
        if (!atext) { atext = this.alt; }
        showPop(atext);
    }, function() { killPop(); });
    $(".gbbutton").hover(function () { $(this).addClass('gbbutton_hover'); }, function () { $(this).removeClass('gbbutton_hover'); });

    if (gebi("target_form")) {gebi("target_form").submit(); }
    hideWait();
    if (!isIE()) { $("#" + target).animate({ opacity: 1 }, 1000); }

// fix unicode issues with getPageasJason

    if (lab_message !== "") { // email order
        if (gebi("subject")) {gebi("subject").value = lab_order_by_email; }
        if (gebi("message")) {gebi("message").value = lab_message; }
    }
    //simpleCart.cartHeaders = ["Name", "Quantity_input", "remove_noHeader", "Total"];

    simpleCart.initializeView();
    simpleCart.load();
    simpleCart.update();
    
    //if (name.find("simpleCart")) { found = true }

    //if ($(".itemContainer").length>0) { showVBCart() } else { hideVBCart() }
}

//=============================================================;
function fix(target) {
    if (isIE()) {
        // IE breakes 'inherit' over tables in quirks mode. Great...;
        var alist = $("." + target + " td"),i;
        for (i = 0; i < alist.length; i++) {
            alist[i].style.fontFamily = getParentStyle(alist[i], "fontFamily");
            alist[i].style.fontSize = getParentStyle(alist[i], "fontSize");
            alist[i].style.color = getParentStyle(alist[i], "color");
            //alist[i].style.position = "relative";
        }
    }
}

//=============================================================;
function ajaxCallback(atarget, data) {
    if (typeof data === "object") {data = toArray(data); }

    if ((atarget === "modal") && (gebi("modal_holder").style.display !== "block")) {
        showModal(1, data, false, true);
    }
    else if ((atarget === "modal2") && (gebi("modal2_holder").style.display !== "block")) {
        showModal(2, data, false, true);
    }
    else {
        setTimeout(function () { pageFinished(data, atarget,false); }, 500);
    }

}


// ======================================================================	;
function setIframeSize(target, externalAddress) {
    getDimensions("setIframesize");
    if (gebi(target).getElementsByTagName("iframe").length !== 0) {

        theframe = gebi(target).getElementsByTagName("iframe")[0];

        if ((theframe.id !== "gbhif") && (theframe.id !== "shif") && (!theframe.src.find("/embed/") )) {
            //var src = theframe.src + " ";
            var src = externalAddress;

            var ifh = false;
            if (externalAddress) {
                ipos = src.indexOf("ifh=");
                if (ipos !== -1) {
                    src = src.substr(ipos + 4);
                    ifh = src.split("&")[0];
                }
            }

            // calculate the extraheight by removing the iframe, calculate the text height and put the iframe back

            var eh = textHeight(target, "setIframesize") - getHeightStuff(target);
            if (target === "content") { tw = contentWidth - getWidthStuff("content"); }
            if (target === "content") { noScrollHeight = contentHeight - eh - getHeightStuff("content"); }

            maxsize = false;
            if (gebi("editorIframe")) { maxsize = true; }

            if (target.find("modal")) { tw = getModalWidth(maxsize) - getWidthStuff("modal_holder") - getWidthStuff("modal"); }
            if (target.find("modal")) {noScrollHeight = getModalHeight(maxsize) - eh - getHeightStuff("modal_holder") - gebi(replace(target, "modal", "closebuttonholder")).offsetHeight - getHeightStuff("modal"); }

            if (gebi("editorIframe")) { noScrollHeight = noScrollHeight - 30; } // need place for the update and cancel button

            if (target === "right") { tw = rightWidth - getWidthStuff("right"); }
            if (target === "right") { noScrollHeight = rightHeight - eh - getHeightStuff("right"); }

            if (target === "left") { tw = leftWidth - getWidthStuff("left"); }
            if (target === "left") { noScrollHeight = leftHeight - eh - getHeightStuff("left"); }

            if (target === "top") { tw = topWidth - getWidthStuff("top"); }
            if (target === "top") { noScrollHeight = topHeight - eh - getHeightStuff("top"); }

            if (ifh) {  // given iframe height from querystring
                theframe.style.height = (ifh * 1) + "px";
                if (ifh > noScrollHeight) {
                    theframe.style.width = (tw - 16 - noPx(getStyle(target, "paddingRight"))) + "px"; // need space for scrollbar
                }
                else {
                    theframe.style.width = tw + "px";
                }
            }
            else {
                theframe.style.height = (noScrollHeight-10) + "px";
                theframe.style.width = tw + "px";
                //alert(theframe.style.height)
            }
            theframe.style.display = "";
        }
        if (typeof externalAddress !== "undefined") {
            theframe.src = externalAddress;
        }


    }


}

// ======================================================================	;
function setNav(content_key, who) {

    disableNavClick = true;

    var a = $("div [content_key^=" + content_key + "]")[0];
    if (a) {
        pageno = findAttribute(a, "pageno");
        mainid = pageno.split("_")[0];
        if (alwaysOpen) { $(gebi("navholder")).accordion("activate", parseInt(mainid, 10)); }
        if (mainid === "00") { mainid = "first"; }
        if (mainid === lastLinkId) { mainid = "last"; }
        if ((pageno.split("_")[1])) {
            // open a sublink;
            subid = pageno;
            $("#link_" + mainid).trigger("click");
            $("#link_" + subid).trigger("click");
        }
        else {
            // open a main link;
            alink = mainid;
            if (mainid === "00") { alink = "first"; }
            if (mainid === lastLinkId) { alink = "last"; }
            $("#link_" + alink).trigger("click"); // show the page;
        }

        if (navPos == "top") {
            if (alwaysOpen) { $(gebi("navholder")).accordion("activate", mainid); }  // close the menu;
        }

    }

    disableNavClick = false;
}


// ======================================================================	;
function getPageNo(content_key) {
    pageno = -1;
    var a = $("div [content_key^='" + content_key + "']")[0];
    if (a) {
        pageno = findAttribute(a, "pageno");
    }
    return pageno;
}






taglist = ";hr;li;ul;h1;h2;h3;h4;select;table;*;";
// ======================================================================	;
function floatStyles(objectname) {
    if (objectname === "navdragger") {
        gebi(objectname).anchorX = parseInt(getPseudoStyle("navX", 0), 10);
        gebi(objectname).anchorY = parseInt(getPseudoStyle("navY", 0), 10);
        gebi(objectname).anchor = getPseudoStyle("navAnchor", "left");
    }
    else if (objectname.find("aux")) {
        var aval = getPseudoStyle(objectname + "Anchor", "left|0|0|");
        gebi(objectname).anchor = aval.split("|")[0];

        gebi(objectname).anchorX = parseInt(aval.split("|")[1], 10);
        gebi(objectname).anchorY = parseInt(aval.split("|")[2], 10);
        gebi(objectname).shownode = aval.split("|")[3];
    }
    else {
        gebi(objectname).anchorX = parseInt(getPseudoStyle(objectname + "X", 0), 10);
        gebi(objectname).anchorY = parseInt(getPseudoStyle(objectname + "Y", 0), 10);
        gebi(objectname).anchor = getPseudoStyle(objectname + "Anchor", "left");
    }

    gebi(objectname).saveX = gebi(objectname).anchorX;
    gebi(objectname).saveY = gebi(objectname).anchorY;


}

var conflict;
//=======================================================;
function setStyleText(aname, atext, ignoreState) {

    if (conflict) { alert("conflict"); return; }
    conflict = true;

    var styleName;
    if (ignoreState) {
        styleName = "." + aname;
    }
    else {
        styleName = getStyleName(aname,"setStyleText");
    }

    apos = styleIndex[styleName];

    if ((apos) || (apos === 0)) {
        theRules[apos].style.cssText = atext;
    }
    else {
        createStyle(aname, "padding", "0px");  // whatever, we will overwriteit straight away;
        apos = styleIndex[styleName];  // should be theRules.length-1
        theRules[apos].style.cssText = atext;

    }
    indexStyle();
    conflict = false;
}


//=======================================================;
function createStyle(name, property, value) {
    if ((value === "") && (property !== "")) { return; }
    var styleName = getStyleName(name,"createStyle");
    if (document.styleSheets[1].insertRule) { //if Firefox;
        document.styleSheets[1].insertRule(styleName + " {" + property.toDash() + ":" + value + ";}", theRules.length);
    }
    else { //else if IE;
        document.styleSheets[1].addRule(styleName, property.toDash() + ":" + value);
    }
    theRules = getRules(1);
    indexStyle();

    return "";
}

skipcount1 = 0;
skipcount2 = 0;
skipcount3 = 0;
//=======================================================;
function setStyle(aname, property, value, ignoreState, index) {
    var styleName;
    
    if (isNumeric(value,aname+" "+property)) { value = value + "px"; }


    if (taglist.find(";" + aname.toLowerCase() + ";")) {
        styleName = aname;
    }
    else {
        if (ignoreState) {
            styleName = "." + aname;
        }
        else {
            styleName = getStyleName(aname,"setStyle");
        }
    }

    // do a check. setting a style is slow, getting it is not

    if (typeof styleIndex[styleName] !== "undefined") {
        if ((getStyle(aname, property, ignoreState) === value)) { skipcount1++;return;}
    }
    else {
        skipcount3++;
    }


    apos = styleIndex[styleName];
    if ((apos) || (apos === 0)) {
        try {
            theRules[apos].style[property] = value;

        }
        catch (err) {
            alert("error in setStyle: " + aname + " " + property + ": " + value);
        }
    }
    else {

        createStyle(aname, property, value);
    }

}





var indexChanged;
var nchanged = 0;

//=======================================================;
function indexStyle() {
    styleIndex = [];var stylename;
    var ruleLength = theRules.length,i;
    for (i = 0; i < ruleLength; i++) {
        if (typeof theRules[i].selectorText === "undefined") {
        }
        else {
            styleName = theRules[i].selectorText.toLowerCase();
        }
        styleIndex[styleName] = i;
    }
    indexChanged = false;
}

//=======================================================;
function getStyle(aname, property, ignoreState, index) {
    var styleName;
    if (ignoreState) {
        styleName = "." + aname;
    }
    else {
        styleName = getStyleName(aname,"getStyle");
    }

    if (indexChanged) { nchanged++; indexStyle(); }
    thestyle = "";
    if ((styleIndex[styleName]) || (styleIndex[styleName] === 0)) {
        astart = styleIndex[styleName];
        //try {
        if (theRules[astart].style[property]) { thestyle = theRules[astart].style[property].toLowerCase(); } else {skipcount2++; }
        //}
        //catch (err) {
        //    a=apenoot
        //}
        return thestyle;

    }
    else {
        return "";
    }

}



// ======================================================================	;
function readStyles() {

    theRules = getRules(1);

    var ruleLength = theRules.length;
    indexStyle();
    var i;
    for (vi = 0; i < theRules.length; i++) {
        var styleName = theRules[i].selectorText.toLowerCase();
        if (styleName.find("_scroller")) {
            if ((!styleName.find("vbar_")) && (!styleName.find("style.r_"))) {

                deleteStyleText(styleName);
                i--;

            }

        }

        if (isMoz()) {
            astyle = theRules[i].style.cssText;
            astyle = replace(astyle, "text-align: center", "text-align:-moz-center");
            astyle = replace(astyle, "text-align: left", "text-align:-moz-left");
            theRules[i].style.cssText = astyle;
        }


    }


    th = noPx(getStyle("top", "height"));
    bh = noPx(getStyle("bottom", "height"));

    if (getStyle("top1_spacer", "display") === "none") { gebi("top1_spacertr").style.display = "none"; }
    if (getStyle("top_holder", "display") === "none") { gebi("top_holdertr").style.display = "none"; }
    if (getStyle("top2_spacer", "display") === "none") { gebi("top2_spacertr").style.display = "none"; }
    if (getStyle("bottom1_spacer", "display") === "none") { gebi("bottom1_spacertr").style.display = "none"; }
    if (getStyle("bottom_holder", "display") === "none") { gebi("bottom_holdertr").style.display = "none"; }
    if (getStyle("bottom2_spacer", "display") === "none") { gebi("bottom2_spacertr").style.display = "none"; }

    // some default styles for style1 to style10 in case they are not set

    for (i = 1; i < 11; i++) {
        if (getStyle("style" + i, "backgroundColor") === "") { setStyle("style" + i, "backgroundColor", "#ffffff"); }
        if (getStyle("style" + i, "padding") === "") { setStyle("style" + i, "padding", "5px"); }
        if (getStyle("style" + i, "border") === "") { setStyle("style" + i, "border", "1px solid #999999"); }
        if (getStyle("style" + i, "color") === "") { setStyle("style" + i, "color", "#666666"); }
        if (getStyle("style" + i, "fontSize") === "") { setStyle("style" + i, "fontSize", "12px"); }
        if (getStyle("style" + i, "fontFamily") === "") { setStyle("style" + i, "fontFamily", "Trebuchet MS"); }

    }

    if (getStyleText("slideholder") === "") {
        setStyle("slideholder", "marginRight", 10);
        setStyle("slideholder", "marginBottom", 10);
    }


    left100 = getPseudoStyle("leftfull", "");
    right100 = getPseudoStyle("rightfull", "");

    styleScrollbars = false;
    styleScrollbars = getBoolPseudoStyle("styleScrollbars", false);

    closeAllClickables = getBoolPseudoStyle("closeAllClickables", false);

    // get the position for the navigation, and set it;

    floatStyles("navdragger");
    navPos = getPseudoStyle("navpos", "");
    gebi("navdragger").isFloat = true;
    // get the position for the toolbox, and set it;

    floatStyles("toolbox");
    gebi("toolbox").isFloat = getBoolPseudoStyle("toolboxFloat", false);  // indicates if detached from bottom pane;

    floatStyles("vbaselink");
    gebi("vbaselink").isFloat = getBoolPseudoStyle("vbaselinkFloat", false); // indicates if detached from toolbox;

    floatStyles("searchspan");
    gebi("searchspan").isFloat = getBoolPseudoStyle("searchspanFloat", false); // indicates if detached from toolbox;

    for (i = 1; i < 11; i++) {
        floatStyles("aux" + i);
        gebi("aux" + i).isFloat = true;
        obj = gebi("aux" + i);
        $(obj).hover(function () { $(this).addClass('aux_hover'); }, function () { $(this).removeClass('aux_hover'); });
        if (obj.shownode !== "") {
            $(obj).bind("click", function() {
                removeAuxClickedStates("round");
                removeClickedStates('all', false, 'readstyles');
                setNav(this.shownode, "readstyles");
                showNode('auxclick', this.shownode, "", "");
                lastPage = this.id;

            });
            $(obj).addClass("auxlink");
        }
    }

    //save coordinates for resetPosition;

    menuOpener = getPseudoStyle("menuOpener", "click");

    alwaysOpen = getBoolPseudoStyle("alwaysOpen", true);

    fixedHeight = getBoolPseudoStyle("fixedHeight", true);

    animation = getBoolPseudoStyle("animation", true);

    showNavText = getBoolPseudoStyle("shownavtext", true);

    useAssets = getBoolPseudoStyle("useAssets", false);
    if (hasDragDrop) { useAssets = false; } // don't use for layout manager

    $("#toolbox .adminbutton").hover(function () { $(this).addClass('adminbutton_hover'); }, function () { $(this).removeClass('adminbutton_hover'); });
    if ((getStyle("body", "overflow") === "hidden") || (getStyle("body", "overflowY") === "hidden")) {
        setScroll('content');
        haveScrollbar = true;
    }
    else {
        setScroll('window');
        haveScrollbar = false;
    }


    $("#sitemap").css("display", "none");
    if (gebi("sitemap")) {
        removeNode(gebi("sitemap"));
    }

    var ah = parseInt(gebi("top1_spacer").offsetHeight, 10);
    if (gebi("swapleftspacer")) {
        if (ah === 0) {
            gebi("swapleftspacer").style.display = "none";
        }
        else {
            gebi("swapleftspacer").style.height = ah + "px";
            gebi("swapleftspacer").style.fontSize = 0 + "px";
        }
    }
    if (gebi("swaprightspacer")) {
        if (ah === 0) {
            gebi("swaprightspacer").style.display = "none";
        }
        else {
            gebi("swaprightspacer").style.height = ah + "px";
            gebi("swaprightspacer").style.fontSize = 0 + "px";

        }
    }

    var pane;
    for (pane in panes) {
        $("#" + panes[pane] + " .link" + panes[pane]).hover(function() { $(this).addClass("link" + panes[pane] + "_hover"); }, function() { $(this).removeClass("link" + panes[pane] + "_hover"); });
    }

    $("#loginpane .button, #searchbuttons .button").hover(function () { $(this).addClass('button_hover'); }, function () { $(this).removeClass('button_hover'); });





    setStyleText("modal2", getStyleText("modal"));
    setStyleText("modal2_holder", getStyleText("modal_holder"));
    setStyleText("vbar_modal2_scroller", getStyleText("vbar_modal_scroller"));
    setStyleText("vglider_modal2_scroller", getStyleText("vglider_modal_scroller"));

    setStyleText("linkmodal2", getStyleText("linkmodal"));


    //deletePseudoStyles();




}

// ======================================================================	;
function getBoolPseudoStyle(aname, defaultIfEmpty) {

    oval = getPseudoStyle(aname, defaultIfEmpty);
    nval = oval;
    if (oval === "") { nval = defaultIfEmpty; }
    else if (oval === "undefined") { nval = defaultIfEmpty; }
    else if (oval === "true") { nval = true; }
    else if (oval === "false") { nval = false; }

    return nval;
}



// ======================================================================	;
function docLoaded() {

    document.documentElement.scrollTop = 0;


    showtime();
    // float them before doing linksstuff, else

    var pane;
    for (pane in panes) {
        imagestuff(panes[pane]);
        linkstuff(panes[pane]);
        JFormaramaStuff(panes[pane]);
        jCDBIStuff(panes[pane]);
        startRotators(panes[pane]);
        fix(pane);  // ie loses inheritance
    }

    docIsLoaded = true;


    $(".popper").hover(function () {
        var atext = this.getAttribute('helptext');
        this.title="";  // by setting a title, ie supresses the tooltip, which is annoying
        if (!atext) { atext = this.alt; }
        showPop(atext);
    }, function () { killPop(); });

    document.body.onmousedown = selectmouse;

    document.body.onmouseup = function () {
        mouseIsDown = false; isdrag = false; dragobject = "";
        document.body.onselectstart = function () { return true; };

    };

    document.body.onmousemove = movemouse;

    window.onfocus = function() {
        for (pane in panes) {
            //startRotators(panes[pane]);
        }
    };

    window.onblur = function() {
        for (pane in panes) {
            //stopRotators(panes[pane]);
        }
    };
    
    
    

    // ie bug doesn't render the images
    if (getStyle("picture_holder", "backgroundColor") === "") { setStyle("picture_holder", "backgroundColor", "#ffffff"); }

    window.onresize = windowresize;
    indexStyle();


    setVsize("all","docloaded");
    if (isIE()) {setVsize("all", "docloaded"); }


    if (onVBPageLoad) { onVBPageLoad(contentIds.content,"docloaded"); }

    if (external_start !== "") {
        external_start(); // this function calls showNodeCallback --> pagefinished and takes care of the below
    }
    else {
        simpleCart.initializeView();
        simpleCart.load();
        simpleCart.update();
    }


    //if (name.find("simpleCart")) { found = true }

    if ($(".itemContainer").length > 0) { showVBCart(); } else { hideVBCart(); }



}

// ======================================================================	;
function setcenter(idToCenter, idToCalculate, addScroll) {
    windowH = noPx(getWindowSize("h"));
    windowW = noPx(getWindowSize("w"));

    // center something in the middle of a screen;
    oldvis = gebi(idToCenter).style.display;

    gebi(idToCenter).style.display = "block";

    if ((!haveScrollbar) && (idToCalculate === "content")) { idToCalculate = "window"; }
    if (idToCalculate === "content") { idToCalculate = "content"; }
    gebi(idToCenter).style.position = "absolute";
    if ((idToCalculate === "window") || (idToCalculate === "screen")) {
        x = windowW / 2 + document.documentElement.scrollLeft - gebi(idToCenter).offsetWidth / 2;
        y = windowH / 2 + document.documentElement.scrollTop - gebi(idToCenter).offsetHeight / 2;
        
    }
    else {
        
        x = findPosX(gebi(idToCalculate)) + gebi(idToCalculate).offsetWidth / 2 - gebi(idToCenter).offsetWidth / 2;
        y = findPosY(gebi(idToCalculate)) + gebi(idToCalculate).offsetHeight / 2 - gebi(idToCenter).offsetHeight / 2;
    }
    if (addScroll) {
    
        var scrollTop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;        
        var scrollLeft = document.documentElement ? document.documentElement.scrollLeft : document.body.scrollLeft;

        document.getElementById(idToCenter).style.left = (x + scrollLeft) + 'px';
        document.getElementById(idToCenter).style.top = (y + scrollTop) + 'px';
        document.getElementById(idToCenter).style.left = x + 'px';
        document.getElementById(idToCenter).style.top = y + 'px';

    }
    else {

        document.getElementById(idToCenter).style.left = x + 'px';
        document.getElementById(idToCenter).style.top = y + 'px';

    }
   
    
    
    gebi(idToCenter).style.display = oldvis;
    return windowH / 2 + document.documentElement.scrollTop;

}


// ======================================================================	;
function showWait(where) {


    where = "screen";
    if (gebi("wait")) {

        gebi("wait").style.width = 85 + "px";
        setcenter("wait", where);
        $("#wait").stop().css("display", "inline-block").css("opacity", 0);
        gebi("wait").style.width = "";
        setcenter("wait", where);
        $("#wait").stop().css("display", "none").css("opacity", 1).fadeIn(500);

    }
}

// ======================================================================	;
function hideWait() {
    if (gebi("wait")) {
        $("#wait").stop().fadeOut(500);
    }
}

//=====================================
function showPop(text, anx, any) {

    if (text === "") { return; }
    //var anx, any;
    if (!anx) { anx = curx ;} if (!any) { any = cury; }

    gebi("poptext").innerHTML = text;

  

    $("#poptext").stop().css("display", "inline-block").css("opacity", 0);
    gebi("poptext").style.width = "";
    if (gebi("poptext").offsetWidth > 300) {
        gebi("poptext").style.width = 300 + "px";
    }
    else {
        gebi("poptext").style.width = "";
    }

    if (anx + gebi("poptext").offsetWidth > $(window).width()-30) {
        anx = anx - gebi("poptext").offsetWidth - 50;
    }
    else {
        anx = anx + 50;
    }
    $("#poptext").stop();
    gebi("poptext").style.left = anx+"px";
    gebi("poptext").style.top = any+"px";
    $("#poptext").css("display", "none").css("opacity", 1).fadeIn(500) ;

}
//=====================================
function killPop() {
    $("#poptext").stop().fadeOut(500);
}

//=====================================
function showPopCentered(text, obj) {

    gebi("poptext").innerHTML = text;
    $("#poptext").stop().css("display", "inline-block").css("opacity", 0);
    gebi("poptext").style.width = "";
    if (gebi("poptext").offsetWidth > 300) {
        gebi("poptext").style.width = 300 + "px";
    }
    else {
        gebi("poptext").style.width = "";
    }

    anx = parseInt(obj.style.left, 10) + parseInt(obj.style.width, 10) / 2 - getscrollwidth("poptext") / 2;
    any = parseInt(obj.style.top, 10) + parseInt(obj.style.height, 10) / 2 - getscrollheight("poptext") / 2;
    gebi("poptext").style.left = anx+"px";
    gebi("poptext").style.top = any+"px";

    $("#poptext").stop().css("display", "none").css("opacity", 1).fadeIn(500);
}


//=====================================
function popTag(text, obj) {
    $(obj).css("opacity", 0.7);
    showPopCentered(text, obj);
}


//=======================================================;
function customSearch(obj) {

    var sb = createSearchButtons();
    var a = document.createElement("div");
    a.appendChild(sb);


    gebi("modal_scroller").innerHTML = "";
    searchResultPane = "modal";
    searchTarget = "modal";

    showModal(1, a.innerHTML + gebi("searchresult").innerHTML, false, true);
    setTimeout(function () { gebi('searchinput').value = obj.value; gebi('searchsubmit').onclick(); }, 600);

    a = null;
    sb = null;

}

// ======================================================================	;
function createSearchButtons() {
    if (gebi("searchbuttons")) { return gebi("searchbuttons"); }
    var adiv = document.createElement("div");
    adiv.id = "searchbuttons";
    var h = "<input type=text   value='' onkeyup=\"if (checkReturn(event)){gebi('searchsubmit').click()}\"  id=searchinput />&nbsp;";
    h = h + "<input type=button class=button value=search id=searchsubmit onclick=\"search(gebi('searchinput').value)\" />&nbsp;";
    h = h + "<input type=button class=button value=X onclick='hidesearch()' />";
    adiv.innerHTML = h;
    return adiv;
}

// ======================================================================	;
function showsearch(target, searchbuttons) {
    if (hasDragDrop) { // layout manager;
        if (dd.elements.searchSpan) {
            if (!gebi("locksearch").checked) { return; }
        }
    }

    var sb = createSearchButtons();

    var a = document.createElement("div");
    a.appendChild(sb);


    gebi(target+"_scroller").innerHTML = "";
    searchResultPane = target;


    if (target === "modal") { showModal(1, a.innerHTML + gebi("searchresult").innerHTML, false, true); }
    a = null;
    sb = null;
    linkstuff(target, true);

    searchTarget = target;
    setVsize(target,"showsearch");
    hideWait();

}


// ======================================================================	;
function hidesearch() {

    if (searchTarget === "modal") {
        closeModal(1, false);
    }
    else {
        thisId = resetId(searchTarget);
        showNode('hidesearch',thisId, searchTarget, "");
    }
}

// ======================================================================	;
function search(astring) {
    extra = "&site_key=" + site_key;
    extra = extra + version;
    extra = extra + "&id=" + md5Hash;
    if (astring !== "") {
        showWait(searchTarget);
        if (forceRemote) { extra = extra + "&forceremote=1"; }

        if (sameDomain) {

            //http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316451;
            // Do Not Send ServerXMLHTTP or WinHTTP Requests to the Same Server (as is done in getpageAsJSON);

            src = vbasedomain + "?relay=search.asp&search=" + encodeURIComponent(astring) + extra;

            $.get(src, function (data) { searchCallBack(searchTarget,data); });
        }
        else {
            src = vbasepath + "search.asp?search=" + encodeURIComponent(astring) + extra;
            getPageAsJSON(src, "searchCallBack('"+searchTarget+"')");
        }

    }
}

// ======================================================================	;
function searchCallBack(searchTarget, data) {
    hideWait();

    gebi(searchTarget+"_scroller").innerHTML = "";
    sb = createSearchButtons();

    var atext = document.createElement("text");
    atext.innerHTML = data;
    gebi("searchresult").innerHTML = data;
    
    var adiv = document.createElement("div");
    adiv.appendChild(sb);
    adiv.appendChild(atext);
    pageFinished(adiv.innerHTML, searchTarget, '', '');
    //return;



    //gebi(searchTarget+"_scroller").appendChild(sb);
    //gebi(searchTarget+"_scroller").appendChild(atext);
    //linkstuff(searchTarget, true);
    //setVsize(searchTarget,"searchcallback");

}



//=====================================
function storeKey(evt) {
    if (evt) { thekey = evt.keyCode; } else { thekey = event.keyCode; }
    if (thekey === 16) { shiftkeydown = true; }
    if (thekey === 17) { controlkeydown = true; }
    if (thekey === 13) { returnkeydown = true; }
    if (thekey === 86) { vkeydown = true; }
    if (thekey === 66) { bkeydown = true; }
    if (thekey === 69) { ekeydown = true; }
    keyIsDown = true;
    if ((controlkeydown) && (shiftkeydown)) {
        $("#cp").slideToggle();
        $("#stylepicker").slideToggle();
    }
}

//=====================================
function clearKey(evt) {
    if (evt) { thekey = evt.keyCode; } else { thekey = event.keyCode; }
    if (thekey === 16) { shiftkeydown = false; }
    if (thekey === 17) { controlkeydown = false; }
    if (thekey === 13) { returnkeydown = false; }
    if (thekey === 86) { vkeydown = false; }
    if (thekey === 66) { bkeydown = false; }
    if (thekey === 69) { ekeydown = false; }
    keyIsDown = false;

}//=====================================
function clearKeys() {

shiftkeydown = false; controlkeydown = false; returnkeydown = false; vkeydown = false;bkeydown = false;  ekeydown = false;  keyIsDown = false;

}


// ======================================================================	;
function edit(target) {  // target = left right top bottom or content;

    if ((target === "content") && (availablePanes.indexOf("C") === -1)) {
        alert("vBase is not configured for the current user to edit the main pane\nNavigate to an editable pane, and double-click this to edit");
        return;
    }

    showEditor(target, site_key);
}

// ======================================================================	;
function logincancelled() {
    doPoll = false;
    gebi("loginpane").style.display = "none";
    faderOut(1);
}

// ======================================================================	;
function login() {
    if (hasDragDrop) { // layout manager;
        if (dd.elements.toolbox) {
            if (!gebi("lock2").checked) { return; }
        }
    }

    faderIn(1);
    $("#loginpane").show(0);
    setcenter("loginpane", "screen");
    $("#loginpane").hide(0);
    $("#loginpane").fadeIn(400, function () { gebi("username").focus(); });
    gebi("username").value = gebi("pusername").value;
    gebi("password").value = gebi("ppassword").value;
}

// ======================================================================	;
function checkpassword() {

    if (gebi("pusername").value === "") { alert("Please check your username"); return; }
    if (gebi("ppassword").value === "") { alert("Please check your password"); return; }
    setCookie("username", gebi("pusername").value, 1);
    setCookie("password", gebi("ppassword").value, 1);
    extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    docLoc = trim(document.location + " ").split("#")[0];
    extra = extra + "&loc=" + encodeURIComponent(docLoc);
    gebi("hidden_iframe").src = vbasepath + "login.asp?r=" + Math.random() + "&site_key=" + assets_site + "&username=" + gebi("pusername").value + "&password=" + gebi("ppassword").value + extra;
    if (!doPoll) {
        doPoll = true;
        poll("");
    }

}

// ======================================================================	;
function logout() {
    gebi("pusername").value = "";
    gebi("ppassword").value = "";
    gebi("username").value = "";
    gebi("password").value = "";
    passwordPassed = false;
    setCookie("username", "", -1);
    setCookie("password", "", 1);
    mayLayout = false;
    mayPages = false;
    maySlides = false;
    mayUsers = false;
    mayAccess = false;
    mayFileupload = false;
    mayImageupload = false;
    mayProducts = false;
    mayEdit=false;
    md5Hash = "";
    reNav();
    showEditStuff();
    if (lastTarget) {
        resetId(lastTarget);
        if (lastId) {
            showNode('logout',lastId, lastTarget, '');
        }
    }
    showLastPage();

    tagsloggedin = false;
    if (hasDragDrop) { reDHTML("toolbox"); }    // size has changed;
    positionOnAnchor("toolbox");

}


// ======================================================================	;
function showAdmin() {

    faderIn(1);
    extra = "";

    if (forceRemote) { extra = "&forceremote=1"; }
    extra = extra + "&vbasepath=" + encodeURIComponent(vbasepath) + "&lan="+language;

    adminSrc = vbasepath + "admin.asp?site_key=" + site_key + "&assets_site=" + assets_site + "&id=" + md5Hash + extra + "&parentloc=" + encodeURIComponent(document.location);  // make sure that parentloc is a the end of the querystring as we will cut it of;

    adminWrapperRef = dhtmlwindow.open(1005, "adminwrapper", "iframe", adminSrc, "vBase Admin", "width=150px,height=150px,resize=1,scrolling=1,center=1");
    adminWrapperRef.onclose = function () {
        faderOut(1);
        doPoll = false;
        return true;
    };

    if (!doPoll) {
        doPoll = true;
        poll("");
    }

}

// ======================================================================	;
function showEditor(atarget, site_key, page_c, haveText) {
    document.documentElement.scrollTop = 0;
    extra = "";
    contentStyle = "";
    editId = "";
    editPane = "";
    if ((atarget) && (atarget !== 'editemail')) {
        //if ((isExternal[atarget]) && (atarget !== "new") && (atarget !== "slides")) {
        if (typeof pi[contentIds[atarget]] !== "undefined") {
            if ((pi[contentIds[atarget]][2] !== "") && (atarget !== "new") && (atarget !== "slides")) {

                mes = "";
                mes = "This is an external link. \n";
                if (mayPages) {

                    if (pi[contentIds[atarget]][3] !== "") {

                        if (!confirm("This is a link to an external page.\nThe content of what you edit here will be included as the header of the external page.\nclick OK to proceed editing.")) { return; }
                    }
                }
                else {
                    //mes = mes + "This cannot be edited.";
                    //alert(mes);
                    //return;
                    if (pi[contentIds[atarget]][3] !== "") {

                        if (!confirm("This is a link to an external page.\nThe content of what you edit here will be included as the header of the external page.\nclick OK to proceed editing.")) { return; }
                    }
                    
                }
            }
        }
        editPane = atarget;
        editId = contentIds[atarget];


        savetarget = atarget;
        if (atarget === "producttext") {
            editId = page_c;
            editPane = "producttext";
            extra = extra + "&content=" + encodeURIComponent(haveText);
        }
        if ((atarget === "gbtopictext") || (atarget === "gbcommenttext")) {
            editId = page_c;
            if (haveText) {
                extra = extra + "&edit=1";
            }
            extra = extra + "&gbId=" + page_c;

        }

        var obj = false;
        if (gebi(atarget)) {
            obj = gebi(atarget);
        }
        else if ($("." + atarget)[0]) {
            obj = $("." + atarget)[0];
        }

        var objwidth = "";

        if (obj) {
            extra = extra + "&width=" + obj.scrollWidth;
            //extra = extra + "&backgroundColor=" + encodeURIComponent(getParentStyle(obj, "backgroundColor"));
            //extra = extra + "&color=" + encodeURIComponent(getStyleProp(obj, "color"));

            extra = extra + "&backgroundColor=";
            extra = extra + "&color=";
            
            extra = extra + "&fontFamily=" + encodeURIComponent(getStyleProp(obj, "fontFamily"));
            extra = extra + "&fontSize=" + getStyleProp(obj, "fontSize");
        }
        else if (atarget === "producttext") {
        }
        else {
            alert("probably trying to edit rich text in blog/guestbook. please add in plain text first");
            return;
        }

    }

    if (forceRemote) { extra = extra + "&forceremote=1"; }
    extra = extra + "&target=" + atarget;
    extra = extra + "&lan=" + language;

    var src = vbasepath + "newedit.asp?r=" + Math.random() + "&site_key=" + site_key + "&assets_site=" + assets_site + "&id=" + md5Hash + "&content_key=" + editId + extra;
    if (atarget === 'editemail') {
        astyle = getStyleText('emailbody');
        if (astyle === "") { astyle = getStyleText('content'); }
        contentStyle = astyle;
        src = vbasepath + "emaillist_composer_new.asp?r=" + Math.random() + "&site_key=" + site_key + "&assets_site=" + assets_site + "&id=" + md5Hash + "&content_key=" + editId + extra;
    }

    //src = src + "&style=" + encodeURIComponent(contentStyle);
    docLoc = trim(document.location + " ").split("#")[0];

    src = src + "&vbasepath=" + encodeURIComponent(vbasepath) + "&r=" + Math.random();

    src = src + "&loc=" + encodeURIComponent(docLoc) + "#";

    // ---------------------------------------------
    html = "<iframe id=editorIframe name=editorIframe frameborder=0 style='width:100%;height:90%;border:0px;overflow:hidden;frame-border:0px' src=" + src + "></iframe>";
    html = html + "<input type=button class=button onclick=update('cancel') value=cancel> <input type=button class=button onclick=update('update') value=update>";
    showModal(2, html, true, false);
    $("#modal2 .button").hover(function () { $(this).addClass('button_hover'); }, function () { $(this).removeClass('button_hover'); });
    //hideWait();
    if (!doPoll) {
        doPoll = true;
        poll("");
    }
}

// ======================================================================	;
function showloginmes() {

    gebi("updatediv").innerHTML = "Login successful!";
    gebi("updatediv").style.display = "inline";
    setcenter("updatediv", "screen");
    //if (lastTarget) { resetId(lastTarget); showNode(lastId, lastTarget, ''); }

    gebi("updatediv").style.backgroundColor = "#ffffff";
    setTimeout(function () { gebi("updatediv").style.display = "none"; }, 1000);
}

// ======================================================================	;
function showupdate() {

    gebi("updatediv").innerHTML = "updating...<br><br><img src='" + vbasepath + "images/wait.gif' />";
    gebi("updatediv").style.display = "inline";
    setcenter("updatediv", "screen");
    gebi("updatediv").style.backgroundColor = "#c0d1a5";

}

// ======================================================================	;
function hideupdate() {

    gebi("updatediv").innerHTML = "Done...";
    gebi("updatediv").style.backgroundColor = "#c0d1a5";
    setTimeout(function () { gebi("updatediv").style.display = "none"; }, 400);
}

// ======================================================================	;
function update(anaction) {
    gebi("editorIframe").src = gebi("editorIframe").src.split("#")[0] + "#" + anaction;
}


// ======================================================================	;
function poll() {
    // polls to see if a login was successfull by interogating the hash fragment of the iframe source;
    // also polls to see if the update or cancel button was pressed;
    var aval;
    if (doPoll) {

        ahash = document.location.hash;
        ahash = replace(ahash, "##", "#");

        if ((ahash.indexOf("#passwordpassed") !== -1)) {
            document.location.hash = "#";
            tagsloggedin = true; // for tagging;
            doPoll = false;

            apos = ahash.indexOf("&md5=");
            md5Hash = ahash.substring(apos + 5).split("_")[0];
            permissions = ahash.substring(apos + 5).split("_")[1];

            if (permissions.indexOf("L") !== -1) { mayLayout = true; }
            if (permissions.indexOf("P") !== -1) { mayPages = true; }
            if (permissions.indexOf("S") !== -1) { maySlides = true; }
            if (permissions.indexOf("U") !== -1) { mayUsers = true; }
            if (permissions.indexOf("A") !== -1) { mayAccess = true; }
            if (permissions.indexOf("F") !== -1) { mayFileupload = true; }
            if (permissions.indexOf("I") !== -1) { mayImageupload = true; }
            if (permissions.indexOf("G") !== -1) { mayProducts = true; }

            availablePanes = ahash.substring(apos + 5).split("_")[2];
            if (availablePanes.length !== 0) { mayEdit = true; }
            passwordPassed = true;
            contentIds["content"] = "-1";  // force content in the next line to be reloaded in case of a cdbi table
            reNav();
            //showLastPage(); // reNav does it already 
            gebi("loginpane").style.display = "none";
            faderOut(1);
            showEditStuff();

            showloginmes();
            gebi("hidden_iframe").src = "";
            if (hasDragDrop) { reDHTML("toolbox"); } // size has changed, now more items;
            positionOnAnchor("toolbox");

        }
        else if (ahash.indexOf("#loginfailure") !== -1) {
            gebi("loginpane").style.display = "none";
            faderOut(1);

            document.location.hash = "#";
            doPoll = false;
            gebi("hidden_iframe").src = "";
        }
        else if (ahash === "#updatecanceled") {
            document.location.hash = "#";
            if (editPane !== "producttext") {
                doPoll = false;
            }
            else {
                adminWrapperRef.moveTo("middle", "middle");
            }
            closeModal(2, false);
        }
        else if (ahash.find("custom=")) {
            document.location.hash = "#";
            alert("please check this hash");
        }
        else if (ahash.find("#updatecompleted")) {
            document.location.hash = "#";
            // a page or pane was updated;
            if (editPane === "producttext") {
                adminWrapperRef.moveTo("middle", "middle");

                aval = ahash.split("{vbaseseperator}")[1];
                aval = decodeURIComponent(aval);
                var newloc = psSrc + "#updatecompleted{vbaseseperator}" + encodeURIComponent(aval);
                window.frames["_iframe-adminwrapper"].location = newloc;
                // here we keep polling;
            }
            else {
                resetId(editPane);
                showNode('#updatecompleted',editId, editPane, "", "");
                doPoll = false;

            }
            closeModal(2, false);

            hideupdate();

        }
        else if (ahash.find("#gbupdatecompleted")) {
            document.location.hash = "#";
            aval = ahash.split("{vbaseseperator}")[1];
            aval = decodeURIComponent(aval);
            aval = replace(aval, "{perc}", "%");
            var gbId = ahash.split("{vbaseseperator}")[2];
            var action = ahash.split("{vbaseseperator}")[3];
            if (action === "insert") {
                gbinsert(gbId, aval);
            }
            else {
                gebi("action").value = "update";
                gebi("gbid").value = gbId;
                gebi("text").value = aval;
                gebi("content_" + gbId).innerHTML = "<img id=img" + gbId + " src='" + vbasepath + "images/wait.gif' />   " + aval;
                document.gbform.submit();
            }

            doPoll = false;
            closeModal(2, false);
            hideupdate();
        }

        else if (ahash === "#navchanged") {
            document.location.hash = "#";
            reNav();
        }
        else if (ahash === "#updatestarted") {
            document.location.hash = "#";
            showupdate();
        }
        else if (ahash.indexOf("#showeditor") !== -1) {  // productshowmanager asks for editor;
            document.location.hash = "#";
            rowno = ahash.split("{vbaseseperator}")[1];
            html = ahash.split("{vbaseseperator}")[2];
            html = decodeURIComponent(html);
            html = replace(html, "{prc}", "%");
            psSrc = ahash.split("{vbaseseperator}")[3];
            if (!psSrc.find("http://")) { psSrc = decodeURIComponent(psSrc); }  //;

            adminWrapperRef.moveTo("-5000", "-5000"); // move out of the way, hiding doen't work;

            showEditor("producttext", assets_site, rowno, html);
        }
        else if (ahash.indexOf("#setframesize") !== -1) {
            document.location.hash = "#";
            atitle = ahash.split("_")[1];
            aw = ahash.split("_")[2];
            ah = ahash.split("_")[3];
            setAdminSize(atitle, aw, ah, ahash.split("_")[3]);
        }

        // poll again;

        if (doPoll) { setTimeout(function () { poll(); }, 500); }
    }
}


// ======================================================================	;
function setAdminSize(atitle, aw, ah, nodelay) {

    if (atitle !== "nochange") {
        adminWrapperRef.handle.firstChild.nodeValue = atitle;
    }
    $("#adminwrapper").stop();
    if (aw === "max") {
        aw = getModalWidth(true) + 35;
        ah = getModalHeight(true);
    }
    else {
        aw = min(aw * 1, getModalWidth(true)) + 35;
        ah = min(ah * 1, getModalHeight(true));
    }
    cw = getscrollwidth("adminwrapper");
    ch = getscrollheight("adminwrapper");
    ch = $("#adminwrapper .drag-contentarea")[0].offsetHeight;
    dw = (cw - aw) / 2;
    dh = (ch - ah) / 2;
    setcenter("adminwrapper", "screen");

    if (nodelay) { // no delay;
        adminWrapperRef.setSize(aw, ah);
        setcenter("adminwrapper", "screen");
    }
    else {
        $("#adminwrapper").stop().animate({ left: "+=" + dw, top: "+=" + dh, width: aw }, 500);
        $("#adminwrapper .drag-contentarea").stop().animate({ height: ah }, 500);
    }


}

// ======================================================================	;
function doubleclicked(obj) {
    if (keyIsDown) {
    //checkSelection()
        if (mayEdit) {
            if (availablePanes.indexOf(obj.id.substring(0, 1).toUpperCase()) === -1) { alert('Sorry, this pane cannot be edited'); return; }
            edit(obj.id);
        }
        else {
            alert("Want to edit? Please login first...");
            clearKeys();
        }
        
    }

}
function checkSelection() {   // unselect anything selected in the text
    var sel = {};
    if (window.getSelection) {
        // Mozilla
        sel = window.getSelection();
    } else if (document.selection) {
        // IE
        sel = document.selection.createRange();
    }

    // Mozilla
    if (sel.rangeCount) {
        sel.removeAllRanges();
        return;
    }

    // IE
    if (sel.text > '') {
        document.selection.empty();
        return;
    }
}

// ======================================================================	;
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

// ======================================================================	;
function getCookie(c_name) {

    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) { c_end = document.cookie.length; }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

// ======================================================================	;
function help() {
    newwin = window.open("http://www.vbaseworks.com?help");
}

// ======================================================================	;
function resetId(atarget) {

    // resets an id of on of the panes to empty, to make sure the page will load the next time;
    // returns (if you need to use it), the original id of atarget;

    var oldid = "";
    oldid = contentIds[atarget];
    contentIds[atarget] = "-1";
    return oldid;

}




// ======================================================================;
function test_email(emailStr) {
    if (emailStr === "") { return false; }
    emailStr = trim(emailStr);
    var emailPat = /^[a-zA-Z][\w\.\-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.\-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
    var matchArray = emailStr.match(emailPat);
    if (matchArray === null) { return false; }
    return true;
}

// ======================================================================;
function email_submit() {

    var aname = "";
    var email = "";
    var telephone = "";
    var address = "";
    var company = "";
    var subject = "";


    if (trim(gebi('name').value) === "") { alert(lab_enter_name); return; }
    if (!test_email(gebi('email').value)) { alert(lab_provide_valid_email); return; }
    if (trim(gebi('subject').value) === "") { alert(lab_enter_subject); return; }

    if (gebi("telephone")) {telephone=gebi("telephone").value;if (trim(gebi('telephone').value) === "") { alert(lab_enter_telephone); return; }}  
    if (gebi("address"))   {address=gebi("address").value;if (trim(gebi('address').value) === "")   { alert(lab_enter_address); return; }}
    if (gebi("company"))   {company=gebi("company").value;}
    
    if (trim(gebi('message').value) === "") { alert(lab_enter_message); return; }
    extra = "";
    if (gebi("docc").checked) { extra = "&docc=yes"; }
    var mes = gebi("message").value;

    aname = encodeURIComponent(gebi('name').value);
    email = encodeURIComponent(gebi('email').value);
    subject = encodeURIComponent(gebi('subject').value);
    telephone = encodeURIComponent(telephone);
    address = encodeURIComponent(address);
    companye = encodeURIComponent(company);
    mes = encodeURIComponent(mes);
    
    url = "emailform.asp?site_key=" + site_key + "&name=" + aname + "&email=" + email + "&message=" + mes + "&subject=" + subject+"&telephone="+telephone+"&address="+address+"&company="+company + extra;
    var data = initData();
    data[2] = ajaxTarget;
    data[4] = url; // extern;
    showNodeCallBack(data,"emailsumbit");
}


// ======================================================================;
function subscribe() {

    xfirstname = trim(gebi('firstname').value);
    xothername = trim(gebi('othername').value);

    xemail = trim(gebi('email').value);
    xemail2 = trim(gebi('email2').value);

    if (xfirstname === "") { alert('Please enter your name'); return; }
    if (!test_email(xemail)) { alert('Please provide a valid email address'); return; }
    if (xemail !== xemail2) { alert('Please check you email address'); return; }


    var extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }

    url = "emaillist.asp?site_key=" + site_key + "&firstname=" + xfirstname + "&email=" + xemail + "&othername=" + extra;
    var data = initData();
    data[2] = ajaxTarget;
    data[4] = url; // extern;
    showNodeCallBack(data,"subscribe");
}


function bodyHasScrollBar() {
    if (document.body.scrollHeight>getWindowSize("h")) {return true;}
    return false;
}

// ======================================================================;
function faderIn(no, opac) {

    if (gebi("fader" + no)) {
        
        var fader = gebi("fader" + no);

        fader.style.width = gebi("body").offsetWidth + "px";
        if (bodyHasScrollBar() && (document.body.style.overflow !== "hidden") && (document.body.style.overflowY !== "hidden")) {
            var atop = $("html").scrollTop();
            gebi("body").style.marginRight = "16px";  // otherwise content start jumping when centered
            
            document.body.style.overflow = "hidden";
            document.body.style.overflowY = "hidden";
            $("html").scrollTop(atop);  // for IE...
            windowW = noPx(getWindowSize("w"));

            fader.style.width = (windowW - 16) + "px";

        }
        else {
            fader.style.width = noPx(getWindowSize("w")) + "px";
        }

        if (!opac) {opac = 0.6;}
        $(fader).stop().css("opacity", "0");

        // fader.style.position = "fixed";  don't do, it gives blurry fonts in FF in ckedit. 
        fader.style.position = "absolute";
        fader.style.height = windowH + "px";
        fader.style.width = windowW + "px";
        fader.style.top = $("html").scrollTop() + "px";

        fader.style.display = "";
        fader.style.display = "block";
        //document.body.style.overflow = "hidden";
        getWindowSize("w");
        $(fader).animate({ opacity: opac }, 500, function () { gebi("body").parentNode.style.backgroundColor = "#d4d0c8"; });
        //$(fader).animate({ opacity: opac }, 500, function () {  });
    }
}

// ======================================================================;
function faderOut(no) {

    gebi("body").parentNode.style.backgroundColor = "";

    if ((getStyle("body", "overflow") === "hidden") || (getStyle("body", "overflowY") === "hidden")) {
        setScroll('content');
        haveScrollbar = true;
    }
    else {
        setScroll('window');
        haveScrollbar = false;
    }
    gebi("body").style.marginRight = "";



    $("#fader" + no).stop().animate({ opacity: 0 }, 500, function () {
        gebi("fader" + no).style.display = "none";

    });

}


//=======================================================;
function showModal(anum, html, maxsize, showCloseButton, externalAddress) {

    killPop();
    fadernum = 2;
    if (anum === 1) { anum = ""; fadernum = 1; }

    if (showCloseButton) {
        gebi("closebuttonholder" + anum).style.display = "";
    }
    else {
        gebi("closebuttonholder" + anum).style.display = "none";
    }

    restoreNode = lastNodeShowed;

    $("#modal" + anum + "_holder").stop();

    if (anum === 2) {
        gebi("modal" + anum + "_holder").style.zIndex = 1010;
    }
    else {
        gebi("modal" + anum + "_holder").style.zIndex = 1000;
    }
    gebi("modal" + anum + "_holder").style.width = noPx(getStyle("modal" + anum + "_holder", "width")) + "px";
    gebi("modal" + anum + "_holder").style.height = getModalHeight(maxsize) + "px";

    $("#fader" + anum).unbind("click");
    gebi("modal" + anum + "_holder").style.width = 150 + "px";
    gebi("modal" + anum + "_holder").style.height = 150 + "px";

    gebi("closebuttonholder" + anum).style.width = "100%";
    setcenter("modal" + anum + "_holder", "screen");

    // backward compatibility in case modal is not styled;

    if ((getStyle("modal" + anum + "_holder", "backgroundColor") === "") && (getStyle("modal" + anum + "_holder", "backgroundImage") === "")) {
        setStyle("modal" + anum + "_holder", "backgroundColor", "#ffffff");
        setStyle("modal" + anum + "_holder", "padding", "5px");
        setStyle("modal" + anum, "backgroundColor", "#ffffff");
        setStyle("modal" + anum, "padding", "5px");
        setStyle("modal" + anum, "textAlign", "left");
    }

    showWait("screen");
    faderIn(fadernum);

    cw = getModalWidth(maxsize);
    ch = getModalHeight(maxsize);


    gebi("modal" + anum + "_holder").style.width = 150 + "px";
    gebi("modal" + anum + "_holder").style.height = 150 + "px";

    gebi("modal" + anum).style.display = "";
    gebi("modal" + anum+"_holder").style.display = "block";
    
    gebi("modal" + anum).style.overflow = "hidden";
    var newleft = noPx(gebi("modal" + anum + "_holder").style.left) - parseInt(cw / 2, 10) + 75;
    var newtop =  noPx(gebi("modal" + anum + "_holder").style.top)  - parseInt(ch / 2, 10) + 75;

    $("#modal" + anum + "_holder").animate({ width: cw, left: newleft, height: ch, top: newtop }, 500, function () {
        pageFinished(html, "modal" + anum, false, externalAddress);
    });

}


//=======================================================;
function getModalHeight(maxsize) {

    // return outer height of modal_holder;

    var sh = getStyle("modal_holder", "height");
    if (maxsize) { sh = "100%"; }
    if (sh === "") { sh = "400"; }
    var ch = "";
    if (sh.indexOf("%") !== -1) { ch = parseInt(sh, 10) / 100 * (windowH - 50); } else { ch = min(parseInt(sh, 10), windowH - 50); }
    return ch;

}



//=======================================================;
function getModalWidth(maxsize) {

    // return outer width of modal_holder;

    var sw = getStyle("modal_holder", "width");
    if (maxsize) { sw = "100%"; }
    if (sw === "") { sw = "400"; }
    var cw = "";
    if (sw.indexOf("%") !== -1) { cw = parseInt(sw, 10) / 100 * (windowW - 50); } else { cw = min(parseInt(sw, 10), windowW - 50); }
    return cw;
}

//=======================================================;
function closeModal(anum, fast) {


    fadernum = 2;
    if (anum === 1) { anum = ""; fadernum = 1; }
    gebi("modal" + anum+"_scroller").innerHTML = "";
    gebi("loginpane").style.display = "";
    setStyle("modal" + anum, "overflow", "auto");      // kiko on ie needs hidden;
    if (fast) {
        $("#modal" + anum + "_holder").stop().fadeOut(0);
        gebi("modal" + anum).style.display = "none";
        faderOut(fadernum);
    }
    else {
        $("#modal" + anum + "_holder").stop().fadeOut(500);
        faderOut(fadernum);
        gebi("modal" + anum).style.display = "none";
        //setNav(restoreNode, "closemodal");
        if (anum === "") { contentIds.modal= ""; }
    }
    removeNode(gebi("vbar_modal" + anum + "_scroller"));
    removeNode(gebi("vbar2_modal" + anum + "_scroller"));
    removeNode(gebi("vglider_modal" + anum + "_scroller"));
    hideWait();
}


//=======================================================;
function removeNode(obj) {
    if (obj) { obj.parentNode.removeChild(obj); obj = null; }
}


//=======================================================;
function checkReturn(evt) {
    (evt) ? thekey = evt.keyCode : thekey = event.keyCode;
    return (thekey == 13) ? true : false;
}


//=======================================================;
function clickables(target) {

    $(".clickable_header").unbind("click", "");
    $(".clickable_header").addClass("clickable_header_clicked");   // note: clicked is hidden state
    $(".clickable_header").hover(function () { $(this).addClass('clickable_header_hover'); }, function () { $(this).removeClass('clickable_header_hover'); });

    $(".clickable_container").hide();
    $(".clickable_container").css("overflow", "hidden");
    hlist = $(".clickable_header");
    var i;
    for (i = 0; i < hlist.length; i++) {
        hlist[i].hcounter = i;
    }


    $(".clickable_header").bind("click", function () {
        if (this.className.find("_clicked")) { // I'm closed. I want to open, so close all others
            if (closeAllClickables) {
                $(".clickable_header").each(function () {
                    if (!this.className.find("_clicked")) {  // should mean that it is currently open
                        $(this).trigger("click");
                    }
                });
            }
        }

        var c = $(".clickable_container")[this.hcounter];
        $(c).stop();


        $(this).toggleClass("clickable_header_clicked");
        $(this).hover(function () { $(this).addClass('clickable_header_hover'); }, function () { $(this).removeClass('clickable_header_hover'); });

        if (this.className.find("clickable_header_clicked")) {
            $(c).animate({ height: 1 }, 500, function () {
                $(c).hide(0).css("height", "");
            });
        }
        else {
            $(c).slideDown(500, function () {
            });
        }

    });



}

//=======================================================;
function setVsize(target, who) {
    getDimensions("setVsize");
    // if target is all then do all, else only target
    var oldstate = state;
    state = "";
    gebi("page").style.width = pageWidth + "px";
    gebi("page").style.height = pageHeight + "px";
    gebi("body").style.height = bodyHeight + "px";
    if ((menuOpener === "mouseover") && (!alwaysOpen)) {
        JQsublink_container.hide();
    }
    if ((target === "all") || (target === "top")) { setContainer("top", topWidth, getStyle("top", "height"),  false); }
    if ((target === "all") || (target === "left")) { setContainer("left", leftWidth, leftHeight,  true); }
    if ((target === "all") || (target === "right")) { setContainer("right", rightWidth, rightHeight,  true); }
    if ((target === "all") || (target === "bottom")) { setContainer("bottom", topWidth, getStyle("bottom", "height"), false); }
    if ((target === "all") || (target === "content")) {setContainer("content", contentWidth, contentHeight, true); }
    if (target === "modal") {
        ch = getModalHeight(false) - getHeightStuff("modal_holder")  - gebi("closebuttonholder").offsetHeight;
        cw = getModalWidth(false) - getWidthStuff("modal_holder");
        setContainer("modal", cw, ch, true);
    }
    if (target === "modal2") {
        maxsize = false;
        if (gebi("editorIframe")) {maxsize = true;}
            ch = getModalHeight(maxsize) - getHeightStuff("modal_holder") - gebi("closebuttonholder2").offsetHeight;
            cw = getModalWidth(maxsize) - getWidthStuff("modal_holder");
            setContainer("modal2", cw, ch, true);
    }

    clickables(target);
    if (target !== "all") {
        state = oldstate;

        //if (target.find("modal")) { setVsize("all") }

        return;
    }

    $("#toolbox .adminbutton").each(function () {
        //if (getStyle("adminbutton", "width") !== "") { this.style.width = noPx(getStyle("adminbutton", "width")) + "px"; }
        //if (getStyle("adminbutton", "height") !== "") { this.style.height = noPx(getStyle("adminbutton", "height")) + "px"; }
    });

    //alert(gebi("vbaselink").style.height)
    floatBox('vbaselink', gebi("vbaselink").isFloat);
    //alert(gebi("vbaselink").style.height)    
    floatBox('searchspan', gebi("searchspan").isFloat);
    floatBox('toolbox', gebi("toolbox").isFloat);
    var i;
    for (i = 1; i < 11; i++) {
        gebi('aux' + i).style.display = "";
        floatBox('aux' + i, true);
        setContainer("aux" + i, getStyle("aux" + i, "width"), getStyle("aux" + i, "height"), true);
    }

    $("#toolbox .adminbutton").each(function() {
        //if (getStyle("adminbutton", "width") !== "") { this.style.width = noPx(getStyle("adminbutton", "width")) + "px"; }
        //if (getStyle("adminbutton", "height") !== "") { this.style.height = noPx(getStyle("adminbutton", "height")) + "px"; }
    });
    //if (getStyle("vbaselink", "width") !== "") { gebi("vbaselink").style.width = noPx(getStyle("adminbutton", "width")) + "px"; }
    //if (getStyle("vbaselink", "height") !== "") { gebi("vbaselink").style.height = noPx(getStyle("adminbutton", "height")) + "px"; }

    floatBox('navdragger', true);

    state = oldstate;
    if (target.find("modal")) {setVsize("all");}

}

//=======================================================;
function positionOnAnchor(objId) {
var obj = gebi(objId);
    var newx, newy;
    if (!obj.isFloat) { return; }
    if (!obj.isFloat == "false") { return; }
    var anchor = obj.anchor;

    pageX = findPosX(gebi("page"));
    pageY = findPosY(gebi("page"));

    if (hasDragDrop) {
        dd.elements[objId].moveTo(0, 0);
    }
    else {
        obj.style.left = 0+"px";
        obj.style.top = 0+"px";
    }
    if (!anchor) { anchor = "left"; }
    var anchorX = obj.anchorX;
    var anchorY = obj.anchorY;
    if (anchor === "left") {
        newX = anchorX + pageX;
        newY = anchorY + pageY;
    }
    if (anchor === "right") {
        newX = pageX + getscrollwidth("page") - anchorX - getscrollwidth(objId);
        newY = anchorY + pageY;
    }
    if (anchor === "leftbottom") {
        newX = anchorX + pageX;
        newY = pageY + getscrollheight("page") - anchorY - getscrollheight(objId);
    }
    if (anchor === "rightbottom") {
        newX = pageX + getscrollwidth("page") - anchorX - getscrollwidth(objId);
        newY = pageY + getscrollheight("page") - anchorY - getscrollheight(objId);
    }



    if (hasDragDrop) {
        dd.elements[objId].moveTo(newX, newY);
    }
    else {
        obj.style.left = newX+"px";
        obj.style.top = newY+"px";
    }
}

//=======================================================;
function deleteStyleText(astyle) {

    if (indexChanged) { nchanged++; indexStyle(); }

    var mysheet = document.styleSheets[1];
    var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    mysheet.crossdelete = mysheet.deleteRule ? mysheet.deleteRule : mysheet.removeRule;
    var i;
    for (i = 0; i < myrules.length; i++) {
        if (myrules[i].selectorText.toLowerCase() === astyle.toLowerCase()) {
            mysheet.crossdelete(i);
            i--; //decrement i by 1, since deleting a rule collapses the array by 1;
            indexChanged = true;
        }
    }

}



//=======================================================;

function unique(a) // return a unique aray
{
    var r = [],i,x;
    o: for (i = 0, n = a.length; i < n; i++) {
        for (x = 0, y = r.length; x < y; x++) {
            if (r[x] == a[i]) { continue o; }
        }
        r[r.length] = a[i];
    }
    return r;
}

// ======================================================================	;
function addOption(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}




// ======================================================================	;
function scroll(aname) {
    // called when a glider is dragged;
    adiv = gebi(replace(aname, "vglider_", ""));
    aglider = gebi(aname);
    if (gebi("vbar_" + replace(aname, "vglider_", ""))) {
        abar = gebi("vbar_" + replace(aname, "vglider_", ""));
        range = abar.offsetHeight - aglider.offsetHeight;

        fraction = (findPosY(aglider) - findPosY(abar)) / range;
        // how much is there to scroll in amount of pixels;
        toscroll = adiv.scrollHeight - adiv.offsetHeight;
        adiv.scrollTop = toscroll * fraction;
        scrollDone(findPosY(aglider));

    }

}

// ======================================================================	;
function scrollClick(aname) {

    // called when clicked on a bar;

    adiv = gebi(aname);
    aglider = gebi("vglider_" + aname);
    abar = gebi("vbar_" + aname);

    // scroll a page at a time
    // if clicked above the glider, scroll up else scroll down

    y = findPosY(aglider) + aglider.offsetHeight / 2;
    toscroll = noPx(adiv.offsetHeight) - 20;

    if (posy > y) {
        toscroll = adiv.scrollTop + toscroll;
    }
    else {
        toscroll = adiv.scrollTop - toscroll;
    }
    $(adiv).stop().animate({ scrollTop: toscroll }, 500, function() {
        scrollDone(findPosY(aglider));
    });



}

// ======================================================================	;
function setGlider(aname) {
    // called when sccrolling (with mousewheel for example, to synchronize the glider;
    if (dragobject !== "") { return true; }
    adiv = gebi(aname);

    if (!gebi("vglider_" + aname)) { return; alert("no bar : " + aname); }
    if (!gebi("vbar_" + aname)) { return; alert("no glider : " + aname); }

    aglider = gebi("vglider_" + aname);
    abar = gebi("vbar_" + aname);




    toscroll = adiv.scrollHeight - adiv.offsetHeight;
    fraction = adiv.scrollTop / toscroll;
    range = abar.offsetHeight - aglider.offsetHeight;

    newy = range * fraction + findPosY(abar);
    aglider.style.top = newy + "px";
    scrollDone(newy);

}

function scrollDone() {}

var posx; var posy;
// ======================================================================	;
function getMouse(e) {
    posx = 0; posy = 0;
    var ev = (!e) ? window.event : e; //IE:Moz;
    if (ev.pageX) {//Moz;
        posx = ev.pageX + window.pageXOffset;
        posy = ev.pageY + window.pageYOffset;
    }
    else if (ev.clientX) {//IE;
        posx = ev.clientX + document.documentElement.scrollLeft;
        posy = ev.clientY + document.documentElement.scrollTop;
    }
    else { return false; } //old browsers;
}




// ======================================================================	;
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent)
        while (1) {
            curleft += obj.offsetLeft + getWidthStuff(obj.id, true);
            if (!obj.offsetParent) break;
            obj = obj.offsetParent;
        }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}


// ======================================================================	;
    function findPosY(obj) {
        var curtop = 0;
        if (obj.offsetParent)
            while (1) {
            curtop += obj.offsetTop + getHeightStuff(obj.id, true);
            if (!obj.offsetParent) break;
            obj = obj.offsetParent;
        }
        else if (obj.y)
            curtop += obj.y;
        return curtop;
    }


//=======================================================;
function showtime(aprompt) {
    now = new Date();
    if (aprompt) { alert(aprompt + ": " + (now - timer)); }
    timer = new Date();
}


// ====================================================================================================;
function setSlideSize(i, image, tw, th) {
    if (image.parentNode) {
        if (image.offsetWidth !== 0) {

            image.parentNode.style.bottom = "";
            image.parentNode.style.right = "";
            image.style.width = "";
            image.style.height = "";
            
            image.parentNode.style.left = (parseInt((tw + (image.offsetWidth - image.width) - image.offsetWidth) / 2, 10))+"px";
            image.parentNode.style.top = (parseInt((th + (image.offsetHeight - image.height) - image.offsetHeight) / 2, 10))+"px";
            
            image.style.visibility = "visible";

        }
    }
}   

// ====================================================================================================;
// guestbook;
// ====================================================================================================;


function gbedit(id) {
    faderIn(2);
    //if (jQuery(".gbform").length > 1) {
    //    //jQuery(".gbform")[0].parentNode.removeChild(jQuery(".gbform")[0]);
    //}
    
    document.body.appendChild(gebi("gbform"));    

    setcenter("editdiv", "screen", true);
    gebi("editdiv").style.display = "inline-block";
    

    
    text = gebi("content_" + id).innerHTML;
    text = replace(text, "<br>", "\n");
    //gebi("editta").value = text;
    if (gebi("gbsubject")) {
        text = gebi("subject_" + id).innerHTML;
        text = replace(text, "<br>", "\n");
        if (gebi("editsubject")) { gebi("editsubject").value = text; }

    }
    gebi("gbupdatebutton").onclick = function () { gbupdate(id); };


    gebi("action").value = "gettext";
    gebi("editId").value = id;
    gebi("editta").value = "..please wait...";
    //gebi("gbform_holder").appendChild(gebi("gbform"))
    gebi('gbupdatebutton').disabled = true;     
    gebi("gbform").submit();
}





//=============================================================;
function gbupdate(id) {


    text = gebi("editta").value;
    text = replace(text, "\n", "<br>");
    gebi("editdiv").style.display = "none";
    gebi("action").value = "update";
    gebi("gbid").value = id;
    gebi("text").value = text;
    gebi("content_" + id).innerHTML = "<img id=img" + id + " src='" + vbasepath + "images/wait.gif' />   " + text;
    faderOut(2);
    if (gebi("editsubject")) {
        text = gebi("editsubject").value;
        text = replace(text, "\n", "<br>");
        gebi("subject").value = text;
    }
    gebi("gbform_holder").appendChild(gebi("gbform"));
    gebi("gbform").submit();

}


//=============================================================;
function gbchanged(acontent) { // called by childwindow!;
    var anaction = gebi("action").value;

    gebi("action").value = "";
    gebi("gbcontent").innerHTML = acontent;
    initPopper();
    $(gebi("gbcontent")).fadeIn(500);
    hideWait();

    target = replace(getContainer(gebi("gbcontent")), "_scroller", "");
    imagestuff(target);

    linkstuff(target);

    JFormaramaStuff(target);
    jCDBIStuff(target);

    if (anaction !== "delete") {
        gebi(ajaxTarget + "_scroller").scrollTop = 0;
    }
    if (haveScrollbar || target.find("modal")) {
        setVsize(target, "pagefinished 1");
    }
    else {
        setVsize("all", "pagefinished 2");

    }

}

//=============================================================;
function initPopper() {
    $(".popper").hover(function () { showPop(this.getAttribute('helptext')); }, function () { killPop(); });
}

//=============================================================;
function gbdelete(id, remark_id) {

    if (remark_id) {
        aprompt = "delete this entry?";
    }
    else {
        aprompt = "delete this entry?\nNote: all comments on this topic will be deleted as well!";
    }
    if (confirm(aprompt)) {
        gebi("action").value = "delete";
        gebi("gbid").value = id;
        gebi("content_" + id).innerHTML = "<img id=img" + id + " src='" + vbasepath + "images/wait.gif' />   ";
        gebi("gbform_holder").appendChild(gebi("gbform"));
        gebi("gbform").submit();
    }
}

//=============================================================;
function gbcancel() {

    gebi('insertdiv').style.display = 'none';
    faderOut(2);
    gebi("insertta").innerHTML = "";
    gebi("picerrordiv").style.display = "none";
    gebi("gbform_holder").appendChild(gebi("gbform"));
}



//=============================================================;
function gbaddcomment(id, userlogedin, authenticate) {
    if (gebi("showsubject").value==="1") {
        gebi("gbsubject").value = "";
        if (id) { //comment on a topic, do not show subject;
            gebi("subjectspan2").style.display = "none";
        }
        else {
            gebi("subjectspan2").style.display = "";
        }
    }
    if (id) {
        //gebi("gbinsertbutton").innerHTML = "Add Comment";
    }
    else {
        //gebi("gbinsertbutton").innerHTML = "Add Topic";
    }
    gebi("insertta").value = "";
    if (jQuery(".gbform").length > 1) {
        //jQuery(".gbform")[1].parentNode.removeChild(jQuery(".gbform")[1]);
    }


    if ((userlogedin !== "True") && (authenticate === "True")) { showUserLogin('blogs',true); return; }
    document.body.appendChild(gebi("gbform"));        if (gebi("fader2")) { faderIn(2); }
    setcenter("insertdiv", "screen", true);
    gebi("insertdiv").style.display = "inline-block";
    gebi("gbinsertbutton").onclick = function () { gbinsert(id); };

}



//=============================================================;
function gbinsert(id, rtext) {  // id is 0 or empty if a new topic;
    // if rtext is given, then we come from rich text editor;

    if (!rtext) {
        if (gebi("countryselector")) { if (gebi("countryselector").options[gebi("countryselector").selectedIndex].text === "") { alert("Please select your country"); return; } }
        if (gebi("gbname")) { if (trim(gebi("gbname").value).length < 6) { alert("Please privide your name (min. 6 chars)"); return; } }
        if (gebi("insertta")) { if (trim(gebi("insertta").value) === "") { alert("Please add your text"); return; } }
        if (gebi("pic_value")) { if (trim(gebi("pic_value")) === "") { alert("Please provide the security number"); return; } }

        gebi("insertdiv").style.display = "none";
    }
    if (gebi("content_" + id)) {
        gebi("content_" + id).innerHTML = "<img id=img" + id + " src='" + vbasepath + "images/wait.gif' />   ";
    }
    else {
        img = document.createElement("img");
        img.src = vbasepath + "images/wait.gif";
        var first = gebi("gbcontent").childNodes[0];
        gebi("gbcontent").insertBefore(img, first);
        gebi("gbcontent").insertBefore(document.createElement("center"), first);

        gebi("gbcontent").insertBefore(document.createElement("br"), first);
        gebi("gbcontent").insertBefore(document.createElement("br"), first);
        var st = getScrollTarget(guestbookTarget);
        $(st).animate({ scrollTop: 0 }, 500);
    }

    if (!id) { id = "NULL"; }
    if (id === "0") { id = "NULL"; }
    if (rtext) {
        text = rtext;
    }
    else {
        text = gebi("insertta").value;
        text = replace(text, "\n", "<br>");
        faderOut(2);

    }

    gebi("action").value = "insert";
    gebi("gbid").value = id;
    gebi("text").value = text;
    gebi("gbform_holder").appendChild(gebi("gbform")); 
    document.gbform.submit();
}

//=============================================================;
function showUserLogin(atype,dofade) {

    if (dofade) { if (gebi("fader2")) { faderIn(2); } }
    setcenter("userloginpane", "screen");
    gebi("userloginpane").style.display = "inline-block";
    extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    extra = extra + version;
    extra = extra + "&lan=" + language;
    gebi("userloginif").src = vbasedomain + "?relay=gblogin.asp&type=" + atype + "&site_key=" + site_key + extra;
    gebi("userloginif").style.height = 350 + "px";
    gebi("userloginif").style.width = 400 + "px";
}

//=============================================================;
function hideUserLogin() {
    $("#userloginpane").fadeOut();
    if (gebi("picture_holder").style.display !== "block") { if (gebi("fader2")) { faderOut(2); } }
    gebi("userloginif").src = "";
}

//=============================================================;
function blacklist(id, blprompt, action) {
    if (confirm(blprompt)) {
        gebi("action").value = action;
        gebi("gbid").value = id;
        gebi("content_" + id).innerHTML = "<img id=img" + id + " src='" + vbasepath + "images/wait.gif' />   ";
        gebi("gbform_holder").appendChild(gebi("gbform"));   
        document.gbform.submit();
    }
}

//=============================================================;
function userlogout(id) {
    gebi("userloginspan").innerHTML = "<img id=img" + id + " src='" + vbasepath + "images/wait.gif' /> ";
    gebi('action').value = 'logout';
    gebi("gbform_holder").appendChild(gebi("gbform"));  
    document.gbform.submit();
}

//=============================================================;
function scrolltonew(id) {

    var st = getScrollTarget(guestbookTarget);
    if (gebi("div_" + id)) {  // a new row might not be visible, cause it's not accepted;
        arow = gebi("div_" + id);
        y = findPosY(arow);
        arow.style.backgroundColor = "#eeeeee";
        arow.style.color = "#0000ff";

        $(st).animate({ scrollTop: y - findPosY(st) }, 500);

    }
    else {
        st.scrollTop = 0;
    }
}
//=============================================================;
function maccept(id, acb) {

    if (acb.checked) {
        gebi("action").value = "accept";
    }
    else {
        gebi("action").value = "reject";
    }
    gebi("gbid").value = id;
    gebi("content_" + id).innerHTML = "<img id=img" + id + " src='" + vbasepath + "images/wait.gif' />   ";
    gebi("gbform_holder").appendChild(gebi("gbform"));
    document.gbform.submit();

}



//=============================================================;
function getScrollTarget(id) { // find out what to scroll, returns the object;

    var st;
    if (id === "content") {
        if (haveScrollbar) {
            st = gebi("content_scroller");
        }
        else {
            st = document.body;
        }
    }
    else if (id === "modal") {
        st = gebi("modal");
    }
    else if ((id === "left") || (id === "right") || (id === "top") || (id === "content")) {
        st = gebi(id + "_scroller");
    }
    else {
        st = document.body;
    }
    return st;

}


// ======================================================================	;
function productPage(num, page_c, asite, ps_name,newtarget) {
    $("#" + ajaxTarget).stop().animate({ opacity: 0 }, 500);
    if (ajaxTarget === "") {
        showWait("content");
    }
    else if (ajaxTarget === "modal") {
        showWait("screen");
    }
    else {
        showWait(ajaxTarget);
    }
    resetId((ajaxTarget));
    var data = initData();
    if (gebi("productsearch")) {
        asearch = gebi("productsearch").value;
    }
    else {
        asearch = "";
    }

    var extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    extra = extra + "&vbcur=" + vbase_currency;
    extra = extra + "&malcur=" + mal_currency;
    extra = extra + "&dec=" + decimals;
    extra = extra + "&mallan=" + mal_language;


    data[4] = vbaseroot + "?relay=productshow.asp&site_key=" + asite + "&page=" + num + "&search=" + asearch + "&ps_name=" + ps_name+extra;
    data[3] = page_c;
    data[2] = newtarget;
    showNodeCallBack(data,"productpage");
}


// ======================================================================	;
function slidePage(num, page_c, asite, ss_name) {
    if (gebi("showcooliris")) {
        if (gebi("showcooliris").style.display === "") { searchCoolIris("cooliris_container", gebi("slidesearch").value); return; }
    }
    $("#" + ajaxTarget).stop().animate({ opacity: 0 }, 500);
    if (ajaxTarget === "") {
        showWait("content");
    }
    else if (ajaxTarget === "modal") {
        showWait("screen");
    }
    else {
        showWait(ajaxTarget);
    }
    resetId((ajaxTarget));
    var data = initData();
    if (gebi("slidesearch")) {
        asearch = gebi("slidesearch").value;
    }
    else {
        asearch = "";
    }


    if ((search !== "") && (num === 1)) { searchCoolIris("cooliris_container", search); }
    var src = vbaseroot + "?relay=slideshow.asp&site_key=" + asite + "&page=" + num + "&search=" + encodeURIComponent(asearch) + "&ss_name=" + ss_name + "&usermd5=" + gbmd5_tags;
    data[4] = src;
    data[3] = page_c;
    data[2] = ajaxTarget;
    showNodeCallBack(data,"slidepage");
}

var gbmd5_tags = "";
var gbmd5_blogs = "";

// ======================================================================	;
function gbloggedin(type, userid, username, userhash) {  // called by child window!;

    if (type === "tags") {
        tagsloggedin = true;
        tagsuserid = userid;
        tagsusername = username;
        gbmd5_tags = userhash;
    }
    else {
        blogsloggedin = true;
        blogsuserid = userid;
        blogssusername = username;
        gbmd5_blogs = userhash;

    }

    if (gebi('userloginspan')) { gebi('userloginspan').innerHTML = "<img src='" + vbasepath + "images/wait.gif' />"; }
    if (document.gbform) { document.gbform.submit(); }
    hideUserLogin();
}



// ======================================================================	;
function searchCoolIris(containerId, search) {
    if (!gebi(containerId)) {return; }
    var a = gebi(containerId);
    var awidth = a.width;
    var aheight = a.height;
    alist = a.innerHTML.split("feed=")[1];
    var newurl = alist.split("\"")[0].split("%26search%3")[0] + encodeURIComponent("&search=" + search);

    var flashvars = {
        feed: newurl,
        showEmbed: false,
        showSearch: false,
        showChrome: false


    };
    var params = {
        allowscriptaccess: "always",
        wmode: "transparent"
    };
    swfobject.embedSWF("http://apps.cooliris.com/embed/cooliris.swf", containerId, awidth, aheight, "9.0.0", "", flashvars, params);

}

// ======================================================================	;
function floatBox(objId, doit, setit) {

    if (doit === "false") { doit = false; }


    var obj = gebi(objId);
    if (doit) {

        if (setit) { obj.isFloat = true; }
        obj.style.position = "absolute";
        obj.originalNode = obj.parentNode;
        gebi("body").appendChild(obj);
        obj.style.height = "100px";

        obj.style.height = "";
        
        if ((hasDragDrop) && (!dd.elements[objId])) {
                        //alert("1: "+objId+" "+gebi(objId).style.height)                        
                        //report(objId)
                        
            ADD_DHTML(objId + RESET_Z);
                        //alert("2: "+objId+" "+gebi(objId).style.height)            
            dd.elements[objId].setDropFunc(function () { drop(objId); });
            dd.elements[objId].setCursor(CURSOR_MOVE);
        }

        if (objId === "vbaselink") { obj.originalNode = gebi("toolbox"); $(obj).removeClass("adminbutton").addClass("vbaselink"); }
        if (objId === "searchspan") { obj.originalNode = gebi("toolbox"); $(obj).removeClass("adminbutton").addClass("searchspan"); }
        if (objId === "toolbox") { obj.originalNode = gebi("bottom"); }

        positionOnAnchor(objId);

    }
    else {
        if (setit) { obj.isFloat = false; }

        if (obj.originalNode) {
            obj.style.width = "";
            obj.style.height = "";
            if ((obj.originalNode.firstChild) && (objId === "vbaselink")) {
                obj.originalNode.insertBefore(obj, obj.originalNode.firstChild);
            }
            else {
                obj.originalNode.appendChild(obj);
            }

            if (hasDragDrop) {

                if (dd.elements[objId]) {
                    dd.elements[objId].del();
                }
            }
            obj.style.width = "";
            obj.style.height = "";
            obj.style.position = "relative";
            obj.style.left = 0+"px";
            obj.style.top = 0+"px";

        }

        if (objId === "vbaselink") { $(obj).removeClass("vbaselink").addClass("adminbutton"); }
        if (objId === "searchspan") { $(obj).removeClass("searchspan").addClass("adminbutton"); }
    }
}




// ======================================================================	;
function deletePseudoStyles() {

    var i;
    for (i = 0; i < theRules.length; i++) {
        if (theRules[i].style.content) {
            if (theRules[i].style.content !== "") { deleteStyleText(theRules[i].selectorText); }
        }
    }
}
// ======================================================================	;
function reNav() {
    extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    extra = extra + "&lan="+language;
    src = vbasepath + "pageinfo.asp?site_key=" + site_key + extra;
    request = new JSONscriptRequest(src, "js");
    request.buildScriptTag();
    request.addScriptTag();


    getJson('nav', 'navCallBack', '', '');
}


var dragobject = "";
var dragmode = "";

var nn6 = document.getElementById && !document.all;
var curx, cury;
var isdrag = false;
disabletag = false;
var targetX = 100;        // apoint in the left top corner of contentTD
var targetY = 100;         // apoint in the left top corner of contentTD

var picLeft;
var picTop;
var picBottom;
var picRight;

// ======================================================================	
function movemouse(e) {

    if (nn6) { xnow = e.pageX; } else { xnow = parseInt(event.clientX, 10) + parseInt(document.documentElement.scrollLeft, 10); }
    if (nn6) { ynow = e.pageY; } else { ynow = parseInt(event.clientY, 10) + parseInt(document.documentElement.scrollTop, 10); }

    xnow = parseInt(xnow + 0, 10);
    ynow = parseInt(ynow + 0, 10);

    dx = xnow - curx;
    dy = ynow - cury;
    curx = xnow;
    cury = ynow;

    if ((isdrag) && (dragobject !== "")) {

        newleft = parseInt(dragobject.style.left + 0, 10);
        newtop = parseInt(dragobject.style.top + 0, 10);
        newwidth = parseInt(dragobject.style.width + 0, 10);
        newheight = parseInt(dragobject.style.height + 0, 10);
        if (dragmode === '') { return; }
        if (dragmode === 'normal') {
            newleft = newleft + dx;
            newtop = newtop + dy;
        }
        if (dragmode.indexOf("bottom") !== -1) {
            newheight = newheight + dy;
        }
        if (dragmode.indexOf("left") !== -1) {
            newwidth = newwidth - dx;
            newleft = newleft + dx;
        }
        if (dragmode.indexOf("right") !== -1) {
            newwidth = newwidth + dx;
        }
        if (dragmode.indexOf("top") !== -1) {
            newheight = newheight - dy;
            newtop = newtop + dy;
        }
        if (dragmode.indexOf("vertical") !== -1) {
            newtop = newtop + dy;
            lt = dragobject.limitTop * 1;
            lb = dragobject.limitBottom * 1;
            if (newtop < lt) { newtop = lt; }
            if (newtop > lb) { newtop = lb; }
            dragobject.style.top = newtop+"px";
            scroll(dragobject.id, false);


            return;

        }

        if (xnow < picLeft) { return; }
        if (xnow > picRight) { return; }

        if (ynow < picTop) { return; }
        if (ynow > picBottom) { return; }


        if (newwidth < 20) { newwidth = 20; }
        if (newheight < 20) { newheight = 20; }
        if (newleft < picLeft) { newleft = picLeft; }
        if (newleft + newwidth > picRight) { newleft = picRight - newwidth; }
        if (newtop + newheight > picBottom) { newtop = picBottom - newheight; }
        if (newtop < picTop) { newtop = picTop; }

        dragobject.style.left = newleft+"px";
        dragobject.style.top = newtop+"px";
        dragobject.style.width = newwidth+"px";
        dragobject.style.height = newheight+"px";

        position_input();

        return false;
    }
}

// ======================================================================	
function selectmouse(e) {
    var fobj = nn6 ? e.target : event.srcElement;
    var topelement = nn6 ? "HTML" : "BODY";
    mouseIsDown = true;
    while (fobj.tagName != topelement && !fobj.className.find("dragme")) {
        fobj = nn6 ? fobj.parentNode : fobj.parentElement;
    }
    if (fobj.className.find("dragme")) {
        isdrag = true;
        document.body.onselectstart = function () { return false; };

        dragobject = fobj;
        if (dragobject.id.find("vbar")) {
            dragobject = gebi(replace(dragobject.id, "vbar_", "vglider_"));
        }
        if (dragmode === 'normal') {

            tx = parseInt(dragobject.style.left + 0, 10);
            ty = parseInt(dragobject.style.top + 0, 10);
        }
        else {

            sx = parseInt(dragobject.style.width + 0, 10);
            sy = parseInt(dragobject.style.height + 0, 10);
        }
        if (nn6) { curx = e.pageX; } else { curx = parseInt(event.clientX, 10) + parseInt(document.documentElement.scrollLeft, 10); }
        if (nn6) { cury = e.pageY; } else { cury = parseInt(event.clientY, 10) + parseInt(document.documentElement.scrollTop, 10); }
        return false;
    }
}



//=====================================
function caption_it() {

    $("#tag_instructions").hide();
    $("#caption_instructions").show();
    $("#tag_controls").hide();
    $("#caption_controls").show();
    gebi("input").style.top = picTop+"px";
    gebi("input").style.left = picLeft + "px";
    $("#input").show();
    gebi("taginput").style.width = 400 + "px";
    $(".tdsmall").css("width", 400);
    text = gebi("caption_holder").innerHTML;
    text = replace(text, "<br>", "/n");
    text = trim(replace(text, "&nbsp;", " "));
    gebi("taginput").value = text;
}

//=====================================
function tagit(e) {
    if (disabletag) { return; }
    if (!tagsloggedin) {
        if (gebi('loginflag').value === '0') {
            $("#picoptions").hide();
            showUserLogin("tags",false);
            return;
        }
        else {
            tagsloggedin = true;
        }
    }
    gebi("taginput").style.width = 200 + "px";
    $(".tdsmall").css("width", 200);

    $("#tag_instructions").show();
    $("#caption_instructions").hide();
    $("#tag_controls").show();
    $("#caption_controls").hide();

    gebi("taginput").value = "your text here..";
    if (nn6) { anx = e.pageX; } else { anx = parseInt(event.clientX, 10) + parseInt(document.documentElement.scrollLeft, 10); }
    if (nn6) { any = e.pageY; } else { any = parseInt(event.clientY, 10) + parseInt(document.documentElement.scrollTop, 10); }
    $(".tag").css("opacity", 0.3); // show all existing

    $("#dragme").show().css("width", 40).css("height", 40).css("left", anx - 20).css("top", any - 20);
    $("#input").show();
    position_input();
}

//=====================================
function position_input() {

    midx = parseInt(gebi("dragme").style.left, 10) + parseInt(gebi("dragme").style.width, 10) / 2;

    gebi("input").style.top = (parseInt(gebi("dragme").style.top, 10) + getscrollheight("dragme") + 5)+"px";
    gebi("input").style.left = (midx - getscrollwidth("input") / 2)+"px";
}

//=====================================
function cancel_tag() {

    // hide edit tag
    $("#dragme").hide();
    $("#input").hide();
}

//=====================================
function taglogout(encodedcookie, acookie) {
    tagsloggedin = false;
    cancel_tag();
    gebi('loginflag').value = '0';
}

//=====================================
function submit_caption() {

    var text = gebi("taginput").value;
    text = replace(text, "\n", "<br>");

    gebi("action").value = "submitcaption";
    gebi("tagtext").value = text;
    gebi("photo_id").value = gebi("imageId").value;
    ttext = "inserting.. <img src='" + vbasepath + "images/wait.gif' />";
    showPop(ttext, picLeft + 10, picTop + 10);
    if (text === "") { text = "&nbsp;"; }
    gebi("caption_holder").innerHTML = text;
    isIE() ? $("#caption_holder").stop().fadeIn(500) : $("#caption_holder").stop().slideDown(500);
    document.sform.submit();

    anid = "img_"+gebi("imageId").value; // id of the small image. we need to change the caption

    gebi(anid).setAttribute("helptext", "<span id=popcaptionspan class=popcaptionspan><b>" + text + "</b></span>");
    // also we have to change the onclick event
    //var oc = gebi(anid).onclick + " "
    //function onclick(event) {
    //    showpic("http://vbaseworks.com/uploadfolder/6D70FE2D-7895-47F8-87BC-6C288A679E4C/images/hash/136292502.jpg", "09-07-2011 Run 1068 Buddha was a hasher too run", "", "http://vbaseworks.com/uploadfolder/6D70FE2D-7895-47F8-87BC-6C288A679E4C/images/hash/136292500.jpg", "93909", "img_93909", true, "True");
    //}
    // ok, forget about it
    
    gebi(anid).caption = text;
    cancel_tag();
}
//=====================================
function submit_tag() {

    if ((gebi("taginput").value === "") || (gebi("taginput").value === "your text here..")) {
        alert("You still need to add text...");
    }
    else {
        var text = gebi("taginput").value;
        text = replace(text, "\n", "<br>");

        gebi("action").value = "submittag";
        gebi("tagtext").value = text;
        gebi("photo_id").value = gebi("imageId").value;
        var imgwidth = getscrollwidth("currentpic");
        var imgheight = getscrollheight("currentpic");

        var left = (parseInt(gebi("dragme").style.left, 10) - picLeft) / imgwidth * 100;
        var top = (parseInt(gebi("dragme").style.top, 10) - picTop) / imgheight * 100;
        var width = parseInt(gebi("dragme").style.width, 10) / imgwidth * 100;
        var height = parseInt(gebi("dragme").style.height, 10) / imgheight * 100;

        gebi("sleft").value = parseInt(left + 0.5, 10);
        gebi("stop").value = parseInt(top + 0.5, 10);
        gebi("swidth").value = parseInt(width + 0.5, 10);
        gebi("sheight").value = parseInt(height + 0.5, 10);

        cancel_tag();

        text = "inserting.. <img src='" + vbasepath + "images/wait.gif' />";
        showPopCentered(text, gebi("dragme"));

        document.sform.submit();
    }
}

//=====================================
function kill_tag(check) {

    l = parseInt(gebi("poptext").style.left, 10);
    r = parseInt(gebi("poptext").style.left, 10) + getscrollwidth("poptext");
    t = parseInt(gebi("poptext").style.top, 10);
    b = parseInt(gebi("poptext").style.top, 10) + getscrollheight("poptext");
    $(".tag").css("opacity", 0);

    if ((curx > l) && (curx < r) && (cury > t) && (cury < b) && (check)) { return; }
    killPop();
}


//=====================================
function getTags(photo_id) {

    callback = 'JFgetdata(getTagCallback)';
    extra = "&photo_id=" + photo_id;
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    src = vbasepath + "gettags.asp?r=" + Math.random() + "&callback=" + callback + extra;
    request = new JSONscriptRequest(src, "js");
    request.buildScriptTag();
    request.addScriptTag();

}

function test() {
    src = "http://localhost/vbase/v300/test.asp?1=1";
    request = new JSONscriptRequest(src, "js");
    request.buildScriptTag();
    request.addScriptTag();


}
//=====================================
function getTagCallback(data) {
    // creates and positions the tags
    //username, tag_id, photo_id, user_id, tagtop, tagleft, tagwidth,tagheight, tagtext, email,givenname,familyname,blacklisted

    ntagfields = 13;
    var i;
    for (i = 0; i < data.length; i = i + ntagfields) {
        username = data[i];
        tag_id = data[i + 1];
        photo_id = data[i + 2];
        user_id = data[i + 3];
        tagtop = data[i + 4];
        tagleft = data[i + 5];
        tagwidth = data[i + 6];
        tagheight = data[i + 7];
        tagtext = data[i + 8];
        tagemail = data[i + 9];
        taggivenname = data[i + 10];
        tagfamilyname = data[i + 11];
        tagblacklisted = data[i + 12];
        if (user_id === 0) { username = "SysAdmin"; }

        newdiv = document.createElement("div");
        document.body.appendChild(newdiv);
        $(newdiv).addClass("tag");

        picWidth = picRight - picLeft;
        picHeight = picBottom - picTop;

        newdiv.style.width = (picWidth / 100 * tagwidth)+"px";
        newdiv.style.height = (picHeight / 100 * tagheight)+"px";
        newdiv.style.left = (picLeft + picWidth / 100 * tagleft)+"px";
        newdiv.style.top = (picTop + picHeight / 100 * tagtop)+"px";
        newdiv.style.zIndex = 10000;
        newdiv.id = "tag_" + tag_id;

        tagtext = tagtext + "<br><br><font style=font-size:9px>Tagged by: " + username;
        if (passwordPassed) {
            tagtext = tagtext + " <br>(" + tagfamilyname + ", " + taggivenname + " " + tagemail + ")" + "<br>";
            tagtext = tagtext + "<a href=\"javascript:delete_tag('" + tag_id + "');void(0);\">delete</a>";
        }
        else if (user_id === tagsuserid) {
            tagtext = tagtext + "<br><a href=\"javascript:delete_tag('" + tag_id + "');void(0);\">delete</a>";
        }
        newdiv.tagtext = tagtext;

        newdiv.onmouseover = function () { popTag(this.tagtext, this); };
        newdiv.onmouseout = function () { kill_tag(true); };
        newdiv.ondblclick = tagit;
        $(".tag").css("opacity", 0.0);

    }

    if (data.length > -1) {

        if (data.length === ntagfields) {
            gebi("ntags").innerHTML = data.length / ntagfields + " tag";
        }
        else {
            gebi("ntags").innerHTML = data.length / ntagfields + " tags";
        }
    }

}

//=====================================
function showtags() {

    $(".tag").css("opacity", 0.7);
    $(".tag").each(function () {
        var aclone = this.cloneNode(true);
        document.body.appendChild(aclone);
        aclone.innerHTML = this.tagtext;
        aclone.style.width = "";
        aclone.style.height = "";

        xcent = parseInt(this.style.left, 10) + parseInt(this.style.width, 10) / 2;
        ycent = parseInt(this.style.top, 10) + parseInt(this.style.height, 10) / 2;
        aclone.className = "tag tagclone";

        aclone.style.left = (xcent - aclone.scrollWidth / 2)+"px";
        aclone.style.top = (ycent - aclone.scrollHeight / 2)+"px";
    });
}

//=====================================
function hidetags() {
    $(".tag").css("opacity", 0);
    $(".tagclone").each(function () { removeNode(this); });
}

//=====================================
function delete_tag(tag_id) {
    if (!confirm("You are about to delete this tag.\nThis cannot be undone.\nAre you sure you want to do this?")) { return; }

    gebi("action").value = "deletetag";
    gebi("tag_id").value = tag_id;
    text = "deleting.. <img src='" + vbasepath + "images/wait.gif' />";
    showPopCentered(text, gebi("tag_" + tag_id));
    document.sform.submit();
}

//=====================================
function removeAllTags() {
    $(".tag").each(function () { removeNode(this); });
    kill_tag(true); // popup text for a tag
    if (gebi("ntags")) {gebi("ntags").innerHTML = "";}
}

//=====================================
function slideshowSubmitted(anaction) {  // called by child window!

    if (anaction === "submitcaption") {
        gebi("poptext").style.display = 'none';
    }
    if (anaction === "submittag") {
        killPop();
        removeAllTags();

        getTags(gebi("imageId").value);
    }
    if (anaction === "deletetag") {
        removeAllTags();
        kill_tag(false);

        getTags(gebi("imageId").value);
    }
}



//=====================================;
function gebi(anid) { return document.getElementById(anid); }




// ======================================================================
function replace(string, text, by) {
    // Replaces text with by in string
    
    if (typeof string==="undefined") {
        
        alert("error in replace: caller is " + arguments.callee.caller.toString());
    }
    
    var strLength = string.length, txtLength = text.length;
    if ((strLength === 0) || (txtLength === 0)) { return string; }

    var i = string.indexOf(text);
    if ((!i) && (text !== string.substring(0, txtLength))) { return string; }
    if (i === -1) { return string; }

    var newstr = string.substring(0, i) + by;

    if (i + txtLength < strLength) {
        newstr += replace(string.substring(i + txtLength, strLength), text, by);
    }
    return newstr;
}

//===================================================================================================
function getWindowSize(item) {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    if (item == 'w') { return parseInt(myWidth, 10); }
    if (item == 'h') { return parseInt(myHeight, 10); }
}



// ======================================================================	
function getscrollheight(anid) {
    return gebi(anid).offsetHeight;
}
// ======================================================================	
function getscrollwidth(anid) {
    if (!gebi(anid)) {alert("no obj: getscrollwidth: " + anid); }
    return gebi(anid).offsetWidth;
}

//=====================================
function ltrim(str) {
    var whitespace = " \t\n\r";
    var s = String(str);
    if (whitespace.indexOf(s.charAt(0)) !== -1) {
        var j = 0, i = s.length;
        while (j < i && whitespace.indexOf(s.charAt(j)) !== -1)
        { j++; }
        s = s.substring(j, i);

    }
    return s;
}

//=====================================
function rtrim(str) {
    var whitespace = " \t\n\r";
    var s = String(str);
    if (whitespace.indexOf(s.charAt(s.length - 1)) !== -1) {
        var i = s.length - 1;       // Get length of string
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) !== -1)
        { i--; }
        s = s.substring(0, i + 1);

    }
    return s;
}

//=====================================
function trim(str) { return rtrim(ltrim(str)); }












// ======================================================================	
//    http://adamv.com/dev/javascript/querystring	
// ======================================================================	
function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};
    this.get = Querystring_get;
    if (qs == null) {
        qs = location.search.substring(1, location.search.length);
        if (qs.indexOf("?") !== -1) {

            // if coming from a proxy page, then we can have 2 questionmarks. start from the last
            qs = qs.substr(qs.indexOf("?") + 1);
        }


        if (qs.length === 0)
        { return; }

        qs = qs.replace(/\+/g, ' ');
        var args = qs.split('&'); // parse out name/value pairs separated via &
        var i;
        for (i = 0; i < args.length; i++) {
            var pair = args[i].split('=');
            var name = unescape(pair[0]);
            if (pair.length === 2) { value = unescape(pair[1]); } else { value = name; }
            //var value = (pair.length==2)
            //	? unescape(pair[1])
            //	: name;

            this.params[name] = value;
        }
    }
}

// ======================================================================	
function Querystring_get(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}





// ======================================================================	
function isNumeric(strString,mes)
//  check for valid numeric strings	
{
    var strValidChars = "0123456789-";
    var strChar;
    var blnResult = true;

    if (typeof strString==="undefined") {alert("isumneric: "+mes);}
    if (strString.length === 0) { return false; }

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}



// ======================================================================	
function removeAllOptions(selectbox) {
    var i;
    for (i = selectbox.options.length - 1; i >= 0; i--) {
        selectbox.remove(i);
    }
}


// ======================================================================	;
function autoSuggest(aval, site_key, ss_name) {
    if (trim(aval).length >3) {
        extra = "";
        if (forceRemote) { extra = extra + "&forceremote=1"; }
        src = vbasepath + "autocomplete.asp?site_key=" + site_key + "&ss_name=" + ss_name + "&search=" + aval + extra;
        jQuery.getJSON(src + "&callback=?", function (data) { JFgetdata(autoSuggestCallBack, data); });
    }
    else {
        removeAllOptions(gebi("myselect"));
        gebi("myselect").style.display = "none";
    }
}

// ======================================================================	;
function autoSuggestCallBack(data) {

    var a = gebi("slidesearch");
    var b = gebi("myselect");
    b.style.position = "absolute";

    removeAllOptions(b);
    gebi("myselect").size = min(10, data.length)+"px";
    var i;
    for (i = 0; i < data.length; i = i + 2) {
        addOption(b, data[i] + " (" + data[i + 1] + ")", data[i]);
    }

    //now position the box

    a = gebi("slidesearch");
    b = gebi("myselect");

    var x = findPosX(a);
    var y = findPosY(a) + a.offsetHeight;



    b.style.top = y+"px";
    b.style.zIndex = 1000;

    b.style.display = "";

    if (a.getAttribute("boxalign") === "left") { //align left with left
        b.style.left = x + "px";
    }
    else { // alight the right side of autosuggest to the right side of slidesearch
        b.style.left = (x - b.offsetWidth + a.offsetWidth + 35) + "px";
    }

}

// ======================================================================	;
function printNode(node) {
    var extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }

    src = vbasepath + "printnode.asp?site_key=" + site_key + "&content_key=" + node + extra + "&id=" + md5Hash;
    imageBrowser = window.open(src, "xyz", "fullscreen=yes,toolbar=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,directories=yes,location=yes");
}

// ======================================================================	;
function toArray(jsonstuff) {
    var j = 0;
    if (jsonstuff.items) {
        var myarray = [],i;
        for (i = 0; i < jsonstuff.items.length; i++) {
            var rec = jsonstuff.items[i],n;
            for (n in rec) {
                fieldname = n;
                myarray[j] = rec[fieldname];

                j++;
            }
        }

        return myarray;
    }
    else {
        return jsonstuff;
    }


}




// ======================================================================	
function navCallBack(data) {
    // select content_key,title,page_no,target,pagecount

    nChapters = 0;
    // count pages

    // "[subscriber id],[Title],[page_no]"
    var i;
    for (i = 0; i < data.length; i = i + nNavFields) {
        pageno = data[i + 2];
        if (pageno.indexOf("_") === -1) { nChapters++; }
    }
    // write out the navigation


    atr = document.createElement("tr");
    atr.id = "navcontent";


    navhtml = "";
    sublinkcounter = 0;
    for (i = 0; i < nChapters; i++) {

        start = getchapter(i, data);

        content_key = data[start];
        atitle = data[start + 1];
        pageno = data[start + 2];
        target = data[start + 3];
        needlogin = data[start + 6];
        extern = data[start + 5];


        if (showNavText === false) { atitle = "&nbsp;"; }
        numparagraphs = getNumParagraphs(pageno, data);

        // ------------------------------------------------------------------------------------------------------
        // here for every chapter
        // ------------------------------------------------------------------------------------------------------

        chapterextra = "";
        linkextra = "";
        if (i === 0) {
            chapterid = "chapter_first";
            linkid = "link_first";
            chapterclass = "chapter chapter_first";
            linkclass = "link link_first " + "link_" + pageno;
        }
        else if (i === nChapters - 1) {
            chapterid = "chapter_last";
            linkid = "link_last";
            chapterclass = "chapter chapter_last";
            linkclass = "link link_last " + "link_" + pageno;
            lastLinkId = pageno;
        }
        else {
            chapterid = "chapter_" + pageno;
            linkid = "link_" + pageno;
            chapterclass = "chapter";
            linkclass = "link " + "link_" + pageno;
        }
        atd = document.createElement("td");
        atd.vAlign = "top";
        atd.id = "row" + i;
        extra = "";
        extra = extra + " pageno=" + pageno + " content_key=" + content_key + " target=" + target + " external='" + extern + "'";

        display = "";
        if (needlogin === "True")  {display = "none"; }
        if (needlogin === true)  { display = "none"; }
        if (needlogin === 1)  { display = "none"; }
        if (needlogin === "1")  { display = "none"; }

        navhtml += "<div   style='position:relative' id=" + chapterid + " class='" + chapterclass + "'" + extra + " >";
        navhtml += "<a style='z-index:4;display:"+display+"' id=" + linkid + "  class='" + linkclass + " acheader'" + extra + "  ><span>" + atitle + "</span></a>";

        if ((numparagraphs !== 0) || (fixedHeight)) {

            navhtml += "<div><!-- necessary to wrap the below in a div without a specific style -->";

            if (numparagraphs === 0) { disp = "style=display:none"; } else { disp = ""; }
            disp = "";

            navhtml += "<div id=sublink_container" + i + "  class='sublink_container' " + disp + ">";

            for (j = 0; j < numparagraphs; j++) {
                content_key = data[start + nNavFields];
                atitle = data[start + nNavFields + 1];
                pageno = data[start + nNavFields + 2];
                target = data[start + nNavFields + 3];
                extern = data[start + nNavFields + 5];

                needlogin = data[start + nNavFields + 6];
                extra = "";
                extra = extra + " class='sublink link_"+pageno+"' pageno=" + pageno + " content_key=" + content_key + " target=" + target + " external='" + extern + "'";

                display = "";
                if (needlogin === "True") { display = "none"; }
                if (needlogin === true) { display = "none"; }
                if (needlogin === 1) { display = "none"; }
                if (needlogin === "1") { display = "none"; }



                navhtml += "<div  style='display:" + display +"' id=link_" + pageno + extra + " ><span>" + atitle + "</span></div>";

                start = start + nNavFields;
                sublinkcounter++;
            }  // end of a paragraph

            navhtml += "</div>"; // sublink container
            navhtml += "</div>"; // wrapper
        }
        navhtml += "</div>"; // chapter
        atd.innerHTML = navhtml;
        navhtml = "";
        atr.appendChild(atd);

    } // end of a chapter

    aparent = gebi("tobereplaced").parentNode;
    aparent.replaceChild(atr, gebi("tobereplaced"));
    atr.id = "tobereplaced";


    JQlink = $("#navholder .link");
    JQsublink = $("#navholder .sublink");
    JQsublink_container = $("#navholder .sublink_container");
    JQchapter = $("#navholder .chapter");


    //-------------------------------------------------------------------
    // add clasname and shownode to the onclick event of link and sublink
    //-------------------------------------------------------------------

    $("#navholder .link,#navholder .sublink").bind("click", function() {
        removeClickedStates('all', true, 'click');
        if ($(this)[0].className.indexOf("sublink") === -1) {
            $(this).addClass('link_clicked');
        }
        else {
            $(this).addClass('sublink_clicked');
        }
        $(this).addClass(this.id + '_clicked');

        target = findAttribute(this, "target");
        page_no = findAttribute(this, "pageno");
        content_key = findAttribute(this, "content_key").toUpperCase();
        externalLink = findAttribute(this, "external").toLowerCase();
        externalLink = replace(externalLink, "&amp;", "&");
        if (changeState) {
            if (state !== "") { changeState(""); }
        }
        if (!disableNavClick) {
            if (!externalLink.find("nolink")) {

                if (vbaseExternal(externalLink)) {
                    var data = initData();
                    data[3] = content_key;
                    data[4] = externalLink;
                    data[2] = target;
                    getPiggies(content_key);

                    showNodeCallBack(data, "navcallback");
                }
                else {
                    showNode('clickevent of nav', content_key, target, "");
                }

                if (target === "content") { lastPage = page_no; }
            }
            else {
                if ($("#link_" + page_no + "_00").length > 0) { $("#link_" + page_no + "_00").trigger("click"); }
            }
        }
    });

    //-------------------------------------------------------------------
    // now some special cases
    //-------------------------------------------------------------------
        $("#link_first").bind("click", function () {
        $(this).addClass('link_clicked');
        $(this).addClass('link_first_clicked');
        $(this).addClass('link_00_clicked');
    });


    $("#link_last").bind("click", function () {
        $(this).addClass('link_clicked');
        $(this).addClass('link_last_clicked');
        $(this).addClass('link_' + lastLinkId + '_clicked');
    });

    //-------------------------------------------------------------------
    // if clicked on a sublink, set the link to clicked
    //-------------------------------------------------------------------

    JQsublink.bind("click", function () {

        achapter = $(this.parentNode.parentNode.parentNode)[0].id;
        alink = replace(achapter, "chapter", "link");
        $(gebi(alink)).addClass('link_clicked');
        if (alink === "link_first") {
            $(gebi(alink)).addClass('link_first_clicked');
        }
        else if (alink === "link_last") {
            $(gebi(alink)).addClass('link_last_clicked');
        }
    });

    i = 0;


    navpos(navPos);
    reaccordion("init");
    //alert(1)

    $("#navholder").hover(function () { $(this).addClass('navholder_hover'); }, function () { $(this).removeClass('navholder_hover'); });
    JQchapter.hover(function () { $(this).addClass('chapter_hover'); }, function () { $(this).removeClass('chapter_hover'); });
    JQlink.hover(function () { $(this).addClass('link_hover'); }, function () { $(this).removeClass('link_hover'); });
    JQsublink_container.hover(function () { $(this).addClass('sublink_container_hover'); }, function () { $(this).removeClass('sublink_container_hover'); });
    JQsublink.hover(function () { $(this).addClass('sublink_hover'); }, function () { $(this).removeClass('sublink_hover'); });
    $("#link_first").hover(function () { $(this).addClass('link_first_hover'); }, function () { $(this).removeClass('link_first_hover'); });
    $("#link_last").hover(function () { $(this).addClass('link_last_hover'); }, function () { $(this).removeClass('link_last_hover'); });
    $("#chapter_first").hover(function () { $(this).addClass('chapter_first_hover'); }, function () { $(this).removeClass('chapter_first_hover'); });
    $("#chapter_last").hover(function () { $(this).addClass('chapter_last_hover'); }, function () { $(this).removeClass('chapter_last_hover'); });

    $("[id^=aux][class^=aux]").each(function () {
        $(this).hover(function () { $(this).addClass(this.id + "_hover"); }, function () { $(this).removeClass(this.id + "_hover"); });
        $(this).click(function () {
            $("[id^=aux][class^=aux]").each(function () {
                $(this).removeClass(this.id + "_clicked");
            });
            removeAuxClickedStates("readstyles");
            $(this).addClass(this.id + "_clicked");
        });
    });

    // click states

    sublinkcounter = 0;

    // for all links inbeteween first and last
    for (i = 1; i < nChapters - 1; i++) {
        start = getchapter(i, data);
        pageno = data[start + 2];

        linkid = "link_" + pageno;

        $("#" + linkid).hover(function () { $(this).addClass(this.id + '_hover'); }, function () { $(this).removeClass(this.id + '_hover'); });
        $("#" + linkid).click(function () { $(this).addClass(this.id + '_clicked'); }, function () { $(this).removeClass(this.id + '_clicked'); });
    }

    if (firstTime) { // page is already loaded as part of the HTML, no need to load again
        //$(".link_" + lastPage).trigger("click")
        setNav($(".link_" + lastPage)[0].getAttribute("content_key"));
        firstTime = false;
    }
    else {
        showLastPage();
    }
    // ad this is the last call of init(), the whole document shold be there now

    if (!docIsLoaded) {
        docLoaded();
    }
    setVsize("all");
}

// ======================================================================	;
function showLastPage() {
    //alert("lastpage")
    if (lastPage.find("aux")) {
        $(gebi(lastPage)).trigger("click");
    }
    else {
        $(".link_" + lastPage).trigger("click");
    }

}


// ======================================================================	;
function moveNodes(sourceNode, targetNode, newWrapperTagName) {// v1.0 Copyright (c) 2006 TJKDesign - Thierry Koblentz
    if (!document.createElement) { return; }
    var nodeRecipient = (targetNode) ? targetNode : document.createElement(newWrapperTagName);
    while (sourceNode.childNodes.length) { nodeRecipient.appendChild(sourceNode.childNodes[0]); }
    if (newWrapperTagName) { sourceNode.appendChild(nodeRecipient); }
}


// ======================================================================	;
function setContainer(name, w, h, doScroll) {


    w = noPx(w);
    h = noPx(h);
    if (w - getWidthStuff(name) <= 0) { return; }
    if (h - getHeightStuff(name) <= 0) { return; }
    if ((w === "") || (h === "")) {return;}
    if ((w === 0) || (h === 0)) {return;}

    var obj = gebi(name);

    obj.style.width = "";
    obj.style.height = "";

    if (!gebi(name + "_scroller")) {
        obj.style.overflow = "hidden";   // needed for Safari
        var adiv = document.createElement("div");
        adiv.id = name + "_scroller";
        adiv.className = name + "_scroller";
        moveNodes(obj, adiv);
        obj.appendChild(adiv);

        adiv.style.position = "relative";

    }
    gebi(name + "_scroller").style.overflow = "hidden";

    gebi(name + "_scroller").style.width = "";
    gebi(name + "_scroller").style.height = "";

    gebi(name + "_scroller").style.width = (w - getWidthStuff(name))+"px";
    gebi(name + "_scroller").style.padding = "";


    obj.style.width = w + "px";
    obj.style.height = h + "px";

    if (h - getHeightStuff(name) <= 0) {alert(name + " (1) height is zero");}
    if (h - getHeightStuff(name) === "0") {alert(name + " (2) height is 0"); }

    gebi(name + "_scroller").style.height = (h - getHeightStuff(name)) + "px";

    var atime = 0;
    if (isIE()) {atime = 500; }
    if (doScroll) {
        setTimeout(function () {
            initScroller(name + "_scroller", "setcontainer");
        }, atime);
    }  // because of IE bug, reports wrong scrollheight
}

// ======================================================================	;
function initScroller(divId, who) {


    //div_id id for example content_scroller
    var barWidth = getStyle("vbar_" + divId, "width");
    var gliderWidth = getStyle("vglider_" + divId, "width");
    if (barWidth === "") { barWidth = 16; } else { barWidth = noPx(barWidth); }
    if (gliderWidth === "") { gliderWidth = 16; } else { gliderWidth = noPx(gliderWidth); }
    sliderWidth = max(gliderWidth, barWidth); // width of the slider
    if (!gebi(divId)) { alert("error in InitScroller: " + who + " " + divId); }
    currentPaddingRight = noPx(getStyle(gebi(divId).parentNode.id, "paddingRight"));
    //      remove anything that might be there

    if (gebi("vbar_" + divId)) {
        var curp = noPx(gebi(divId).style.paddingRight);
        gebi(divId).style.paddingRight = 0 + "px";
    }

    removeNode(gebi("vglider_" + divId));
    removeNode(gebi("vbar_" + divId));
    removeNode(gebi("vbar2_" + divId));

    //      anythng to do ?

    if (!hasScroll(gebi(divId))) { return; }

    if (!styleScrollbars) {

        gebi(divId).style.overflowX = "hidden";
        gebi(divId).style.overflowY = "auto";
        gebi(divId).style.paddingRight = (currentPaddingRight + sliderWidth) + "px";

        return;
    }



    var adiv = gebi(divId);
    adiv.onscroll = function() { setGlider(divId); };
    var abar;
    if (!gebi("vbar_" + divId)) {
        abar = document.createElement("div");
        abar.className = "vbar_" + divId + " " + "dragme";
        abar.style.position = "absolute";
        abar.style.overflow = "hidden";
        abar.id = "vbar_" + divId;
        gebi("body").appendChild(abar);
    }
    else {
        abar = gebi("vbar_" + divId);
    }
    var newstylename = "vbar_" + divId;
    gebi(divId).style.paddingRight = (currentPaddingRight + sliderWidth) + "px";
    abar.style.height = gebi(divId).offsetHeight + "px";

    setStyle("vbar_" + divId, "width", barWidth);
    abar.style.width = noPx(barWidth) + "px";

    aw = noPx(abar.style.width);
    if (getStyle("vbar_" + divId, "borderWidth") === "") {
        abar.style.marginLeft = ((sliderWidth - aw) / 2) + "px";
    }

    abar.style.display = "";
    abar.onclick = function(event) { getMouse(event); scrollClick(divId); };

    var newGlider = false;
    var aglider;
    if (!gebi("vglider_" + divId)) {
        newGlider = true;
        aglider = document.createElement("div");
        aglider.className = "vglider_" + divId + " " + "dragme";
        aglider.style.position = "absolute";
        aglider.style.overflow = "hidden";

        aglider.id = "vglider_" + divId;
        gebi("body").appendChild(aglider);
    }
    else {
        aglider = gebi("vglider_" + divId);
    }

    newstylename = "vglider_" + divId;

    aglider.style.position = "absolute";
    aglider.style.display = "";

    setStyle("glider_" + divId, "width", gliderWidth);
    aglider.style.width = noPx(gliderWidth) + "px";

    aw = noPx(aglider.style.width);
    aglider.style.marginLeft = noPx((sliderWidth - aw) / 2) + "px";

    var y = findPosY(adiv, true);
    var x = $(adiv).offset().left + adiv.offsetWidth - sliderWidth;
    abar.style.left = x + "px";
    y = $(adiv).offset().top;

    abar.style.top = y + "px";
    aglider.style.left = x + "px";
    aglider.style.top = y + "px";
    abar2 = document.createElement("div");
    abar2.style.width = sliderWidth + "px";
    abar2.style.height = abar.offsetHeight + "px";
    abar.parentNode.insertBefore(abar2, abar);
    abar2.id = "vbar2_" + divId;

    abar2.style.backgroundColor = "transparent";
    abar2.style.position = "absolute";
    abar2.style.left = x + "px";
    abar2.style.top = y + "px";
    abar2.onclick = function(event) { getMouse(event); scrollClick(divId); };
    aheight = noPx(gebi(divId).offsetHeight);

    var range = aheight - noPx(getStyle("vglider_" + divId, "height"));
    aglider.onmouseover = function() { dragmode = 'vertical'; };
    abar.onmouseover = function() { dragmode = 'vertical'; };

    abar2.style.zIndex = 9;
    if (divId === "modal_scroller") { abar2.style.zIndex = 1001; }
    if (divId === "modal2_scroller") { abar2.style.zIndex = 1011; }

    abar.style.zIndex = 10;
    if (divId === "modal_scroller") { abar.style.zIndex = 1002; }
    if (divId === "modal2_scroller") { abar.style.zIndex = 1012; }

    aglider.style.zIndex = 11;
    if (divId === "modal_scroller") { aglider.style.zIndex = 1003; }
    if (divId === "modal2_scroller") { aglider.style.zIndex = 1013; }

    aglider.limitTop = y;
    aglider.limitBottom = y + range;


    // attach mousewheel
    $("#" + divId).unbind('mousewheel');
    $("#" + divId).bind('mousewheel', function(event, delta) {

        if (delta > 0) { adiv.scrollTop = adiv.scrollTop - 20; }
        if (delta < 0) { adiv.scrollTop = adiv.scrollTop + 20; }
        return false;
    });
    $(abar2).unbind('mousewheel');
    $(abar2).bind('mousewheel', function(event, delta) {
        if (delta > 0) { adiv.scrollTop = adiv.scrollTop - 20; }
        if (delta < 0) { adiv.scrollTop = adiv.scrollTop + 20; }
        return false;
    });
    $(abar).unbind('mousewheel');
    $(abar).bind('mousewheel', function(event, delta) {
        if (delta > 0) { adiv.scrollTop = adiv.scrollTop - 20; }
        if (delta < 0) { adiv.scrollTop = adiv.scrollTop + 20; }
        return false;
    });
    $(aglider).unbind('mousewheel');
    $(aglider).bind('mousewheel', function(event, delta) {
        if (delta > 0) { adiv.scrollTop = adiv.scrollTop - 20; }
        if (delta < 0) { adiv.scrollTop = adiv.scrollTop + 20; }
        return false;
    });

    if (isIE()) { // ie sometimes renders the glider with a wrong z_index after a window resize
        aglider.style.top = (noPx(aglider.style.top) + 100) + "px";

        setTimeout(function() {
            aglider.style.top = (noPx(aglider.style.top) - 100) + "px";
        }, 100);

    }




    // now this for webkit browsers who don't re-render the text after a dynamically padding change
    // don't use a=b.innerHTML; b.innerHTML=""; b.innerHTML=a as you will lose the onclick events
    // so, instead to some node jugling:
    // return
    var a = gebi(divId).parentNode;
    document.body.appendChild(gebi(divId));

    a.appendChild(gebi(divId));


}

//=======================================================;
function textHeight(id, who) {

    gebi(id).style.height = "";
    setStyle(id, "height", "");
    gebi(id + "_scroller").style.height = "";
    setStyle(id + "_scroller", "height", "");

    return gebi(id + "_scroller").scrollHeight + getHeightStuff(id);
}


var margins;
//=======================================================;
function getDimensions(who) {
    
    if (gebi("navdragger")) {gebi("navdragger").style.display = "none";}  // in case it sticks out to the right IE
    windowH = noPx(getWindowSize("h"));

    windowW = noPx(getWindowSize("w"));
    if (gebi("navdragger")) {gebi("navdragger").style.display = "";}

    topHeight = noPx(getStyleNH2("top", "height"));
    bottomHeight = noPx(getStyleNH2("bottom", "height"));
    leftWidth = noPx(getStyle("left_holder", "width"));
    rightWidth = noPx(getStyle("right_holder", "width"));

    var margins = gebi("top1_spacer").offsetHeight + topHeight + gebi("top2_spacer").offsetHeight;
    margins = margins + gebi("bottom1_spacer").offsetHeight + bottomHeight + gebi("bottom2_spacer").offsetHeight;


    fullPageWidth = windowW;
    pageWidth = getStyle("page", "width");

    if (pageWidth === "") { pageWidth = "100%"; }

    if (pageWidth.indexOf("%") !== -1) {
        p = parseInt(pageWidth, 10);
        pageWidth = fullPageWidth * p / 100;
    }
    else {
        pageWidth = parseInt(pageWidth, 10);
    }

    bodyWidth = windowW;

    topWidth = pageWidth - getWidthStuff("page") - noPx(getStyleNH("pageleft_spacer", "width")) - noPx(getStyleNH("pageright_spacer", "width"));
    
    //var x = getStyleNH("left1_spacer", "width") + getStyleNH("left_holder", "width") + getStyleNH("left2_spacer", "width") + max(getscrollwidth("pageleft_spacer"), getStyleNH("pageleft_spacer", "width"));
    //x = x + getStyleNH("right1_spacer", "width") + getStyleNH("right_holder", "width") + getStyleNH("right2_spacer", "width") + max(getscrollwidth("pageright_spacer"), getStyleNH("pageright_spacer", "width"));
    
    var x = getStyleNH("left1_spacer", "width") + getStyleNH("left_holder", "width") + getStyleNH("left2_spacer", "width") + getStyleNH("pageleft_spacer", "width");
    x = x + getStyleNH("right1_spacer", "width") + getStyleNH("right_holder", "width") + getStyleNH("right2_spacer", "width") +getStyleNH("pageright_spacer", "width");
    
    contentWidth = pageWidth - x - getWidthStuff("page") - getWidthStuff("content_outer");
    if ((!haveScrollbar)) {
        bodyHeight = textHeight("content") + 20 +getHeightStuff("content_outer") + margins + getHeightStuff("body") + getHeightStuff("page");

        var L = textHeight("left") + margins + getHeightStuff("body") + getHeightStuff("page");
        var R = textHeight("right") + margins + getHeightStuff("body") + getHeightStuff("page");
        if (isSwapped("left")) { L = L - margins; }
        if (isSwapped("right")) { R = R - margins; }

        bodyHeight = max(L, bodyHeight);
        bodyHeight = max(R, bodyHeight);
        bodyHeight = max(bodyHeight, windowH);
    }
    else { // limited to the visible window size;

        bodyHeight = windowH;
    }

    pageHeight = bodyHeight - getHeightStuff("body");

    middleHeight = pageHeight - margins - getHeightStuff("page");
    margins = parseInt(gebi("top1_spacer").offsetHeight, 10);
    margins = margins + parseInt(gebi("bottom2_spacer").offsetHeight, 10);

    leftmax = middleHeight;
    rightmax = middleHeight;
    if (isSwapped("left")) { leftmax = pageHeight - margins - getHeightStuff("page"); }
    if (isSwapped("right")) { rightmax = pageHeight - margins - getHeightStuff("page"); }

    if (left100 === "yes") {
        leftHeight = leftmax;
    }
    else {
        leftHeight = min(textHeight("left"), leftmax);
    }

    if (right100 === "yes") {
        rightHeight = rightmax;
    }
    else {
        rightHeight = min(textHeight("right"), rightmax);
    }


    contentHeight = middleHeight - getHeightStuff("content_outer");


}



//=======================================================;
function getContainer(node) {
    if (node.id) { if ("content|left|right|top|bottom|modal|modal2|".find(node.id)) {return node.id;} }
    dir = "";
    while ((node = node.parentNode)) {
        if (node.id !== "") {
            if ("content_scroller|left_scroller|right_scroller|top_scroller|bottom_scroller|modal_scroller|modal2|".find(node.id)) {return node.id; }
        }
    }
    return "";
}





//=============================================================;
function isIE() {
    return $.browser.msie;
}

//=============================================================;
function isMoz() {
    return $.browser.mozilla;
}

//=============================================================;
function isWebKit() {
    return $.browser.webkit;
}
//=============================================================;
function isOpera() {
    return $.browser.opera;
}

// ======================================================================	;
function getParentStyle(obj, prop) {


    while (1) {
        cn = trim(obj.className).split(" ")[0];    //  pie adds classname pie_hover
        if (cn !== "") {
            //if (typeof rounding[cn] !== "undefined") {
                if (prop === "backgroundColor") {
                    aval = getOrigBackground(cn);
                }
                else {
                    aval = getStyle(cn, prop);
                }
                if ((aval !== "") && (aval !== "transparent")) {return aval; }
            //}
        }
        if (!obj.parentNode) { break; }
        obj = obj.parentNode;
    }
    return "";

}


//=============================================================;
function getOrigBackground(classname) {
    if (classname === "") { return ""; }
    str = getStyleText(classname, true).toLowerCase();
    curstyle = getStyle(classname, "backgroundColor");

    if ((curstyle !== "initial") && (curstyle !== "transparent") && (curstyle !== "")) { return curstyle; }
    ar = str.split("-gradient");
    if (ar.length > 0 && (typeof ar[1] !== "undefined")) {
        p = ar[1].split(",");

        if (isIE()) { return trim(p[1]); }
        if (isMoz()) { return rgb2hex(p[1] + "," + p[2] + "," + p[3]); }
        if (isWebKit) {
            p = ar[1].split("from")[1].split("))")[0] + ")";
            return rgb2hex(p.substring(1));
        }
    }
    return "";

}





var picInProgress = false;
//=======================================================;
function showpic(href, caption, prev, next, imgid, spanid, isSlideFromSlideshow, tagable) {
    if (picInProgress) { return; }
    picInProgress = true;   // to prevent double click
    setTimeout(function() { picInProgress = false; }, 2000);
    // spanid holds the id of the smaller image, imgid just the numeric id of the database;
    var startwidth,startheight;
    var image;
    var asrc;
    var previmage;
    var nextimage;
    var ph = gebi("picture_holder");
    removeAllTags();
    removeNode(gebi("caption_holder"));

    $("#prevbutton,#nextbutton,#closebutton").css("display", "none");
    setStyle("prevbutton", "display", "none");
    setStyle("nextbutton", "display", "none");
    setStyle("closebutton", "display", "none");
    $("#prevbutton,#nextbutton,#closebutton").css("display", "");


    reserve = 20 + getHeightStuff("thumb_holder");
    if (isSlideFromSlideshow) {reserve = 70 + getHeightStuff("thumb_holder"); }  // height to substract from the image for thumbstuff
    
    if (ph.style.display === "none") {

        ph.innerHTML = "";

        oldImage = document.createElement("img");
        oldImage.style.display = "none";
        ph.appendChild(oldImage);
        startwidth = 150;
        startheight = 150;

        ph.style.width = startwidth + "px";
        ph.style.height = startheight + "px";
        if (getStyle("picture_holder", "backgroundColor") === "") { setStyle("picture_holder", "backgroundColor", "#ffffff"); }

        $("#fader3").unbind("click");


        ph.style.display = "inline";
        $(ph).css("opacity", 1);
        yOffset = setcenter("picture_holder", "screen",true);
        ph.style.display = "none";

        if (vbaseParent !== "") {
            window.parent.location = vbaseParent + "#offset=" + yOffset;
        }

        $(ph).stop().fadeIn(500);


        image = document.createElement("img");
        image.src = "";
        image.id = "currentpic";
        image.onmouseout = function () { kill_tag(false); };
        image.style.cursor = "hand";
        image.style.cursor = "pointer";
        $(image).css("opacity", 0);

        faderIn(3, 1);

        if (isSlideFromSlideshow) {
            ph.style.top = (noPx(ph.style.top) - 60)+"px";
        }
    }
    else {
        image = document.createElement("img");
        image.src = "";
        image.id = "currentpic";
        image.onmouseout = function () { kill_tag(false); };
        image.style.cursor = "hand";
        image.style.cursor = "pointer";

        oldImage = ph.childNodes[0];
        startwidth = noPx(ph.offsetWidth);
        startheight = noPx(ph.offsetHeight);

    }
    gebi("imageId").value = imgid;

    $(image).stop().animate({ opacity: 0 }, 0);

    var captionHeight = 0;

    gebi("editCaption").style.display = "none";

    $("#fader3").bind("click", function () { closepic(); });


    image.onload = function() {

        $(oldImage).stop().animate({ opacity: 0 }, 300, function() { removeNode(oldImage); });


        if (isSlideFromSlideshow) { thumbs(); slideStuff(); }

        var cw = noPx(image.width); //actual width of image
        var ch = noPx(image.height);  // actual height

        // now this is the size of the image, the outer dimensions of the box should be bigger: + de padding and the border

        cw = cw + getWidthStuff("picture_holder");
        ch = ch + getHeightStuff("picture_holder");

        var newleft = noPx(ph.style.left) - cw / 2 + (startwidth / 2);
        var newtop = noPx(ph.style.top) - ch / 2 + (startheight / 2);

        xcenter = windowW / 2 + document.documentElement.scrollLeft;
        newleft = xcenter - cw / 2;

        ycenter = (windowH) / 2 - (reserve - 20) / 2 + document.documentElement.scrollTop;
        newtop = ycenter - ch / 2;


        $(ph).animate({ width: cw, left: newleft, height: ch, top: newtop }, 500, function() {
            if (next !== "") {
                nextimage = new Image();
                nextimage.onload = function() {
                    hlButton("nextbutton");
                    addImage(getImageSource2(next, reserve));
                };
                nextimage.src = getImageSource2(next, reserve);
                setStyle("nextbutton", "display", "block");
                gebi("nextbutton").onclick = function() { $(gebi(spanid).parentNode.parentNode.nextSibling).find("img")[0].onclick(); };
            }

            //var a = function (anid) {
            //    return function () {
            //        gebi(anid).click()
            //    };
            //} (anid);  //closure!            


            if (prev !== "") {
                previmage = new Image();
                previmage.onload = function() {
                    hlButton("prevbutton");
                    addImage(getImageSource2(prev, reserve));
                };
                previmage.src = getImageSource2(prev, reserve);
                setStyle("prevbutton", "display", "block");
                gebi("prevbutton").onclick = function() { $(gebi(spanid).parentNode.parentNode.previousSibling).find("img")[0].onclick(); };
            }
            setStyle("closebutton", "display", "block");
            fixIEBlur("picture_holder");


            ph.appendChild(image);

            $(image).stop().animate({ opacity: 1 }, 300);
            hideWait();

            // set some globals, needed for tagging

            picLeft = findPosX(gebi("currentpic"));
            picRight = picLeft + getscrollwidth("currentpic");
            picTop = findPosY(gebi("currentpic"));
            picBottom = picTop + getscrollheight("currentpic");
            if (isSlideFromSlideshow) { getTags(imgid); }

            a = document.createElement("div");
            a.id = "caption_holder";
            a.className = "caption_holder";
            if (getStyleText("caption_holder") === "") {
                setStyle("caption_holder", "backgroundColor", "#000");
                setStyle("caption_holder", "color", "#fff");
                setStyle("caption_holder", "padding", "3px");
            }
            a.style.width = (gebi("currentpic").offsetWidth - noPx(getStyle("caption_holder", "marginLeft")) - noPx(getStyle("caption_holder", "marginRight"))) + "px";
            a.innerHTML = caption;
            a.style.position = "absolute";
            ph.appendChild(a);
            a.style.top = (noPx(getStyle("picture_holder", "paddingTop"))) + "px";
            a.style.left = (noPx(getStyle("picture_holder", "paddingLeft"))) + "px";
            $(a).css("opacity", 0.9);
            if (caption === "") { a.style.display = "none"; }
            setTimeout(function() { isIE() ? $("#caption_holder").stop().fadeOut(500) : $("#caption_holder").stop().slideUp(500); }, 4000);

            image.onmouseover = function() {
                if (gebi("caption_holder").innerHTML !== "") {
                    isIE() ? $("#caption_holder").stop(true, true).fadeIn(500) : $("#caption_holder").stop(true, true).slideDown(500);

                    setTimeout(function() { isIE() ? $("#caption_holder").stop(true, true).fadeOut(500) : $("#caption_holder").stop(true, true).slideUp(500); }, 4000);
                }
            };

            if (gebi("dragme")) {

                if (isSlideFromSlideshow) {
                    if ((passwordPassed) || (tagable === "True")) {
                        image.ondblclick = tagit;
                        showPop("double click this picture to add a tag", picLeft + 5, picBottom - 30);
                        setTimeout(function() { killPop(); }, 2000);

                    }
                }
            }
            if ((passwordPassed) && (isSlideFromSlideshow)) {
                gebi("editCaption").style.display = "";
                ph.appendChild(gebi("editCaption"));
                gebi("editCaption").style.display = "block";
                gebi("editCaption").style.position = "absolute";
                gebi("editCaption").style.top = 0 + "px";
            }

            ci = gebi("closebutton");
            document.body.appendChild(ci);
            ci.style.top = findPosY(ph) + "px";
            ci.style.left = (findPosX(ph) + ph.offsetWidth + 5) + "px";

            // keep an array of successfully loaded images
            found = false;
            addImage(asrc);
            picInProgress = false;

        });

        //});
    };

    image.spanid = spanid;

    asrc = vbasepath + "image.php?image=" + encodeURIComponent(href) + "&height=" + (windowH - getHeightStuff("picture_holder") - reserve) + "&width=" + (windowW - 20);

    if (href.find("picapic.asp")) {
        asrc = asrc + "&height=" + (windowH - getHeightStuff("picture_holder") - reserve) + "&width=" + (windowW - 20);

    }
    else {
        asrc = vbasepath + "image.php?image=" + href + "&height=" + (windowH - getHeightStuff("picture_holder") - reserve) + "&width=" + (windowW - 20);
    }
    // check if picture is in stock;
    //image.src = encodeURIComponent(asrc);
    image.src = asrc;

    if (!haveImage(asrc)) {
        showWait("screen");
        setcenter("wait", "picture_holder");
    }
}


//=======================================================
function addImage(asrc) {
    var found=false;
    var i;
    for (i = 0; i < imgArray.length; i++) {
        if (imgArray[i] === asrc) { found = true ;}
    }
    if (!found) { imgArray.push(asrc); }
}

//=======================================================
function haveImage(asrc) {
    var i;
    for (i = 0; i < imgArray.length; i++) {
        if (imgArray[i] === asrc) { return true; }
    }
    return false;
}

//=======================================================
function hlButton(imgId) {  // flash a button if image is loaded
    var i = gebi(imgId);
    i.style.border = "1px solid #666666";
    i.style.height = 23 + "px";
    i.style.width = 23 + "px";
    setTimeout(function () {
        i.style.border = "0px solid #666666";
        i.style.height = 25 + "px";
        i.style.width = 25 + "px";
    }, 1000);
}


//=======================================================;
function getImageSource2(thumbId,reserve) {

    // get's the source of a picture taking in acount the screen size;
    //alert(remotePath + "image.php?image=" + encodeURIComponent(thumbId) + "&height=" + (windowH - getHeightStuff("picture_holder") - reserve) + "&width=" + (windowW - 20));
    return remotePath + "image.php?image=" + thumbId + "&height=" + (windowH - getHeightStuff("picture_holder") - reserve) + "&width=" + (windowW - 20);
}


//===========================================================================
function thumbs() {

    lbh = 40;
    lbw = 480 - 25 - 25;
    spacerwidth = 10;

    var i;
    setStyle("thumb_holder", "display", "block");

    if (gebi("thumb_holder").innerHTML !== "") {
        i=0;
        $("#thumb_holder .slideimage").each(function () {
            $(this).css("opacity", "0.5").css("border", "0px solid #ffffff").css("height", lbh);
            if (this.id == "img_" + gebi("imageId").value) {
                $(this).css("border", "1px solid #ffffff").css("height", lbh - 2);
                $(this).animate({ opacity: 1 }, 1000);
                nowOffset = i;
                nowShowing = this;
            }
            i = i + this.offsetWidth + spacerwidth;
        });
        gebi("thumb_holder").style.top = (windowH - gebi("thumb_holder").offsetHeight - 20 + document.documentElement.scrollTop)+"px";
        lb.scrollLeft = (nowOffset - lbw / 2) + nowShowing.offsetWidth / 2;
        return;
    }

removeNode(gebi("lb"));




if (!gebi("lb")) { lb = document.createElement("div"); }

lb.id="lb";
lb.style.width = lbw + "px";
lb.style.height = lbh + "px";
lb.style.overflow = "hidden";

spacer = document.createElement("span");
spacer.style.width = spacerwidth + "px";
spacer.style.display="inline-block";
spacer.style.height = lbh + "px";

gebi("thumb_holder").innerHTML="";
gebi("thumb_holder").appendChild(lb);
gebi("thumb_holder").style.width = lbw + "px";
gebi("thumb_holder").style.height = lbh + "px";

gebi("thumb_holder").style.width = (lbw + getWidthStuff("thumb_holder")) + "px";
gebi("thumb_holder").style.height = (lbh + getHeightStuff("thumb_holder")) + "px";

gebi("thumb_holder").style.marginTop = "10px";

innerdiv=document.createElement("div");

lb.appendChild(innerdiv);
innerdiv.style.height = lbh + "px";

innerdiv.style.whiteSpace="nowrap";

i=0;
jQuery(".slideimage").each(function() {

    c = this.cloneNode(true);
    //alert(c.id)
    c.onload = "";
    anid = this.id;
    c.id = anid + "_clone";
    var a = function(anid) {
        return function() {
            // jQuery(gebi(anid)).trigger("click"); doesn't work anymore for ie. only if you bind the click with jquery

            gebi(anid).onclick();
            thumbs();
        };
    } (anid);  //closure!

    c.onclick = a;

    c.style.height = lbh + "px";
    innerdiv.appendChild(c);
    innerdiv.appendChild(spacer.cloneNode(true));

    m = -(c.offsetHeight - lbh) / 2;

    if (m < 0) { c.style.marginTop = m; }
    c.style.display = "inline";
    c.style.verticalAlign = "top";
    $(c).css("opacity", 0.5);

    if (c.id == "img_" + gebi("imageId").value + "_clone") {
        nowShowing = c;
        $(nowShowing).css("opacity", 1).css("border", "1px solid #ffffff").css("height", lbh - 2);
        nowOffset = i;
    }
    i = i + c.offsetWidth + spacerwidth;
});


$('#thumb_holder .slideimage').unbind('mouseenter mouseleave');



lb.scrollLeft = (nowOffset - lbw / 2) + nowShowing.offsetWidth / 2;

jQuery(lb).bind("mouseleave", function (event) { clearTimeout(lb.th); });
jQuery(lb).bind("mouseenter", function (event) { clearTimeout(lb.th); });
jQuery(lb).bind("click", function (event) { clearTimeout(lb.th); });

jQuery(lb).bind("mousemove", function (event) {
    var middle = findPosX(lb) + lb.offsetWidth / 2;
    clearTimeout(lb.th);
    inc = 4;
    if (event.pageX > middle + 50) {
        lb.th = setInterval(function () { lb.scrollLeft = lb.scrollLeft + inc; }, 10);
    }
    else if (event.pageX < middle - 50) {
        lb.th = setInterval(function () { lb.scrollLeft = lb.scrollLeft + inc * -1; }, 10);
    }
});

a = gebi("thumb_holder");
setcenter("thumb_holder", "screen");
a.style.top = (windowH - a.offsetHeight - 20+document.documentElement.scrollTop)+"px";



}

//===========================================================================
function slideStuff() {

    // previous and next buttons, ntags, 'tag this image', 

    // buttons

    var lb = gebi("lb");
    var th = gebi("thumb_holder");
    var thtop = noPx(th.style.top) + th.offsetHeight / 2 - 12 + noPx(getStyle("prevbutton", "marginTop")) + 10;

    document.body.appendChild(gebi("prevbutton"));
    gebi("prevbutton").style.left = (noPx(th.style.left) - 30 + noPx(getStyle("prevbutton", "marginLeft"))) + "px";
    gebi("prevbutton").style.top = thtop+"px";

    document.body.appendChild(gebi("nextbutton"));
    gebi("nextbutton").style.left = (noPx(th.style.left) + th.offsetWidth + 5 + noPx(getStyle("nextbutton", "marginLeft"))) + "px";
    gebi("nextbutton").style.top = thtop+"px";


    if (!gebi("ntags")) { a = document.createElement("div"); a.id = "ntags"; }


    a = gebi("ntags");
    a.className = "ntags";
    document.body.appendChild(a);
    if (getStyleText("ntags") === "") {
        setStyle("ntags", "color", "#666666");
        setStyle("ntags", "backgroundColor", "#000000");
    }
    a.style.top = (noPx(gebi("thumb_holder").style.top) + 37 + noPx(getStyle("ntags", "marginTop"))+3-15)+"px";
    a.style.width = 50 + "px";

    a.style.left = (jQuery("#thumb_holder").offset().left + gebi("thumb_holder").offsetWidth + 5 + noPx(getStyle("ntags", "marginLeft")) + 30) + "px";


    setStyle("ntags", "display", "block");
    gebi("ntags").style.display = "block";



}


//===========================================================================
function traverse(node) {
    if (node.id !== "") {alert(node.id); }
    $(node).children().each(function() {
        traverse(this);
    });
    
}






// ======================================================================	;
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

// ======================================================================	;
function showVBCart() {

    $(".vbcart")[0].style.left = (windowW - 320) + "px";
    $(".vbcart").show(0);
    if (isIE()) { $(".vbcart")[0].previousSibling.style.display = ""; }
    $(".vbcart_scroller").slideDown(500);
    $(".vbup").show(0);
    $(".vbdown").hide(0);
}

// ======================================================================	;
function hideVBCart() {
    setStyle("vbcart", "behavior", "");

    $(".vbcart").hide(0);
    if (isIE()) { $(".vbcart")[0].previousSibling.style.display = "none"; }
    
    $(".vbcart_scroller").hide(0);
    $(".vbup").hide(0);
    $(".vbdown").show(0);
}

// scrapemalls has to be copied to a site! (like PIE.htc)


// ======================================================================	;
function malsCheckout() {

    a = document.location + " ";

    // 1) empty the cart, if any: submit the form to an iframe, put it in th

    gebi("malsform").target = "malwin";
    gebi("malsform").action = "scrapemals.php?url=http://" + mal_server + ".aitsafe.com/cf/addmulti.cfm&mal_server=" + mal_server;

    adiv = gebi("forminputs");
    adiv.innerHTML = "";
    var i = 0;
    jQuery(".itemName").each(function() {

        if (i > 0) {
            inp = document.createElement("input");
            adiv.appendChild(inp);
            inp.name = "product" + i;
            inp.value = this.innerHTML;

            quantity = parseInt(jQuery(".itemQuantity")[i].childNodes[0].value, 10);
            inp = document.createElement("input");
            adiv.appendChild(inp);
            inp.name = "qty" + i;
            inp.value = quantity;

            inp = document.createElement("input");
            adiv.appendChild(inp);
            inp.name = "price" + i;
            price = jQuery(".itemTotal")[i].innerHTML;
            price = replace(replace(replace(price, vbase_currency, ""), ",", ""), " ", "");
            inp.value = price / quantity;


        }

        i++;
    });

    gebi("malsform").submit();
    simpleCart.empty();

}

// ======================================================================	;
function emptyCart() {

    // seems impossible to empty the cart (mals)
    malwin = window.open("about:blank", "malwin");
    
    // we take malsform, change the action to a hidden iframe
    gebi("malsform").action = "scrapemals.php?url=http://" + mal_server + ".aitsafe.com/cf/addmulti.cfm&action=getform&mal_server=" + mal_server;
    gebi("malsform").target = "hif";
    gebi("malsform").submit();  // when loaded , it will call emtycart2

}

// ======================================================================	;
function emptyCart2(data) {

    // we come here after

    gebi("malshtml").innerHTML = jQuery('.hif').contents()[0].body.innerHTML;
    jQuery(".malshtml").find("input[name^='itemquant']").val(0);
    a = jQuery(".malshtml").find("form")[0];
    if (a) {   // if the cart is empty, then there is no form
        a.action = "scrapemals.php?url=http://" + mal_server + ".aitsafe.com/cf/recalc.pht&action=empty&mal_server=" + mal_server;
        a.target = "hif";
        a.submit();
    }
    else {
        malsCheckout();
    }

}
var malwin;



// ======================================================================	;
function emailCheckout() {

    grandtotal = 0;
    var i = 0;
    val = lab_order_by_email + ": \n\n";
    jQuery(".itemContainer").find(".itemName").each(function() {

        product = this.innerHTML;
        quantity = jQuery(".itemContainer").find(".itemQuantity")[i].childNodes[0].value;

        price = jQuery(".itemContainer").find(".itemTotal")[i].innerHTML;
        price = replace(price, vbase_currency, "");
        price = replace(price, " ", "");
        price = replace(price, ",", "");
        total = price;
        price = (price / quantity).toFixed(decimals);

        grandtotal = grandtotal + (total * 1);
        val = val + "-- " + product + " " + quantity + " @ " + vbase_currency + " " + addCommas(price) + " = " + vbase_currency + " " + addCommas(total) + "\n\n";
        i++;


    });
    grandtotal = grandtotal.toFixed(decimals);
    val = val + lab_total + ": " + vbase_currency + " " + addCommas(grandtotal);

    atarget = "content";
    if ((atarget === "modal2") && (gebi("modal2_holder").style.display !== "block")) { showModal(2, "", false, true); }

    lab_message = val + "\n\n" + lab_additional_info + ":\n\n";
    val = encodeURIComponent(val + "\n\n" + lab_additional_info + ":\n\n");

    var data = initData();
    extra = "";

    if (forceRemote) { extra = extra + "&forceremote=1"; }
    data[4] = "emailform.asp?site_key=" + site_key + "&body=" + val + "&subject=" + lab_order_by_email + "&r=" + Math.random();
    data[2] = "content";
    showNodeCallBack(data, "showcart1");

    simpleCart.empty();
}

// ===================================================================== not used
function deleteSimpleCartCookies() {
    var cookies = document.cookie.split(";");
    var i;
    for (i = 0; i < cookies.length; i++) {
        name = cookies[i].split("=")[0];
        if (name.find("simpleCart")) {alert(name);eraseCookie(name);}
    }
}

//  ==========================================================================
function stopRotators(target) {
    $("#" + target + " .rotator").each(function() {
        clearTimeout(this.timeoutHandle);
        this.onload = "";
        $(this).stop(true, true).css("opacity", 1);
    });
}
//  ==========================================================================
function startRotators(target) {
    $("#" + target + " .rotator").each(function() {
        var atime = this.src.split("time=")[1];
        if ((atime) && (typeof atime !== 'undefined')) { atime = atime.split("&")[0] * 1000; } else { atime = 5000; }
        rotate(this, atime);
    });
}

// ===================================================================== not used
function rotate(img1, time) {

    if (img1) {
        clearTimeout(img1.timeoutHandle)
        var asrc = img1.src
        if (asrc.indexOf("&r=") !== -1) { asrc = asrc.substr(0, asrc.indexOf("&r=")); }
        if (asrc.indexOf("&r=") === -1) { asrc = asrc + "&r=" + Math.random(); }
        
        var img2 = document.createElement("img")
        img2.onload = function() {
            if ((img1) && (img1.parentNode)) {
                $(img2).animate({ opacity: 1 }, 500)
                $(img1).animate({ opacity: 0 }, 500, function() {
                    img1.parentNode.replaceChild(img2, img1)
                    img2.style.position = "relative"
                    img2.style.top = 0
                    img2.style.left = 0
                    img2.style.position = "relative"
                    img2.className = img1.className
                    img2.timeoutHandle = setTimeout(function() { rotate(img2, time) }, time)
                })
            }
        }
        img2.src = asrc
        $(img2).css("opacity", 0)
        document.body.appendChild(img2)
        if (img1.parentNode) {
            img1.parentNode.appendChild(img2)
            img2.style.position = "absolute"
            img2.style.top = getStyleProp(img1.parentNode, "paddingTop")
            img2.style.left = getStyleProp(img1.parentNode, "paddingLeft")
        }
    }
}
