// 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 userloggedin=false;
    var tagsloggedin=false;
    var tagsuserid="";
    var tagsusername="";

    var blogsloggedin=false;
    var blogsuserid="";
    var blogsusername="";

    var linkhlp=[];
    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 contentScrollerHeight;
    var contentScrollerWidth;
    var topHeight;
    var bottomHeight;

    var searchTarget="";
    var haveProducts=false;

    var md5Hash="";
    var site_c;
    var start=false;
    var username="";
    var password="";
    var lastClicked="";
    var passwordPassed=false;
    var docLoc="";
    var showWhenHover=false;
    var haveScrollbar=false;
    var lastId;
    var topId;
    var leftId;
    var bottomId;
    var rightId;
    var modalId;
    var state="";
    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 toHandles=[]; // holds setTimeout-handles;

    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 supended=false;   // flag to indicate to stop all actions because we are updating or so;
    var abort=-1;


    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|vbar_modal|";
    objects=objects+"vglider_modal2|vbar_modal2|";
    objects=objects+"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+"gbcommentseperator|gbcomment|gbcommentheader|gbtopic|gbtopicheader|gbtopicholder|gbpage|gbnavigation|gbsubject|gbtopicseperator|hr|vbaselink|searchspan|";
    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";

    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 contentHeight;

    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 (((vbasedomain.indexOf("localhost")!==-1) || (vbasedomain.indexOf("vbaseworks")!==-1)) && (!vbasedomain.find("panel.vbaseworks"))){
        if ((vbaseroot===vbasedomain)||(vbasedomain.indexOf("localhost")!==-1)) {
            sameDomain=true;
        }
    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);});
        $("#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) {

    //alert("aux remove " + 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) {
        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) {
        document.body.style.overflow="hidden";
        gebi("document_body").scrollTop=0;
            if (something==="content") {

                setStyle("document_body",'overflowY','hidden');

                setStyle("content_scroller",'overflow','auto');
                setStyle("content_scroller",'overflowY','auto');
                setStyle("content_scroller",'overflowX','hidden');
                haveScrollbar=true;
            }
            else {

                setStyle("content_scroller",'overflow','auto');
                setStyle("content_scroller",'overflowY','auto');
                setStyle("content_scroller",'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+"=============== 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;

    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;

    var a=getStyle(id,"height");
    var b=gebi(id).style.height;
    setStyle(id,"height","");
    gebi(id).style.height="";

    gebi(id).style.overflow="hidden";

    var c=gebi(id).offsetHeight;

    setStyle(id,"height",a);
    gebi(id).style.height=b;

    return c;


}

//=======================================================;
function getStyleNH(name,prop) {
    // get dimensions if objetc is not hidden;

    //var d=eval("gebi('"+name+"').style."+prop);
    var d=gebi(name).style[prop];

    if (d==="") {
         d=noPy(getStyle(name,prop));
    }

    if (gebi(name).style.display==="none") {d=0;}
    if (getStyle(name,"display")==="none") {d=0;}
    return noPy(d);
}


//=======================================================;
function swap(id) {
    if (!isSwapped(id)) {
        // not yet swapped;
        a=gebi(id+"_holder").childNodes[0];
        adiv=document.createElement("div");
        adiv.id="swap"+id+"spacer";
        var ah=parseInt(gebi("top1_spacer").offsetHeight,10);
        if (ah===0) {
            adiv.style.display="none";
        }
        else {
            adiv.style.height=ah;
        }

        gebi("page"+id+"_spacer").appendChild(adiv);
        gebi("page"+id+"_spacer").appendChild(a);

    }
    else {
        // already swapped;
        gebi("page"+id+"_spacer").childNodes[0].parentNode.removeChild(gebi("page"+id+"_spacer").childNodes[0]);
        a=gebi("page"+id+"_spacer").childNodes[0];
        gebi(id+"_holder").appendChild(a);

    }
}


//=======================================================;
function isSwapped(id) {
    if (trim(gebi(id+"_holder").innerHTML)==="") {return true;}
    return false;
}

//=======================================================;
function setContentHeight(target,fudge) {

    if (target==="modal") {return;}

    if (!haveScrollbar) {
        setVsize("setContentHeight",true,fudge);
    }
    else {
        if (target==='content') {
            gebi("content_scroller").scrollTop=0;
        }
        else {
            gebi(target).scrollTop=0;
        }
        document.body.scrollTop=0;

        getDimensions(false);


        setNewHeight("left",textHeight("left"));
        if (left100==="yes") {
            if (textHeight("left")<leftHeight){setNewHeight("left",leftHeight);}
        }
        else {
            //setNewHeight("left",leftHeight);
        }
        setNewHeight("right",textHeight("right"));
        if (right100==="yes") {
            if (textHeight("right")<rightHeight){setNewHeight("right",rightHeight);}
        }
        else {
            //setNewHeight("right",rightHeight);
        }

        if (target==="content") {
            setNewHeight("content",max(contentHeight,textHeight("content")));
        }
        else if (target==="top") {
            setNewHeight("top",topHeight);
        }
        else if (target==="bottom") {
            setNewHeight("bottom",bottomHeight);
        }
    }

    if (target==="content") {initScroller("content_scroller");}
    if (target==="left") {initScroller("left_scroller");}
    if (target==="right") {initScroller("right_scroller");}
    if (target==="modal") {initScroller("modal");}
    if (target==="modal2") {initScroller("modal2");}
    initScroller("document_body");



}

var currentWindowW=0;
var currentWindowH=0;
var resizeHandle;
//=======================================================;
function windowresize() {

    // IE fires multiple times;
    windowH=noPy(getWindowSize("h"));
    windowW=noPy(getWindowSize("w"));
    if ((windowW!==currentWindowW) || (windowH!==currentWindowH)) {
        clearTimeout(resizeHandle);
        resizeHandle=setTimeout(function() {
            setVsize("windowresize",true);
            if (onVBPageLoad) {onVBPageLoad(-1);}
            currentWindowW=windowW;
            currentWindowH=windowH;

        },500);
    }
    else {
    }
}

//=======================================================;
function hasScrollBar(elem) {
    if (elem.clientHeight < elem.scrollHeight) {
        return true;
    }
    return false;
}

//=======================================================;
function setNewHeight(paneId,newHeight) {

    gebi(paneId).style.height=newHeight-heightWaste(paneId);
}




//===================================================================================================;
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;
       }
        else {

            if (gebi("vbcenter")) {
                gebi("body").appendChild(gebi("page_holder"));
                gebi("body").removeChild(gebi("vbcenter"));
                setStyle("document_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() {

        // 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("content","backgroundColor")==="") {
            if (isIE())  {
                $("#content").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++;
        var caption="vBase";
        if (src.find("type=image")) {caption="vBase Image Browser";}

        if (tinyBrowserWrapperRef) {
            tinyBrowserWrapperRef.show();
            tinyBrowserWrapperRef.moveTo("middle","middle");

            //gebi("tinyBrowserWrapper").style.zIndex=gebi("tinyBrowserWrapper").style.zIndex+10;
            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");
            //gebi("tinyBrowserWrapper").style.zIndex=zIndex;

            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) {

        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];


                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];}
                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) {
                        
                            data[2]="modal2";
                            data[4]="http://"+mal_server+".aitsafe.com/cf/review.cfm?userid="+merchant_id+""; // extern;
                            showNodeCallBack(data);
                        }
                        else if (showproduct) {
                            var extra="";
                            //if (forceRemote) {extra=extra + "&forceremote=1";}
                            data[4]="productshow.asp?site_c=" + site_c +"&p_id="+product_id + extra;
                            data[2]="modal2";
                            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")) {
            a.parentNode.removeChild(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;
        }

        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="";
}

var saveScrollTop;
var curpic;


var imgArray2=[];
var imgArrayCounter2=0;

//=======================================================;
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";

    //alert("prev: " + prev +"\nnext :" + next);

   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=noPy(gebi("picture_holder").style.width);
        startheight=noPy(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(noPy(image.width)+20,410);
        var ch=noPy(image.height)+40+captionHeight;
        var newleft=noPy(ph.style.left)-cw/2+(startwidth/2);
        var newtop=noPy(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=vbasepath+"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 vbasepath+"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 noPy(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=noPy(getStyle(styleName,"paddingLeft"));
    pr=noPy(getStyle(styleName,"paddingRight"));
    bl=noPy(getStyle(styleName,"borderLeftWidth"));
    br=noPy(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=noPy(getStyle(styleName,"marginLeft"));
    mr=noPy(getStyle(styleName,"marginRight"));
    ml=0;
    mr=0;
    if (leftOnly) {return bl;}
    return pl+pr+bl+br+ml+mr;
}

//=============================================================;
function getHeightStuff(styleName,topOnly) {
    pt=noPy(getStyle(styleName,"paddingTop"));
    pb=noPy(getStyle(styleName,"paddingBottom"));
    bt=noPy(getStyle(styleName,"borderTopWidth"));
    bb=noPy(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=noPy(getStyle(styleName,"marginTop"));
    mb=noPy(getStyle(styleName,"marginBottom"));
    mt=0;
    mb=0;
    if (topOnly) {return (bt);}
    return (pt+pb+bt+bb+mt+mb);
}//=============================================================;


var divcounter=0;

// ======================================================================	;
function roundstuff(target) {
    // 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 (target==="content") {alert(width + " "+height)}


            if (width!=="")  {width=parseInt(width,10);img.setAttribute("width",width);}
            if (height!=="") {height=parseInt(height,10);img.setAttribute("height",height);}
            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);
            }
            //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=vbasepath+"image.php/myimage.jpg?image="+encodeURIComponent(decodeURIComponent(img.src))+w+h+cr;
                        var newsrc=vbasepath+"image.php/myimage.jpg?image="+encodeURIComponent(asrc)+w+h+cr;
                        //var newsrc="http://vbaseworks.com/v167/image.php/myimage.jpg?image="+encodeURIComponent(asrc)+w+h+cr;
                        img.src=newsrc;
                        img.id="img_"+imgID;
                        imgID++;
                    }
                }
                else {
                        img.src=asrc;
                }
            }
            else {
                img.src=asrc;
                img.id=img.src+"&rotorId=" + rotorId;
                //img.onload=function(){round("image"+target);};
                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.appendChild(txt);

                aspan.style.position="relative";

                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;
                    }
                }
                else {

                   // aspan.style.verticalAlign=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) {atime=atime*1000;} else {atime=5000;}
                img.time=atime;
                
                a=function(img) {
                    return function() {
                        setTimeout(function(){rotate(img.id,img.target);},img.time*1);
                     };
                }(img);
                
                $(img).bind("load",a);

                
                //var time=img.src.split("time=")[1];

                //rotate(img.id,target);
            }
        }
    }
}    


