//

// alert("caller is " + arguments.callee.caller.toString());


// vbasepath:   always 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 useAssets = false;
var timer = new Date();

var styleIndex = [];  //index for a style in theRules of stylesheet. this is 3x faster then cycling through the rules

var rcounter = 0;

var imgArray = [];
var imgArrayCounter = 0;

var saveScrollTop;
var curpic;
var lastTarget;
var psSrc;  // source of productshowmanager;

var mouseIsDown = false;
var imgArray2 = [];
var imgArrayCounter2 = 0;

// var userloggedin=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_c;
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 pageColor = "";
var bodyColor = "";

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 piclensTarget = "";

var isExternal = [];
isExternal.top = false;
isExternal.bottom = false;
isExternal.left = false;
isExternal.right = false;
isExternal.content = false;
isExternal.modal = false;
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 rounding = [];

var objects = "slideshowbackground|slideshowheader|slideshowstart|modal|modal_holder|modal2|modal2_holder|left|right|top|bottom|content_outer|content_scroller|content|body|page|navholdertable|navholder|chapter|link|sublink_container|sublink|chapter_first|link_first|chapter_last|link_last|adminbutton|linktop|linkleft|linkright|linkbottom|linkcontent|linkmodal|linkmodal2|backup|example|";
objects = objects + "productheader|producttext|productholder|productpicture|productbackground|emailbody|adminbutton|vglider|vbar|";
objects = objects + "vglider_right_scroller|vbar_right_scroller|";
objects = objects + "vglider_left_scroller|vbar_left_scroller|";
objects = objects + "vglider_content_scroller|vbar_content_scroller|";
objects = objects + "vglider_modal_scroller|vbar_modal_scroller|";
objects = objects + "vglider_modal2_scroller|vbar_modal2_scroller|";
//objects=objectoundings+"vglider_document_body|vbar_document_body|";
objects = objects + "slideholder|imagecontent|imageright|imageleft|imagetop|imagemodal|imagemodal2|picture_holder|navdragger|navcontenttable|";
objects = objects + "buynow|checkcart|qty|productpr|caption_holder|toolbox|";
objects = objects + "gbtopictext|gbcommenttext|gbcommentseperator|gbcomment|gbcommentheader|gbtopic|gbtopicheader|gbtopicholder|gbpage|gbnavigation|gbsubject|gbtopicseperator|hr|vbaselink|searchspan|gbbutton|";
objects = objects + "aux1|aux2|aux3|aux4|aux5|aux6|aux7|aux8|aux9|aux10|";
objects = objects + "pageleft_spacer|pageright_spacer|top1_spacer|top2_spacer|bottom1_spacer|bottom2_spacer|left1_spacer|left2_spacer|right1_spacer|right2_spacer|printfriendly|modified|test|";
objects = objects + "style1|style2|style3|style4|style5|style6|style7|style8|style9|style10|";
objects = objects + "vbar_aux1_scroller|vglider_aux1_scroller|gbbutton|fieldset";

var vBaseObjects = objects.split("|");

var navObjects = "navholder|chapter|link|sublink_container|sublink|chapter_first|link_first|chapter_last|link_last".split("|");

rounding.backup = "";

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);
};

//=======================================================;
function init() {
    readStyles();
    if ((vbaseroot === vbasedomain) || (vbasedomain.indexOf("localhost") !== -1)) {
        sameDomain = true;
    }

    gebi("body").style.textAlign = "left"

    imagestuff("left");
    imagestuff("right");
    imagestuff("top");
    imagestuff("bottom");
    imagestuff("modal");
    imagestuff("content");

    gebi("pusername").value = getCookie("username");
    gebi("ppassword").value = getCookie("password");

    $("#top").bind("dblclick", function () { doubleclicked(this); });
    $("#left").bind("dblclick", function () { doubleclicked(this); });
    $("#right").bind("dblclick", function () { doubleclicked(this); });
    $("#bottom").bind("dblclick", function () { doubleclicked(this); });
    $("#content").bind("dblclick", function () { doubleclicked(this); });
    $("#modal").bind("dblclick", function () { doubleclicked(this); });
    $("#aux1").bind("dblclick", function () { doubleclicked(this); });
    $("#loginspan").bind("click", function () { login(); });

    if (product_id !== "") {
        var data = initData();
        var extra = "";
        if (forceRemote) { extra = extra + "&forceremote=1"; }
        data[4] = "productshow.asp?site_c=" + site_c + "&p_id=" + product_id + extra + "&startdate=" + startdate;
        data[2] = "modal";
        showNodeCallBack(data);
    }

    // at last load the navigation;
    navCallBack(navdata);
}

//=====================================;
function initData() {
    var data = [];
    for (var i = 0; i < 10; i++) {
        data[i] = "";
    }
    return data;

}

var nfields = 6; // amount of fields retrieved by the query;


// ======================================================================	;
function getNumParagraphs(chapter, data) {

    var numparagraph = 0;
    for (var j = 0; j < data.length; j = j + nfields) {
        var thispage = data[j + 2];
        if ((thispage === chapter) && (j < data.length - 2)) {
            for (var k = j + nfields; k < data.length; k = k + nfields) {
                thispage = data[k + 2];
                if (thispage.indexOf("_") !== -1) {
                    numparagraph++;
                }
                else {
                    return numparagraph;
                }
            }
        }
    }
    return numparagraph;
}



// ======================================================================	;
function getchapter(pointer, data) {
    //returns index of the array data;
    anindex = 0;
    for (var ic = 0; ic < data.length; ic = ic + nfields) {

        pageno = data[ic + 2];
        if (pageno.indexOf("_") === -1) {
            if (pointer === anindex) { return ic; }
            anindex++;
        }
    }
    alert("chapter not found:" + pointer);
}

//===================================================================================================;
function removeAuxClickedStates(who) {


    $("[id^=aux][class^=aux]").each(function () {
        var alist = this.className.split(" ");
        for (var i = 0; i < alist.length; i++) {
            if (alist[i].find("_clicked")) {
                $(this).removeClass(alist[i]);
            }
        }
    });
}

//===================================================================================================;
function removeClickedStates(what, includeAux, who) {
    if (includeAux) { removeAuxClickedStates("removeClicked"); }

    if ((what == "all") || (what === "link")) {
        //            $('a.acheader[@class*=_clicked]').each(function(){
        $("a.acheader[class*='_clicked']").each(function () {

            list = this.className.split(" ");
            for (var i = 0; i < list.length; i++) {
                if (list[i].indexOf("_clicked") !== -1) {

                    $(this).removeClass(list[i]);
                    if (this.roundingclicked) { $(this).removeClass(this.roundingclicked); }
                }
            }
        });
    }

    if ((what == "all") || (what === "sublink")) {
        $("#navholder .sublink[class*='_clicked']").each(function () {
            list = this.className.split(" ");
            for (var i = 0; i < list.length; i++) {
                if (list[i].indexOf("_clicked") !== -1) {
                    $(this).removeClass(list[i]);
                    if (this.roundingclicked) { $(this).removeClass(this.roundingclicked); }
                }
            }
        });
    }
}

//===================================================================================================;
function accordion(who) {
    //return
    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) {

    //gebi("document_body").scrollTop=0;

    document.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"


        //setStyle("document_body",'overflow','auto');
        //setStyle("document_body",'overflowY','auto');
        //setStyle("document_body",'overflowX','hidden');
        haveScrollbar = false;
    }
}

//=======================================================;
function rgb2hex(value) {
    var hex = "", v, h, i;
    var regexp = /([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)/;
    var h = regexp.exec(value);
    for (var 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) {
    if (taglist.find(";" + aname + ";")) { return aname; }
    return ("." + aname + state).toLowerCase();
}

//=======================================================;
function getRules() {

    theRules = [];
    if (document.styleSheets[1].cssRules) {
        return document.styleSheets[1].cssRules;
    }
    else if (document.styleSheets[1].rules) {
        return document.styleSheets[1].rules;
    }
    alert("rules not supported in this browser");
}

//=======================================================;
function report(stylename, returnString) {
    if (returnString) {
        sep = "<br>";
    }
    else {
        sep = "\n";
    }
    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) + sep;
    //s=s+"textheight: "+textHeight(stylename)+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 textHeight(id) {

    // returns the height of a pane, if not set to any height. rounding should be removed. there might be an inner pane _scroller;

    var a = getStyle(id, "height");
    var b = gebi(id).style.height;
    var c = getStyle(id, "overflowY");
    var d = gebi(id).style.overflowY;

    setStyle(id, "height", "");
    gebi(id).style.height = "";
    setStyle(id, "overflowY", "");
    gebi(id).style.overflowY = "";

    if (gebi(id + "_scroller")) {
        var e = getStyle(id + "_scroller", "height");
        var f = gebi(id + "_scroller").style.height;
        var g = getStyle(id + "_scroller", "overflowY");
        var h = gebi(id + "_scroller").style.overflowY;

        setStyle(id + "_scroller", "height", "");
        gebi(id + "_scroller").style.height = "";
        setStyle(id + "_scroller", "overflowY", "");
        gebi(id + "_scroller").style.overflowY = "";

    }

    // otherwise an image with css float will not be calculated
    gebi(id).style.overflow = "hidden";

    //gebi(id).style.border="1px solid #ffff00"
    var i = gebi(id).offsetHeight;
   // alert(id+": "+i)
    setStyle(id, "height", a);
    gebi(id).style.height = b;
    setStyle(id, "overflowY", c);
    gebi(id).style.overflowY = d;

    if (gebi(id + "_scroller")) {
        setStyle(id + "_scroller", "height", e);
        gebi(id + "_scroller").style.height = f;
        setStyle(id + "_scroller", "overflowY", g);
        gebi(id + "_scroller").style.overflowY = h;
    }

    return i;
}

//=======================================================;
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 ((windowW !== currentWindowW) || (windowH !== currentWindowH)) {
        clearTimeout(resizeHandle);
        resizeHandle = setTimeout(function () {
            setVsize("all");
            if (onVBPageLoad) { onVBPageLoad(-1); }
            currentWindowW = windowW;
            currentWindowH = windowH;

        }, 500);
    }
    else {
    }
}

//=======================================================;
function hasScrollBar(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 getbackroundImageProp(target, prop) {
    //src="http://localhost/vbase/v156/test.php?file=rounded.php&corners="+r+"&borders=tlrb&borderwidth=1&ds="+ds+"&radius="+asize+"&w="+w+"&h="+h+"&bgc="+bgc+"&fgc="+fgc;
    var val = "";
    src = getStyle(target, "backgroundImage", true);
    if (src.indexOf("rounded.php") !== "") {
        alist = src.split("&");
        for (var i = 0; i < alist.length; i++) {
            if (alist[i].split("=")[0] === prop) {
                val = alist[i].split("=")[1];
                return val.toLowerCase();
            }
        }
    }
    return val;
}


// ======================================================================	;
function setcentered(flag) {
    if (flag) {
        var c = document.createElement("center");
        c.id = "vbcenter";
        //c.style.width="100%";
        //c.style.height="100%";
        gebi("body").insertBefore(c, gebi("page_holder"));
        c.appendChild(gebi("page_holder"));
        //setStyle("document_body","textAlign","center");  // doesn't work, still write it to use it as aflag;
        setStyle("body", "textAlign", "center");  // doesn't work, still write it to use it as aflag;
    }
    else {

        if (gebi("vbcenter")) {
            gebi("body").appendChild(gebi("page_holder"));
            gebi("body").removeChild(gebi("vbcenter"));
            //setStyle("document_body","textAlign","");
            setStyle("body", "textAlign", "");
        }

    }

}


// ======================================================================	;

function navpos(pane) {
    if (pane === "top") {
        $("#navcontenttable .chapter").css("display", "inline-block");

        for (var 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 (var 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 (getStyle(target, "backgroundColor") === "") {
        if (isIE()) {
            $("#"+target).css("filter", "");
        }
    }
}

//=============================================================;
function getPageAsJSON(url, acallback) {
    url = replace(url, "?", "&");
    if (acallback) {
        acallback = 'JFgetdata(' + acallback + ')';
        src = vbasepath + "getpageasjson.asp?url=" + url + "&callback=" + acallback;
    }
    else {
        src = url + "?1=1";
    }
    request = new JSONscriptRequest(src, "js");
    request.buildScriptTag();
    request.addScriptTag();
}

// ======================================================================	;
function showUpload(feid) {
    if (!feid) { feid = 'none'; }

    if (gebi('yesno')) { gebi('yesno').style.display = 'none'; }
    if ((mayFileupload) && (!mayImageupload)) {
        src = vbasepath + "tinybrowser/upload.php?type=file&" + feid + "=none&site_c=" + assets_site + "&id=" + md5Hash + "&vbasepath=" + vbasepath + "#docloc=" + encodeURIComponent(document.location);
        showTiny(src);
    }
    else if ((!mayFileupload) && (mayImageupload)) {
        src = vbasepath + "tinybrowser/upload.php?type=image&" + feid + "=none&site_c=" + assets_site + "&id=" + md5Hash + "&vbasepath=" + vbasepath + "#docloc=" + encodeURIComponent(document.location);
        showTiny(src);

    }
    else {
        if (gebi('yesno')) {
            gebi("yesno").style.display = "";
            setcenter("yesno", "screen");
            gebi("yesno").style.display = "none";

            $("#yesno").fadeIn(500);

        }
    }
}

var instance = 0;
var tinyZindex = 11002;
// ======================================================================	;

function showTinyB(src) {
    tinyZindex = tinyZindex + 10;
    var caption = "vBase";
    if (src.find("type=image")) { caption = "vBase Image Browser"; }

    if (tinyBrowserWrapperRef) {
        tinyBrowserWrapperRef.show();
        gebi("tinyBrowserWrapper").style.zIndex = tinyZindex;
        tinyBrowserWrapperRef.moveTo("middle", "middle");

        tinyBrowserWrapperRef.onclose = function () {
            tinyBrowserWrapperRef = false;
            return true;
        };
    }

    else {
        instance++;
        tinyBrowserWrapperRef = dhtmlwindow.open(tinyZindex, "tinyBrowserWrapper", "iframe", src, caption, "width=700px,height=" + (windowH - 50) + "px,resize=1,scrolling=1,center=1");

        tinyBrowserWrapperRef.onclose = function () {
            tinyBrowserWrapperRef = false;
            return true;
        };
    }
}



// ======================================================================	;
function showTiny(src) {

    try {
        imageBrowser.focus();
    }
    catch (err) {
        imageBrowser = window.open(src, "xyz", "fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=yes,width=800,height=500");
    }
}



// ======================================================================	;
function showUpload2(type) {
    //alert("showUpload2")

    gebi('yesno').style.display = 'none';
    if (type === "f") {
        src = vbasepath + "tinybrowser/upload.php?type=file&feid=none&site_c=" + assets_site + "&id=" + md5Hash + "&vbasepath=" + vbasepath + "#docloc=" + encodeURIComponent(document.location);
    }
    else {
        src = vbasepath + "tinybrowser/upload.php?type=image&feid=none&site_c=" + assets_site + "&id=" + md5Hash + "&vbasepath=" + vbasepath + "#docloc=" + encodeURIComponent(document.location);
    }
    showTiny(src);
}

// ======================================================================	;
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 function 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");

    listLength = alist.length;

    for (var i = 0; i < listLength; i++) {
        var a = alist[i];
        if ((a.href !== "") && (a.href !== "http://vbaseworks.com") && (a.id !== "vbaselink")) {

            // 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 = "";
            //var linkname=a.childNodes;
            linkId++;

            if (!linkInnerIsImage) {

                var aspan = document.createElement("span");
                aspan.style.display = "inline-block";  // without this can't assign a height;
                //aspan.style.verticalAlign="middle";

                aspan.innerHTML = a.innerHTML;
                aspan.dropshadow = a.className;

                aspan.className = "link" + target;
                a.parentNode.insertBefore(aspan, a);
                $(aspan).hover(function () { $(this).addClass("link" + target + "_hover"); }, function () { $(this).removeClass("link" + target + "_hover"); });

            }
            else {
                var aspan = document.createElement("span");
                aspan.innerHTML = a.innerHTML;
                var innerspan = aspan.childNodes[0];

                if (innerspan.style) {

                    aspan.style.marginLeft = innerspan.style.marginLeft;
                    aspan.style.marginRight = innerspan.style.marginRight;
                    aspan.style.marginTop = innerspan.style.marginTop;
                    aspan.style.marginBottom = innerspan.style.marginBottom;

                    innerspan.style.marginLeft = "";
                    innerspan.style.marginRight = "";
                    innerspan.style.marginTop = "";
                    innerspan.style.marginBottom = "";

                    if (isIE()) {
                        aspan.style.styleFloat = innerspan.style.styleFloat; innerspan.style.styleFloat = "";
                    }
                    else {
                        aspan.style.cssFloat = innerspan.style.cssFloat; innerspan.style.cssFloat = "";
                    }
                    aspan.style.verticalAlign = innerspan.style.verticalAlign; innerspan.style.verticalAlign = "";
                }
                aspan.className = "imagelink";
                a.parentNode.insertBefore(aspan, a);

            }

            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://") {

                rest = a.href.substring(8);

                var content_c = rest.split("#")[0];
                content_c = replace(content_c, "/", ""); // 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];
                    aspan.id = "linkid" + linkId + "|" + content_c + "|" + ananchor + "|" + linktarget;
                }
                else {
                    aspan.id = "linkid" + linkId + "|" + content_c + "|" + ananchor;
                }

                aspan.onclick = function () {

                    thisId = this.id;

                    // Safari issue;

                    thisId = replace(thisId, "%23", "|");

                    ananchor = thisId.split("|")[2];
                    content_c = thisId.split("|")[1].toUpperCase();
                    if (thisId.split("|")[3]) {
                        ltarget = thisId.split("|")[3];
                    }
                    else {
                        ltarget = '';
                    }

                    showcart = false;
                    showproduct = false;
                    if (content_c.indexOf("VBASEPRODUCT:") !== -1) {
                        product_id = content_c.split(":")[1];
                        if (product_id === "0") {
                            showcart = true;
                        }
                        else {
                            showproduct = true;
                        }
                    }

                    var data = initData();

                    pageno = getPageNo(content_c);
                    if (pageno !== -1) {  // if -1 then the page is not part of the navigation;
                        setNav(content_c, "linkstuff");

                    }
                    if (showcart) {
                        if (ltarget === "") { ltarget = "modal2"; }
                        showWait(ltarget);

                        data[2] = ltarget;
                        data[4] = "http://" + mal_server + ".aitsafe.com/cf/review.cfm?userid=" + merchant_id + ""; // extern;
                        showNodeCallBack(data);
                    }
                    else if (showproduct) {
                        if (ltarget === "") { ltarget = "modal2"; }
                        showWait(ltarget);

                        var extra = "";
                        //if (forceRemote) {extra=extra + "&forceremote=1";}
                        data[4] = "productshow.asp?site_c=" + site_c + "&p_id=" + product_id + extra;
                        data[2] = ltarget;
                        showNodeCallBack(data);
                    }

                    else {
                        showNode(content_c, ltarget, ananchor);
                    }
                };
                a.style.display = "none";
                a.href = "";
            }
            else {

                aspan.id = linkId + "|" + (a.href);
                aspan.id = replace(aspan.id, "%20", " ");
                if (a.href.indexOf("mailto:") !== -1) {
                    aspan.onclick = function () {
                        win = window.open(this.id.split("|")[1]);
                        if (win && win.open && !win.closed) { win.close(); }
                    };
                }
                if (a.href.indexOf("javascript") !== -1) {
                    aspan.onclick = function () {
                        eval(this.id.split("|")[1]);
                    };
                }
                else if (linkTargetIsImage) {
                    // make sure we open it with showpic();
                    var prevsrc = "";
                    var nextsrc = "";
                    var imgid = "";
                    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; }
                    }
                    aspan.link = a.href;
                    aspan.prev = prevsrc;
                    aspan.next = nextsrc;
                    aspan.imgid = imgid;
                    aspan.tagable = tagable;
                    aspan.caption = caption;
                    isSlideFromSlideshow = false;
                    if (a.id.find("vbslide|")) { isSlideFromSlideshow = true; }
                    aspan.isSlideFromSlideshow = isSlideFromSlideshow;
                    aspan.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 windo. if switching to other language, open in same window;

                    if ((a.href.find("?lan=")) || (a.href.find("&lan="))) {
                        aspan.onclick = function () {
                            faderIn(2);
                            showWait("screen");
                            document.location = this.id.split("|")[1];
                        };
                    }
                    else if (a.href.find("noaction")) {
                    }
                    else {
                        aspan.onclick = function () { window.open(this.id.split("|")[1]); };
                    }

                }

                a.style.display = "none";
                a.href = "";

            }
        }
    }

    alist = gebi(target).getElementsByTagName("a");

    for (var i = 0; i < alist.length; i++) {
        var a = alist[i];
        if ((a.style.display === "none") && (a.id !== "vbaselink")) {
            removeNode(a);
            a = null;
            i--;
        }
    }



    if (isIE()) {

        // IE breakes 'inherit' over tables. Great...;

        var alist = gebi(target).getElementsByTagName("td");

        for (var 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");
        }
    }

    $("#vbaselink").removeClass("linkbottom");

    // look for JFormarama tags and process them
    // see documentation in JFormarama.js

    JFormaramaStuff(target);






}





// ======================================================================	;
function getParentStyle(obj, prop) {

    while (1) {
        if (getStyle(obj.className, prop) !== "") { return getStyle(obj.id, prop); }

        if (!obj.parentNode) { break; }
        obj = obj.parentNode;
    }
    return "";

}



// ======================================================================	;
function goToAnchor(atarget) {
    // jumpt to an anchor if jumpToAnchor is not empty;

    if (atarget === "") { atarget = "content"; }

    if (anchor[atarget] !== "") {

        ananchor = anchor[atarget];
        if (atarget === "content") {
            newtarget = "content_scroller";
        }
        else {
            newtarget = atarget + "_scroller";
        }

        alist = gebi(atarget).getElementsByTagName("a");
        for (var i = 0; i < alist.length; i++) {
            if (alist[i].name.toLowerCase() === ananchor.toLowerCase()) {
                if (!haveScrollbar) {
                    pos = findPosY(alist[i]);
                    $("body").animate({ scrollTop: pos }, 500);
                }
                else {
                    pos = findPosY(alist[i]) - findPosY(gebi(newtarget)) - 10;
                    //gebi("content_scroller").scrollTop=;
                    $("#" + newtarget).animate({ scrollTop: pos }, 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 showpic(href, caption, prev, next, imgid, spanid, isSlideFromSlideshow, tagable) {
    //isSlideFromSlideshow
    // spanid holds the id of the smaller image, imgid just the numeric id of the database;

    var startwidth;
    var startheight;
    var image;
    var asrc;
    var previmage;
    var nextimage;
    var ph = gebi("picture_holder");

    removeAllTags();

    gebi("prevbutton").style.display = "none";
    gebi("nextbutton").style.display = "none";


    if (gebi("caption_holder").style.visibility === "hidden") {

        saveScrollTop = gebi("content_scroller").scrollTop;
        ph.style.width = "150px";
        ph.style.height = "150px";
        startwidth = 150;
        startheight = 150;

        unround("picture_holder");
        if (getStyle("picture_holder", "backgroundColor") === "") { setStyle("picture_holder", "backgroundColor", "#ffffff"); }

        $("#fader2").unbind("click");

        gebi("piccenter").innerHTML = "";

        ph.style.display = "inline";
        $("#picture_holder").css("opacity", 1);
        gebi("caption_holder").style.width = 150;
        setcenter("picture_holder", "screen");
        ph.style.display = "none";


        $("#picture_holder").stop().fadeIn(500);


        showWait("screen");


        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(2, "#000000");

    }
    else {
        gebi("caption_holder").style.width = 150;
        setcenter("picture_holder", "screen");

        image = gebi("piccenter").childNodes[0];
        $(image).fadeOut(500);
        gebi("piccenter").removeChild(image);
        startwidth = noPx(gebi("picture_holder").style.width);
        startheight = noPx(gebi("picture_holder").style.height);
        showWait("screen");

    }

    gebi("imageId").value = imgid;



    gebi("caption_holder").innerHTML = caption + "&nbsp;";
    var captionHeight = getCaptionHeight(caption + "&nbsp;");

    gebi("tagme").style.display = "none";
    gebi("editCaption").style.display = "none";


    image.onload = function () {
        gebi("caption_holder").style.width = 400;

        gebi("closeicon").style.display = "";
        $(image).fadeIn(500);

        gebi("picture_holder").style.width = startwidth;


        var cw = max(noPx(image.width) + 20, 410);
        var ch = noPx(image.height) + 40 + captionHeight;
        var newleft = noPx(ph.style.left) - cw / 2 + (startwidth / 2);
        var newtop = noPx(ph.style.top) - ch / 2 + (startheight / 2);

        $("#picture_holder").animate({ width: cw, left: newleft, height: ch, top: newtop }, 500, function () {
            if (prev !== "") { previmage = new Image(); previmage.src = getImageSource(prev); gebi("prevbutton").style.display = ""; gebi("prevbutton").onclick = function () { gebi(prev).onclick(); }; }
            if (next !== "") { nextimage = new Image(); nextimage.src = getImageSource(next); gebi("nextbutton").style.display = ""; gebi("nextbutton").onclick = function () { gebi(next).onclick(); }; }

            gebi("caption_holder").style.visibility = "visible";

            if (isSlideFromSlideshow) { getTags(imgid); }

            gebi("piccenter").appendChild(image);

            $(image).animate({ opacity: 1 }, 1000);
            hideWait();
            round("picture_holder");
            picLeft = findPosX(gebi("currentpic"));
            picRight = picLeft + getscrollwidth("currentpic");

            picTop = findPosY(gebi("currentpic"));
            picBottom = picTop + getscrollheight("currentpic");
            $("#fader2").bind("click", function () { closepic(); });

            if (gebi("dragme")) {

                if (isSlideFromSlideshow) {
                    if ((passwordPassed) || (tagable === "True")) {
                        image.ondblclick = tagit;
                        gebi("tagme").style.display = "";
                    }
                }
            }
            if ((passwordPassed) && (isSlideFromSlideshow)) { gebi("editCaption").style.display = ""; }


        });
    };


    image.spanid = spanid;

    if (href.indexOf("picapic.asp") !== -1) {
        asrc = href + "&height=" + (windowH - 75) + "&width=" + (windowW - 75) + "&freeze=true";
    }
    else {
        asrc = remotePath + "image.php/myimage.jpg?image=" + encodeURIComponent(href) + "&height=" + (windowH - 75 - captionHeight) + "&width=" + (windowW - 75);
    }

    // check if picture is in stock;

    for (var i = 0; i < imgArray2.length; i++) {
        if (imgArray2[i].src === asrc) {
            if (imgArray2[i].width) {
                imgArray2[i].onload = image.onload;
                image = imgArray2[i];
                image.onload();

                return;
            }
            else {
                alert("failed");
            }


        }
    }
    image.src = asrc;

}






//=======================================================;
function getCaptionHeight(caption) {
    var newcaption = "&nbsp;";
    gebi("caption_holder").style.height = "";
    if (caption !== "") { newcaption = "&nbsp;"; }
    gebi("caphlpdiv").style.display = "";
    gebi("caption2_holder").innerHTML = newcaption;
    var captionHeight = gebi("caption2_holder").scrollHeight;
    gebi("caphlpdiv").style.display = "none";
    gebi("caption_holder").style.height = max(captionHeight, 25);
    return captionHeight;

}

//=======================================================;
function getImageSource(spanId) {

    // get's the source of a picture taking in acount the screen size;
    var aspan = gebi(spanId);
    var captionHeight = getCaptionHeight(aspan.caption);
    return remotePath + "image.php/myimage.jpg?image=" + encodeURIComponent(aspan.link) + "&height=" + (windowH - 75 - captionHeight) + "&width=" + (windowW - 75);
}

//=======================================================;
function closepic() {

    removeAllTags();
    if (gebi("currentpic")) { gebi("currentpic").onload = ""; }
    hideWait(); // just in case the picture didn't load;
    gebi("caption_holder").style.visibility = "hidden";
    $("#picture_holder").stop().fadeOut(500, function () { gebi("piccenter").innerHTML = ""; gebi("caption_holder").innerHTML = ""; });
    gebi("loginpane").style.display = "";
    faderOut(2);
    if (gebi("dragme")) { cancel_tag(); }

}

//=======================================================;
function noPx(aval) {
    if (aval === "") { return 0; }
    return parseInt(aval, 10);
}




//=======================================================;
function getStyleText(aname, ignoreState) {

    var styleName;
    if (ignoreState) {
        styleName = "." + aname;
    }
    else {
        styleName = getStyleName(aname);
    }

    apos = styleIndex[styleName];
    if ((apos) || (apos === 0)) {
        return theRules[apos].style.cssText;
    }
    else {
        return "";
    }

}

//=============================================================;
function isIE() {
    ua = navigator.userAgent.toLowerCase();
    if ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)) {
        return true;
    }
    return false;
}


//=============================================================;
function widthWaste(styleName) {
    if (isIE()) { return 0; }
    return getWidthStuff(styleName);
}

//=============================================================;
function heightWaste(styleName) {
    if (isIE()) { return 0; }
    return getHeightStuff(styleName);
}


//=============================================================;
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 marginsW(styleName) {
    ml = noPx(getStyle(styleName, "marginLeft"));
    mr = noPx(getStyle(styleName, "marginRight"));
    return ml + mr;
}
function marginsH(styleName) {

    mt = noPx(getStyle(styleName, "marginTop"));
    mb = noPx(getStyle(styleName, "marginBottom"));
    return mt + mb;

}
//=============================================================;
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;

// ======================================================================	;
function roundstuff(target) {
    return
    // if the div's don't have an id, set one;
    $("#" + target + " .rounded").each(function () {
        if (this.id === "") { this.id = "rdiv_" + divcounter; divcounter++; }
    });
    $("#" + target + " .rounded_small").each(function () {
        if (this.id === "") { this.id = "rdiv_" + divcounter; divcounter++; }
    });
    $("#" + target + " .rounded_normal").each(function () {
        if (this.id === "") { this.id = "rdiv_" + divcounter; divcounter++; }
    });
    $("#" + target + " .rounded_big").each(function () {
        if (this.id === "") { this.id = "rdiv_" + divcounter; divcounter++; }
    });
    if ($("#" + target + " .rounded").length > 0) { round("rounded"); }
    if ($("#" + target + " .rounded_small").length > 0) { round("rounded_small"); }
    if ($("#" + target + " .rounded_normal").length > 0) { round("rounded_normal"); }
    if ($("#" + target + " .rounded_big").length > 0) { round("rounded_big"); }

}

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;

    if (isproducttext) {
        var alist = $(".producttext img");
    }
    else {
        var alist = gebi(target).getElementsByTagName("img");
    }
    for (var i = 0; i < alist.length; i++) {

        var img = alist[i];


        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;", "&");
        }

        //asrc=replace(asrc,"http://vbaseworks.com/","http://localhost/vbase/")

        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/myimage.jpg?image=" + encodeURIComponent(asrc) + w + h + cr;

                    img.src = newsrc;
                    img.id = "img_" + imgID;
                    imgID++;
                }
                //img.src=asrc;

            }
            else {
                img.src = asrc;
            }
        }
        else {
            img.src = asrc;
            img.id = img.src + "&rotorId=" + rotorId;
            rotorId++;
        }

        if (img.src.indexOf("print_friendly") === -1) {
            var aspan = document.createElement("span");
            //var txt=document.createElement("text");
            //txt.innerHTML="<br>"+img.src

            img.parentNode.insertBefore(aspan, img);

            aspan.appendChild(img);

            aspan.style.position = "relative";

            if (img.hspace === -1) { img.hspace = ""; }
            if (img.vspace === -1) { img.vspace = ""; }


            aspan.style.marginLeft = img.hspace;
            aspan.style.marginRight = img.hspace;
            aspan.style.marginTop = img.vspace;
            aspan.style.marginBottom = img.vspace;

            img.vspace = "";
            img.hspace = "";

            if (img.style.marginLeft !== "") { aspan.style.marginLeft = img.style.marginLeft; }
            if (img.style.marginRight !== "") { aspan.style.marginRight = img.style.marginRight; }
            if (img.style.marginTop !== "") { aspan.style.marginTop = img.style.marginTop; }
            if (img.style.marginBottom !== "") { aspan.style.marginBottom = img.style.marginBottom; }

            img.style.margin = 0;

            aspan.style.display = "inline-block";
            aspan.style.position = "relative";

            if ((img.align === "left") || (img.align === "right")) {
                if (isIE()) {
                    aspan.style.styleFloat = img.align;
                }
                else {

                    aspan.style.cssFloat = img.align;
                }
            }
            img.align = "";

            aspan.className = aspan.className + " " + "image" + target;
            aspan.dropshadow = img.className;
        }

    }

}