function xxstopRotators(target) {
    var alist=gebi(target).getElementsByTagName("img");
    for (var i=0;i< alist.length;i++) {
        var img=alist[i];
        clearTimeout(img.timeoutHandle);
        $(img).stop().css("opacity",1);
        if (img.id.indexOf("_rotator")!==-1) {img.parentNode.removeChild(img);img=null;}
    }
}            
        


//  ==========================================================================
    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) {
        var img=gebi(who);

        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.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);
                img.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;
            }
            
            clearTimeout(b.timeoutHandle);
            if (who===base) {
            
                r.src=src;
                
                r.onload=function(){
                
                    b.timeoutHandle=setTimeout(function(){rotate(rotator,target); },5000);

                    b.isLoaded=false;
                    r.isLoaded=true;
                    if ( (r.width!==b.width) || (r.width!==b.width) ) {
                        $(b).animate({opacity:0},250,function(){
                            $(b).css("display","");$(r).css("display","").animate({opacity:1},250);
                            });
                    }
                    else {
                        $(r).css("display","").animate({opacity:1},500,function(){
                            $(b).css("opacity",0).css("display","");
                            });
                    }
                };
            }
            else {
                
                b.src=src;
                
                b.onload=function(){
                
                b.timeoutHandle=setTimeout(function(){rotate(base,target);},5000);

                
                    r.style.visibility='visible';
                
                    r.isLoaded=false;
                    b.isLoaded=true;
                    if ((r.width!==b.width) || (r.height!==b.height)) {
                        $(r).animate({opacity:0},250,function(){$(r).css("display","");$(b).css("display","").animate({opacity:1},250);});
                    }
                    else {
                        $(b).css("display","").animate({opacity:1},500,function(){$(r).css("opacity",0).css("display","");});
                    }
                };
                
            }// 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);

    }
}


var lastTarget;