// ======================================================================	;
function stopRotators(target) {

    var alist = gebi(target).getElementsByTagName("img");

    for (var i = 0; i < alist.length; i++) {
        var img = alist[i];
        if (img.src.indexOf("picapic.asp") !== -1) {
            clearTimeout(img.timeoutHandle);
            img.isloaded = false;
            img.onload = "";
            if (gebi(img.id + "_rotator")) {
                gebi(img.id + "_rotator").isLoaded = false;
                gebi(img.id + "_rotator").onload = "";

            }
            $(img).stop().css("opacity", 1);

        }
    }

}

//  ==========================================================================
function startRotators(target) {
    var alist = gebi(target).getElementsByTagName("img");
    for (var i = 0; i < alist.length; i++) {
        var img = alist[i];
        if (img.id.indexOf("_rotator") === -1) {
            if (img.src.indexOf("picapic.asp") !== -1) {
                img.target = target;
                atime = img.src.split("time=")[1];
                if ((atime) && (typeof atime !== 'undefined')) { atime = atime.split("&")[0] * 1000; } else { atime = 5000; }

                img.time = atime;

                a = function (img) {
                    return function () {
                        setTimeout(function () { rotate(img.id, img.target, atime); }, img.time * 1)
                    };
                } (img);  //closure!

                $(img).bind("load", a);

            }
        }
    }
}

//=======================================================;
function isSwapped(id) {
    if (trim(gebi(id + "_holder").innerHTML) === "") { return true; }
    return false;
}




//  ==========================================================================
function restartRotator(id) {
    return;
    if (gebi(id).isFrozen) {
        gebi(id).isFrozen = false;

        if (gebi(id).isLoaded) {
            rotate(id);
        }
        else {
            rotate(id + "_rotator");
        }
    }
}
//  ==========================================================================
function freezeRotator(id) {
    return;
    clearTimeout(gebi(id).timeoutHandle);
    gebi(id).isFrozen = true;
    gebi(id).onload = "";
    if (gebi(id + "_rotator")) { gebi(id + "_rotator").onload = ""; }

}

//  ==========================================================================
function rotate(who, target, atime) {
    //alert(target)
    var base = who;
    if (base.indexOf("_rotator") !== -1) { base = base.substr(0, base.indexOf("_rotator")); }
    var rotator = base + "_rotator";

    if (gebi(base)) { // maybe the page doesn't exist anymore
        var b = gebi(base);
        $(b).unbind("load");
        var origsrc = gebi(base).src;
        var src = origsrc;
        if (src.indexOf("&r=") !== -1) { src = src.substr(0, src.indexOf("&r=")); }
        if (src.indexOf("&r=") === -1) { src = src + "&r=" + Math.random(); }

        if (!gebi(rotator)) {
            var newimage = $(b).clone(true)[0];
            newimage.src = null
            newimage.style.position = "absolute";

            newimage.style.top = findPosY(b) - findPosY(b.parentNode);
            newimage.style.left = findPosX(b) - findPosX(b.parentNode);

            newimage.id = rotator;
            $(newimage).css("opacity", 0);
            gebi(base).parentNode.appendChild(newimage);
            newimage.onmouseover = function () { freezeRotator(base); };
            newimage.onmouseout = function () { restartRotator(base); };

        }
        var r = gebi(rotator);

        if (b.isFrozen) {

            gebi("msg").innerHTML = "frozen";
            return;
        }
        //alert(b.time)

        clearTimeout(b.timeoutHandle);
        // alert(who)
        if (who === base) {

            r.onload = function () {
                //alert("loaded")
                b.timeoutHandle = setTimeout(function () { rotate(rotator, target, atime); }, atime);
                b.isLoaded = false;
                r.isLoaded = true;

                if ((r.width !== b.width) || (r.height !== b.height)) {
                    $(b).animate({ opacity: 0 }, 250, function () { $(r).animate({ opacity: 1 }, 250); });
                }
                else {
                    $(r).animate({ opacity: 1 }, 500, function () { $(b).css("opacity", 0); });

                }
            };
            r.src = src;

        }
        else {

            b.onload = function () {
                //alert("loaded")
                b.timeoutHandle = setTimeout(function () { rotate(base, target, atime); }, atime);
                r.isLoaded = false;
                b.isLoaded = true;

                if ((r.width !== b.width) || (r.height !== b.height)) {
                    $(r).animate({ opacity: 0 }, 250, function () { $(b).animate({ opacity: 1 }, 250); });
                }
                else {
                    //alert("b")
                    $(b).css("opacity", 1) //below
                    $(r).animate({ opacity: 0 }, 500)
                    //$(b).animate({opacity:1},500,function(){$(r).css("opacity",0);});
                }
            };
            b.src = src;


        } // JScript File


    }
}


//  =============================================================================;
function getJson(type, callback, content_c, target, panchor, assets_site) {
    // type should be 'nav','content' or 'panes';

    callback = 'JFgetdata(' + callback + ')';
    extra = "";
    if (content_c !== "") {
        extra = "&content_c=" + content_c;
    }
    if (target !== "") {
        extra = extra + "&target=" + target;
    }
    if (panchor !== "") {
        extra = extra + "&anchor=" + panchor;
    }
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    if ((type === "slideshows") || (type === "products")) {
        src = vbasepath + "getjson.asp?r=" + Math.random() + "&site_c=" + assets_site + "&type=" + type + "&callback=" + callback + extra;
    }
    else {
        src = vbasepath + "getjson.asp?r=" + Math.random() + "&site_c=" + site_c + "&type=" + type + "&callback=" + callback + extra;
    }

    request = new JSONscriptRequest(src, "js");
    request.buildScriptTag();
    request.addScriptTag();
}

// ======================================================================	;
function JFgetdata(callback, jsonstuff) {

    var j = 0;
    var myarray = [];
    for (var i = 0; i < jsonstuff.items.length; i++) {
        var rec = jsonstuff.items[i];
        for (var 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(id, atarget, ananchor, doNotCheckPiggyBack) {
    lastId = id;
    lastTarget = atarget;
    for (var i = 1; i < 11; i++) {
        if (gebi("aux" + i).shownode === id) {
            removeAuxClickedStates("shownode");
            $("#aux" + i).addClass(gebi("aux" + i).roundingclicked);
        }
    }


    if (atarget === "modal") {
        lastNodeShowed = id;
    }
    else {
        lastNodeShowed = id;
    }

    if (lastNodeShowed) {
        closeModal(1);
        closeModal(2);
    }



    // 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 (gebi("modal_holder").style.display="block");

    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) {
        if ((piggyBack[id] === '') || (piggyBack[id])) {
            if (piggyBack[id] !== '') {
                var alist = piggyBack[id].split(",");
                var atargetlist = piggyTarget[id].split(",");
                for (var i = 0; i < alist.length - 1; i++) {
                    showNode(alist[i], atargetlist[i], "", true); // do not check for piggybacks on piggybacks;
                }
            }
        }
        else {

            getJson("piggyback", "piggybackCallback", id, "", "");

        }
    }
    // check if the page is already loaded, if so, skip;
    var skip = false;
    //alert(id+"\n"+contentIds[atarget])
    if (!contentIds[atarget]) { contentIds[atarget] = "-1" }
    if (id.toUpperCase() === contentIds[atarget].toUpperCase()) { skip = true; }
    //alert(skip)
    if (!skip) {
        //gets the content of the page when clicked on a nav div;
        showEditStuff();



        // if atarget is empty (this happens when a link in a page points to target=default), then jQuery throws an exception;
        if (atarget !== "") {
            if (isIE()) {
                $("#" + atarget + " img").css("visibility", "hidden");
            }
            $("#" + atarget).stop().animate({ opacity: 0 }, 500);
        }

        if (atarget === "") {
            showWait("content");
        }
        else if (atarget === "modal") {
            showWait("screen");
        }
        else {
            showWait(atarget);
        }
        //setTimeout(function(){getJson("content","showNodeCallBack",id,atarget,ananchor);},2000);
        getJson("content", "showNodeCallBack", id, atarget, ananchor);
    }


}

var piggyBack = [];  // array of ID's to load with a page;
var piggyTarget = []; // array of targets;

// ======================================================================	;
function piggybackCallback(pdata) {

    var original_page = pdata[5];
    piggyBack[original_page] = '';
    piggyTarget[original_page] = '';

    for (var 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_c,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[original_page] = piggyBack[original_page] + newdata[3] + ",";
            piggyTarget[original_page] = piggyTarget[original_page] + newdata[2] + ",";
        }
    }
}

// ========================================================================;
function showNodeCallBack(data) {

    if (beforeVBPageLoad) { beforeVBPageLoad(); }

    //data contains: content,page_no,target, content_c , external,anchor;
    var myhtml = data[0];
    var target = data[2];
    var id = data[3];
    var extern = data[4];
    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")) {
        if (gebi("modal_holder").style.display === "block") { closeModal(1, true); }
    }
    gebi("left_holder").style.display = "";
    gebi("right_holder").style.display = "";
    gebi("navdragger").style.display = "";
    gebi("top_holder").style.display = "";

    //if (target==='content') {
    //    if ((getStyle("document_body","overflow")==="hidden") || (getStyle("document_body","overflowY")==="hidden")) {
    //        setScroll('content');
    //        haveScrollbar=true;
    //    }
    //    else {
    //         setScroll('window');
    //        haveScrollbar=false;
    //     }
    //  }

    var doit = false;
    if (extern !== "") {
        isExternal[target] = extern;
        if (extern.indexOf("calendar.asp") !== -1) {

            //calendar.asp?site_c=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 ((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("ss_piclens") !== -1) || (extern.indexOf("ps.asp") !== -1) || (extern.indexOf("email.asp") !== -1) || (extern.indexOf("emaillist.asp") !== -1)) {
            if (extern.find("guestbook.asp")) { guestbookTarget = target; }
            // extern:  slideshow.asp?site_c=123&ss_id=abc;

            extern = replace(extern, "slideshow.asp?", vbaseroot + "?relay=slideshow.asp&usermd5=" + gbmd5_tags + "&");
            extern = replace(extern, "guestbook.asp?", vbasedomain + "?relay=guestbook.asp&");
            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"; }
            extern = extern + version;
            if (md5Hash !== "") { extern = extern + "&id=" + md5Hash; }
            extern = extern + "&rnd=" + Math.random();
            if (extern.find("productshow.asp")) { extern = extern + "&mal_server=" + mal_server + "&merchant_id=" + merchant_id; }
            if ((extern.indexOf("slideshow.asp") !== -1) && (!tagsloggedin)) { extern = extern + "&taglogout=1"; }

            // external page, however we need to inject the HTML in the main body, as opposed to using a iframe.;
            // the iframe cannot commucicate with vBase when used cross-domain, like embropatch.com;
            if ((target === "modal") && (gebi("modal_holder").style.display !== "block")) { showModal(1, false, true); }

            piclensTarget = target;
            if ((piclensTarget === "modal") && (gebi("modal_holder").style.display !== "block")) { showModal(1, false, true); }
            if ((piclensTarget === "modal2") && (gebi("modal2_holder").style.display !== "block")) { showModal(2, false, true); }

            //jQuery.getJSON(extern+"&callback=?", function(data){JFgetdata(picLensCallback,data);});
            if (sameDomain) {
                //http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316451;
                $.get(extern, function (data) { picLensCallback(data); });
            }
            else {
                //$.get(extern,function(data){picLensCallback(data);});
                getPageAsJSON(extern, "picLensCallback");
            }
        }
        else {
            //gebi(target).innerHTML=myhtml;
            myhtml = myhtml + "<iframe  name=extif  id=extif scrolling='auto'  frameborder='0' src='" + extern + "' style='background-color:#ffffff;border-width: 0px; margin: 0px; padding: 0px;'>";
            doit = true;
        }
    }
    else {
        isExternal[target] = false;
        doit = true;
    }
    if (doit) {

        $("#" + target).stop();
        if ((target === "modal") && (gebi("modal_holder").style.display !== "block")) { showModal(1, false, true); }
        if ((target === "modal2") && (gebi("modal2_holder").style.display !== "block")) { showModal(2, false, true); }
        if (myhtml) {
            if (!isIE()) {

                //myhtml=replace(myhtml,"<img ","<img style=visibility:hidden onload=\"$(this).css('opacity',0).css('visibility','visible').animate({opacity:1},500)\" ");
            }
            else {
                //myhtml=replace(myhtml,"<img ","<img onload=\"$(this).css('visibility','visible')\" ");
            }
        }

        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>";
            }
        }
        stopRotators(target);
        gebi(target).innerHTML = "";
        gebi(target).innerHTML = myhtml;

        //      all links invisible;
        var alist = gebi(target).getElementsByTagName("a");
        for (var i = 0; i < alist.length; i++) {
            if (alist[i].name === "") {
                alist[i].style.visibility = "hidden";
            }
        }

        roundstuff(target);
        imagestuff(target);
        $("#" + target).css("opacity", 1);
        startRotators(target);

        linkstuff(target);

        if (!target.find("modal")) { // modal will round itself after animation;
            round("link" + target);
        }


        round("image" + target);
        for (var i = 1; i < 11; i++) {
            round('style' + i);
        }
        if (onVBPageLoad) { onVBPageLoad(id); }

        hideWait();
        if (!target.find("modal")) { setIframeSize(target) };
        //$("#"+target).stop().css("opacity",1)
        $("#" + target).stop().animate({ opacity: 1 }, 500, function () {
            fixIEBlur(target);
        });

        if (target !== "modal") {
            if (haveScrollbar) {
                setVsize(target);
            }
            else {
                setVsize("all");
            }
        }
        goToAnchor(target);


    }

}
// ======================================================================	;
function setIframeSize(target) {

    getDimensions()
    if (gebi(target).getElementsByTagName("iframe").length !== 0) {
        theframe = gebi(target).getElementsByTagName("iframe")[0];
        var src = theframe.src + " ";

        var ifh = false;
        ipos = src.indexOf("ifh=");
        if (ipos !== -1) {
            src = src.substr(ipos + 4);
            ifh = src.split("&")[0];
        }

        if ((theframe.id !== "gbhif") && (theframe.id !== "shif")) {

            // calculate the extraheight by removing the iframe, calculate the text height and put the iframe back

            aplaceholder = document.createElement("span");

            theframe.style.display = "none"

            pt = getStyle(target, "paddingTop")
            pb = getStyle(target, "paddingBottom")
            setStyle(target, "paddingTop", "")
            setStyle(target, "paddingBottom", "")
            
            var eh = textHeight(target);
            setStyle(target, "paddingTop", pt)
            setStyle(target, "paddingBottom", pb)


            //alert(gebi(target).innerHTML)
            //alert(eh)
            //alert(getHeightStuff(target))
            //if (eh === 0) { eh = eh + getHeightStuff(target) }
            theframe.style.display = ""
            // done

            if (target === "content") { tw = contentWidth - getWidthStuff("content") }
            if (target === "content") { noScrollHeight = contentHeight - eh - getHeightStuff("content") ; }   

            if (target.find("modal")) { tw = getModalWidth() - getWidthStuff("modal_holder") - getWidthStuff("modal")- widthWaste("modal") }
            if (target.find("modal")) { noScrollHeight = getModalHeight() - getHeightStuff("modal_holder") - heightWaste("modal")-eh - 22 }; // 22 is for the close buttom; }  

            if (target.find("modal")) { noScrollHeight = noPx(gebi("modal").style.height) - heightWaste("modal") - eh }; // 22 is for the close buttom; }  

            //gebi("modal" + anum).style.height = getModalHeight(maxsize) - getHeightStuff("modal" + anum + "_holder") - heightWaste("modal") - 22;
           // gebi("modal" + anum).style.width = getModalWidth(maxsize) - getWidthStuff("modal" + anum + "_holder") - widthWaste("modal");



            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"); }   

            theframe.style.display = "none";
            if (ifh) {
                theframe.style.height = (ifh * 1) -heightWaste(target) ; 
                if (ifh > noScrollHeight) {
                    theframe.style.width = tw - 16 - noPx(getStyle(target, "paddingRight")); // need space for scrollbar
                }
                else {
                    theframe.style.width = tw;
                }
            }
            else {
                theframe.style.height = noScrollHeight;
                theframe.style.width = tw;
            }

            theframe.style.display = "";
        }
    }
    //if (target.find("modal")) { initScroller2("modal_scroller"); }
}