// ======================================================================	;
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);
        }
    }

    // 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===contentId)) {setNav(id);anchor.content=ananchor;goToAnchor("content");return;}
    if ((ananchor!=="") && (atarget==="content") && (id===contentId)) {setNav(id);anchor.content=ananchor;goToAnchor(atarget);return;}
    if ((ananchor!=="") && (atarget==="top") && (id===topId)) {setNav(id);anchor.top=ananchor;goToAnchor(atarget);return;}
    if ((ananchor!=="") && (atarget==="bottom") && (id===bottomId)) {setNav(id);anchor.bottom=ananchor;goToAnchor(atarget);return;}
    if ((ananchor!=="") && (atarget==="left") && (id===leftId)) {setNav(id);anchor.left=ananchor;goToAnchor(atarget);return;}
    if ((ananchor!=="") && (atarget==="right") && (id===rightId)) {setNav(id);anchor.right=ananchor;goToAnchor(atarget);return;}
    if ((ananchor!=="") && (atarget==="modal") && (id===modalId)) {setNav(id);anchor.modal=ananchor;goToAnchor(atarget);return;}


      // 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;
    if ((atarget==="content") && (contentId===id)) {skip=true;}
    if ((atarget==="left") && (leftId===id)) {skip=true;}
    if ((atarget==="right") && (rightId===id)) {skip=true;}
    if ((atarget==="top") && (topId===id)) {skip=true;}
    if ((atarget==="bottom") && (bottomId===id)) {skip=true;}
    if ((atarget==="modal") && (modalId===id)) {skip=true;}
    if (!skip) {
        //gets the content of the page when clicked on a nav div;
        showEditStuff();


        if (atarget==="modal") {
            lastNodeShowed=id;
        }
        else {
            lastNodeShowed=id;
        }

    if (lastNodeShowed) {
        closeModal(1);
        closeModal(2);
    }

        // 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 ((target==="content") && (contentId===id)) {hideWait();return;}
    if ((target==="left") && (leftId===id)) {hideWait();return;}
    if ((target==="right") && (rightId===id)) {hideWait();return;}
    if ((target==="top") && (topId===id)) {hideWait();return;}
    if ((target==="bottom") && (bottomId===id)) {hideWait();return;}
    if ((target==="modal") && (modalId===id)) {hideWait();return;}

    if (target==="content") {contentId=id;}
    if (target==="top") {topId=id;}
    if (target==="left") {leftId=id;}
    if (target==="right") {rightId=id;}
    if (target==="bottom") {bottomId=id;}
    if (target==="modal") {modalId=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='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('"+contentId+"')\"><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",0);
        startRotators(target);

        //var saveheight=gebi(target).style.height;
        //if ((target!=="modal") && (target!=="modal2")) {gebi(target).style.height=""}

        if (target==="content") {initScroller("content_scroller");}
        if (target==="left") {initScroller("left_scroller");}
        if (target==="right") {initScroller("right_scroller");}
        if (target==="modal") {initScroller("modal");}
        if (target==="modal2") {initScroller("modal2");}
        initScroller("document_body");

        $("#"+target).stop().animate({opacity:1},300,function(){
            fixIEBlur();
        });

        linkstuff(target);
        setContentHeight(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);}
        goToAnchor(target);

        setIframeSize(target);
        hideWait();
        
    }

}
// ======================================================================	;
   function setIframeSize(target) {
        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.parentNode.replaceChild(aplaceholder,theframe);
                eh=textHeight(target);
                aplaceholder.parentNode.replaceChild(theframe,aplaceholder);
                aplaceholder=null;
                
                // done
                
                if (target==="content") {
                    theframe.style.display="none";

                    theframe.style.height=contentHeight-getHeightStuff("content")-eh-20;
                    if (ifh) { theframe.style.height=ifh;}

                    theframe.style.width=getscrollwidth("content_outer")-getWidthStuff("content_outer")-getWidthStuff("content_scroller")-getWidthStuff("content");
                    theframe.style.display="";
                }
                else if ((target==="modal") || (target==="modal2")) {


                    theframe.width=getModalWidth()-getWidthStuff("modal_holder")-getWidthStuff("modal")-15;
                    theframe.height=getModalHeight()-getHeightStuff("modal_holder")-getHeightStuff("modal")-eh-22;
                    if (theframe.height<300) { theframe.height=200;}
                    if (ifh) { theframe.style.height=ifh;}

                    //gebi("modal").style.overflow="hidden";
                }
                else {
                    theframe.width=getscrollwidth(target)-getWidthStuff(target);
                    theframe.height=middleHeight-getHeightStuff(target);
                    if (ifh) { theframe.style.height=ifh;}

                }
            }
        }
  }

// ======================================================================	;
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;
            document.styleSheets[1].insertRule(styleName+" {"+property.toDash()+":"+value+";}", theRules.length);
        }
        else { //else if IE;
            document.styleSheets[1].addRule(styleName, property.toDash()+":"+value);
        }
        //alert(name)
        theRules=getRules();
        styleIndex[styleName]=theRules.length-1;
        
        indexChanged=true;
        return "";
    }


    //=======================================================;
    function setStyle(aname,property,value,ignoreState,index) {
        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];
        if ((apos) || (apos===0)) {
            theRules[apos].style[property]=value;
        }
        else {
            createStyle(aname,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();
    indexStyle();
 
    pageColor=getStyle("page","backgroundColor");
    bodyColor=getStyle("body","backgroundColor");

    setStyle("left_scroller","width",noPy(getStyle("left","width")));
    setStyle("right_scroller","width",noPy(getStyle("right","width")));
    th=noPy(getStyle("top","height"));
    bh=noPy(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,"readsyles");
                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;}

   //return;
    $("#toolbox .adminbutton").hover(function () {$(this).addClass('adminbutton_hover');},function () {$(this).removeClass('adminbutton_hover');});
    //alert(getStyle("document_body","overflow"))
    if ((getStyle("document_body","overflow")==="hidden") || (getStyle("document_body","overflowY")==="hidden")) {
        setScroll('content');
        haveScrollbar=true;

    }
    else {
        setScroll('window');
        haveScrollbar=false;
    }

    $("#sitemap").css("display","none");
    if (gebi("sitemap")) {
        gebi("sitemap").parentNode.removeChild(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();
    
    //windowH=noPy(getWindowSize("h"));
    //windowW=noPy(getWindowSize("w"));
    

}

// ======================================================================	;
function getBoolPseudoStyle(aname,defaultIfEmpty) {
    val=getPseudoStyle(aname,defaultIfEmpty);
    if (val==="") {val=defaultIfEmpty;}
    if (val==="true") {val=true;}
    if (val==="false") {val=false;}
    return val;
}



// ======================================================================	;
function docLoaded() {

    

    // float them before doing linksstuff, else 
    floatBox('vbaselink',gebi("vbaselink").isFloat);

    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("docLoaded",false);
        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++) {
            floatBox('aux'+i,true);
            gebi('aux'+i).style.display="";

        }
    
    round();
    //setVsize();
    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() {isdrag=false;dragobject="";};
    
    document.body.onmousemove=movemouse;
    
    // ie bug doesn't render the images
    if (getStyle("picture_holder","backgroundColor")==="") {setStyle("picture_holder","backgroundColor","#ffffff");}
        if (onVBPageLoad) {onVBPageLoad(contentId);}


 }

// ======================================================================	;
function setcenter(idToCenter,idToCalculate,addScroll) {
    windowH=noPy(getWindowSize("h"));
    windowW=noPy(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_scroller";}
    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';
    }
    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 showsearch(target,searchbuttons) {
        if (hasDragDrop) { // layout manager;
            if (dd.elements.searchSpan) {
                if (!gebi("locksearch").checked) {return;}
            }
        }

        searchResultPane=target;

        // 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();
        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;
        setContentHeight(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("searchresult").innerHTML=data; // to save;
        sb=gebi(searchTarget).childNodes[0].cloneNode(true);

        gebi(searchTarget).innerHTML="";
        gebi(searchTarget).appendChild(sb);
        txt=document.createElement("text");
        txt.innerHTML=data;
        gebi(searchTarget).appendChild(txt);

        linkstuff(searchTarget,true);
        setContentHeight(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 ((vkeydown) && (bkeydown) && (ekeydown)) {errorReport();}
	
}

//=====================================
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(anaction) {  // target = left right top bottom or content;

        if ((anaction==="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;
        }
        if (!passwordPassed) {showneedloginmes();login();return;}

        showEditor(anaction, 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;
                }
            }

            if (atarget==="top") {editId=topId;editPane="top";}
            else if (atarget==="bottom") {editId=bottomId;editPane="bottom";}
            else if (atarget==="left") {editId=leftId;editPane="left";}
            else if (atarget==="right") {editId=rightId;editPane="right";}
            else if (atarget==="modal") {editId=modalId;editPane="modal";}
            else {editId=contentId;editPane="content";}

            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;
            }

            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");
                }

                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;}";
            }
        }

        if (forceRemote) {extra=extra + "&forceremote=1";}
        extra=extra+"&target="+atarget;
        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="1px solid #ff0000";
        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 showneedloginmes() {
            gebi("updatediv").innerHTML="Please login first..";
            gebi("updatediv").style.display="inline";
            setcenter("updatediv","screen");
            gebi("updatediv").style.backgroundColor="#FFA28C";
            setTimeout(function(){gebi("updatediv").style.display="none";},2000);
        }
    // ======================================================================	;
        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;
        }