// ======================================================================	;
function setNav(content_c, who) {

    if (!alwaysOpen) { return; }

    disableNavClick = true;

    var a = $("div [content_c^=" + content_c + "]")[0];
    if (a) {
        pageno = findAttribute(a, "pageno");
        mainid = pageno.split("_")[0];

        $(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") {
            $(gebi("navholder")).accordion("activate", mainid); // close the menu;
        }

    }

    disableNavClick = false;
}


// ======================================================================	;
function getPageNo(content_c) {
    pageno = -1;
    var a = $("div [content_c^=" + content_c + "]")[0];
    if (a) {
        pageno = findAttribute(a, "pageno");
    }
    return pageno;
}



// ======================================================================	;
function showLastPage() {
    if (lastPage === "00") {
        $(gebi("link_first")).trigger("click");
    }
    else if (lastPage === lastLinkId) {
        $(gebi("link_last")).trigger("click");
    }
    else {
        $(gebi("link_" + lastPage)).trigger("click");
    }
}

taglist = ";hr;li,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;


}

//=======================================================;
function setStyleText(aname, atext, ignoreState) {

    var styleName;
    if (ignoreState) {
        styleName = "." + aname;
    }
    else {
        styleName = getStyleName(aname);
    }

    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;

    }

}


//=======================================================;
function createStyle(name, property, value) {

    if ((value === "") && (property !== "")) { return; }
    var styleName = getStyleName(name);

    if (document.styleSheets[1].insertRule) { //if Firefox;
        //alert(property+" "+property.toDash())
        document.styleSheets[1].insertRule(styleName + " {" + property.toDash() + ":" + value + ";}", theRules.length);
    }
    else { //else if IE;
        document.styleSheets[1].addRule(styleName, property.toDash() + ":" + value);
    }
    theRules = getRules();
    styleIndex[styleName] = theRules.length - 1;

    return "";
}


//=======================================================;
function setStyle(aname, property, value, ignoreState, index) {

    if ((isIE()) && (buffer)) { setStyle2(aname, property, value, ignoreState, index); return; }
    var styleName;
    if (isNumeric(value)) { value = value + "px"; }
    if (taglist.find(";" + aname + ";")) {
        styleName = aname;
    }
    else {
        if (ignoreState) {
            styleName = "." + aname;
        }
        else {
            styleName = getStyleName(aname);
        }
    }


    apos = styleIndex[styleName];
    //alert(apos+" "+styleName+" "+property+" "+value)
    if ((apos) || (apos === 0)) {
        try {
            theRules[apos].style[property] = value;
        }
        catch (err) {
            //alert(aname + " " + property + " " + value)
            //alert("caller is " + arguments.callee.caller.toString())
        }
    }
    else {

        createStyle(aname, property, value);
    }

}

var bufferstring = ""
buffer = false
//=======================================================;
function setStyle2(aname, property, value, ignoreState, index) {

    if (ignoreState) { ignoreState = 1 }
    if (ignoreState === false) { ignoreState = 0 }
    if (typeof ignoreState === "undefined") { ignoreState = 0 }

    if (aname === "flush") {
        var text = (document.styleSheets[1].cssText + bufferstring).toLowerCase()
        var ar = text.split("}")
        //ar=unique(ar) // can go wrong!
        text = ""
        for (var i = 0; i < ar.length; i++) {
            text = text + ar[i] + "}"
        }
        document.styleSheets[1].cssText = text
        //gebi("content").innerHTML=text
        buffer = false
        bufferstring = ""
        indexStyle()

    }
    else {
        var styleName;
        if (isNumeric(value)) { value = value + "px"; }
        if (taglist.find(";" + aname + ";")) {
            styleName = aname;
        }
        else {
            if (ignoreState) {
                styleName = "." + aname;
            }
            else {
                styleName = getStyleName(aname);
            }
        }

        bufferstring = bufferstring + styleName + "{" + property + ":" + value + ";" + "} "

    }
}




var indexChanged;
var nchanged = 0;

//=======================================================;
function indexStyle() {
    styleIndex = [];
    var ruleLength = theRules.length;

    for (var i = 0; i < ruleLength; i++) {
        var styleName = theRules[i].selectorText.toLowerCase();
        styleIndex[styleName] = i;
    }
    indexChanged = false;
}

//=======================================================;
function getStyle(aname, property, ignoreState, index) {
    if (ignoreState) {
        var styleName = "." + aname;
    }
    else {
        var styleName = getStyleName(aname);
    }

    if (indexChanged) { nchanged++; indexStyle(); }

    if ((styleIndex[styleName]) || (styleIndex[styleName] === 0)) {
        astart = styleIndex[styleName];
        thestyle = theRules[astart].style[property].toLowerCase();
        if (thestyle.indexOf("rgb") !== -1) { thestyle = rgb2hex(thestyle); }
        return thestyle;

    }
    else {
        return "";
    }

}



// ======================================================================	;
function readStyles() {

    theRules = getRules();

    var ruleLength = theRules.length;

    for (var i = 0; i < theRules.length; i++) {
        var styleName = theRules[i].selectorText.toLowerCase();
        if (styleName.find("_scroller")) {
            if ((!styleName.find("vbar_")) && (!styleName.find("vglider_"))) {

                //alert(styleName)
                deleteStyleText(styleName);
                i--;

            }
        }
    }




    indexStyle();

    pageColor = getStyle("page", "backgroundColor");
    bodyColor = getStyle("body", "backgroundColor");

    th = noPx(getStyle("top", "height"));
    bh = noPx(getStyle("bottom", "height"));

    //gebi("top").style.height=th-heightWaste("top");
    //setStyle("top_holder","height",th);

    //gebi("bottom").style.height=bh-heightWaste("bottom");
    //setStyle("bottom_holder","height",bh);
    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 (var 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"); }

    }



    for (var icnt = 0; icnt < vBaseObjects.length; icnt++) {
        rounding[vBaseObjects[icnt]] = getPseudoStyle("rounding_" + vBaseObjects[icnt], "");
    }


    //gebi("left").style.overflow="hidden";
    //gebi("right").style.overflow="hidden";

    rounding.rounded = "normal tl tr bl br";
    rounding.rounded_normal = "normal tl tr bl br";
    rounding.rounded_small = "small tl tr bl br";
    rounding.rounded_big = "big tl tr bl br";

    left100 = getPseudoStyle("leftfull", "");
    right100 = getPseudoStyle("rightfull", "");

    styleScrollbars = false;
    styleScrollbars = getBoolPseudoStyle("styleScrollbars", 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 (var 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, 'rounding');
                setNav(this.shownode, "readstyles");
                showNode(this.shownode, "", "");


            });
            $(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

    //return;
    $("#toolbox .adminbutton").hover(function () { $(this).addClass('adminbutton_hover'); }, function () { $(this).removeClass('adminbutton_hover'); });
    //if ((getStyle("document_body","overflow")==="hidden") || (getStyle("document_body","overflowY")==="hidden")) {
    if ((getStyle("body", "overflow") === "hidden") || (getStyle("body", "overflowY") === "hidden")) {
        setScroll('content');
        haveScrollbar = true;
    }
    else {
        setScroll('window');
        haveScrollbar = false;
    }

    if (scrollOverrule !== "") {
        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;
        }
    }
    if (gebi("swaprightspacer")) {
        if (ah === 0) {
            gebi("swaprightspacer").style.display = "none";
        }
        else {
            gebi("swaprightspacer").style.height = ah;
        }
    }


    $("#top .linktop").hover(function () { $(this).addClass('linktop_hover'); }, function () { $(this).removeClass('linktop_hover'); });
    $("#left .linkleft").hover(function () { $(this).addClass('linkleft_hover'); }, function () { $(this).removeClass('linkleft_hover'); });
    $("#right .linkright").hover(function () { $(this).addClass('linkright_hover'); }, function () { $(this).removeClass('linkright_hover'); });
    $("#content .linkcontent").hover(function () { $(this).addClass('linkcontent_hover'); }, function () { $(this).removeClass('linkcontent_hover'); });
    $("#bottom .linkbottom").hover(function () { $(this).addClass('linkbottom_hover'); }, function () { $(this).removeClass('linkbottom_hover'); });
    $("#modal .linkmodal").hover(function () { $(this).addClass('linkmodal_hover'); }, function () { $(this).removeClass('linkmodal_hover'); });

    $("#loginpane .button, #searchbuttons .button").hover(function () { $(this).addClass('button_hover'); }, function () { $(this).removeClass('button_hover'); });


    ar = taglist.split(";");
    for (var i = 0; i < ar.length; i++) {
        rounding[ar[i]] = "";
    }


    setStyleText("modal2", getStyleText("modal"));
    setStyleText("modal2_holder", getStyleText("modal_holder"));
    rounding.modal2 = rounding.modal;
    rounding.modal2_holder = rounding.modal_holder;

    setStyleText("linkmodal2", getStyleText("linkmodal"));
    rounding.linkmodal2 = rounding.modal2;

    deletePseudoStyles();

    //for (var i=1;i<11;i++) {
    //gebi("aux"+i).content_c=auxId[i]
    //}

    //windowH=noPx(getWindowSize("h"));
    //windowW=noPx(getWindowSize("w"));




}

// ======================================================================	;
function getBoolPseudoStyle(aname, defaultIfEmpty) {
    oval = getPseudoStyle(aname, defaultIfEmpty);
    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() {
    showtime()
    // float them before doing linksstuff, else

    startRotators("content");
    startRotators("left");
    startRotators("right");
    startRotators("top");
    startRotators("bottom");
    startRotators("modal");


    linkstuff("left");
    linkstuff("right");
    linkstuff("top");
    linkstuff("bottom");
    linkstuff("content");

    linkstuff("modal");

    if (startpage) {

        var id = "link_" + startpage;
        if (startpage === "00") { id = "link_first"; }
        if (startpage === lastLinkId) { id = "link_last"; }
        if (gebi(id)) {
            $(gebi(id)).addClass(id + "_clicked");
            gebi(id).clicked = true;
        }

    }


    setVsize("all", true); // skip the rounding, cause we need to round everyting
    //if (isIE()){setTimeout(function(){setVsize()},500);}
    //if (isIE()) { setVsize("all") }


    //round();


    if (isIE()) { buffer = true }

    for (var i in rounding) {
        if (rounding[i] !== "") newround3(i)  // there is nothing to unround
    }
    if (isIE()) { setStyle2("flush") }


    docIsLoaded = true;
    gebi("caption_holder").style.visibility = "hidden";

    $(".popper").hover(function () { showPop(this.getAttribute('helptext')); }, 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;

    // ie bug doesn't render the images
    if (getStyle("picture_holder", "backgroundColor") === "") { setStyle("picture_holder", "backgroundColor", "#ffffff"); }
    if (onVBPageLoad) { onVBPageLoad(contentIds['content']); }

    window.onresize = windowresize;
    setTimeout(function () { indexStyle() }, 500)
    //showtime("loaded")

}

// ======================================================================	;
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 + getScrollXY()[0] - getscrollwidth(idToCenter) / 2;
        y = windowH / 2 + getScrollXY()[1] - getscrollheight(idToCenter) / 2;
    }
    else {
        x = findPosX(gebi(idToCalculate)) + getscrollwidth(idToCalculate) / 2 - getscrollwidth(idToCenter) / 2;
        y = findPosY(gebi(idToCalculate)) + getscrollheight(idToCalculate) / 2 - getscrollheight(idToCenter) / 2;
    }
    if (addScroll) {
        //document.getElementById(idToCenter).style.left=x+gebi("document_body").scrollLeft+'px';
        //document.getElementById(idToCenter).style.top=y+gebi("document_body").scrollTop+'px';
        document.getElementById(idToCenter).style.left = x + document.body.scrollLeft + 'px';
        document.getElementById(idToCenter).style.top = y + document.body.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;

}

// ======================================================================	;
function showWait(where) {
    if (gebi("wait")) {
        setcenter("wait", where);
        $("#wait").stop().css("opacity", 0).css("display", "").animate({ opacity: 1 }, 500);
    }
}

// ======================================================================	;
function hideWait() {
    if (gebi("wait")) {
        $("#wait").stop().animate({ opacity: 0 }, 500, function () { $("#wait").css("display", "none"); });
    }
}

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; }
        }
    }
    gebi(target).innerHTML = "";
    searchResultPane = target;
    if (target === "modal") { showModal(1, false, true); }
    sb = createSearchButtons();
    gebi(target).appendChild(sb);

    if (gebi("searchresult").innerHTML !== "") {
        aclone = gebi("searchresult").cloneNode(true);
        aclone.style.display = "";
        gebi(target).appendChild(aclone);

    }
    linkstuff(target, true);

    searchTarget = target;
    setVsize(target);
    hideWait();

    return








    // searchbuttons is the id of a search inputs and buttons, which is normally hidden;

    if (target === "modal") { showModal(1, false, true); }

    if ((gebi(searchbuttons).style.display !== "none") && (searchTarget !== "")) {
        hidesearch();
    }

    $("#" + target).css("opacity", 1);
    fixIEBlur(target);
    document.body.scrollTop = 0;
    gebi("content_scroller").scrollTop = 0;

    searchTargetHTML = gebi(target).innerHTML; // safe the comtent of the pane;

    if (gebi("searchresult").innerHTML !== "") {
        gebi(target).innerHTML = gebi("searchresult").innerHTML;
        linkstuff(target, true);
    }
    var aclone = gebi(searchbuttons).cloneNode(true);
    aclone.getElementsByTagName("input")[0].id = "searchinput";

    if (gebi(target).childNodes[0]) {
        gebi(target).insertBefore(aclone, gebi(target).childNodes[0]);
    }
    else {
        gebi(target).appendChild(aclone);
    }
    $("#modal .button").hover(function () { $(this).addClass('button_hover'); }, function () { $(this).removeClass('button_hover'); });

    $(aclone).show(500, function () { gebi("searchinput").focus(); });
    searchTarget = target;
    setVsize(target);
    hideWait();
}


// ======================================================================	;
function hidesearch() {

    if (searchTarget === "modal") {
        closeModal(1, false);
    }
    else {
        thisId = resetId(searchTarget);
        showNode(thisId, searchTarget, "");
    }
}

// ======================================================================	;
function search(astring) {
    //ss=gebi("searchstring").value;
    extra = "&site_c=" + site_c;
    extra = extra + version;

    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(data); });
        }
        else {
            src = vbasepath + "search.asp?search=" + encodeURIComponent(astring) + extra;
            //$.get(src,function(data){searchCallBack(data);});
            getPageAsJSON(src, "searchCallBack");
        }

    }
}

// ======================================================================	;
function searchCallBack(data) {
    hideWait();

    gebi(searchTarget).innerHTML = ""
    sb = createSearchButtons()

    var atext = document.createElement("text")
    atext.innerHTML = data
    gebi("searchresult").innerHTML = data
    gebi(searchTarget).appendChild(sb)
    gebi(searchTarget).appendChild(atext)
    linkstuff(searchTarget, true);

    setVsize(searchTarget)

}



//=====================================
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 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_c);
}

// ======================================================================	;
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, "#000000");
    $("#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_c=" + 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;
    md5Hash = "";
    showEditStuff();
    if (lastTarget) {
        resetId(lastTarget);
        if (lastId) {
            showNode(lastId, lastTarget, '');
        }
    }
    showLastPage();

    tagsloggedin = false;
    if (hasDragDrop) { reDHTML("toolbox"); }    // size has changed;
    round("adminbutton");
    positionOnAnchor("toolbox");

}


// ======================================================================	;
function showAdmin() {

    faderIn(1, "#ffffff");
    extra = "";

    if (forceRemote) { extra = "&forceremote=1"; }
    extra = extra + "&vbasepath=" + encodeURIComponent(vbasepath);

    adminSrc = vbasepath + "admin.asp?site_c=" + site_c + "&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_c, page_c, cstring) {

    document.body.scrollTop = 0;
    extra = "";
    contentStyle = "";
    editId = "";
    editPane = "";
    if ((atarget) && (atarget !== 'editemail')) {
        if ((isExternal[atarget]) && (atarget !== "new") && (atarget !== "slides")) {
            mes = "";
            mes = "This is an external link. \n";
            if (mayPages) {

                if (isExternal[atarget] !== "") {
                    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;
            }
        }
        editPane = atarget
        editId = contentIds[atarget]

        if (atarget === "producttext") {
            editId = page_c;
            editPane = "producttext";
            extra = extra + "&content=" + encodeURIComponent(cstring);
        }
        if (atarget === "guestbook") {
            editId = page_c;
            if (cstring) {
                extra = extra + "&content=" + encodeURIComponent(cstring);
            }
            extra = extra + "&gbId=" + page_c;
        }


        unround(atarget) // otherwise, we don't get the right background colors etc
        if ("top,bottom,left,right,content,modal".find(atarget)) {
            if (getStyleProp(gebi(atarget), "backgroundColor") === "transparent") {
                acolor = getParentBk(gebi(atarget));
            }
            else {
                acolor = getStyleProp(gebi(atarget), "backgroundColor");
            }
            if (atarget === "modal") {
                acolor = getStyle("modal", "backgroundColor")
                if (acolor === "") { acolor = getStyle("modal_holder", "backgroundColor") }
            }
            if (atarget === "content") {
                acolor = getStyle("content", "backgroundColor")
                if (acolor === "") { acolor = getStyle("content_outer", "backgroundColor") }
                if (acolor === "") { acolor = getStyle("page", "backgroundColor") }
            }

            contentStyle = contentStyle + "." + atarget + "{background-color:" + acolor + ";}";
            contentStyle = contentStyle + "." + atarget + "{color:" + getStyleProp(gebi(atarget), "color") + ";}";
            contentStyle = contentStyle + "." + atarget + "{font-family:" + getStyleProp(gebi(atarget), "fontFamily") + ";}";
            contentStyle = contentStyle + "." + atarget + "{font-size:" + getStyleProp(gebi(atarget), "fontSize") + ";}";
            contentStyle = contentStyle + "." + atarget + "{font-weight:" + getStyleProp(gebi(atarget), "fontWeight") + ";}";
            contentStyle = contentStyle + "." + atarget + "{width:" + (gebi(atarget).scrollWidth - widthWaste(atarget)) + "px;}";
            //contentStyle = contentStyle + "." + atarget + "{border:1px solid #aaaaaa;border-right:2px solid #888888;border-bottom:2px solid #888888;}";
        }

        round(atarget)
    }

    if (forceRemote) { extra = extra + "&forceremote=1"; }
    extra = extra + "&target=" + atarget;
    //setStyle(atarget,"height","")
    //gebi(atarget).style.height=""
    var src = vbasepath + "edit.asp?r=" + Math.random() + "&site_c=" + site_c + "&assets_site=" + assets_site + "&id=" + md5Hash + "&content_c=" + editId + extra;
    if (atarget === 'editemail') {
        astyle = getStyleText('emailbody');
        if (astyle === "") { astyle = getStyleText('content'); }
        contentStyle = astyle;
        src = vbasepath + "emaillist_composer.asp?r=" + Math.random() + "&site_c=" + site_c + "&assets_site=" + assets_site + "&id=" + md5Hash + "&content_c=" + editId + extra;
    }

    src = src + "&style=" + encodeURIComponent(contentStyle);
    docLoc = trim(document.location + " ").split("#")[0];

    src = src + "&vbasepath=" + encodeURIComponent(vbasepath);
    src = src + "&loc=" + encodeURIComponent(docLoc) + "#";
    showModal(2, true, false);
    //showModal2(true);

    var aframe = document.createElement("iframe");
    aframe.id = "editorIframe";
    aframe.name = "editorIframe";

    gebi("modal2").appendChild(aframe);
    aframe.style.width = "100%";
    aframe.style.height = "95%";
    aframe.src = src;
    aframe.frameBorder = 0;
    aframe.style.border = 0;
    aframe.style.overflow = "hidden";

    spantext = "<input type=button class=button onclick=update('cancel') value=cancel> <input type=button class=button onclick=update('update') value=update>";
    var aspan = document.createElement("span");
    aspan.innerHTML = spantext;
    gebi("modal2").appendChild(aspan);


    $("#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;

    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;
            showLastPage();
            gebi("loginpane").style.display = "none";
            faderOut(1);
            showEditStuff();
            showloginmes();
            gebi("hidden_iframe").src = "";
            if (hasDragDrop) { reDHTML("toolbox"); } // size has changed, now more items;
            round("adminbutton");
            positionOnAnchor("toolbox");

        }
        else if (ahash.indexOf("#loginfailure") !== -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");
            //eval(ahash.split("=")[1]);
        }
        else if (ahash.find("#updatecompleted")) {
            document.location.hash = "#";
            // a page or pane was updated;
            if (editPane === "producttext") {
                adminWrapperRef.moveTo("middle", "middle");

                var 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(editId, editPane, "", "");
                doPoll = false;

            }
            closeModal(2, false);

            hideupdate();

        }
        else if (ahash.find("#gbupdatecompleted")) {
            document.location.hash = "#";
            var aval = ahash.split("{vbaseseperator}")[1];
            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 = "#";
            getJson('nav', 'navCallBack', "", "");
        }
        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(title, 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) {
        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...")
        }

    }

}

// ======================================================================	;
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 manageUsers() {
    alert("not yet implemented");
}

// ======================================================================	;
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 showCart(callerForm, atarget, somerowno) {

    // the cart will always be shown in Modal;

    if ((atarget === "modal2") && (gebi("modal2_holder").style.display !== "block")) { showModal(2, false, true); }

    resetId(atarget);


    if (merchant_id === "") {

        val = "Order for product: ";
        val = val + gebi("vbproduct_" + somerowno).value + " $ " + gebi("vbprice_" + somerowno).value;

        if (gebi("vbqty_" + somerowno)) {
            val = val + " (" + gebi("vbqtycaption_" + somerowno).value + ": " + gebi("vbqty_" + somerowno).value + ")";
        }
        val = encodeURIComponent(val + "\n\nPlease add additional information here:\n\n");

        var data = initData();
        extra = "";

        if (forceRemote) { extra = extra + "&forceremote=1"; }
        data[4] = "emailform.asp?site_c=" + site_c + "&body=" + val + "&subject=order by email&r=" + Math.random();
        data[2] = "modal2";
        showNodeCallBack(data);
    }
    else {

        form = callerForm.cloneNode(true);
        gebi(atarget).innerHTML = "";
        adiv = document.createElement("div");
        adiv.innerHTML = "<iframe name=target_iframe  id=target_iframe onload=hideWait() frameborder=0 style='margin:0px;padding:0px;border-width:0px'></iframe>";

        form.style.display = "none";

        gebi(atarget).appendChild(form);
        gebi(atarget).appendChild(adiv);

        // copy selected values from old to the new form;

        selects = callerForm.getElementsByTagName("select");
        newselects = form.getElementsByTagName("select");
        for (var i = 0; i < selects.length; i++) {
            newselects[i].value = selects[i].value;
        }

        form.setAttribute("target", "target_iframe");

        setIframeSize(atarget);
        form.submit();
    }
}


// ======================================================================;
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() {

    if (trim(gebi('name').value) === "") { alert('Please enter your name'); return; }
    if (!test_email(gebi('email').value)) { alert('Please provide a valid email address'); return; }
    if (trim(gebi('name').value) === "") { alert('Please enter a subject'); return; }

    if (trim(gebi('message').value) === "") { alert('Please enter your message'); return; }
    extra = "";
    if (gebi("docc").checked) { extra = "&docc=yes"; }
    var mes = gebi("message").value;
    //mes=replace(mes,'\n','<br>');
    url = "emailform.asp?site_c=" + site_c + "&name=" + encodeURIComponent(gebi("name").value) + "&email=" + gebi("email").value + "&message=" + encodeURIComponent(mes) + "&subject=" + encodeURIComponent(gebi("subject").value) + extra;
    var data = initData();
    data[2] = piclensTarget;
    data[4] = url; // extern;
    showNodeCallBack(data);
}


// ======================================================================;
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_c=" + site_c + "&firstname=" + xfirstname + "&email=" + xemail + "&othername=" + extra;
    var data = initData();
    data[2] = piclensTarget;
    data[4] = url; // extern;
    showNodeCallBack(data);
}



// ======================================================================;
function faderIn(no, color) {
    if (gebi("fader" + no)) {
        $("#fader" + no).stop().css("opacity", "0");
        gebi("fader" + no).style.width = bodyWidth
        //gebi("fader"+no).style.height=getscrollheight("document_body");
        gebi("fader" + no).style.height = document.body.scrollHeight
        gebi("fader" + no).style.display = "";
        gebi("fader" + no).style.display = "block";

        $("#fader" + no).animate({ opacity: 0.6 }, 500);
    }
}

// ======================================================================;
function faderOut(no) {

    $("#fader" + no).stop().animate({ opacity: 0 }, 500, function () {
        gebi("fader" + no).style.display = "none";

    });

}


//=======================================================;
function customSearch(obj) {
    if (obj.value !== "") {
        showsearch('modal', 'searchbuttons');
        gebi('searchinput').value = obj.value;
        setTimeout(function () { gebi('searchsubmit').onclick(); }, 500);
        obj.value = "";
    }

}
//=======================================================;
function showModal(anum, maxsize, showCloseButton) {

    fadernum = 2;
    if (anum === 1) { anum = ""; fadernum = 1; }

    if (showCloseButton) {
        gebi("closebuttonholder" + anum).style.display = "";
    }
    else {
        gebi("closebuttonholder" + anum).style.display = "none";
    }

    restoreNode = lastNodeShowed;
    saveScrollTop = gebi("content_scroller").scrollTop;

    $("#modal" + anum + "_holder").stop();
    $("#modal" + anum).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")) - widthWaste("modal" + anum + "_holder");
    gebi("modal" + anum + "_holder").style.height = getModalHeight() - heightWaste("modal" + anum + "_holder");

    $("#fader" + anum).unbind("click");
    gebi("modal" + anum).innerHTML = "";
    gebi("modal" + anum + "_holder").style.width = 150;
    gebi("modal" + anum + "_holder").style.height = 150;

    gebi("closebuttonholder" + anum).style.width = "100%";
    setcenter("modal" + anum + "_holder", "screen");
    gebi("modal" + anum).style.display = "";

    // 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", "5");
        setStyle("modal" + anum, "backgroundColor", "#ffffff");
        setStyle("modal" + anum, "padding", "5");
        setStyle("modal" + anum, "textAlign", "left");
    }

    showWait("screen");
    faderIn(fadernum, "#000000");
    $("#modal" + anum).stop().animate({ opacity: 1 }, 1);

    cw = getModalWidth(maxsize);
    ch = getModalHeight(maxsize);

    cw = cw - widthWaste("modal" + anum + "_holder");
    ch = ch - heightWaste("modal" + anum + "_holder");
        
    gebi("modal" + anum).style.height = getModalHeight(maxsize) - getHeightStuff("modal" + anum + "_holder") - heightWaste("modal") - 22;
    gebi("modal" + anum).style.width = getModalWidth(maxsize) - getWidthStuff("modal" + anum + "_holder") - widthWaste("modal");

    //alert(getModalHeight(maxsize))
   //alert(getHeightStuff("modal" + anum + "_holder"))
    //alert(heightWaste("modal"))
   //alert("showmo: "+(getModalHeight(maxsize) - getHeightStuff("modal" + anum + "_holder") - heightWaste("modal") - 22))
    gebi("modal" + anum + "_holder").style.width = 150;
    gebi("modal" + anum + "_holder").style.height = 150;

    unround("modal" + anum);
    unround("modal" + anum + "_holder");

    gebi("modal" + anum).style.display = "none";
    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 () {
        $("#modal" + anum).fadeIn(500, function () {
            $("#modal" + anum).css("opacity", "");  // otherwise IE will not render selectboxes when scrolling;
            $("#modal" + anum).css("filter", "");
            //setContainer("modal"+anum,cw,ch-22,true,true)
            setVsize("modal" + anum)
            if (anum === "") { setIframeSize("modal" + anum); }
            round("modal" + anum + "_holder");
            goToAnchor("modal")
            hideWait();


        });
    });

}


//=======================================================;
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).innerHTML = "";
    gebi("loginpane").style.display = "";


    setStyle("modal" + anum, "overflow", "auto");      // kiko on ie needs hidden;
    gebi("modal" + anum).style.overflow = "auto";
    if (fast) {
        $("#modal" + anum + "_holder").stop().fadeOut(0);
        gebi("modal" + anum).style.display = "none";
        $("#fader" + anum).stop().css("opacity", 0).css("display", "none");
    }
    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"))
}


//=======================================================;
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 setVsize(target, noround) {
    // if target is all then do all, else only target

    var oldstate = state
    state = ""

    getDimensions()
    gebi("page").style.width = pageWidth - widthWaste("page");
    gebi("page").style.height = pageHeight - heightWaste("page");
    gebi("body").style.height = bodyHeight - heightWaste("body");

    if ((menuOpener === "mouseover") && (!alwaysOpen)) {
        JQsublink_container.hide();
    }

    var doRound = false
    if (target !== "all") { doRound = true } // else we round at the end of this sub

    if ((target === "all") || (target === "top")) { setContainer("top", topWidth, getStyle("top", "height"), doRound, false); }
    if ((target === "all") || (target === "left")) { setContainer("left", leftWidth, leftHeight, doRound, true); }
    if ((target === "all") || (target === "right")) { setContainer("right", rightWidth, rightHeight, doRound, true); }
    if ((target === "all") || (target === "bottom")) { setContainer("bottom", topWidth, getStyle("bottom", "height"), doRound, false); }
    if ((target === "all") || (target === "content")) { setContainer("content", contentWidth, contentHeight, doRound, true); }
    //if ((target==="all") || (target==="modal")) {setContainer("modal",contentWidth,contentHeight,doRound,true);}

    if (target === "modal") {
        anum = ""
        maxsize = false
        
        ch = getModalHeight(maxsize) - getHeightStuff("modal_holder") - heightWaste("modal") - 22;
        cw = getModalWidth(maxsize) - getWidthStuff("modal_holder") - widthWaste("modal");

        setContainer("modal" + anum, cw, ch, true, true)
    }

    for (var i = 1; i < 11; i++) {
        round("style"+i)

    }


    if (target !== "all") {
        state = oldstate

        return;
    }



    $("#toolbox .adminbutton").each(function () {
        if (getStyle("adminbutton", "width") !== "") { this.style.width = noPx(getStyle("adminbutton", "width")) - widthWaste("adminbutton"); }
        if (getStyle("adminbutton", "height") !== "") { this.style.height = noPx(getStyle("adminbutton", "height")) - heightWaste("adminbutton"); }
    });

    floatBox('navdragger', true);
    floatBox('vbaselink', gebi("vbaselink").isFloat);
    floatBox('searchspan', gebi("searchspan").isFloat);
    floatBox('toolbox', gebi("toolbox").isFloat);


    for (var 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, true)

    }

    $("#toolbox .adminbutton").each(function () {
        if (getStyle("adminbutton", "width") !== "") { this.style.width = noPx(getStyle("adminbutton", "width")) - widthWaste("adminbutton"); }
        if (getStyle("adminbutton", "height") !== "") { this.style.height = noPx(getStyle("adminbutton", "height")) - heightWaste("adminbutton"); }
    });
    if (getStyle("vbaselink", "width") !== "") { gebi("vbaselink").style.width = noPx(getStyle("adminbutton", "width")) - widthWaste("adminbutton"); }
    if (getStyle("vbaselink", "height") !== "") { gebi("vbaselink").style.height = noPx(getStyle("adminbutton", "height")) - heightWaste("adminbutton"); }


    if (!noround) {
        round("top");
        round("left");
        round("right");
        round("bottom");
        round("content_outer");
        round("content");
        round("body");
        round("page");
    }
    state = oldstate
    //alert("after"+" "+getStyle("page", "width"))

}