var psSrc;  // source of productshowmanager;
    // ======================================================================	;
    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,"","","");
                    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"+id+" src='"+vbasepath+"images/wait.gif' />   "+aval;
                    //faderOut(2);
                    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);
            }
        }

    }

    // ======================================================================	;
    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://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="";
        if (atarget==="top") {oldid=topId;topId=-1;}
        if (atarget==="left") {oldid=leftId;leftId=-1;}
        if (atarget==="right") {oldid=rightId;rightId=-1;}
        if (atarget==="bottom") {oldid=bottomId;bottomId=-1;}
        if (atarget==="content") {oldid=contentId;contentId=-1;}
        if (atarget==="modal") {oldid=contentId;modalId=-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="100%";
        gebi("fader"+no).style.height=getscrollheight("document_body");
        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===1) {
        gebi("modal"+anum+"_holder").style.zIndex=1000;
    }
    else {
        gebi("modal"+anum+"_holder").style.zIndex=1010;
    }

    gebi("modal"+anum+"_holder").style.width=noPy(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");

    gebi("modal"+anum+"_holder").style.width=getModalWidth(maxsize)-widthWaste("modal"+anum+"_holder");
    gebi("modal"+anum+"_holder").style.height=getModalHeight(maxsize)-widthWaste("modal"+anum+"_holder");
    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=noPy(gebi("modal"+anum+"_holder").style.left)-parseInt(cw/2,10)+75;
    var newtop=noPy(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","");
            initScroller("modal"+anum);
            round("modal"+anum+"_holder");
            round("modal"+anum);

            if (anum==="") {setIframeSize("modal"+anum);}
        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="";

    initScroller("modal"+anum);

    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==="") {modalId="";}
    }
}











//=======================================================;
function checkReturn(evt){
	(evt) ? thekey=evt.keyCode : thekey=event.keyCode;
    return (thekey == 13) ? true : false;
}


//=======================================================;
function setVsize(who,doround,fudge) {

    windowH=noPy(getWindowSize("h"));
    windowW=noPy(getWindowSize("w"));

   var oldstate=state;
   state="";

   gebi("document_body").style.height=windowH;
   gebi("document_body").style.width=windowW;

    getDimensions();

    setStyle("right","overflow","");
    setStyle("right","overflowX","");
    setStyle("right","overflowY","");
    setStyle("right","width","");
    setStyle("left","overflow","");
    setStyle("left","overflowX","");
    setStyle("left","overflowY","");
    setStyle("left","width","");


    gebi("body").style.width=bodyWidth-widthWaste("body");
    gebi("body").style.height=bodyHeight-heightWaste("body");

    gebi("page").style.width=pageWidth-widthWaste("page");
    gebi("page").style.height=pageHeight-heightWaste("page");


    setNewHeight("left",textHeight("left"));
    if (left100==="yes") {
        if (textHeight("left")<leftHeight){setNewHeight("left",leftHeight);}
    }
    else {
        //setNewHeight("left",leftHeight);
    }

    setNewHeight("right",textHeight("right"));
    if (right100==="yes") {
        if (textHeight("right")<rightHeight){setNewHeight("right",rightHeight);}
    }
    else {
        //setNewHeight("right",rightHeight);
    }

    setNewHeight("left_scroller",leftHeight);
    setNewHeight("right_scroller",rightHeight);

    if (getStyle("right_scroller","overflowY")==="") {setStyle("right_scroller","overflowY","auto");}
    if (getStyle("left_scroller","overflowY")==="")  {setStyle("left_scroller","overflowY","auto");}

    setNewHeight("content",max(contentHeight,textHeight("content")));
    setNewHeight("content_scroller",contentScrollerHeight);
    if ((fudge) && isIE()) {setNewHeight("content_scroller",contentScrollerHeight+1);}
    setNewHeight("content_outer",middleHeight);

    setNewHeight("top",topHeight);
    setNewHeight("bottom",bottomHeight);
    gebi("content_scroller").style.width=contentScrollerWidth-widthWaste("content_scroller");
    //gebi("content").style.width=contentScrollerWidth-getWidthStuff("content_scroller")-widthWaste("content");

    gebi("top").style.width=topWidth-widthWaste("top");

    gebi("bottom").style.width=topWidth-widthWaste("bottom");

    for (var i=1;i<11;i++) {
        if (getStyle("aux"+i,"width")!=="")  {gebi("aux"+i).style.width=noPy(getStyle("aux"+i,"width"))-widthWaste("aux"+i);}
        if (getStyle("aux"+i,"height")!=="") {gebi("aux"+i).style.height=noPy(getStyle("aux"+i,"height"))-heightWaste("aux"+i);}
        if (gebi("style"+i)) {if (getStyle("style"+i,"width")!=="")  {gebi("style"+i).style.width=noPy(getStyle("style"+i,"width"))-widthWaste("style"+i);}}
        if (gebi("style"+i)) {if (getStyle("style"+i,"height")!=="") {gebi("style"+i).style.height=noPy(getStyle("style"+i,"height"))-heightWaste("style"+i);}}

    }
    

    for (var i=1;i<11;i++) {
        if (getStyle("aux"+i,"width")!=="") {
            gebi("aux"+i).style.width=noPy(getStyle("aux"+i,"width"))-widthWaste("aux"+i);
        }                    
        if (getStyle("aux"+i,"height")!=="") {
            gebi("aux"+i).style.height=noPy(getStyle("aux"+i,"height"))-heightWaste("aux"+i);
        }                    
    }
    $("#toolbox .adminbutton").each(function() {
        if (getStyle("adminbutton","width")!=="") {
            this.style.width=noPy(getStyle("adminbutton","width"))-widthWaste("adminbutton");
        }                    
        if (getStyle("adminbutton","height")!=="") {
            this.style.height=noPy(getStyle("adminbutton","height"))-heightWaste("adminbutton");
        }                    
    
        
    });
    
    


    window.onresize=windowresize;

    if (doround) {
    
        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++) {
            floatBox('aux'+i,true);
            gebi('aux'+i).style.display="";

        }
    
        round("top");
        round("left");
        round("right");
        round("content_outer");
        round("content_scroller");
        round("content");
        round("body");
        round("page");

    }

    initScrollers();

    state=oldstate;
}