//=======================================================;
function positionOnAnchor(objId) {


    var obj = gebi(objId);
    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;
        obj.style.top = 0;
    }
    if (!anchor) { anchor = "left"; }
    var anchorX = obj.anchorX;
    var anchorY = obj.anchorY;
    if (anchor === "left") {
        var newX = anchorX + pageX;
        var newY = anchorY + pageY;
    }
    if (anchor === "right") {
        var newX = pageX + getscrollwidth("page") - anchorX - getscrollwidth(objId);
        var newY = anchorY + pageY;
    }
    if (anchor === "leftbottom") {
        var newX = anchorX + pageX;
        var newY = pageY + getscrollheight("page") - anchorY - getscrollheight(objId);
    }
    if (anchor === "rightbottom") {
        var newX = pageX + getscrollwidth("page") - anchorX - getscrollwidth(objId);
        var newY = pageY + getscrollheight("page") - anchorY - getscrollheight(objId);
    }



    if (hasDragDrop) {
        dd.elements[objId].moveTo(newX, newY);
    }
    else {
        obj.style.left = newX;
        obj.style.top = newY;
    }

}

//=======================================================;
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;

    for (var 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 round(classname) {
    if (classname) {
        if (rounding[classname] === "") {
            return
        }
        else {
            unround(classname);
            newround3(classname);
        }
    }
    else {
        for (var i in rounding) {
            if (rounding[i] !== "") unround(i)  // there is nothing to unround
            if (rounding[i] !== "") newround3(i)  // there is nothing to unround
        }

    }
}



//=======================================================;
function newround3(classname, generate) {


    sstate = state
    //state=""
    //useAssets=false
    var destroyed = false;
    var assetsArray = [];

    if ((!classname) || (classname.find("sublink")) || (classname.find("chapter"))) {
        if ($(gebi("navholder")).accordion()) {
            $(gebi("navholder")).accordion("destroy"); JQsublink_container.show();
            destroyed = true;
        }
    }

    var r = rounding[classname];
    var asize = 16;
    var doit = false;
    var ds = "";  //drop shadow;
    var cutoffbottom = 0;  // cut's the bottom of a shadow.;
    var cutoffright = 0;  // cut's the bottom of a shadow.;
    var symetric = 0;  // top to bottom shading;
    var filetype = "jpg";
    if (typeof r === "undefined") { alert("r undefined: " + classname) }
    if (!r) { alert(classname) }
    if (typeof r !== "string") { alert("r no string: " + classname + "\n\n" + r) }

    if (r.indexOf("r100") !== -1) { asize = 100; r = replace(r, "r100", ""); }
    if (r.indexOf("r200") !== -1) { asize = 200; r = replace(r, "r200", ""); }
    if (r.indexOf("large") !== -1) { asize = 64; r = replace(r, "large", ""); }
    if (r.indexOf("big") !== -1) { asize = 32; r = replace(r, "big", ""); }
    if (r.indexOf("small") !== -1) { asize = 8; r = replace(r, "small", ""); }
    if (r.indexOf("tiny") !== -1) { asize = 4; r = replace(r, "tiny", ""); }
    if (r.indexOf("micro") !== -1) { asize = 2; r = replace(r, "micro", ""); }
    if (r.indexOf("shadow") !== -1) { doit = true; ds = 2; r = replace(r, "shadow", ""); }
    if (r.indexOf("cutoffright") !== -1) { doit = true; cutoffright = 1; r = replace(r, "cutoffright", ""); }
    if (r.indexOf("cutoffbottom") !== -1) { doit = true; cutoffbottom = 1; r = replace(r, "cutoffbottom", ""); }
    if (r.indexOf("png") !== -1) { filetype = "png"; r = replace(r, "png", ""); }
    if (r.indexOf("sym") !== -1) { symetric = "1"; r = replace(r, "sym", ""); }

    r = replace(r, "normal", "");
    r = replace(r, "cutoff", "");


    dohover = false //flag to see if we have to do hovers as well
    doclick = false

    //if (getStyleText(classname+"_hover",true)!=="") {dohover=true;}
    //if (getStyleText(classname+"_clicked",true)!=="") {doclick=true;}


    if (getStyle(classname + "_hover", "backgroundColor", true) !== "") { dohover = true; }
    if (getStyle(classname + "_clicked", "backgroundColor", true) !== "") { doclick = true; }

    if (getcolor("efgc_hover", r, classname) !== "") { doit = true; dohover = true }
    var efgc_hover = getcolor("efgc_hover", rounding[classname], classname);
    var bgc_hover = getcolor("bgc_hover", rounding[classname], classname);

    //if (classname === "link") { alert(dohover) }

    if (getcolor("efgc_clicked", r, classname) !== "") { doit = true; doclick = true }
    var efgc_clicked = getcolor("efgc_clicked", rounding[classname], classname);
    var bgc_clicked = getcolor("bgc_clicked", rounding[classname], classname);

    //if (classname === "link") { alert(doclick) }

    if (getcolor("efgc", r, classname) !== "") { doit = true; }
    var efgc_nostate = getcolor("efgc", rounding[classname], classname);
    var bgc_nostate = getcolor("bgc", rounding[classname], classname);

    r = deletecolor("eh", r); // extra height;
    r = deletecolor("efgc", r);
    r = deletecolor("bgc", r);
    r = deletecolor("efgc", r);
    r = deletecolor("bgc_hover", r);
    r = deletecolor("bgc_clicked", r);
    r = deletecolor("efgc_hover", r);
    r = deletecolor("efgc_clicked", r);
    r = deletecolor("fgc_clicked", r);
    r = replace(r, " ", "");
    if (r !== "") { doit = true; }
    if ((doit)) {

        var bt = noPx(getStyle(classname, "borderTopWidth", true));
        var bb = noPx(getStyle(classname, "borderBottomWidth", true));
        var bl = noPx(getStyle(classname, "borderLeftWidth", true));
        var br = noPx(getStyle(classname, "borderRightWidth", true));

        var borderwidth = bt;
        borderwidth = max(borderwidth, bb);
        borderwidth = max(borderwidth, bl);
        borderwidth = max(borderwidth, br);

        if (bgc_nostate === "") {
            if (classname === "page") {
                var bgc_nostate = bodyColor;
            }
            else {
                var bgc_nostate = pageColor;
            }
        }

        bgc_nostate = replace(bgc_nostate, "#", "");

        bordercolor = "";
        var bordercolor = getStyle(classname, "borderTopColor", true);
        if (trim(bordercolor) === "-moz-use-text-color") { bordercolor = getStyle(classname, "color", true); }
        if (trim(bordercolor) === "") { bordercolor = getStyle(classname, "color", true); }
        if (bordercolor.indexOf("rgb") !== -1) { bordercolor = rgb2hex(bordercolor).substr(1); } else { bordercolor = bordercolor.substr(1); }
        anindex = false;

        var borders = "";

        if (bt > 0) { borders += 't'; }
        if (bl > 0) { borders += 'l'; }
        if (br > 0) { borders += 'r'; }
        if (bb > 0) { borders += 'b'; }

        if (getStyle(classname, "borderTopStyle", true) === "none") { bt = 0; }
        if (getStyle(classname, "borderLeftStyle", true) === "none") { bl = 0; }
        if (getStyle(classname, "borderRightStyle", true) === "none") { br = 0; }
        if (getStyle(classname, "borderBottomStyle", true) === "none") { bb = 0; }

        var pt = noPx(getStyle(classname, "paddingTop", true));
        var pl = noPx(getStyle(classname, "paddingLeft", true));
        var pr = noPx(getStyle(classname, "paddingRight", true));
        var pb = noPx(getStyle(classname, "paddingBottom", true));

        nostate = classname
        var alist = $("." + classname);
        for (var i3 = 0; i3 < alist.length; i3++) {

            rcounter++;
            var obj = alist[i3];

            if ((obj)) {

                var oldstate = state;
                state = "";
                //obj.newstylename="";
                var h = noPx(obj.style.height);
                var w = noPx(obj.style.width);
                var fixedSize = false;

                if ((getStyle(nostate, "width", true) !== "") && (getStyle(nostate, "height", true) !== "")) { fixedSize = true; }

                if (h === 0) {
                    h = obj.offsetHeight;
                }
                else {
                    h = h + heightWaste(nostate);
                }
                if (w === 0) {
                    w = obj.offsetWidth;
                }
                else {
                    w = w + widthWaste(nostate);
                }


                if (ds !== "") {
                    if (!cutoffbottom) { h = h - 5; }
                    if (!cutoffright) { w = w - 5; }
                }
                if ((ds === "") && (borders === "") && ((r === "") || (r.find("efgc")))) {
                    w = 1;
                    filetype = "jpg";
                    bgrepeat = "repeat-x";
                }
                else {
                    bgrepeat = "no-repeat";
                }


                if (classname === "body") {
                    h = noPx(getWindowSize("h"))
                    bgrepeat = bgrepeat + " fixed "


                }


                state = oldstate;

                classname = nostate
                bgc = bgc_nostate
                efgc = efgc_nostate
                newround4(pt, pl, pb, pr, bt, bl, bb, br, classname, nostate, efgc, bgc, r, borders, borderwidth, ds, asize, w, h, bordercolor, cutoffright, cutoffbottom, efgc, filetype, symetric, obj, assetsArray, generate, bgrepeat, dohover, doclick, fixedSize)
                if (dohover) {

                    //if (classname === "link") { alert("now doing hover") }

                    newclassname = nostate + "_hover"
                    //bgc=bgc_hover
                    efgc = efgc_hover
                    newround4(pt, pl, pb, pr, bt, bl, bb, br, newclassname, nostate, efgc, bgc, r, borders, borderwidth, ds, asize, w, h, bordercolor, cutoffright, cutoffbottom, efgc, filetype, symetric, obj, assetsArray, generate, bgrepeat, dohover, doclick, fixedSize)
                }
                if (doclick) {
                    //if (classname === "link") { alert("now doing clicked") }

                    newclassname = nostate + "_clicked"

                    //bgc=bgc_hover
                    efgc = efgc_clicked
                    newround4(pt, pl, pb, pr, bt, bl, bb, br, newclassname, nostate, efgc, bgc, r, borders, borderwidth, ds, asize, w, h, bordercolor, cutoffright, cutoffbottom, efgc, filetype, symetric, obj, assetsArray, generate, bgrepeat, dohover, doclick, fixedSize)
                }
                else {

                    //if (classname === "link") { alert("No clicked") }

                }

            } // end if (obj)

        } // end if doit

    }

    // now create background images which are stored in the array

    if (generate) {
        for (var i in assetsArray) {
            if (assetsArray[i] !== 1) {
                gebi("msgarea").innerHTML = assetsArray[i];
                $.ajax({
                    type: "GET",
                    url: assetsArray[i],
                    async: false
                });
            }
        }
    }
    if (destroyed) { reaccordion("newround"); }
    state = sstate


}

function newround4(pt, pl, pb, pr, bt, bl, bb, br, classname, nostate, efgc, bgc, r, borders, borderwidth, ds, asize, w, h, bordercolor, cutoffright, cutoffbottom, efgc, filetype, symetric, obj, assetsArray, generate, bgrepeat, dohover, doclick, fixedSize) {

    //if (nostate==="link") {alert(classname+" "+r+" "+borders+" "+asize)}

    var fgc = getStyle(classname, "backgroundColor", true);
    if (fgc.indexOf("rgb") !== -1) { fgc = rgb2hex(fgc).substr(1); } else { fgc = fgc.substr(1); }

    if ((efgc !== "") || (bgc !== "") | (r !== "")) {

        //if (nostate===("link")) {alert(classname)}

        var oldstate = state;
        state = "";

        var rparameters = "corners=" + r + "&borders=" + borders + "&borderwidth=" + borderwidth;
        rparameters = rparameters + "&ds=" + ds + "&radius=" + asize + "&w=" + w + "&h=" + h + "&bgc=" + bgc + "&fgc=" + fgc + "&bordercolor=" + bordercolor;
        rparameters = rparameters + "&cutoffright=" + cutoffright + "&cutoffbottom=" + cutoffbottom + "&efgc=" + efgc + "&f=" + filetype + "&symetric=" + symetric;
        //if (classname==="link") {alert(classname+" "+rparameters)}

        rmd5 = hex_md5(rparameters);

        if ((classname.find("_hover")) && (dohover)) {

            // do this only if any hover is styled

            newname = "rounded_" + nostate + "_hover_" + rmd5;
            obj.roundinghover = newname;
            //$(obj).unbind('mouseenter mouseleave');
            $(obj).hover(function () { $(obj).addClass(obj.roundinghover); }, function () { $(obj).removeClass(obj.roundinghover); });
        }
        else if ((classname.find("_clicked")) && (doclick)) {

            newname = "rounded_" + nostate + "_clicked_" + rmd5;
            obj.roundingclicked = newname;

            $(obj).click(function () {
                if (this.id.find("aux")) { removeAuxClickedStates("round"); }
                $(this).addClass($(this)[0].roundingclicked);
                // in case of a sublink, set the link to clicked

                if ((this.className.find("sublink")) && (!this.className.find("sublink_container"))) {
                    achapter = this.parentNode.parentNode.parentNode.id;
                    alink = replace(achapter, "chapter", "link");
                    if (gebi(alink)) { $(gebi(alink)).addClass(gebi(alink).roundingclicked); }
                }

            });
            if (obj.clicked) {

                $(obj).addClass(obj.roundingclicked);
                obj.clicked = false;

            }
        }
        else {

            if ((classname.find("_hover")) || (classname.find("_clicked"))) { alert("error") }

            newname = "rounded_" + nostate + "_normal_" + rmd5;
            obj.roundingnormal = newname;
            //$(obj).addClass(newname);
            obj.newstylename = newname;
        }


        //if (nostate==="link") {alert(aval)}

        var src = vbasepath + "rounded.php?" + rparameters;
        //alert(src)
        //if (classname.find("link")) {alert(obj.id+" "+obj.clicked)}

        outfile = rmd5 + "." + filetype;


        //if (classname.find("link")) {alert(classname+"\n\n"+rparameters+"\n\n"+outfile)}

        var prgrm = vbasepath + "create_assets.asp?site_c=" + site_c + "&infile=" + encodeURIComponent(src + "&nocache=1") + "&outfile=" + encodeURIComponent(outfile);
        var newsrc = vbaseroot + "uploadfolder/" + site_c + "/assets/" + outfile;

        if ((useAssets && fixedSize) && (!classname.find("modal"))) {
            var imagesrc = newsrc;
        }
        else {
            var imagesrc = src;
        }
        //if (classname.find("modal")) {alert(imagesrc+" "+w+" "+h)}
        var url = ""

        if ((w > 0) && (h > 0)) {  // for example modal_holder which is invisible
            url = "url(\"" + imagesrc + "\")"

            if (typeof assetsArray[newname] === "undefined") {

                setStyle(newname, "padding", (pt + bt) + "px " + (pr + br) + "px " + (pb + bb) + "px " + (pl + bl) + "px", true); // top right bottom left

                setStyle(newname, "border", "0", true); // background: #fff url(image.gif) no-repeat top left
                //if (classname.find("link")) {alert(newname+"\n"+getStyleText(newname))}
                setStyle(newname, "background", "transparent " + url + " " + bgrepeat, true)
                //if (classname.find("link")) {alert(newname+"\n"+getStyleText(newname))}

                //if (classname.find("link")) {alert(newname+"\n"+getStyleText(newname,true)+"\n"+(pt+bt)+"px "+(pr+br)+"px "+(pb+bb)+"px "+(pl+bl)+"px")}

            }
            if ((generate) && (fixedSize) && (w > 0) && (h > 0)) {
                assetsArray[newname] = prgrm;
            }
            else {
                assetsArray[newname] = 1;
            }





            if ((classname.find("_hover")) || (classname.find("_clicked"))) {
                preload(imagesrc);

            }
            else {
                //if (classname==="vbaselink") {alert(obj.newstylename)}

                var img = new Image();
                img.onload = function (obj) {
                    return function () { $(obj).addClass(obj.newstylename); };
                } (obj);
                img.src = imagesrc;
                
                $(obj).addClass(obj.newstylename)
                //if (classname==="link") {alert(imagesrc)}

                a = setTimeout(function (obj, img) {
                    return function () {
                        if (imageLoaded(img)) { $(obj).addClass(obj.newstylename); }

                    };
                } (obj, img), 100);
            }
        }



    } // end of efgc<>"" or bgc<>""
    state = oldstate;

}

//=======================================================;

function unique(a) // return a unique aaray
{
    var r = [];
    o: for (var i = 0, n = a.length; i < n; i++) {
        for (var x = 0, y = r.length; x < y; x++) {
            if (r[x] == a[i]) { continue o; }
        }
        r[r.length] = a[i];
    }
    return r;
}
//=======================================================;
function imageLoaded(img) {

    if (!img.complete) {
        return false; // firefox is always complete
    }
    if (typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
        return false;
    }
    return true;
}

//=======================================================;
function unround(target) {
    // target=classname. not states required.;
    // here we delete from the stylesheet the classes rounded_ (definded by obj.roundingnormal, obj.roundinghover) etc;
    // and remove all these references from the obj.className;


    var alist = [];
    if ((!target) || (target === "")) {
        alist = $("[class*=rounded_]");
    }
    else {
        alist = $("." + target);
    }
    for (var i = 0; i < alist.length; i++) {
        var obj = alist[i];



        //alert(obj.className + "\n" + obj.roundingnormal)
        if (obj.roundingnormal) { $(obj).removeClass(obj.roundingnormal); }
        if (obj.roundinghover) { $(obj).removeClass(obj.roundinghover); }
        if (obj.className.find("_clicked")) { obj.clicked = true; }
        if (obj.roundingclicked) { $(obj).removeClass(obj.roundingclicked); }

        //goes wrong in the editor
        var cn = obj.className.split(" ")
        var ncn=""
        for (var j=0;j<cn.length;j++) {
            if (!cn[j].find("rounded_")) {
                ncn=ncn+cn[j]+" "
            }
        }
        obj.className=trim(ncn)



        aselector = obj.roundingnormal;
        var borders = getbackroundImageProp(aselector, "borders");
        var borderwidth = noPx(getbackroundImageProp(aselector, "borderwidth"));
        var bordercolor = "#" + getbackroundImageProp(aselector, "bordercolor");

        if (trim(bordercolor) === "-moz-use-text-color") { bordercolor = getStyle(aselector, "color", true); }
        if (bordercolor.indexOf("rgb") !== -1) { bordercolor = rgb2hex(bordercolor); } else { bordercolor = bordercolor; }

        if (borders.indexOf("t") !== -1) { setStyle(target, "borderTop", borderwidth + "px solid " + bordercolor, true); setStyle(target, "paddingTop", noPx(getStyle(aselector, "paddingTop", true)) - borderwidth, true); }
        if (borders.indexOf("l") !== -1) { setStyle(target, "borderLeft", borderwidth + "px solid " + bordercolor, true); setStyle(target, "paddingLeft", noPx(getStyle(aselector, "paddingLeft", true)) - borderwidth, true); }
        if (borders.indexOf("r") !== -1) { setStyle(target, "borderRight", borderwidth + "px solid " + bordercolor, true); setStyle(target, "paddingRight", noPx(getStyle(aselector, "paddingRight"), true) - borderwidth, true); }
        if (borders.indexOf("b") !== -1) { setStyle(target, "borderBottom", borderwidth + "px solid " + bordercolor, true); setStyle(target, "paddingBottom", noPx(getStyle(aselector, "paddingBottom"), true) - borderwidth, true); }

        deleteStyleText("." + obj.roundingnormal);
        deleteStyleText("." + obj.roundinghover);
        deleteStyleText("." + obj.roundingclicked);

    }

}





//=======================================================;
function preload(src) {

    // use to store rollovers;

    var tar = imgArray[src]
    if (!tar) {
        imgArray[src] = new Image();
        imgArray[src].src = src
    }
    return


    for (var i = 0; i < imgArray.length; i++) {
        if (imgArray[i].src === src) { return; }
    }
    imgArray[imgArrayCounter] = new Image();
    imgArray[imgArrayCounter].src = src;
    imgArrayCounter++;

}


//=======================================================;
function getParentBk(x, stylename) {
    var el = x.parentNode, c;
    stylename = el.className;

    while (el.tagName.toUpperCase() != "HTML" && (c = getBk(el, stylename)) == "transparent") {
        el = el.parentNode;
        stylename = el.className;
    }
    if (c == "transparent") { c = "#FFFFFF"; }
    return (c);
}


//=======================================================;
function getBk(x, stylename) {
    if (getStyle(stylename, "backgroundImage", true).indexOf("rounded.php") !== -1) {
        var c = "#" + getbackroundImageProp(stylename, "fgc", true);
    }
    else {
        var c = getStyleProp(x, "backgroundColor");

    }

    if (c == null || c == "transparent" || c.find("rgba(0, 0, 0, 0)")) {
        return ("transparent");
    }
    if (c.find("rgb")) { c = rgb2hex(c); }
    return (c);
}


// ======================================================================	;
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;


    }

}

// ======================================================================	;
function scrollClick(aname) {

    // called when clicked on a bar;

    adiv = gebi(aname);
    aglider = gebi("vglider_" + aname);
    abar = gebi("vbar_" + aname);

    fraction = (posy - findPosY(abar)) / abar.offsetHeight;
    toscroll = adiv.scrollHeight - adiv.offsetHeight;
    $(adiv).stop().animate({ scrollTop: toscroll * fraction }, 500);

}

// ======================================================================	;
function setGlider(aname) {
    // called when sccrolling (with mousewheel for example, to synchronize the glider;
    if (dragobject !== "") { return; }
    adiv = gebi(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;

}


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.body.scrollLeft;
        posy = ev.clientY + document.body.scrollTop;
    }
    else { return false; } //old browsers;
}


// ======================================================================	;
function getcolor(which, roundstring, debugId) {
    var astring = " " + replace(roundstring, "  ", " ") + " ";
    ipos = astring.indexOf(" " + which + "=");
    if (ipos === -1) { return ""; }
    astring = astring.substr(ipos + which.length + 1);
    ipos2 = astring.indexOf(" ");
    astring = astring.substr(1, ipos2);
    return trim(astring);
}
// ======================================================================	;
function deletecolor(which, roundstring) {
    var astring = " " + replace(roundstring, "  ", " ") + " ";
    acolor = getcolor(which, astring, "delete");
    roundstring = replace(astring, " " + which + "=" + acolor, "");
    return trim(roundstring);
}


// ======================================================================	;
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 picLensCallback(data) {

    if ((piclensTarget !== "modal") && (piclensTarget !== "modal2")) {
        $("#" + piclensTarget).stop();
    }
    if ((piclensTarget === "modal") && (gebi("modal_holder").style.display !== "block")) { showModal(1, false, true); }
    if ((piclensTarget === "modal2") && (gebi("modal2_holder").style.display !== "block")) { showModal(2, false, true); }
    gebi(piclensTarget).innerHTML = data;



    $("#" + piclensTarget + " img").css("opacity", "0");

    $("#" + piclensTarget).animate({ opacity: 1 }, 500, function () {
        fixIEBlur(piclensTarget); $("#" + piclensTarget + " img").animate({ opacity: 1 }, 500);
        round("productbackground");
        round("productheader");
        round("productholder");
        round("productpicture");
        round("producttext");

        imagestuff(piclensTarget, true);
        roundGb();  // round guestbook

    });
    for (var i = 1; i < 11; i++) {
        round('style' + i);
    }

    setIframeSize(piclensTarget);

    if (haveScrollbar) {
        setVsize(piclensTarget);
    }
    else {
        setVsize("all");
    }

    roundstuff(piclensTarget);
    linkstuff(piclensTarget);



    $(".popper").hover(function () { showPop(this.getAttribute('helptext')); }, function () { killPop(); });
    hideWait();
}



//=============================================================;
function roundGb() {
    round("gbpage");
    round("gbtopicheader");
    round("gbsubject");
    round("gbtopic");
    round("gbtopictext");
    round("gbcommentheader");
    round("gbcomment");
    round("gbcommenttext");
    round("gbcommentseperator");
    round("gbtopicholder");
}

// ====================================================================================================;
// guestbook;
// ====================================================================================================;

function gbedit(id) {
    faderIn(2);
    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); };

}

//=============================================================;
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;
    }

    document.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);
    gebi("gbwait").style.display = "none";
    roundGb();

    if (anaction !== "delete") {
        gebi(piclensTarget + "_scroller").scrollTop = 0
    }
    if (haveScrollbar) {
        setVsize(piclensTarget);
    }
    else {
        setVsize("all");
    }

}

//=============================================================;
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").submit();
    }
}

//=============================================================;
function gbcancel() {

    gebi('insertdiv').style.display = 'none';
    faderOut(2);
    gebi("insertta").innerHTML = "";
    gebi("picerrordiv").style.display = "none";

}



//=============================================================;
function gbaddcomment(id, userlogedin, authenticate) {
    if (gebi("gbsubject")) {
        if (id) { //comment on a topic, do not show subject;
            gebi("subjectdiv").style.display = "none";
        }
        else {
            gebi("subjectdiv").style.display = "";
        }
    }
    if (id) {
        gebi("gbinsertbutton").value = "Add Comment";
    }
    else {
        gebi("gbinsertbutton").value = "Add Topic";
    }

    document.body.appendChild(gebi("gbform"))
    if ((userlogedin !== "True") && (authenticate === "True")) { showUserLogin('blogs'); return; }
    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("gbsubject")) && (gebi("subjectdiv").style.display === "")) { if (trim(gebi("gbsubject").value) === "") { alert("Please provide a subject"); 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);
        //gebi("gbcontent").innerHTML="<br><br><center><img id=img"+id+" src='"+vbasepath+"images/wait.gif' /></center>   "+gebi("gbcontent").innerHTML;
        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;
    document.gbform.submit();
}

//=============================================================;
function showUserLogin(atype) {

    if (gebi("fader2")) { faderIn(2); }
    setcenter("userloginpane", "screen");
    gebi("userloginpane").style.display = "inline-block";
    extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }
    gebi("userloginif").src = vbasedomain + "?relay=gblogin.asp&type=" + atype + "&site_c=" + site_c + extra;
    gebi("userloginif").style.height = 350;
    gebi("userloginif").style.width = 400;
}

//=============================================================;
function hideUserLogin() {
    $("#userloginpane").fadeOut();
    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' />   ";
        document.gbform.submit();
    }
}

//=============================================================;
function userlogout() {
    gebi("userloginspan").innerHTML = "<img id=img" + id + " src='" + vbasepath + "images/wait.gif' /> ";
    gebi('action').value = 'logout';
    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' />   ";
    document.gbform.submit();

}

//=============================================================;
function busy() {
    gebi("gbcontent").style.display = "none";
    gebi("gbwait").style.display = "inline";
}



//=============================================================;
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) {

    $("#" + piclensTarget).stop().animate({ opacity: 0 }, 500);
    if (piclensTarget === "") {
        showWait("content");
    }
    else if (piclensTarget === "modal") {
        showWait("screen");
    }
    else {
        showWait(piclensTarget);
    }
    resetId((piclensTarget));
    var data = initData();
    if (gebi("productsearch")) {
        asearch = gebi("productsearch").value;
    }
    else {
        asearch = "";
    }

    //            extern=replace(extern,"slideshow.asp?",vbasedomain+"?relay=slideshow.asp&usermd5="+gbmd5_tags+"&");


    data[4] = vbaseroot + "?relay=productshow.asp&site_c=" + asite + "&page=" + num + "&search=" + asearch + "&ps_name=" + ps_name;
    data[3] = page_c;
    data[2] = piclensTarget;
    showNodeCallBack(data);
}


// ======================================================================	;
function slidePage(num, page_c, asite, ss_name) {
    if (gebi("showcooliris")) {
        if (gebi("showcooliris").style.display === "") { searchCoolIris("cooliris_container", gebi("slidesearch").value); return; }
    }
    $("#" + piclensTarget).stop().animate({ opacity: 0 }, 500);
    if (piclensTarget === "") {
        showWait("content");
    }
    else if (piclensTarget === "modal") {
        showWait("screen");
    }
    else {
        showWait(piclensTarget);
    }
    resetId((piclensTarget));
    var data = initData();
    if (gebi("slidesearch")) {
        asearch = gebi("slidesearch").value;
    }
    else {
        asearch = "";
    }

    //            extern=replace(extern,"slideshow.asp?",vbasedomain+"?relay=slideshow.asp&usermd5="+gbmd5_tags+"&");


    if ((search !== "") && (num === 1)) { searchCoolIris("cooliris_container", search); }
    data[4] = vbaseroot + "?relay=slideshow.asp&site_c=" + asite + "&page=" + num + "&search=" + asearch + "&ss_name=" + ss_name;
    data[3] = page_c;
    data[2] = piclensTarget;
    showNodeCallBack(data);
}

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) {
    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(url, containerId, width, height, version, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn);
    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("document_body").appendChild(obj);
        document.body.appendChild(obj);
        if ((hasDragDrop) && (!dd.elements[objId])) {
            ADD_DHTML(objId + RESET_Z);
            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;
            obj.style.top = 0;

        }

        if (objId === "vbaselink") { $(obj).removeClass("vbaselink").addClass("adminbutton"); }
        if (objId === "searchspan") { $(obj).removeClass("searchspan").addClass("adminbutton"); }
    }
}




// ======================================================================	;
function deletePseudoStyles() {


    for (var i = 0; i < theRules.length; i++) {
        if (theRules[i].style["content"]) {
            if (theRules[i].style["content"] !== "") { deleteStyleText(theRules[i].selectorText); }
        }
    }
}
// ======================================================================	;
function reNav() {
    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.body.scrollLeft, 10); }
    if (nn6) { ynow = e.pageY; } else { ynow = parseInt(event.clientY, 10) + parseInt(document.body.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;
            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;
        dragobject.style.top = newtop;
        dragobject.style.width = newwidth;
        dragobject.style.height = newheight;

        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.body.scrollLeft, 10); }
        if (nn6) { cury = e.pageY; } else { cury = parseInt(event.clientY, 10) + parseInt(document.body.scrollTop, 10); }
        return false;
    }
}



//=====================================
function caption_it() {

    //if(!passwordPassed) {return}
    $("#tag_instructions").hide();
    $("#caption_instructions").show();
    $("#tag_controls").hide();
    $("#caption_controls").show();
    gebi("input").style.top = picTop;
    gebi("input").style.left = picLeft;
    $("#input").show();
    gebi("taginput").style.width = 400;
    $(".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");
            return;
        }
        else {
            tagsloggedin = true;
        }
    }
    gebi("taginput").style.width = 200;
    $(".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.body.scrollLeft, 10); }
    if (nn6) { any = e.pageY; } else { any = parseInt(event.clientY, 10) + parseInt(document.body.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;
    gebi("input").style.left = midx - getscrollwidth("input") / 2;
}

//=====================================
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;
    document.sform.submit();
    anid = gebi("currentpic").spanid; // id of the small image. we need to change the caption
    gebi(anid).title = 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("popcontainer").style.left, 10);
    r = parseInt(gebi("popcontainer").style.left, 10) + getscrollwidth("popcontainer");
    t = parseInt(gebi("popcontainer").style.top, 10);
    b = parseInt(gebi("popcontainer").style.top, 10) + getscrollheight("popcontainer");
    $(".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 getTagCallback(data) {

    // creates and positions the tags
    //username, tag_id, photo_id, user_id, tagtop, tagleft, tagwidth,tagheight, tagtext, email,givenname,familyname,blacklisted

    nfields = 13;

    for (var i = 0; i < data.length; i = i + nfields) {
        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;
        newdiv.style.height = picHeight / 100 * tagheight;
        newdiv.style.left = picLeft + picWidth / 100 * tagleft;
        newdiv.style.top = picTop + picHeight / 100 * tagtop;
        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>";
            //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 === nfields) {
        gebi("ntags").innerHTML = data.length / nfields + " tag";
    }
    else {
        gebi("ntags").innerHTML = data.length / nfields + " 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;
        aclone.style.top = ycent - aclone.scrollHeight / 2;
    });
}