//=======================================================;
function positionOnAnchor(objId) {

    var obj=gebi(objId);
    if (!obj.isFloat) {return;}
    var anchor=obj.anchor;
    
    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+findPosX(gebi("page"));
        var newY=anchorY+findPosY(gebi("page"));
    }
    if (anchor==="right") {
        var newX=findPosX(gebi("page"))+getscrollwidth("page")-anchorX-getscrollwidth(objId);
        var newY=anchorY+findPosY(gebi("page"));
    }
    if (anchor==="leftbottom") {
        var newX=anchorX+findPosX(gebi("page"));
        var newY=findPosY(gebi("page"))+getscrollheight("page")-anchorY-getscrollheight(objId);
    }
    if (anchor==="rightbottom") {
        var newX=findPosX(gebi("page"))+getscrollwidth("page")-anchorX-getscrollwidth(objId);
        var newY=findPosY(gebi("page"))+getscrollheight("page")-anchorY-getscrollheight(objId);
    }

    if (hasDragDrop) {    
        dd.elements[objId].moveTo(newX,newY);
    }
    else {
        obj.style.left=newX;
        obj.style.top=newY;
    }

}

//=======================================================;
function getDimensions(limit) {


    /* 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=noPy(getStyle("top_holder","height"));
    bottomHeight=noPy(getStyle("bottom_holder","height"));

    gebi("content_scroller").style.overflow="";  //remove style, could have been set with shoform();
    gebi("content").style.height="";
    gebi("content").style.height="";
    setStyle("content","height","");


    var topH=gebi("top_holder").offsetHeight;
    var bottomH=gebi("bottom_holder").offsetHeight;

    var margins=       gebi("top1_spacer").offsetHeight+topH+gebi("top2_spacer").offsetHeight;
    margins=margins+gebi("bottom1_spacer").offsetHeight+bottomH+gebi("bottom2_spacer").offsetHeight;

    if ((!haveScrollbar) && (!limit)) {
        bodyHeight=gebi("content").offsetHeight+getHeightStuff("content_scroller")+getHeightStuff("content_outer")+margins+getHeightStuff("body")+getHeightStuff("page");
        if ($("#content #extif").length>0) {
                    bodyHeight=gebi("content").offsetHeight+400+getHeightStuff("content_scroller")+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;
    }

    bodyWidth=windowW;

    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);
    }

    pageHeight=bodyHeight-getHeightStuff("body");

    middleHeight=pageHeight-margins-getHeightStuff("page");
    contentScrollerHeight=middleHeight-getHeightStuff("content_outer");
    contentHeight=contentScrollerHeight-getHeightStuff("content_scroller");
    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);
    }

    topWidth=pageWidth-getWidthStuff("page")-noPy(getStyleNH("pageleft_spacer","width"))-noPy(getStyleNH("pageright_spacer","width"));

    var w=noPy(getStyle("page","width"));
    var w=pageWidth;
    var x=getStyleNH("left1_spacer","width")+getStyleNH("left_holder","width")+getStyleNH("left2_spacer","width")+max(getscrollwidth("pageleft_spacer"),getStyleNH("pageleft_spacer","width"));
    x=x+getStyleNH("right1_spacer","width")+getStyleNH("right_holder","width")+getStyleNH("right2_spacer","width")+max(getscrollwidth("pageright_spacer"),getStyleNH("pageright_spacer","width"));

    var w=w-x;
    contentScrollerWidth=w-getWidthStuff("page")-getWidthStuff("content_outer");

    }







//=======================================================;
function deleteStyleText(astyle) {

    var mysheet=document.styleSheets[1];
    var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;
    mysheet.crossdelete=mysheet.deleteRule? mysheet.deleteRule : mysheet.removeRule;

   // apos=styleIndex[astyle]alert(apos)    
   // if ((apos) || (apos===0)) {
   //     mysheet.crossdelete(apos);
   //     styleIndex[apos]=false
   // }
    
   // return
    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) {
    unround(classname);
    newround2(classname);
}

var rcounter=0;
//=======================================================;
function newround2(classname,generate) {
    //alert("newround: "+classname);
    var destroyed=false;
    var assetsArray=[];
    var nAssets=0;
    
    for (var i=0;i< theRules.length;i++) {
        var selector=theRules[i].selectorText.toLowerCase().substr(1);

        if ((selector===classname) || (selector===classname+"_hover") ||(selector===classname+"_clicked" )|| (!classname) || (classname==="")) {
        if (!selector.find("rounded_")) {

        if ((!classname) || (classname.find("sublink")) || (classname.find("chapter")) ) {
            if ($(gebi("navholder")).accordion()) {
                $(gebi("navholder")).accordion("destroy");JQsublink_container.show();
                destroyed=true;
            }
        }

        //if (((selector.indexOf(what)!==-1) && (what!=="")) || ((what==="") && (selector.indexOf("_clicked")===-1) && (selector.indexOf("_hover")===-1)))  {
        var nostate=replace(replace(selector,"_hover",""),"_clicked","");
        var baseStyle=nostate;
        if (nostate.indexOf("linkright_")!==-1) {baseStyle="linkright";}
        if (nostate.indexOf("linkleft_")!==-1) {baseStyle="linkleft";}
        if (nostate.indexOf("linktop_")!==-1) {baseStyle="linktop";}
        if (nostate.indexOf("linkbottom_")!==-1) {baseStyle="linkbottom";}
        if (nostate.indexOf("linkcontent_")!==-1) {baseStyle="linkcontent";}

        if (nostate.indexOf("imageright_")!==-1) {baseStyle="imageright";}
        if (nostate.indexOf("imageleft_")!==-1) {baseStyle="imageleft";}
        if (nostate.indexOf("imagetop_")!==-1) {baseStyle="imagetop";}
        if (nostate.indexOf("imagebottom_")!==-1) {baseStyle="imagebottom";}
        if (nostate.indexOf("imagecontent_")!==-1) {baseStyle="imagecontent";}

        for (var i2=1;i2<11;i2++) {
            if ((!nostate.find("vbar_")) && (!nostate.find("vglider_")))
            if (nostate.find("aux"+i2)) {baseStyle="aux"+i2;}
        }
        //if (nostate.indexOf("vglider_")!==-1) {baseStyle="vglider"}
        //if (nostate.indexOf("vbar_")!==-1) {baseStyle="vbar"}
        if (rounding[baseStyle]) {

            var anindex=false;
            //if (baseStyle===nostate) {anindex=i}

            var r=rounding[baseStyle];
            var asize=16;
            var doit=false;
            //var id=this.id;
            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 (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","");

            if (selector.find("_hover")) {
                if (getcolor("efgc_hover",r,baseStyle)!=="") {doit=true;}
                var efgc=getcolor("efgc_hover",rounding[baseStyle],baseStyle);
                var bgc=getcolor("bgc_hover",rounding[baseStyle],baseStyle);
            }
            else if (selector.find("_clicked")) {
                if (getcolor("efgc_clicked",r,baseStyle)!=="") {doit=true;}
                var efgc=getcolor("efgc_clicked",rounding[baseStyle],baseStyle);
                var bgc=getcolor("bgc_clicked",rounding[baseStyle],baseStyle);
            }
            else {
                if (getcolor("efgc",r,baseStyle)!=="") {doit=true;}
                var efgc=getcolor("efgc",rounding[baseStyle],baseStyle);
                var bgc=getcolor("bgc",rounding[baseStyle],baseStyle);
            }
            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 (baseStyle==="link") {alert(selector+" "+baseStyle+" "+doit);}

            if (r!=="") {doit=true;}
            if ((doit)) {
                var borderwidth=noPy(getStyle(nostate,"borderTopWidth",true,anindex));
                borderwidth=max(borderwidth,noPy(getStyle(nostate,"borderBottomWidth",true,anindex)));    
                borderwidth=max(borderwidth,noPy(getStyle(nostate,"borderLeftWidth",true,anindex)));    
                borderwidth=max(borderwidth,noPy(getStyle(nostate,"borderRightWidth",true,anindex)));    
                if (bgc==="") {
                    if (selector==="page") {
                        var bgc=bodyColor;
                    }
                    else {
                        var bgc=pageColor;
                    }
                }
                bgc=replace(bgc,"#","");
                var fgc=getStyle(selector,"backgroundColor",true,anindex);
                if (fgc.indexOf("rgb")!==-1) {fgc=rgb2hex(fgc).substr(1);} else {fgc=fgc.substr(1);}

                bordercolor="";
                //if (borderwidth>0) {
                    var bordercolor=getStyle(selector,"borderTopColor",true,anindex);
                    if (trim(bordercolor)==="-moz-use-text-color") {bordercolor=getStyle(selector,"color",true,anindex);}
                    if (trim(bordercolor)==="") {bordercolor=getStyle(selector,"color",true,anindex);}
                    if (bordercolor.indexOf("rgb")!==-1) {bordercolor=rgb2hex(bordercolor).substr(1);} else {bordercolor=bordercolor.substr(1);}
                //}
                anindex=false;
                //setStyle(selector,"backgroundColor","",true);
                var borders="";
                if (noPy(getStyle(nostate,"borderTopWidth",true,anindex))>0){borders +='t';}
                if (noPy(getStyle(nostate,"borderLeftWidth",true,anindex))>0){borders +='l';}
                if (noPy(getStyle(nostate,"borderRightWidth",true,anindex))>0){borders +='r';}
                if (noPy(getStyle(nostate,"borderBottomWidth",true,anindex))>0){borders +='b';}

                var bt=noPy(getStyle(nostate,"borderTopWidth",true,anindex));
                var bb=noPy(getStyle(nostate,"borderBottomWidth",true,anindex));
                var bl=noPy(getStyle(nostate,"borderLeftWidth",true,anindex));
                var br=noPy(getStyle(nostate,"borderRightWidth",true,anindex));
                if (getStyle(nostate,"borderTopStyle",true,anindex)==="none") {bt=0;}
                if (getStyle(nostate,"borderLeftStyle",true,anindex)==="none") {bl=0;}
                if (getStyle(nostate,"borderRightStyle",true,anindex)==="none") {br=0;}
                if (getStyle(nostate,"borderBottomStyle",true,anindex)==="none") {bb=0;}

                var alist=$("."+nostate);
                for (var i3=0;i3<alist.length;i3++) {

                    rcounter++;
                    var obj=alist[i3];


                    if ((obj)) {
                    var oldstate=state;
                    state="";
                    //obj.newstylename="";
                    var h=noPy(obj.style.height);
                    var w=noPy(obj.style.width);
                    var fixedSize=false;

                    if ((getStyle(baseStyle,"width")!=="") && (getStyle(baseStyle,"height")!=="")) {fixedSize=true;}

                    //if  ((h!==0)  && (w!==0)) {fixedSize=true}

                    if (h===0) {
                        h=obj.offsetHeight;
                    }
                    else {
                        h=h+heightWaste(baseStyle);
                    }
                    if (w===0) {
                        w=obj.offsetWidth;
                    }
                    else {
                        w=w+widthWaste(baseStyle);
                    }

                    //if (baseStyle==="gbcomment") {alert(w+" "+h);}
                    

                        if (ds!==""){
                            if (!cutoffbottom) {h=h-5;}
                            if (!cutoffright) {w=w-5;}
                        }
                        if ((ds==="") && (borders==="") && ((r==="") || (r.find("efgc")) )) {
                            w=1;
                            filetype="jpg";
                            repeat="repeat-x";
                        }
                        else {
                            repeat="no-repeat";
                        }
                        //if ((w===1) && (h===1)) {alert(baseStyle)}

                        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;
                        
                        rmd5=hex_md5(rparameters);

                        if (selector.find("_hover")) {
                            newname="rounded_"+baseStyle+"_hover_"+rmd5;
                            obj.roundinghover=newname;
                            $(obj).unbind('mouseenter mouseleave');
                            $(obj).hover(function(){$(this).addClass($(this)[0].roundinghover);},function(){$(this).removeClass($(this)[0].roundinghover);});
                        }
                        else if (selector.find("_clicked")) {
                            newname="rounded_"+baseStyle+"_clicked_"+rmd5;
                            obj.roundingclicked=newname;

                            $(obj).click(function(){
                                if (this.id.find("aux")) {removeAuxClickedStates("round");}
                                $(this).addClass($(this)[0].roundingclicked);
                            });
                            if (obj.clicked) {
                                $(obj).addClass(obj.roundingclicked);
                                obj.clicked=false;
                            }
                        }
                        else {
                            newname="rounded_"+baseStyle+"_normal_"+rmd5;
                            obj.roundingnormal=newname;
                            //$(obj).addClass(newname);
                            obj.newstylename=newname;
                            

                        }
             
                        setStyle(newname,"backgroundColor","transparent",true);  // this does not work for border;

                        state=oldstate;

                        setStyle(newname,"backgroundRepeat",repeat,true,anindex);
                        setStyle(newname,"borderTopWidth","0px",true,anindex);
                        setStyle(newname,"borderLeftWidth","0px",true,anindex);
                        setStyle(newname,"borderRightWidth","0px",true,anindex);
                        setStyle(newname,"borderBottomWidth","0px",true,anindex);
                        setStyle(newname,"paddingTop",noPy(getStyle(nostate,"paddingTop",true,anindex))+bt,true,anindex);
                        setStyle(newname,"paddingLeft",noPy(getStyle(nostate,"paddingLeft",true,anindex))+bl,true,anindex);
                        setStyle(newname,"paddingRight",noPy(getStyle(nostate,"paddingRight",true,anindex))+br,true,anindex);
                        setStyle(newname,"paddingBottom",noPy(getStyle(nostate,"paddingBottom",true,anindex))+bb,true,anindex);


                        var src=vbasepath+"rounded.php?"+rparameters;

                        outfile=rmd5+"."+filetype;

                        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 ((generate) && (fixedSize) && (w>0) && (h>0))  {
                            assetsArray[nAssets]=prgrm;
                            nAssets++;
                        }
                        
                        if (useAssets && fixedSize) {
                            var imagesrc=newsrc;
                         }
                         else {
                            var imagesrc=src;

                        }
                        if ((w!==0) && (h!==0)) {  // for example modal_holder which is invisible

                            setStyle(newname,"backgroundImage","url(\""+imagesrc+"\")",true,anindex);
                            if ((selector.find("_hover")) || (selector.find("_clicked"))) {
                                preload(imagesrc);
                            }
                            else {
                                var img=new Image();
                                img.onload=function(obj) {
                                    return function() {$(obj).addClass(obj.newstylename);};
                                }(obj);
                                img.src=imagesrc;
                            
                            }
                            
                            a=setTimeout(function(obj,img) {
                                return function() {
                                    if (imageLoaded(img)) {$(obj).addClass(obj.newstylename);}
                                
                                };
                            }(obj,img),100);
                        }
                        else {
                            //alert(baseStyle)
                        }
                }

            }

            }
            }


        }
        }
    }
    
    // now create background images which are stored in the array
    
    assetsArray=unique(assetsArray);
    for (var i=0;i<assetsArray.length;i++) {
        gebi("msgarea").innerHTML=assetsArray[i];
        $.ajax({
          type: "GET",
          url: assetsArray[i],
          async: false
        });
    }

    if (destroyed) {reaccordion("newround");}

}

//=======================================================;

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];

        if (obj.roundingnormal) {$(obj).removeClass(obj.roundingnormal);}
        if (obj.roundinghover) {$(obj).removeClass(obj.roundinghover);}
        if (obj.className.find("rounded_clicked")) {obj.clicked=true;}
        if (obj.roundingclicked) {$(obj).removeClass(obj.roundingclicked);}

        aselector=obj.roundingnormal;
        var borders=getbackroundImageProp(aselector,"borders");
        var borderwidth=noPy(getbackroundImageProp(aselector,"borderwidth"));
        var bordercolor="#"+getbackroundImageProp(aselector,"bordercolor");

        //if (target==="aux2") {alert(borderwidth);}

        if (trim(bordercolor)==="-moz-use-text-color") {bordercolor=getStyle(aselector,"color",true,anindex);}
        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",noPy(getStyle(aselector,"paddingTop",true))-borderwidth,true);}
        if (borders.indexOf("l")!==-1) {setStyle(target,"borderLeft",  borderwidth+"px solid "+bordercolor,true);setStyle(target,"paddingLeft",noPy(getStyle(aselector,"paddingLeft",true))-borderwidth,true);}
        if (borders.indexOf("r")!==-1) {setStyle(target,"borderRight", borderwidth+"px solid "+bordercolor,true);setStyle(target,"paddingRight",noPy(getStyle(aselector,"paddingRight"),true)-borderwidth,true);}
        if (borders.indexOf("b")!==-1) {setStyle(target,"borderBottom",borderwidth+"px solid "+bordercolor,true);setStyle(target,"paddingBottom",noPy(getStyle(aselector,"paddingBottom"),true)-borderwidth,true);}

        deleteStyleText("."+obj.roundingnormal);
        deleteStyleText("."+obj.roundinghover);
        deleteStyleText("."+obj.roundingclicked);

    }

}




var imgArray=[];
var imgArrayCounter=0;

//=======================================================;
function preload(src) {

    // use to store rollovers;

    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 initScrollers() {
    initScroller("right_scroller");
    initScroller("content_scroller");
    initScroller("left_scroller");
    initScroller("modal");
    initScroller("modal2");
    initScroller("document_body");
}

// ======================================================================	;
    function initScroller(divId) {

        if ((!hasScrollBar(gebi(divId))) || (!styleScrollbars)) {
            if (gebi("vglider_"+divId)) {gebi("vglider_"+divId).parentNode.removeChild(gebi("vglider_"+divId));}
            if (gebi("vbar_"+divId)) {gebi("vbar_"+divId).parentNode.removeChild(gebi("vbar_"+divId));}
            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;
            if (divId==="document_body") {
                document.body.appendChild(abar);
            }
            else {
                document.body.appendChild(abar);
            }
        }
        else {
            var abar=gebi("vbar_"+divId);
        }
        var newstylename="vbar_"+divId;

        var eh=getcolor("eh",rounding["vbar_"+divId],"vbar_"+divId); // extra height. needed if rounded to cover the scrollbar;
        if (eh==="") {eh=0;}

        abar.style.height=gebi(divId).offsetHeight-heightWaste("vbar_"+divId)+eh*2;

        var awidth=getStyle("vbar_"+divId,"width");
        if (awidth==="") {awidth=16;}
        setStyle("vbar_"+divId,"width",awidth);
        abar.style.width=noPy(awidth)-widthWaste("vbar_"+divId);

        abar.style.display="";
        abar.onclick=function(event) {getMouse(event);scrollClick(divId);};

        abar.style.zIndex=9;
        if (divId==="modal") {abar.style.zIndex=1001;}
        if (divId==="modal2") {abar.style.zIndex=1002;}

        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;
            if (divId==="document_body") {
                document.body.appendChild(aglider);
            }
            else {
                document.body.appendChild(aglider);
            }
        }
        else {
            var aglider=gebi("vglider_"+divId);
        }

        newstylename="vglider_"+divId;

        aglider.style.zIndex=10;
        aglider.style.position="absolute";
        aglider.style.display="";

        awidth=getStyle("vglider_"+divId,"width");
        if (awidth==="") {awidth=16;}
        setStyle("glider_"+divId,"width",awidth);
        aglider.style.width=noPy(awidth)-widthWaste("vglider_"+divId);
        if (divId==="modal") {aglider.style.zIndex=1002;}
        if (divId==="modal2") {aglider.style.zIndex=1012;}

        var y=findPosY(adiv);
        var x=findPosX(adiv)+adiv.offsetWidth-16;
        abar.style.left=x;
        abar.style.top=y-eh;
        aglider.style.left=x;
        aglider.style.top=y-eh;


        if (divId==="modal") {gebi("vglider_modal").style.zIndex=1002;}
        if (divId==="modal2") {gebi("vglider_modal2").style.zIndex=1012;}

        aheight=noPy(gebi(divId).offsetHeight);


        var range=aheight-noPy(getStyle("vglider_"+divId,"height"));
        aglider.onmouseover=function(){dragmode='vertical';};
        aglider.onmouseout=function(){dragmode='';};
        abar.onmouseover=function(){dragmode='vertical';};
        abar.onmouseout=function(){dragmode='';};
        
        aglider.limitTop=y;
        aglider.limitBottom=y+range;
        round("vbar_"+divId);
        round("vglider_"+divId);

    }



// ======================================================================	;
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();
        log(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;

        roundstuff(piclensTarget);
        linkstuff(piclensTarget);
        //round();
        $("#"+piclensTarget+" img").css("opacity","0");

        $("#"+piclensTarget).animate({opacity:1},500,function(){
            fixIEBlur(); $("#"+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);
        }
        setContentHeight(piclensTarget,true);
        
        
        $("#"+piclensTarget+ " img").each(function(){
            $(this).bind("load",function(){
            
                //checkLast(piclensTarget);
            
            });
        
        });
        
        
        
        setIframeSize(piclensTarget);
        if (piclensTarget==="content") {initScroller("content_scroller");}
        if (piclensTarget==="left") {initScroller("left_scroller");}
        if (piclensTarget==="right") {initScroller("right_scroller");}
        if (piclensTarget==="modal") {initScroller("modal");}
        if (piclensTarget==="modal2") {initScroller("modal2");}
        initScroller("document_body");
        $(".popper").hover(function () {showPop(this.getAttribute('helptext'));},function () {killPop();});
        hideWait();

    }

    function checkLast(target) {
        
        var allLoaded=true;
        $("#"+target+ " img").each(function(){
            if (isIE()) {
                if ((!this.complete)) {allLoaded=false;}
            }
            else {
                if (this.naturalWidth===0) {allLoaded=false;}
            }
        });
        if (allLoaded) {alert("last");setContentHeight(target);}
     
    
    }

    //=============================================================;
    function roundGb() {
        round("gbpage");
        round("gbtopicheader");
        round("gbsubject");
        round("gbtopic");
        round("gbtopictext");
        round("gbcommentheader");
        round("gbcomment");
        round("cgbommenttext");
        round("gbcommentseperator");
        round("gbtopicholder");
    }            

// ====================================================================================================;
// guestbook;
// ====================================================================================================;

 function gbedit(id) {
    faderIn(2);
    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() { // called by childwindow!;
    window.parent.gebi("action").value="";
    window.parent.gebi("gbcontent").innerHTML=gebi("gbcontent").innerHTML;
    window.parent.initPopper();
    $(window.parent.gebi("gbcontent")).fadeIn(500);
    window.parent.gebi("gbwait").style.display="none";
    window.parent.roundGb();
}

//=============================================================;
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' />   ";

        document.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";
    }

    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").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) {
    var obj=gebi(objId);

    if (doit) {
        if (setit) {obj.isFloat=true;}
        obj.style.position="absolute";
        obj.originalNode=obj.parentNode;
        gebi("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";

  while (fobj.tagName != topelement && !fobj.className.find("dragme"))
  {
    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
  }
  if (fobj.className.find("dragme"))
  {
    isdrag = true;
    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(){this.parentNode.removeChild(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(){this.parentNode.removeChild(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(id) {return document.getElementById(id);}


// ======================================================================	


// ======================================================================	     
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) {

	if (document.all) {
		return parseInt(gebi(anid).clientHeight,10);
	}
	else {
		return parseInt(gebi(anid).offsetHeight,10);
	}
}
// ======================================================================	
function getscrollwidth(anid) {
	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 errorReport() {

    mes="";
    mes=mes + version.substr(1);
    
    gebi("content").innerHTML=mes;
    setContentHeight();
    

}

// ======================================================================	
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>";
        
        //navhtml += "<div pageno='"+pageno+"' id="+chapterid+" class='"+chapterclass+"' >";
        //navhtml += "<a style='z-index:4' id="+linkid+"  class='"+linkclass+" acheader' ><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) {
            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");
        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=noPy(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=noPy(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();
     }
     
}            