//=====================================
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
    gebi("ntags").innerHTML = "";
}

//=====================================
function slideshowSubmitted(anaction) {  // called by child window!

    if (anaction === "submitcaption") {
        gebi("popcontainer").style.display = 'none';
    }
    if (anaction === "submittag") {
        killPop();
        removeAllTags();

        getTags(gebi("imageId").value);
    }
    if (anaction === "deletetag") {
        removeAllTags();
        kill_tag(false);

        getTags(gebi("imageId").value);
    }
}


//=====================================
function showPop(text, anx, any) {
    if (text === "") { return; }
    if (!anx) { var anx = curx + 50; } if (!any) { var any = cury; }
    gebi("popcontainer").style.display = "inline-block";
    gebi("popcontainer").style.width = 500;
    $("#popshadow").css("opacity", 0.5)[0].innerHTML = text;
    $("#poptext").css("opacity", 1)[0].innerHTML = text;
    if ($("#popcaptionspan")[0]) { $("#poptext hr").css("width", $("#popcaptionspan")[0].scrollWidth); }


    gebi("popcontainer").style.width = gebi("poptext").scrollWidth + 6;
    gebi("popcontainer").style.height = gebi("poptext").scrollHeight + 6;
    any = min(any, windowH - gebi("poptext").scrollHeight + 6 - 20);
    gebi("popcontainer").style.display = "none";

    gebi("popcontainer").style.left = anx;
    gebi("popcontainer").style.top = any;

    $("#popcontainer").stop().css("display", "none").css("opacity", 1).fadeIn(500);

}
//=====================================
function killPop() {
    $("#popcontainer").stop().fadeOut(500);
}

//=====================================
function showPopCentered(text, obj) {

    gebi("popcontainer").style.display = "inline-block";
    gebi("popcontainer").style.width = 500;
    $("#popshadow").css("opacity", 0.5)[0].innerHTML = text;
    $("#poptext").css("opacity", 1)[0].innerHTML = text;
    if ($("#popcaptionspan")[0]) { $("#poptext hr").css("width", $("#popcaptionspan")[0].scrollWidth); }

    gebi("popcontainer").style.width = gebi("poptext").scrollWidth + 6;
    gebi("popcontainer").style.height = gebi("poptext").scrollHeight + 6;
    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("popcontainer").style.left = anx;
    gebi("popcontainer").style.top = any;

    gebi("popcontainer").style.display = "none";

    $("#popcontainer").stop().css("display", "none").css("opacity", 1).fadeIn(500);
}


//=====================================
function popTag(text, obj) {
    $(obj).css("opacity", 0.7);
    showPopCentered(text, obj);
}

//=====================================;
function gebi(anid) { return document.getElementById(anid); }


// ======================================================================	


// ======================================================================	
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof window.pageYOffset == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
}


// ======================================================================
function replace(string, text, by) {
    // Replaces text with by in string
    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
    if (document.all) {
        return parseInt(gebi(anid).clientHeight, 10);
    }
    else {
        return parseInt(gebi(anid).offsetHeight, 10);
    }
}
// ======================================================================	
function getscrollwidth(anid) {
    if (!gebi(anid)) { alert("no obj: getscrollwidth: "+ anid) }
    return gebi(anid).offsetWidth
    if (document.all) {
        return parseInt(gebi(anid).clientWidth, 10);
    }
    else {
        return parseInt(gebi(anid).offsetWidth, 10);
    }
}

//=====================================
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 &

        for (var 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)
//  check for valid numeric strings	
{
    var strValidChars = "0123456789-";
    var strChar;
    var blnResult = true;

    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_c, ss_name) {
    if (trim(aval) !== "") {
        extra = "";
        if (forceRemote) { extra = extra + "&forceremote=1"; }
        src = vbasepath + "autocomplete.asp?site_c=" + site_c + "&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(5, data.length);
    for (var 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;
    b.style.zIndex = 1000;

    if (data.length > 0) { b.style.display = ""; } else { b.style.display = "none"; }

    if (a.getAttribute("boxalign") === "left") { //align left with left
        b.style.left = x;
    }
    else { // alight the right side of autosuggest to the right side of slidesearch
        b.style.left = x - b.offsetWidth + a.offsetWidth + 35;
    }


}

// ======================================================================	;
function printNode(node) {
    var extra = "";
    if (forceRemote) { extra = extra + "&forceremote=1"; }

    src = vbasepath + "printnode.asp?site_c=" + site_c + "&content_c=" + node + extra;
    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;

    var myarray = [];
    for (var i = 0; i < jsonstuff.items.length; i++) {
        var rec = jsonstuff.items[i];
        for (var n in rec) {
            fieldname = n;
            //myarray[j]=eval("rec."+trim(fieldname+" "));
            myarray[j] = rec[fieldname];

            j++;
        }
    }

    return myarray;


}




// ======================================================================	
function navCallBack(data) {


    // select content_c,title,page_no,target,pagecount

    nChapters = 0;
    // count pages

    // "[subscriber id],[Title],[page_no]"


    for (var i = 0; i < data.length; i = i + nfields) {
        pageno = data[i + 2];
        if (pageno.indexOf("_") === -1) { nChapters++; }
    }

    // write out the navigation


    atr = document.createElement("tr");
    atr.id = "navcontent";


    navhtml = "";
    sublinkcounter = 0;
    for (var i = 0; i < nChapters; i++) {

        start = getchapter(i, data);

        content_c = data[start];
        atitle = data[start + 1];
        pageno = data[start + 2];
        target = data[start + 3];
        //idNames[content_c]=atitle;


        if (showNavText === false) { atitle = "&nbsp;"; }
        //atitle=replace(atitle,"'","\'");
        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_c=" + content_c + " target=" + target + " ";

        navhtml += "<div  id=" + chapterid + " class='" + chapterclass + "'" + extra + " >";
        navhtml += "<a style='z-index:4' 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_c = data[start + nfields];
                atitle = data[start + nfields + 1];
                pageno = data[start + nfields + 2];
                target = data[start + nfields + 3];

                extra = "";
                extra = extra + " pageno=" + pageno + " content_c=" + content_c + " target=" + target + " ";

                navhtml += "<div  id=link_" + pageno + "  class=sublink " + extra + " ><span>" + atitle + "</span></div>";

                start = start + nfields;
                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_c = findAttribute(this, "content_c");
        if (changeState) {
            if (state !== "") { changeState(""); }
        }
        if (!disableNavClick) {
            //if (this.id === "link_first") { alert("onclick: "+ content_c) }
            showNode(content_c, target, "");
            if (target === "content") { lastPage = page_no; }
        }
    });

    //-------------------------------------------------------------------
    // 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');
        }
    });

    var i = 0;
    // copy styles to width and height

    for (var icnt = 0; icnt < navObjects.length; icnt++) {
        if (getStyle(navObjects[icnt], "height") !== "") {
            astyle = replace(navObjects[icnt], "_first", "");
            astyle = replace(astyle, "_last", "");
            $("#navholdertable ." + navObjects[icnt]).each(function () {
                this.style.height = noPx(getStyle(navObjects[icnt], "height", true)) - heightWaste(astyle);
            });
        }
        if (getStyle(navObjects[icnt], "width") !== "") {
            astyle = replace(navObjects[icnt], "_first", "");
            astyle = replace(astyle, "_last", "");

            $("#navholdertable ." + navObjects[icnt]).each(function () {
                this.style.width = noPx(getStyle(navObjects[icnt], "width"), true) - widthWaste(astyle);
            });
        }
    }


    navpos(navPos);
    reaccordion("init");

    $("#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 (var 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


        if (lastPage === "00") {
            $(gebi("link_first")).addClass("link_clicked");
            $(gebi("link_first")).addClass("link_first_clicked");
        }
        else if (lastPage === lastLinkId) {
            $(gebi("link_first")).addClass("link_clicked");
            $(gebi("link_last")).addClass("link_last_clicked");
        }
        else {
            $(gebi("link_" + lastPage)).addClass("link_clicked");
        }
        firstTime = false;
    }
    else {
        round();
        showLastPage();

    }
    // ad this is the last call of init(), the whole document shold be there now

    if (!docIsLoaded) {
        docLoaded();
    }

}


// ======================================================================	;
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, doRound, doScroll) {

    w = noPx(w)
    h = noPx(h)

    if (w - getWidthStuff(name) <= 0) { return; }
    if (h - getHeightStuff(name) <= 0) { return; }
    //alert(name+" "+w+" "+h)
    if ((w === "") || (h === "")) { return }
    if ((w === 0) || (h === 0)) { return }
    unround(name)

    gebi(name).style.width = ""
    gebi(name).style.height = ""

    obj = gebi(name)

    if (!gebi(name + "_scroller")) {


        var adiv = document.createElement("div")
        obj.parentNode.appendChild(adiv)
        //adiv.appendChild(obj)
        //obj.id=name+"_scroller"
        //adiv.id=name

        adiv.id = name + "_scroller"
        moveNodes(obj, adiv)
        obj.appendChild(adiv)

    }
    gebi(name + "_scroller").style.overflow = "hidden"
    gebi(name + "_scroller").style.width = ""
    gebi(name + "_scroller").style.height = ""
    gebi(name).style.width = w - widthWaste(name)

    gebi(name + "_scroller").style.width = w - getWidthStuff(name)
    gebi(name + "_scroller").style.padding = ""

    gebi(name).style.height = h - heightWaste(name)
    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)


    if (doScroll) { initScroller2(name + "_scroller"); }

    if (doRound) { round(name) }
}

// ======================================================================	;
function initScroller2(divId) {
    // 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
    //alert(divId)
    currentPaddingRight = noPx(getStyle(gebi(divId).parentNode.id, "paddingRight"))
    //alert(divId)
    //      remove anything that might be there

    if (gebi("vbar_" + divId)) {
        var curp = noPx(gebi(divId).style.paddingRight)
        gebi(divId).style.paddingRight = 0
        if (!isIE()) { gebi(divId).style.width = noPx(gebi(divId).style.width) + curp }
    }
    removeNode(gebi("vglider_" + divId));
    removeNode(gebi("vbar_" + divId));
    removeNode(gebi("vbar2_" + divId));



    //      anythng to do ?
    if (!hasScrollBar(gebi(divId))) { return }
    if (!styleScrollbars) {
        gebi(divId).style.overflow = "auto"
        gebi(divId).style.paddingRight = currentPaddingRight + sliderWidth
        if (!isIE()) { gebi(divId).style.width = noPx(gebi(divId).style.width) - (currentPaddingRight + sliderWidth) }

        return
    }


    var adiv = gebi(divId);
    gebi(divId).scrollTop = 0;
    adiv.onscroll = function () { setGlider(divId); };

    if (!gebi("vbar_" + divId)) {
        var abar = document.createElement("div");
        abar.className = "vbar_" + divId + " " + "dragme";
        abar.style.position = "absolute";
        abar.style.overflow = "hidden";
        abar.id = "vbar_" + divId;
        document.body.appendChild(abar);
    }
    else {
        var abar = gebi("vbar_" + divId);
    }
    var newstylename = "vbar_" + divId;
    //setStyle(divId,"paddingRight",currentPaddingRight+sliderWidth)
    gebi(divId).style.paddingRight = currentPaddingRight + sliderWidth
    if (!isIE()) { gebi(divId).style.width = noPx(gebi(divId).style.width) - (currentPaddingRight + sliderWidth) }

    abar.style.height = gebi(divId).offsetHeight - heightWaste("vbar_" + divId)

    setStyle("vbar_" + divId, "width", barWidth);
    abar.style.width = noPx(barWidth) - widthWaste("vbar_" + divId);

    aw = noPx(abar.style.width)
    if (getStyle("vbar_" + divId, "borderWidth") === "") {
        abar.style.marginLeft = (sliderWidth - aw) / 2
    }

    abar.style.display = "";
    abar.onclick = function (event) { getMouse(event); scrollClick(divId); };


    var newGlider = false;
    if (!gebi("vglider_" + divId)) {
        newGlider = true;
        var aglider = document.createElement("div");
        aglider.className = "vglider_" + divId + " " + "dragme";
        aglider.style.position = "absolute";
        aglider.style.overflow = "hidden";

        aglider.id = "vglider_" + divId;
        document.body.appendChild(aglider);
    }
    else {
        var aglider = gebi("vglider_" + divId);
    }

    newstylename = "vglider_" + divId;

    aglider.style.position = "absolute";
    aglider.style.display = "";

    setStyle("glider_" + divId, "width", gliderWidth);
    aglider.style.width = noPx(gliderWidth) - widthWaste("vglider_" + divId);

    aw = noPx(aglider.style.width)
    aglider.style.marginLeft = (sliderWidth - aw) / 2

    var y = findPosY(adiv, true);
    var x = findPosX(adiv, true) + adiv.offsetWidth - sliderWidth;
    abar.style.left = x;
    abar.style.top = y;
    aglider.style.left = x;
    aglider.style.top = y;
    abar2 = document.createElement("div")
    abar2.style.width = sliderWidth
    abar2.style.height = abar.offsetHeight
    abar.parentNode.insertBefore(abar2, abar);
    abar2.id = "vbar2_" + divId
    //abar2.parentNode.insertBefore(abar,abar2);

    abar2.style.backgroundColor = "transparent"
    abar2.style.position = "absolute"
    abar2.style.left = x;
    abar2.style.top = y;
    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'; };
    //aglider.onmouseout=function(){dragmode='';};
    abar.onmouseover = function () { dragmode = 'vertical'; };
    //abar.onmouseout=function(){dragmode='';};

    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_scroler") { 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;
    round("vbar_" + divId);
    round("vglider_" + divId);

    // 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;
    });
}


//=======================================================;
function getDimensions(limit) {
    windowH = noPx(getWindowSize("h"));
    windowW = noPx(getWindowSize("w"));
    //windowH=gebi("body").offsetHeight
    //report("body")
    /* returns the outer width and heights of the following. (add Width an Height to get variable names);
    body;
    page;
    content;
    contentScroller;
    contentOuter;
    top;
    bottom;
    left;
    right;
    leftScroller;
    rightScroller;
    leftText;
    rightText;
    */

    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 - widthWaste("body");
    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"));
    //x = x + marginsW("right")

    contentWidth = pageWidth - x - getWidthStuff("page") - getWidthStuff("content_outer")

    if ((!haveScrollbar) && (!limit)) {
        //bodyHeight=gebi("content").offsetHeight+getHeightStuff("content_outer")+margins+getHeightStuff("body")+getHeightStuff("page");
        //alert(1)
        bodyHeight = textHeight("content") + getHeightStuff("content_outer") + margins + getHeightStuff("body") + getHeightStuff("page");
        if ($("#content #extif").length > 0) {
            //bodyHeight=textHeight("content")+400+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");
    var margins = parseInt(gebi("top1_spacer").offsetHeight, 10);
    margins = margins + parseInt(gebi("bottom2_spacer").offsetHeight, 10);

    //report("left");

    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");
    //  if (!haveScrollbar){alert("here");contentHeight=max(contentHeight,textHeight("content"));}


    txt = "contentHeight: " + contentHeight
    txt = txt + "<br>contentWidth: " + contentWidth
    txt = txt + "<br>middleHeight: " + middleHeight
    txt = txt + "<br>stuff: " + getHeightStuff("content_outer")
    txt = txt + "<br>pageHeight: " + pageHeight
    txt = txt + "<br>bodyHeight: " + bodyHeight
    txt = txt + "<br>windowHeight: " + windowH
    txt = txt + "<br>document.body.clientHeight: " + document.body.clientHeight

    //document.body.clientHeight
    //gebi("content").innerHTML = txt
}



//=======================================================;
function border(target, color) {
    if (!color) {color="#ff0000"}
    gebi(target).style.border="1px solid "+color
}