
function dragStart(event,id,cell){dragStartFull(event,id,cell,null,null,0,null,null,null);}
function dragStartFull(event,id,cell,func,lbx,lby,ubx,uby,cur){
    var el,x,y;dragObj.cell=cell;if(null==cur){cur="move";}
    cell.style.cursor=cur;document.body.style.cursor=cur;
    dragObj.func=func;dragObj.lbx=lbx;dragObj.lby=lby;dragObj.ubx=ubx;dragObj.uby=uby;
    if(id){dragObj.elNode=gID(id);}else{dragObj.elNode=cell;}
    if(browser.isIE || browser.isOP){
        x=window.event.clientX+document.documentElement.scrollLeft+document.body.scrollLeft;
        y=window.event.clientY+document.documentElement.scrollTop+document.body.scrollTop;
    }
    else{x=event.clientX+window.scrollX;y=event.clientY+window.scrollY;}
    dragObj.cursorStartX=x;dragObj.cursorStartY=y;
    dragObj.elStartLeft=parseInt(dragObj.elNode.style.left,10);
    dragObj.elStartTop=parseInt(dragObj.elNode.style.top,10);
    if(isNaN(dragObj.elStartLeft)){dragObj.elStartLeft=0;}
    if(isNaN(dragObj.elStartTop)){dragObj.elStartTop=0;}
    dragObj.elNode.style.zIndex=++dragObj.zIndex;
    if(browser.isIE){
	    document.attachEvent("onmousemove",dragGo);document.attachEvent("onmouseup",dragStop);
	    window.event.cancelBubble=true;window.event.returnValue=false;
    }
    else
    {
	    document.addEventListener("mousemove",dragGo,true);document.addEventListener("mouseup",dragStop,true);
	    event.preventDefault();
    }
}
function dragGo(event){
    var x, y;
    if(browser.isIE || browser.isOP){
        x=window.event.clientX+document.documentElement.scrollLeft+document.body.scrollLeft;
        y=window.event.clientY+document.documentElement.scrollTop+document.body.scrollTop;
    }
    else{x=event.clientX+window.scrollX;y=event.clientY+window.scrollY;}
    x=dragObj.elStartLeft+x-dragObj.cursorStartX;y=dragObj.elStartTop+y-dragObj.cursorStartY;
    if(dragObj.lbx!=null&&x<dragObj.lbx){dragObj.elNode.style.left=dragObj.lbx+"px";x=dragObj.lbx;}
    else if(dragObj.ubx!=null&&x>dragObj.ubx){dragObj.elNode.style.left=dragObj.ubx+"px";x=dragObj.ubx;}
    else{dragObj.elNode.style.left=x+"px";}
    if(dragObj.lby!=null&&y<dragObj.lby){dragObj.elNode.style.top=dragObj.lby+"px";y=dragObj.lby}
    else if(dragObj.uby!=null&&y>dragObj.uby){dragObj.elNode.style.top=dragObj.uby+"px";y=dragObj.uby;}
    else{dragObj.elNode.style.top=y+"px";}
    if(dragObj.func!=null){setTimeout(dragObj.func+'('+x+','+y+')',0);}
    if(browser.isIE){window.event.cancelBubble=true;window.event.returnValue=false;}
    else{event.preventDefault();}
}
function dragStop(event) {
    dragObj.cell.style.cursor = "default";document.body.style.cursor = 'default';
    if(browser.isIE){document.detachEvent("onmousemove",dragGo);document.detachEvent("onmouseup",dragStop);}
    else{document.removeEventListener("mousemove",dragGo,true);document.removeEventListener("mouseup",dragStop,true);}
}
function closeDragWindow(area){closeDragWindow2(area,true);}
function closeDragWindow2(area,focus){var area=gID(area);if(area!=null){if(focus&&browser.isFF){gID('keywordBox').focus();}area.style.display="none";}}
var dragObj = new Object();dragObj.zIndex = 10;
function vecCopy(a,b){a.x=b.x;a.y=b.y;}
function gID(e){return document.getElementById(e);}
function getTar(e){if(browser.isIE){return window.event.srcElement;}return e.target;}
function isNumberInRange(a,b,r){return Math.abs(a-b)<=Math.abs(a+r-b);}
function normalizeVector(v){var t=Math.sqrt(v.x*v.x+v.y*v.y);if(t==0){return new Vector();}return new Vector(v.x/t,v.y/t);}
function createXMLObject(){var x=null;if(window.XMLHttpRequest){x=new XMLHttpRequest();}else if(window.ActiveXObject){x=new ActiveXObject("Microsoft.XMLHTTP");}return x;}
function genericKeyPress(e,f){if(e.keyCode==13||e.keyCode==3){f();if(e.stopPropagation){e.stopPropagation();}e.cancelBubble=true;if(e.preventDefault){e.preventDefault();}e.returnValue=false;e.cancel=true;}}
function getWinWidth(){if(browser.isOP){return document.body.clientWidth;}else{return document.documentElement.clientWidth;}}
function getWinHeight(){if(browser.isOP){return document.body.clientHeight;}else{return document.documentElement.clientHeight;}}
function addElement(e,p){if(browser.isIE){p.insertAdjacentElement("beforeEnd",e);}else{p.appendChild(e);}}
function getDirectionBetweenPoints(x,y){return normalizeVector(new Vector(y.x-x.x,y.y-x.y));}
function exceededDownloadLimit(s){if(null==curUser){return (Number(ipAmtDown)>4096);}else if(null!=curUser){if(curUser.FullAuthValue>1&&s==512){return false;}else{return (Number(curUser.MegsUsedToday)>Number(curUser.FullDownAmt));}}}
function mainInit(){
    topPanelInit();siteStatsPanelInit();userStatsPanelInit();newsPanelInit();explorerPanelInit();treePanelInit();previewPanelInit();mainResize(1);
    gID('PageLoadingSpan').style.display='none';gID('PageContentSpan').style.display='';
    if(getCookie('agreeToEULA')!=null){agreeToEULA=1;}
    if(loadImageOnPageLoad!=''){imageClicked(loadImageOnPageLoad);if(loadTreeOnPageLoad==''){getImage(loadImageOnPageLoad, displayFullImage2, false);}else{setTimeout('createTreeInfo('+loadImageOnPageLoad+',"'+loadTreeOnPageLoad+'")',0);}}
    else if(loadQuesOnPageLoad!=''){setTimeout("faqLoadonPageLoad();",0);}
    else if(loadDivOnPageLoad!=''){setTimeout(loadDivOnPageLoad+"Clicked()",0);}
    else if(loadSearchOnPageLoad!=''){keywordSearch2(new SearchObject(loadSearchOnPageLoad),'&QType=List');}
    else{setTimeout('createRandomTree()',100);}
    if(loadRightOnPageLoad!=''){searchTabClicked(gID(loadRightOnPageLoad));}
    if(loadLeftOnPageLoad!=''){explorerTabClicked(gID(loadLeftOnPageLoad));}
    if(((!browser.isIE&&!browser.isFF)||(browser.isIE&&browser.version<6)||(browser.isFF&&browser.version<1.5))&&getCookie('unsupBrow')==null)
    {genericShowDragDiv('BrowserCautionArea','Alert!',350,adFirefoxAd);setCookie('unsupBrow',1);gID('CloseBrowserCautionAreaButton').focus();}
    if(browser.isOP){operaRenderHack1();}
}
function operaRenderHack1()
{
    gID('SiteStatsPanelDiv').style.display = 'none';
    gID('NewsPanelDiv').style.display = 'none';
    gID('UserStatsPanelDiv').style.display = 'none';
    setTimeout('operaRenderHack2();',500);
}
function operaRenderHack2()
{
    gID('SiteStatsPanelDiv').style.display = '';
    gID('NewsPanelDiv').style.display = '';
    gID('UserStatsPanelDiv').style.display = '';
}
function mainResize(r){
    var iW=getWinWidth();var iH=getWinHeight();if(iW<970){iW=970;}if(iH<630){iH=630;}
    topPanelResize(iW,iH);userStatsPanelResize(iW,iH);newsPanelResize(iW,iH);
    explorerPanelResize(iW,iH);treePanelResize(iW,iH);previewPanelResize(iW,iH);
    if(r>0){setTimeout('mainResize('+(r-1)+');',200);}        
}
function panelSlideArrowClicked(n, i){
    var e = gID(n);
    if(slideArray[i].IntervalId != -1){clearInterval(slideArray[i].IntervalId);}
    topSliderHeight = parseInt(slideArray[i].topElement.style.height);
    if(slideArray[i].helperFunction != null){setTimeout(slideArray[i].helperFunction+'(false)', 0);}
    if(topSliderHeight >= 148){slideArray[i].IntervalId = setInterval('panelSlideIn('+i+')', 15);e.style.backgroundPosition = '-67px -244px';}
    else{slideArray[i].IntervalId = setInterval('panelSlideOut('+i+')', 15);e.style.backgroundPosition = '-56px -244px';}
}
function panelSlideIn(i){
    var e=slideArray[i];var iE=null;
    var tSH=parseInt(e.topElement.style.height);
    var bSH=parseInt(e.bottomElement.style.height);
    var bST=parseInt(e.bottomElement.style.top);
    if(tSH-slideSpeed>20){
        e.topElement.style.height=(tSH-slideSpeed)+'px';e.bottomElement.style.top=(bST-slideSpeed)+'px';
        e.bottomElement.style.height=(bSH+slideSpeed)+'px';
        for(var j=0;j<e.internalEls.length;j++){
            iE=e.internalEls[j];
            if(iE.height){iE.internalElement.style.height=((bSH+slideSpeed)*iE.factor)-iE.offset+'px';}
            else{iE.internalElement.style.top=((bSH+slideSpeed)*iE.factor-iE.offset)+'px';}
        }   
    }else{
        e.topElement.style.height='20px';e.bottomElement.style.top='106px';
        clearInterval(e.IntervalId);e.IntervalId=-1;mainResize();
        if(e.helperFunction!= null){setTimeout(e.helperFunction+'(true)', 0);}
    }
}
function panelSlideOut(i){
    var e = slideArray[i];var iE = null;
    var tSH = parseInt(e.topElement.style.height);
    var bSH = parseInt(e.bottomElement.style.height);
    var bST = parseInt(e.bottomElement.style.top);
    if(tSH + slideSpeed < 148){
        e.bottomElement.style.height = (bSH - slideSpeed) + 'px';
        for(var j=0; j<e.internalEls.length; j++){
            iE = e.internalEls[j];
            if(iE.height){iE.internalElement.style.height = ((bSH - slideSpeed)*iE.factor - iE.offset) + 'px';}
            else{iE.internalElement.style.top = ((bSH - slideSpeed)*iE.factor - iE.offset) + 'px';}
        }
        e.bottomElement.style.top = (bST + slideSpeed) + 'px';
        e.topElement.style.height = (tSH + slideSpeed) + 'px';      
    }else{
        e.bottomElement.style.top = '231px';e.topElement.style.height = '148px';
        clearInterval(e.IntervalId);e.IntervalId = -1;mainResize();
        if(e.helperFunction != null){setTimeout(e.helperFunction+'(true)', 0);}
    }
}
function getImage(IDI,fN,f){
    if(GLOBAL_imageTable[''+IDI] == null || f){
        var u = queryURL + '?IDImage=' + IDI + '&QType=Single';var x = createXMLObject();
        if(x != null){
            x.onreadystatechange = function(){if(x.readyState == 4){returnImage(x.responseText, fN);}}
            x.open ('GET', u, true);x.send ('');
        }
    }else{fN(GLOBAL_imageTable[''+IDI]);}
}
function returnImage(r, fN){var i=eval('('+r+')');if(typeof(i)!="string"){addImageLocal(i,false);}fN(i);}
function addImageLocal(i,c){if(i==null){return;}var t=GLOBAL_imageTable[''+i.IDImage];if(t!=null&&t.imgEls!=null){i.imgEls=t.imgEls;}if(i.imgEls==null){i.imgEls=new Object();}if(c){for(var j=1;j<=3;j++){if(i.imgEls[j]==null){i.imgEls[j]=createImgEl(j,i.IDImage,i.Name);}}}GLOBAL_imageTable[''+i.IDImage]=i;}
function createImgEl(t,i,n){var el=document.createElement('img');el.title=n;el.border='0';el.style.height='100%';el.style.width='100%';el.src=imageURL+'?IDImage='+i+'&IDTFS='+t;return el;}
function loadGraphics(p){var i;for(var j=0; j<p.length; j++){i = new Image();i.src = p[j];GLOBAL_imgArray.push(i);}}
function genericShowDragDiv(i,n,w,f){genericShowDragDiv2(i,n,w,f,null,null);}
function genericShowDragDiv2(i,n,w,f,l,t){
    setTimeout('urchinTracker("/divs/'+i+'");',0);var a=gID(i);
    if(null==a){a=genericCreateDragDiv(i,n,w,f);createdDragDivs.push(i);return;}
    if(null!=l){a.style.left=l;}if(null!=t){a.style.top=t;}
    a.style.zIndex=++dragObj.zIndex;a.style.display="";
    var b=gID(i+'Container');b.style.height="";
    b.style.height=(parseInt(b.clientHeight)+10)+'px';
    if('RegisterArea'==i||'RequestArea'==i){b.style.overflow='auto';}
    if(null!=f){f(a);}
}
function genericCreateDragDiv(i,n,w,f)
{
    var a=gID(i+'Content');var l=(getWinWidth()/2-w/2);var z=document.createElement('span');
    z.innerHTML+='<div id="'+i+'" style="position:absolute;left:'+l+'px;top:'+dragDivStartYPos+'px;z-index:1;display:none;width:'+w+'px;height:1px;"><div style="position:absolute;width:'+w+'px;height:16px;border:1px solid #2C8BC5;top:0px;left:0px;cursor:default;color:#FFFFFF;font-weight:bold;background-image:url(Images/WebGraphics/repeaters_horz_1x83.gif);background-position:0px -63px;overflow:hidden;" onmousedown="dragStart(event, \''+i+'\', this);"><span style="position:relative;top:1px;" id="'+i+'Title">&nbsp;'+n+'</span><div style="cursor:pointer;position:absolute;top:3px;right:3px;height:11px;width:11px;background-image:url(Images/WebGraphics/combined_100x283.gif);background-position:-78px -244px;" onclick="closeDragWindow(\''+i+'\');"></div></div><div style="text-align:center;position:absolute;top:17px;left:0px;width:'+w+'px;border:1px solid #2C8BC5;background-color:#F0F2F9;" id="'+i+'Container"></div></div>';
    dragDivStartYPos+=dragDivYPosMod;addElement(z,gID('dragDivHolder'));
    if(null==a){
        gID(i+'Container').innerHTML='<span>Loading...</span>';
        var u=divURL+'?page='+i;var x=createXMLObject();
        if(null!=x){
            x.onreadystatechange=function(){
                if(4==x.readyState){
                    genericCreateDragDiv2(x.responseText,i,f);
                }
            }
            x.open('GET',u,true);x.send('');
        }
        genericShowDragDiv(i,null,null,null);return;
    }
    gID(i+'Container').appendChild(a);gID('PageContentSpan').removeChild(gID(i+'FirstHolder'));genericShowDragDiv(i,null,null,f);
}
function genericCreateDragDiv2(r,i,f){gID(i+'Container').innerHTML=r;genericShowDragDiv(i,null,null,f);}
function getCookieVal(offset){
  var endstr=document.cookie.indexOf(";", offset);
  if(-1==endstr){endstr=document.cookie.length;}
  return unescape(document.cookie.substring(offset,endstr));
}
function setCookie(name,value) {
  document.cookie=name+"="+escape(value);
}
function getCookie(name){
  var arg=name+"=";
  var alen=arg.length;
  var clen=document.cookie.length;
  var i=0;
  while(i<clen){
    var j=i+alen;
    if (document.cookie.substring(i,j)==arg)
      return getCookieVal(j);
    i=document.cookie.indexOf(" ",i)+1;
    if(i==0){break;}
  }
  return null;
}
function sha1Hash(msg)
{
    var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
    msg += String.fromCharCode(0x80);
    var l = Math.ceil(msg.length/4) + 2;
    var N = Math.ceil(l/16);
    var M = new Array(N);
    for (var i=0; i<N; i++) {
        M[i] = new Array(16);
        for (var j=0; j<16; j++) { 
            M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) | 
                      (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
        }
    }
    M[N-1][14] = ((msg.length-1) >>> 30) * 8;
    M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;
    var H0 = 0x67452301;
    var H1 = 0xefcdab89;
    var H2 = 0x98badcfe;
    var H3 = 0x10325476;
    var H4 = 0xc3d2e1f0;
    var W = new Array(80); var a, b, c, d, e;
    for (var i=0; i<N; i++) {
        for (var t=0;  t<16; t++) W[t] = M[i][t];
        for (var t=16; t<80; t++) W[t] = ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
        a = H0; b = H1; c = H2; d = H3; e = H4;
        for (var t=0; t<80; t++) {
            var s = Math.floor(t/20);
            var T = (ROTL(a,5) + f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
            e = d;
            d = c;
            c = ROTL(b, 30);
            b = a;
            a = T;
        }
        H0 = (H0+a) & 0xffffffff;
        H1 = (H1+b) & 0xffffffff; 
        H2 = (H2+c) & 0xffffffff; 
        H3 = (H3+d) & 0xffffffff; 
        H4 = (H4+e) & 0xffffffff;
    }
    return H0.toHexStr() + H1.toHexStr() + H2.toHexStr() + H3.toHexStr() + H4.toHexStr();
}
function f(s, x, y, z) 
{
    switch (s) {
    case 0: return (x & y) ^ (~x & z);
    case 1: return x ^ y ^ z;
    case 2: return (x & y) ^ (x & z) ^ (y & z);
    case 3: return x ^ y ^ z;
    }
}
function ROTL(x, n)
{
    return (x<<n) | (x>>>(32-n));
}
Number.prototype.toHexStr = function()
{
    var s="", v;
    for (var i=7; i>=0; i--) { v = (this>>>(i*4)) & 0xf; s += v.toString(16); }
    return s;
}
function Vector(x,y){this.x=0;this.y=0;if(x){this.x=x;}if(y){this.y=y;}}
function PanelSlideInfo(){this.topElement=null;this.bottomElement=null;this.bottomElementOffset=241;this.internalEls=new Array();this.IntervalId=-1;this.helperFunction=null;}
function IntElSlideInfo(){this.internalElement=null;this.offset=0;this.height=true;this.factor=1;}
function ImgTypeObject(fN,iN,dN){this.fullName=fN;this.id=iN;this.dispName=dN;this.hasType=false;this.IDTFS=-1;}
function ImgTypesObject(){this.texture=new ImgTypeObject('Texture','PreviewTextureTab','Texture');this.object=new ImgTypeObject('Object','PreviewObjectTab','Object');this.normal=new ImgTypeObject('Normal Map','PreviewNormalTab','Normal');this.height=new ImgTypeObject('Height Map','PreviewHeightTab','Height');this.scene=new ImgTypeObject('Scene','PreviewSceneTab','Scene');}
function Browser(){
    var ua, s, i;this.isIE=false;this.isFF=false;this.isNS=false;this.isOP=false;this.version=null;ua=navigator.userAgent;s="MSIE";
    if ((i=ua.indexOf(s))>=0){this.isIE=true;this.version=parseFloat(ua.substr(i+s.length));return;}
    s="Firefox/";if((i=ua.indexOf(s))>=0){this.isFF=true;this.isNS=true;this.version=parseFloat(ua.substr(i+s.length));return;}
    s="Opera/";if((i=ua.indexOf(s))>=0){this.isOP=true;this.version=parseFloat(ua.substr(i+s.length));return;}
    s="Gecko";if((i=ua.indexOf(s))>=0){this.isNS=true;this.version=6.1;return;}}
function ExplorerNode(){this.children=new Array();this.image=false;this.name='';this.expanded=false;}
function SearchObject(k){this.keywords=k;this.textures=true;this.objects=true;this.scenes=true;this.normals=false;this.heights=false;this.red='';this.green='';this.blue='';this.range=10;this.tabNum=-1;this.qType="List";}
var browser=new Browser();var slideArray=new Array();slideArray.push(new PanelSlideInfo());slideArray.push(new PanelSlideInfo());slideArray.push(new PanelSlideInfo());
/* wz_jsgraphics.js v. 2.33
The latest version is available at http://www.walterzorn.com
Copyright (c) 2002-2004 Walter Zorn. All rights reserved.
Created 3. 11. 2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 24.10.2005
Performance optimizations for Internet Explorer
by Thomas Frank and John Holdsworth.
fillPolygon method implemented by Matthieu Haller.
High Performance JavaScript Graphics Library.
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.*/
var jg_ihtm,jg_ie,jg_fast,jg_dom,jg_moz,jg_n4=(document.layers&&typeof(document.classes)!="undefined");var regex=/%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;
function chkDHTM(x,i){x=document.body||null;jg_ie=x&&typeof(x.insertAdjacentHTML)!="undefined";jg_dom=(x&&!jg_ie&&typeof(x.appendChild)!="undefined"&&typeof(document.createRange)!="undefined"&&typeof(i=document.createRange()).setStartBefore!="undefined"&&typeof(i.createContextualFragment)!="undefined");jg_ihtm=!jg_ie&&!jg_dom&&x&&typeof(x.innerHTML)!="undefined";jg_fast=jg_ie&&document.all&&!window.opera;jg_moz=jg_dom&&typeof(x.style.MozOpacity)!="undefined";}
function pntDoc(){this.wnd.document.write(jg_fast?this.htmRpc():this.htm);this.htm='';}
function pntCnvDom(){var x=document.createRange();x.setStartBefore(this.cnv);x=x.createContextualFragment(jg_fast?this.htmRpc():this.htm);this.cnv.appendChild(x);this.htm='';}
function pntCnvIe(){this.cnv.insertAdjacentHTML("BeforeEnd",jg_fast?this.htmRpc():this.htm);this.htm='';}
function pntCnvIhtm(){this.cnv.innerHTML+=this.htm;this.htm='';}function pntCnv(){this.htm='';}
function mkDiv(x,y,w,h){this.htm+='<div style="position:absolute;left:'+x+'px;top:'+y+'px;width:'+w+'px;height:'+h+'px;clip:rect(0,'+w+'px,'+h+'px,0);'+'background-color:'+this.color+(!jg_moz?';overflow:hidden':'')+';"><\/div>';}
function mkDivIe(x,y,w,h){this.htm+='%%'+this.color+';'+x+';'+y+';'+w+';'+h+';';}
function mkDivPrt(x,y,w,h){this.htm+='<div style="position:absolute;border-left:'+w+'px solid '+this.color+';left:'+x+'px;top:'+y+'px;width:0px;height:'+h+'px;clip:rect(0,'+w+'px,'+h+'px,0);background-color:'+this.color+(!jg_moz?';overflow:hidden':'')+';"><\/div>';}
function htmRpc(){return this.htm.replace(regex,'<div style="overflow:hidden;position:absolute;background-color:$1;left:$2;top:$3;width:$4;height:$5"></div>\n');}
function htmPrtRpc(){return this.htm.replace(regex,'<div style="overflow:hidden;position:absolute;background-color:$1;left:$2;top:$3;width:$4;height:$5;border-left:$4px solid $1"></div>\n');}
function mkLin(x1,y1,x2,y2){if(x1>x2){var _x2=x2;var _y2=y2;x2=x1;y2=y1;x1=_x2;y1=_y2;}var dx=x2-x1,dy=Math.abs(y2-y1),x=x1,y=y1,yIncr=(y1>y2)?-1:1;if(dx>=dy){var pr=dy<<1,pru=pr-(dx<<1),p=pr-dx,ox=x;while((dx--)>0){++x;if(p>0){this.mkDiv(ox,y,x-ox,1);y+=yIncr;p+=pru;ox=x;}else{p+=pr;}}this.mkDiv(ox,y,x2-ox+1,1);}else{var pr=dx<<1,pru=pr-(dy<<1),p=pr-dy,oy=y;if(y2<=y1){while((dy--)>0){if(p>0){this.mkDiv(x++,y,1,oy-y+1);y+=yIncr;p+=pru;oy=y;}else{y+=yIncr;p+=pr;}}this.mkDiv(x2,y2,1,oy-y2+1);}else{while((dy--)>0){y+=yIncr;if(p>0){this.mkDiv(x++,oy,1,y-oy);p+=pru;oy=y;}else{p+=pr;}}this.mkDiv(x2,oy,1,y2-oy+1);}}}
function jsGraphics(id,wnd){this.drawLine=mkLin;this.setPrintable=function(arg){this.printable=arg;if(jg_fast){this.mkDiv=mkDivIe;this.htmRpc=arg?htmPrtRpc:htmRpc;}else{this.mkDiv=jg_n4?mkLyr:arg?mkDivPrt:mkDiv;}};this.drawPolyline=this.drawPolyLine=function(x,y,s){for(var i=0;i<x.length-1;i++){this.drawLine(x[i],y[i],x[i+1],y[i+1]);}};this.clear=function(){this.htm="";if(this.cnv){this.cnv.innerHTML=this.defhtm;}};this.color=treeGlobals.LINE_COLOR;this.htm='';this.wnd=wnd||window;if(!(jg_ie||jg_dom||jg_ihtm)){chkDHTM();}this.cnv=id;this.defhtm=(this.cnv&&this.cnv.innerHTML)?this.cnv.innerHTML:'';this.paint=jg_dom?pntCnvDom:jg_ie?pntCnvIe:jg_ihtm?pntCnvIhtm:pntCnv;this.setPrintable(false);}
/* end wz_jsgraphics.js graphics library */
var newsIntervalId = -1;
var mainNewsEntry = null;
var mainNewsDiv = null;
var currentNewsEntry = -1;
var currentNewsShowing = null;
var currentNewsContentWidth = 0;

function newsPanelInit()
{
   slideArray[newsSlideIndex].topElement = gID('NewsPanelDiv');  
}

function newsPanelResize(inWidth, inHeight)
{
    inWidth=inWidth-420;
    gID('NewsPanelDiv').style.width = inWidth + "px";
    currentNewsContentWidth = inWidth - 91;
    if(currentNewsShowing != null)
        currentNewsShowing.style.width = currentNewsContentWidth + "px"; 
}

function showNews(newsID, origPos)
{
    if(newsIntervalId != -1)
        return;
    
    var spanEl = gID("NewsMoreSpan" + newsID);
    mainNewsDiv = gID('NewsHolderDiv');
    mainNewsEntry = gID('NewsPost' + newsID);
    if(mainNewsEntry == null)
        return;
    
    if(spanEl.innerHTML == "more")
    {
        spanEl.innerHTML = "less";
        currentNewsEntry = mainNewsDiv.childNodes.length-1;
        newsIntervalId = setInterval('newsSlideIn('+newsID+')', 15);  
        mainNewsEntry.style.borderBottom = '1px solid #2c8bc5';      
    }
    else
    {
        spanEl.innerHTML = "more";
        currentNewsEntry = -1;
        newsIntervalId = setInterval('newsSlideOut('+newsID+','+origPos+')', 15);
        mainNewsEntry.style.borderBottom = ''; 
    }
}

function newsSlideIn(newsID)
{
    if(currentNewsEntry < 0)
    {
        clearInterval(newsIntervalId);
        mainNewsEntry.style.top = "5px";
        currentNewsShowing = gID('NewsPostContent' + newsID);
        currentNewsShowing.style.width = currentNewsContentWidth + "px"; 
        currentNewsShowing.style.display = "";
        newsIntervalId = -1;
        mainNewsEntry = null;
        currentNewsEntry = newsID;
    }
    else if(mainNewsDiv.childNodes[currentNewsEntry] != mainNewsEntry && mainNewsDiv.childNodes[currentNewsEntry].style)
    {
        if(parseInt(mainNewsEntry.style.top) > parseInt(mainNewsDiv.childNodes[currentNewsEntry].style.top))
        {
            mainNewsEntry.style.top = mainNewsDiv.childNodes[currentNewsEntry].style.top;        
        }
        mainNewsDiv.childNodes[currentNewsEntry].style.display = "none";  
    }
    currentNewsEntry--;
}

function newsSlideOut(newsID, origPos)
{
    if(currentNewsEntry < 0)
    {
        currentNewsShowing.style.display = "none";        
        currentNewsShowing = null;
    }
    else if(currentNewsEntry < mainNewsDiv.childNodes.length)
    {
        if(mainNewsDiv.childNodes[currentNewsEntry] == mainNewsEntry)
        {
            mainNewsEntry.style.top = origPos+"px";
            mainNewsEntry = null;       
        }
        else if(mainNewsDiv.childNodes[currentNewsEntry].style)
        {
            if(mainNewsEntry != null)
            {
                mainNewsEntry.style.top = (parseInt(mainNewsDiv.childNodes[currentNewsEntry].style.top) + 18) + 'px';
            }
            mainNewsDiv.childNodes[currentNewsEntry].style.display = ""; 
        }
    }
    else
    {
        clearInterval(newsIntervalId);
        newsIntervalId = -1;
        mainNewsEntry = null;    
    }
    currentNewsEntry++;    
}
function siteStatsPanelInit(){slideArray[siteStatsSlideIndex].topElement = gID('SiteStatsPanelDiv');}
function treeGlobalsObject()
{
    this.treeHashTable = new Object();
    this.levelSizes = new Object();
    this.levelSizes['0'] = '3';
    this.levelSizes['1'] = '2';
    this.levelSizes['2'] = '1';
    this.TREE_HOLDER_WIDTH = 360;
    this.EXP_SIZE_FAC = 8;
    this.EXP_POS_FAC = this.EXP_SIZE_FAC/2;
    this.EXP_FINAL_SIZE = parseInt(TFSs[this.levelSizes['0']].Size);
    this.NODE_VELOCITY = 9;
    this.LINE_COLOR = "#0099CC";
    this.loadingHTML = '<table style="position:absolute;top:35px;left:-35px;color:#666666;"><tr><td style="text-align:center;white-space:nowrap;">Loading tree...</td></tr></table>';
    this.errorHTML = '<table style="position:absolute;left:-35px;color:#666666;"><tr><td style="text-align:center;white-space:nowrap;">Connection Error.</td></tr></table>';
    this.noResultsHTML = '<table style="position:absolute;left:-35px;color:#666666;"><tr><td style="text-align:center;white-space:nowrap;">No Results Found.</td></tr></table>';
    
    this.expandedNode = null;
    this.treeLoading = false;
    
    this.addTree = function(tree){
        this.treeHashTable[''+tree.tabNum] = tree;    
    }
    
    this.removeTree = function(tabNum){
        var temp = this.treeHashTable[''+tabNum];
        if(temp == null){return;}
        clearInterval(temp.slideIntervalId);
        this.treeHashTable[''+tabNum] = null;
    }
    
    this.getTree = function(tabNum){
        return this.treeHashTable[''+tabNum];
    }
    
    this.getNode = function(tabNum, imageId){
        return this.treeHashTable[''+tabNum].nodes[''+imageId];
    }
    
    this.setExpandedNode = function(n)
    {
        if(this.expandedNode!=null)
            this.expandedNode.shrinkNode();
        this.expandedNode = n;
        if(browser.isIE)
        {
	        document.attachEvent("onmousemove",cancleExpandedNode);
	    }
        else
        {
	        document.addEventListener("mousemove",cancleExpandedNode,true);
	    }
    }
}

function cancleExpandedNode(event)
{
    var el = getTar(event);
    if(el == treeGlobals.expandedNode || el.parentNode == treeGlobals.expandedNode 
        || el.parentNode.parentNode == treeGlobals.expandedNode)
        return;
    if(browser.isIE){document.detachEvent("onmousemove",cancleExpandedNode);}
    else{document.removeEventListener("mousemove",cancleExpandedNode,true);}
    if(treeGlobals.expandedNode != null)
        treeGlobals.expandedNode.shrinkNode();    
}

var treeGlobals = new treeGlobalsObject();
function createNode(tree, image, level)
{
    addImageLocal(image,false);
    var theNode = document.createElement('div');
      
    theNode.setImg = function(tfs)
    {
	    this.link.innerHTML = '';
	    var i=this.image.imgEls[tfs];
	    if(null==i)
	    {
	        i=createImgEl(tfs,this.image.IDImage,this.image.Name);
	    }
	    addElement(i,this.link);
	    this.image.imgEls[tfs]=createImgEl(tfs,this.image.IDImage,this.image.Name);
    }
    
    theNode.swap = function()
    {
        this.parentTreeNode.image = this.image;
	    this.parentTreeNode.setImg(this.parentTreeNode.IDTFS);
        this.style.display = 'none';    
    }
    
    theNode.growNode = function(){
    	if(!this.tree.canGrowNodes || this.expanded){return;}
    	treeGlobals.setExpandedNode(this);
    	this.expanded = true;
        clearInterval(this.expandIntervalID);
        this.style.zIndex = 100;
	    this.setImg(treeGlobals.levelSizes['0']);   
        this.expandIntervalID = setInterval('growNodeRun('+this.image.IDImage+','+this.tree.tabNum+')', 30);        
    }
        
    theNode.shrinkNode = function(){
        if(!this.expanded){return;}
        treeGlobalsObject.expandedNode=null;
        this.expanded = false;
        clearInterval(this.expandIntervalID);
        this.expandIntervalID = setInterval('shrinkNodeRun('+this.image.IDImage+','+this.tree.tabNum+',false)', 30); 
    }
    
    theNode.nodeClicked = function(event){
        var node = this;      
        if(!node.tree.canGrowNodes){return;}
        if(node.level == 0)
        {
            setupPreviewPane(node.image.IDImage, this.tree.panel.query);
            return;
        }
        node.tree.canGrowNodes = false;
        node.tree.readyToExpand = false;
        node.tree.getTree(node.image.IDImage);
        node.tree.currentNode = node;
        setupPreviewPane(node.image.IDImage, this.tree.panel.query);
        if(node.expanded)
        {
            node.expanded = false;
            clearInterval(node.expandIntervalID);
            node.expandIntervalID = setInterval('shrinkNodeRun('+node.image.IDImage+','+node.tree.tabNum+',true)', 30); 
        }
        else
        {
            setTimeout('slideInNodesSetup('+node.tree.tabNum+')', 40);
        }
    }
    
    theNode.applyInPos = function(){
	    vecCopy(this.curPos,this.inPos);
        this.applyCurPos();
    }
    
    theNode.applyOutPos = function(){
	    vecCopy(this.curPos,this.outPos);
        this.applyCurPos();
    }
    
    theNode.applyCurPos = function(){
        this.style.left = Math.round(this.curPos.x) + 'px';
        this.style.top = Math.round(this.curPos.y) + 'px'; 
    }
        
    theNode.applyOrigSize = function(){
        this.cSize = this.oSize;
        this.applyCurSize();
    }
    
    theNode.applyCurSize = function(){
        this.style.width = this.cSize + 'px';
        this.style.height = this.cSize + 'px';
    }
    
    theNode.setNewOutPos = function(apply){
        if(0==this.level){return;}
        
        this.inPos = new Vector(this.parentTreeNode.outPos.x + this.parentTreeNode.oSize/4,
				   this.parentTreeNode.outPos.y + this.parentTreeNode.oSize/4);
        vecCopy(this.outPos,this.inPos);
        this.outPos.x += this.trigAngle.x*this.tree.branchLen[''+this.level];
        this.outPos.y += this.trigAngle.y*this.tree.branchLen[''+this.level];
        theNode.drawConnectingLine();
        if(apply)
            this.applyOutPos();
    }
    
    theNode.drawConnectingLine = function(){
        var s=this.oSize/2;
        this.tree.g.drawLine(Math.round(this.inPos.x+s),Math.round(this.inPos.y+s),Math.round(this.outPos.x+s),Math.round(this.outPos.y+s));
    }

    theNode.tree = tree;
    theNode.image = image;
    theNode.level = level;
    theNode.style.position = 'absolute';
    theNode.style.backgroundColor = '#e0e2e9';
    theNode.onclick = theNode.nodeClicked;
    theNode.innerHTML = '<a onclick="return false;" href="index.php?Tree='+image.Name+'&IDImage='+image.IDImage+'"></a>';
    theNode.IDTFS = treeGlobals.levelSizes[''+theNode.level];
    theNode.oSize = parseInt(TFSs[''+theNode.IDTFS].Size);
    theNode.curPos = new Vector();
    theNode.outPos = new Vector();
    if(1>=theNode.image.NumChildren)
        theNode.treeAngleMod = 0;
    else
        theNode.treeAngleMod = (2*Math.PI)/(theNode.image.NumChildren*(2*level+1));
    theNode.applyOrigSize();
    theNode.parentTreeNode = theNode.tree.nodes[''+theNode.image.Parent]; 
    theNode.link = theNode.childNodes[0];
    if(0 == level)
    {
        theNode.treeAngle = Math.PI/2;
        theNode.parentTreeNode = theNode
        theNode.tree.rootNode = theNode;
        theNode.inPos = new Vector(-theNode.oSize/2,-theNode.oSize/2);
        vecCopy(theNode.outPos,theNode.inPos);
    }
    else 
    {
        theNode.treeAngle = theNode.parentTreeNode.treeAngle; 
        theNode.parentTreeNode.treeAngle += theNode.parentTreeNode.treeAngleMod;
        theNode.trigAngle = new Vector(Math.cos(theNode.treeAngle),Math.sin(theNode.treeAngle));
        theNode.treeAngle -= theNode.treeAngleMod/(4-theNode.image.NumChildren);
        theNode.setNewOutPos(false);
        theNode.dirVec = getDirectionBetweenPoints(theNode.inPos,theNode.outPos);
        theNode.dirVec.x *= treeGlobals.NODE_VELOCITY;
        theNode.dirVec.y *= treeGlobals.NODE_VELOCITY;
        theNode.style.display = 'none';
        theNode.onmouseout = theNode.shrinkNode;
        theNode.onmouseover = theNode.growNode;
    }
    theNode.style.zIndex = theNode.level+1;
    theNode.applyInPos();
    theNode.setImg(theNode.IDTFS);
    theNode.tree.addNodeToTree(theNode);  
    return theNode;
}

function growNodeRun(imageID,tabNum)
{
    var node = treeGlobals.getNode(tabNum,imageID);
    if(node.cSize + treeGlobals.EXP_SIZE_FAC >= treeGlobals.EXP_FINAL_SIZE)
    {
        node.cSize = treeGlobals.EXP_FINAL_SIZE;
        var t = (node.cSize - node.oSize)/2;
        node.curPos.x = node.outPos.x - t;
        node.curPos.y = node.outPos.y - t;
        clearInterval(node.expandIntervalID);
    }
    else
    {
        node.cSize += treeGlobals.EXP_SIZE_FAC;
        node.curPos.x -= treeGlobals.EXP_POS_FAC;
        node.curPos.y -= treeGlobals.EXP_POS_FAC;
    }
    node.applyCurSize();
    node.applyCurPos();
}

function shrinkNodeRun(imageID,tabNum,collapse)
{
    var node = treeGlobals.getNode(tabNum,imageID);
    if(node.cSize - treeGlobals.EXP_SIZE_FAC <= node.oSize)
    {
        
        node.applyOutPos();
        node.applyOrigSize();
        node.setImg(node.IDTFS);
        node.style.zIndex = 1;
        clearInterval(node.expandIntervalID);
        if(collapse)
            setTimeout('slideInNodesSetup('+node.tree.tabNum+')', 40);
        return;   
    }
    node.cSize -= treeGlobals.EXP_SIZE_FAC;
    node.curPos.x += treeGlobals.EXP_POS_FAC;
    node.curPos.y += treeGlobals.EXP_POS_FAC;
    node.applyCurPos();
    node.applyCurSize(); 
}
var allowScroll = false;
var currentScrollId = -1;
var tabNumber = 0;
var currentHighNumber = -1;
var numOfTabs = 0;
var tabWidth = 75;
var tabScrollSpeed = 10;
var tabScrollElement = null;
var maxWidthFactorWOScroll = 33;
var maxWidthFactorWithScroll = 56;
var currentHighPanel = null;

function resizeTabArea()
{
    var cw = numOfTabs*tabWidth;
    var maxWidth = parseInt(gID('TreePanelDiv').style.width);
    var MWwoS = maxWidth - maxWidthFactorWOScroll;
    var MWwS = maxWidth - maxWidthFactorWithScroll;
    gID('tabHoldingDiv').style.width=cw+'px';
    gID('tabHoldingTable').style.width=cw+'px';

    if(cw <= (MWwoS))
    {
        disableScrolling(cw, MWwoS, MWwS)
    }
    else
    {
        enableScrolling(cw, MWwoS, MWwS);
        if(currentHighNumber != -1)
            scrollToTab(gID('treeTab'+currentHighNumber));
    }
}

function createTab(tabName, search)
{
    var tabID = 'treeTab' + tabNumber;
    var panelID = 'treePanel' + tabNumber;
    
    var mainPanel = gID('TreePanelDiv');
    
    var panel = document.createElement('div');
    panel.style.position = 'absolute';
    panel.style.left = '0px';
    panel.style.top = '20px';
    panel.style.width = '100%';
    panel.style.display = 'none';
    panel.tabNum = tabNumber;
    panel.id = panelID;
    
    var innerPanel = document.createElement('div');
    innerPanel.style.position = 'absolute';
    innerPanel.style.left = '0px';
    innerPanel.style.width = '100%';
    innerPanel.style.overflow = 'auto';
    
    if(null==search)
    {
        innerPanel.style.top = '0px';
        innerPanel.hasSearch = false;
        panel.searchPanel = null;
    }
    else
    {
        innerPanel.style.display = 'none';
        innerPanel.style.borderTop = '1px solid #333333';
        innerPanel.innerHTML = '<table style="color:#666666; border-collapse: collapse; width:100%;"><tr><td style="text-align:center;">Performing search...</td></tr></table>';
        search.tabNum = tabNumber;
        innerPanel.hasSearch = true;
        innerPanel.style.top = '50px';
        var searchPanel = document.createElement('div');
        searchPanel.style.position = 'absolute';
        searchPanel.style.left = '0px';
        searchPanel.style.height = '49px';
        searchPanel.style.width = '100%';
        searchPanel.style.overflow = 'hidden'; 
        searchPanel.innerHTML = generateSearchPanelHTML(search);
        panel.searchPanel = searchPanel;
        panel.query = search;
        addElement(searchPanel, panel);
    }
    
    panel.innerPanel = innerPanel;
    addElement(innerPanel, panel);
    addElement(panel, mainPanel);
       
    var tabArea = gID('mainTabArea');
    var cell = tabArea.insertCell(tabArea.cells.length);
    
    numOfTabs++;
    resizeTabArea();
    
    cell.className = 'unHorTab';    
    cell.style.width = tabWidth + 'px';
    cell.id = tabID;
    cell.tabNum = tabNumber;
    cell.onclick = tabClicked;
    cell.ondblclick = tabClose;
    cell.innerHTML = '<DIV style="width:'+(tabWidth-2)+'px;"><SPAN style="white-space:nowrap;text-align:left;" id="innerTabSpan' + tabNumber + '">' + tabName + '</SPAN></DIV>';
    var inSpan = gID('innerTabSpan' + tabNumber);   
    if(inSpan.offsetWidth > tabWidth-25)
    {
        cell.title = tabName;
        var i = 1;
        inSpan.innerHTML = '';
        while(inSpan.offsetWidth < (tabWidth-25) && i < tabName.length)
        {
            inSpan.innerHTML = tabName.substr(0,i) + '...';
            i++;
        }
    }
    cell.style.overflow='hidden';
    
    tabClickEl(cell);  
     
    return tabNumber++;
}

function closeCurrentTab()
{
    if(currentHighNumber == -1)
        return;
    var e = gID('treeTab' + currentHighNumber);
    tabCloseEl(e);
}

function tabClose(event)
{
	tabCloseEl(getTar(event));	
}

function tabCloseEl(element)
{
    if(element != null && element.tagName == "SPAN")
        element = element.parentNode;
    if(element != null && element.tagName == "DIV")
        element = element.parentNode;
        
    var tabArea = gID('mainTabArea');
    var panelArea = gID('TreePanelDiv');
    var tabNum = element.tabNum;
    
    if(tabNum == currentHighNumber)
    {
        var i = -1;
        if(tabArea.cells.length > 1)
        {
            i = element.cellIndex;
            if(i == 0)
                i = 1;
            else
                i--;
        }
        
        if(i >= 0)
        {   
            tabClickEl(tabArea.cells[i]);
        }
        else
        {       
            tabClickEl(null);
        }
    }

    var panel = gID('treePanel' + tabNum);
    if(panel != null)
    {
        if(panel.tree != null)
        {
            treeGlobals.removeTree(tabNum);
        }
        panelArea.removeChild(panel);
    }
    
    tabArea.deleteCell(element.cellIndex);
    
    numOfTabs--;
    if(browser.isOP)
        gID('tabHoldingTable').style.display='none';
    resizeTabArea();
    if(browser.isOP)
        gID('tabHoldingTable').style.display='';
}

function tabClicked(event)
{
    tabClickEl(getTar(event));
}

function tabClickEl(element)
{
    if(element != null && element.tagName == "SPAN")
        element = element.parentNode;
    if(element != null && element.tagName == "DIV")
        element = element.parentNode;
    
    if(currentHighNumber != -1)
    {
        var currentTab = gID('treeTab' + currentHighNumber);
        if(currentTab == null)
        {
            currentHighNumber = -1;
            return;
        }
        
        if(currentTab == element)
            return;
            
        currentTab.className = 'unHorTab';
        
        treeInernalPanelToResize = null;
        slideArray[newsSlideIndex].internalEls.pop();
        
        currentHighPanel.style.display = 'none';
        currentHighPanel.innerPanel.style.display = 'none';
    }
    
    currentHighPanel = null;
    currentHighNumber = -1;
    
    if(element != null)
    {
        currentHighNumber = element.tabNum;
        currentHighPanel = gID('treePanel' + element.tabNum);
        if(currentHighPanel == null)
            return;
        
        element.className = 'selHorTab';       
        
        currentHighPanel.style.display = "";
        var factor = 2;
        if(currentHighPanel.searchPanel != null)
        {
            currentHighPanel.searchPanel.style.height='';
            factor = currentHighPanel.searchPanel.clientHeight + 5;
            currentHighPanel.searchPanel.style.height=factor+'px';
            currentHighPanel.innerPanel.style.top=factor+'px';
            factor+=2;      
        }
        
        currentHighPanel.innerPanel.style.height = (parseInt(gID('TreeTableSpace').style.height) - factor) + 'px';       
        
        if(currentHighPanel.tree != null)
            currentHighPanel.tree.resizeTree();
        
        currentHighPanel.innerPanel.style.display='';       
                
        var temp = new IntElSlideInfo();
        temp.internalElement = currentHighPanel.innerPanel;
        temp.offset = 18 + factor;
        slideArray[newsSlideIndex].internalEls.push(temp);
        
        scrollToTab(element);
    }
}

function scrollToTab(tab)
{
    if(allowScroll)
    {
        if(currentScrollId != -1){clearInterval(currentScrollId);}
        var start = tab.cellIndex*tabWidth;
        var end = start + tabWidth;
        var visWidth = parseInt(gID('TreePanelDiv').style.width) - maxWidthFactorWithScroll;
        tabScrollElement = gID('tabHoldingDiv');
        var pos = parseInt(tabScrollElement.style.left);
        if(pos + start < 0)
        {
            currentScrollId = setInterval('tabScrollToPoint(\"r\", '+visWidth+', '+start+')', 15);            
        }
        else if(pos + end > visWidth)
        {
            currentScrollId = setInterval('tabScrollToPoint(\"l\", '+visWidth+', '+end+')', 15);            
        }  
    }
}

function tabScrollStart(direction)
{
    if(!allowScroll || currentScrollId != -1)
        return;
    
    var visWidth = parseInt(gID('TreePanelDiv').style.width) - maxWidthFactorWithScroll;
    tabScrollElement = gID('tabHoldingDiv');
    currentScrollId = setInterval('tabScroll(\"'+direction+'\", '+visWidth+')', 15);
}

function tabScrollToPoint(direction, visibleWidth, point)
{
    var pos = parseInt(tabScrollElement.style.left);
    var newPos = 0;
    if(direction == 'l')
    {
        newPos = pos - tabScrollSpeed;
        var width = parseInt(tabScrollElement.style.width);
        if((width + newPos) <= visibleWidth)
        {
            tabScrollElement.style.left = (visibleWidth - width) + 'px';
            tabScrollStop();        
        }
        else if((point + newPos) <= visibleWidth)
        {
            tabScrollElement.style.left = (visibleWidth - point) + 'px';
            tabScrollStop();
        }
        else
        {
            tabScrollElement.style.left = newPos + 'px';       
        }
    }
    else
    {
        newPos = pos + tabScrollSpeed;
        if(newPos >= -1)
        {
            tabScrollElement.style.left = '-1px';
            tabScrollStop();        
        }
        else if((point + newPos) >= -1)
        {
            tabScrollElement.style.left = '-' + (point+1) + 'px';
            tabScrollStop();
        }
        else
        {
            tabScrollElement.style.left = newPos + 'px';       
        }   
    }
}

function tabScroll(direction, visibleWidth)
{
    var pos = parseInt(tabScrollElement.style.left);
    var newPos = 0;
    if(direction == 'l')
    {
        newPos = pos - tabScrollSpeed;
        var width = parseInt(tabScrollElement.style.width);
        if((width + newPos) <= visibleWidth)
        {
            tabScrollElement.style.left = (visibleWidth - width) + 'px';
            tabScrollStop();        
        }
        else
        {
            tabScrollElement.style.left = newPos + 'px';       
        }
    }
    else
    {
        newPos = pos + tabScrollSpeed;
        if(newPos >= -1)
        {
            tabScrollElement.style.left = '-1px';
            tabScrollStop();        
        }
        else
        {
            tabScrollElement.style.left = newPos + 'px';       
        }   
    }
}

function tabScrollStop()
{
    if(currentScrollId == -1)
        return;
        
    clearInterval(currentScrollId);
    currentScrollId = -1;
}

function enableScrolling(cw, MWwoS, MWwS)
{
    gID('tabHoldingOuterDiv').style.width=MWwoS+'px';
    gID('tabRepeaterDiv').style.display='none';
    gID('tabScrollRightDiv').style.display='';
    gID('tabScrollLeftDiv').style.display='';
    gID('tabScrollEndDiv').style.display='';
    var tabDiv=gID('tabHoldingDiv');
    if(cw+parseInt(tabDiv.style.left)<=MWwS)
        tabDiv.style.left=(MWwS-cw)+'px';          
    allowScroll=true;
}

function disableScrolling(cw, MWwoS, MWwS)
{
    gID('tabHoldingDiv').style.left='-1px';
    gID('tabScrollRightDiv').style.display='none';
    gID('tabScrollLeftDiv').style.display='none';
    gID('tabScrollEndDiv').style.display='none';
    gID('tabHoldingOuterDiv').style.width=cw+'px';
    var rep=gID('tabRepeaterDiv');
    rep.style.left=cw+'px';
    rep.style.width=(MWwoS-cw+10)+'px';
    rep.style.display='';    
    allowScroll=false;
}

function treeSlideHelper(end)
{
    if(currentHighPanel == null)
        return;
    
    if(!end)
    {
        currentHighPanel.innerPanel.style.display = 'none';
    }
    else
    {
        if(currentHighPanel.tree != null)
            currentHighPanel.tree.resizeTree();
        currentHighPanel.innerPanel.style.display = '';
    }
}

function generateSearchPanelHTML(search)
{
    var html = '<font style="font-size:2pt;">&nbsp;</font><br>';
    html += '<table width="100%" style="color:#666666; border-collapse: collapse;" cellpadding="2">' +
                '<tr>' +
                    '<td align="left" width="80px">' +
                        '<b>&nbsp;Keywords: </b>' +
                    '</td>' +
                    '<td align="left" with="100px">' +
                        search.keywords +
                    '</td>' +
                    '<td width="20px">&nbsp;</td><td align="left" width="75px"><b>Must Include: </b></td><td align="left">';
    if(!search.normals && !search.heights)
    {
        html += "Any";
    }
    else
    {
        if(search.normals)
            html += "Normal";
        
        if(search.normals && search.heights)
            html += " and Height";
        else if(search.heights)
            html += "Height";    
    }
    html += '</td><td align="right"><span style="cursor:pointer;" onclick="fillSearchFromTab(' + search.tabNum + ');"><b title="Fill in the search fields with the criteria used for this search">Fill search fields</b></span>&nbsp;&nbsp;&nbsp;</td></tr><tr><td align="left"><b>&nbsp;Image Types: </b></td><td align="left">';
    if(search.textures && search.objects && search.scenes)
    {
        html+= "All";
    }
    else
    {
        if(search.textures)
            html += "Textures";
        
        if(search.textures && search.objects)
            html += ", Objects";
        else if(search.objects)
            html += "Objects";
        
        if((search.textures || search.objects) && search.scenes)
            html += ", Scenes";
        else if(search.scenes)
            html += "Scenes";
     }
     html += '</td><td width="20px">&nbsp;</td><td align="left"><b>Colors: </b></td><td>'
     if(search.red == '' && search.green == ''&& search.blue == '')
     {
        html += "No Color Requirement";     
     }
     else
     {
        html += search.red + ', ' + search.green + ', ' + search.blue + ' +/- ' + search.range;
     }
     html += '</td><td align="right"><span style="cursor:pointer;" onclick="duplicateTab(' + search.tabNum + ');"><b title="Create a new tab with the criteria used on this search">Duplicate Search</b></span>&nbsp;&nbsp;&nbsp;</td>' +
                '</tr>' +
            '</table>';
     
     return html;
}
function treePanelInit()
{
    slideArray[newsSlideIndex].bottomElement = gID('TreePanelDiv');
    slideArray[newsSlideIndex].helperFunction = 'treeSlideHelper';
    var temp = new IntElSlideInfo();
    temp.internalElement = gID('TreeTableSpace');
    temp.offset = 18;
    slideArray[newsSlideIndex].internalEls.push(temp);
}

function treePanelResize(inWidth, inHeight)
{
    var area = gID('TreePanelDiv');
    var inArea = gID('TreeTableSpace');
    inWidth = (inWidth - 420)
    area.style.width=inWidth+'px';
    treeGlobals.TREE_HOLDER_WIDTH = inWidth;
       
    inHeight = (inHeight - parseInt(area.style.top) - 10);
    area.style.height = inHeight + "px";
    inHeight-=18; 
    inArea.style.height = (inHeight) + "px";
    if(currentHighPanel != null)
    {
        inHeight-=2;
        if(currentHighPanel.searchPanel != null)
            inHeight -= parseInt(currentHighPanel.searchPanel.style.height);
        currentHighPanel.innerPanel.style.height = (inHeight) + "px";
        
        if(currentHighPanel.tree != null)
        {
            setTimeout('currentHighPanel.tree.resizeTree();', 0);
        }
    }    
    resizeTabArea();
    
    if(inHeight<inWidth)
        inWidth = inHeight;
    
    treeGlobals.NODE_VELOCITY = inWidth/40.0;
}

function createTreeFromImage(image)
{
    createTreeInfo(image.IDImage,image.Name);
}

function createTreeInfo(id,name)
{
    var num = createTab(name);
    var tree = new Tree(gID('treePanel' + num));
    tree.getTree(id);
}

function createRandomTree()
{
    resizeTabArea();
    var id = Math.ceil(Math.random()*1000);
    var num = createTab("Random");
    var tree = new Tree(gID('treePanel' + num));
    tree.getTree(id);
    if(browser.isOP)
    {
        gID('tabHoldingTable').style.display='none';
        setTimeout('gID(\'tabHoldingTable\').style.display=\'\';',1000);
    }
}

function Tree(panel)
{
    //properties
    
    this.canGrowNodes = false;
    this.slideIntervalId = -1;
    this.currentNode = null;
    this.rootNode = null;
    this.totalLevels = 2;
    this.data = null;
    this.readyToExpand = true;
    this.nodes = new Object();
    
    this.panel = panel;
    this.panel.innerPanel.innerHTML = '';
    this.panel.tree = this;
    this.tabNum = this.panel.tabNum;
    
    treeGlobals.addTree(this);
    
    this.treeEl = document.createElement('div');
    this.treeEl.style.position = 'absolute';
    this.treeEl.style.left = '0px';
    this.treeEl.style.top = '0px';
    this.treeEl.style.width = '0px';
    this.treeEl.style.height = '0px';
    this.treeEl.style.zIndex = 2;
    this.treeEl.innerHTML = treeGlobals.loadingHTML;
    
    this.lineEl = document.createElement('div');
    this.lineEl.style.position = 'absolute';
    this.lineEl.style.left = '0px';
    this.lineEl.style.top = '0px';
    this.lineEl.style.width = '0px';
    this.lineEl.style.height = '0px';
    this.lineEl.style.zIndex = 1;
    this.branchLen = new Object();
    		
    var point = document.createElement('div');
    point.style.position = 'absolute';
    point.style.left = '50%';
    point.style.top = '50%';
    point.style.width = '0px';
    point.style.height = '0px';
    
    addElement(this.lineEl,point);
    addElement(this.treeEl,point);
    addElement(point,this.panel.innerPanel);
    
    this.g = new jsGraphics(this.lineEl);

    this.addNodeToTree = function(node){
        addElement(node,this.treeEl);
        this.nodes[''+node.image.IDImage] = node;
    }
    
    this.calculateBranchLen = function(){
        var w = treeGlobals.TREE_HOLDER_WIDTH;
        var h = parseInt(this.panel.innerPanel.style.height);
        if(w < h)
            h=w;
        h = (h-75) / 4.0;
        if(Math.abs(h-this.branchLen['1'])<treeGlobals.NODE_VELOCITY)
            return false; //don't bother resizing
        this.branchLen['1'] = h;
        this.branchLen['2'] = h;
        return true;
    }
    
    this.resizeTree = function(){
        if(!this.readyToExpand || this.rootNode == null || !this.calculateBranchLen()){return;}
        this.panel.innerPanel.style.display = 'none';
        clearInterval(this.slideIntervalId);
        this.slideIntervalId = -1;
        this.canGrowNodes = false;
        this.g.clear();
        this.rootNode.setNewOutPos(true);
        for(var i=1;i<=this.totalLevels;i++)
        {
            for(var key in this.nodes)
            { 
                cnode = this.nodes[key];
                if(cnode.level == i)
                {
                    cnode.setNewOutPos(true);
                    cnode.style.display = '';
                }
            }
        }
        this.g.paint();
        this.canGrowNodes = true;
        this.panel.innerPanel.style.display = '';
    }
    
    this.slideOutNodesSetup = function(){
        clearInterval(this.slideIntervalId);
        this.slideIntervalId = setInterval('slideOutNodes(1,'+this.tabNum+')', 30);
    }
    
    this.getTree = function(imageID){
        var url = queryURL + '?IDImage=' + imageID;
        if(this.panel.query != null)
            url += createUrlFromSearchObj(this.panel.query, true);
        else
            url += '&QType=Tree';
        var xmlObj = createXMLObject();
        var ref = this;
        if(xmlObj != null){
            xmlObj.onreadystatechange = function(){
                if(xmlObj.readyState == 4){
                    ref.resetTree(xmlObj.responseText,false);
                }
            }
            xmlObj.open ('GET', url, true);
            xmlObj.send ('');
        }
    }
    
    this.resetTree = resetTree;
    this.fillTree = fillTree;
}

function resetTree(serverResponse,setPreview)
{
    if(serverResponse == null || serverResponse == '')
    {
        this.data = -1;
    }
    else
    {   
        this.data = eval('(' + serverResponse + ')');
        if(this.data.length <= 0 || this.data[0].length <= 0)
        {
            this.data = -2;
        }
        else if(setPreview)
        {
            addImageLocal(this.data[0][0],false);
            setupPreviewPane(this.data[0][0].IDImage, this.panel.query);
        }
    }
    if(this.readyToExpand)
        this.fillTree();
}

function fillTree()
{      
    this.treeEl.innerHTML = '';
    this.nodes = new Object();
    this.rootNode = null;
    
    if(this.data == -1)
    {
        this.data=null;
        this.treeEl.innerHTML = treeGlobals.errorHTML;
        return;
    }
    else if(this.data == -2)
    {
        this.data=null;
        this.treeEl.innerHTML = treeGlobals.noResultsHTML;
        return;
    }    
    this.totalLevels = this.data.length-1;
        
    this.calculateBranchLen();

    for(var i=0;i<this.data.length;i++)
	    for(var j=0; j<this.data[i].length;j++)
	        createNode(this, this.data[i][j], i);
	
	this.data = null;
    
    this.slideOutNodesSetup();
    
    for(var key in this.nodes)
        addImageLocal(this.nodes[key].image,true);
        
}

function slideOutNodes(nodeLevel,tabNum)
{
    var allNodesSlid = true;
    var cnode = null;
    var xRange = false;
    var yRange = false;
    var tree = treeGlobals.getTree(tabNum);
    
    for(var key in tree.nodes)
    { 
        cnode = tree.nodes[key];
        if(nodeLevel == cnode.level)
        {
            if(cnode.style.display != ''){cnode.style.display='';}
            xRange = isNumberInRange(cnode.curPos.x, cnode.outPos.x, cnode.dirVec.x);
            yRange = isNumberInRange(cnode.curPos.y, cnode.outPos.y, cnode.dirVec.y);
            if(!xRange || !yRange)
            {
                allNodesSlid = false;
                if(!xRange)
                {
                    cnode.curPos.x += cnode.dirVec.x;
                }
                if(!yRange)
                {
                    cnode.curPos.y += cnode.dirVec.y;
                }
                cnode.applyCurPos();         
            }
            else
            {
                cnode.style.cursor = 'pointer';
                cnode.applyOutPos();
            }
        }
    }
    
       
    if(allNodesSlid)
    {
        clearInterval(tree.slideIntervalId);
        if(nodeLevel < tree.totalLevels)
        { 
	        nodeLevel++;
            setTimeout('treeGlobals.getTree('+tabNum+').slideIntervalId = setInterval("slideOutNodes('+nodeLevel+','+tabNum+')", 30);', 200);
        }
        else
        {
            tree.g.paint();
            tree.canGrowNodes = true;
            tree.slideIntervalId = -1;        
        }
    }
}

function slideInNodesSetup(tabNum)
{
    var tree = treeGlobals.getTree(tabNum);
    clearInterval(tree.slideIntervalId);
    tree.g.clear();    
    tree.slideIntervalId = setInterval('slideInNodes('+tree.totalLevels+','+tree.tabNum+')', 30);
}

function slideInNodes(nodeLevel,tabNum)
{
    var tree = treeGlobals.getTree(tabNum);
    var allNodesSlid = true;
    var cnode = null;
    for(var key in tree.nodes)
    {
        cnode = tree.nodes[key];
        if(nodeLevel == cnode.level)
        {
            xRange = isNumberInRange(cnode.curPos.x, cnode.inPos.x, -cnode.dirVec.x);
            yRange = isNumberInRange(cnode.curPos.y, cnode.inPos.y, -cnode.dirVec.y);
            if(!xRange || !yRange)
            {
                allNodesSlid = false;
                if(!xRange)
                {
                    cnode.curPos.x -= cnode.dirVec.x;
                }
                if(!yRange)
                {
                    cnode.curPos.y -= cnode.dirVec.y;
                }
                cnode.applyCurPos();         
            }
            else
            {
                cnode.applyInPos();
                if(cnode.image.IDImage != tree.currentNode.image.IDImage)
                    cnode.style.display = 'none';
            }
        }
    }
    
    if(allNodesSlid)
    {
        clearInterval(tree.slideIntervalId);
        if(tree.currentNode.level == nodeLevel)
        {
            tree.currentNode.swap();
            tree.currentNode = tree.currentNode.parentTreeNode;                
        }
        if(nodeLevel > 1)
        {
            nodeLevel--;
            setTimeout('treeGlobals.getTree('+tabNum+').slideIntervalId = setInterval("slideInNodes('+nodeLevel+','+tabNum+')", 30);', 200);
        }
        else 
        {
            tree.treeEl.innerHTML += treeGlobals.loadingHTML;
            setTimeout('shortTreeWait('+tabNum+')', 200);
            tree.slideIntervalId = -1;   
        }
    }
}

function shortTreeWait(tabNum)
{
    var tree = treeGlobals.getTree(tabNum);
    tree.readyToExpand = true;
    if(tree.data != null)
        tree.fillTree();
}
var histErrorPanelIntervalID = -1;
var histErrorPanel = null;
var previewSelectedId = -1;

function explorerPanelInit()
{
    explorerPanelLogin();
    slideArray[siteStatsSlideIndex].bottomElement = gID('ExplorerPanelDiv');
    var temp = new IntElSlideInfo();
    temp.internalElement = gID('explorerRepeaterDiv');
    temp.offset = 254;
    slideArray[siteStatsSlideIndex].internalEls.push(temp);   
    temp = new IntElSlideInfo();
    temp.internalElement = gID('explorerContentDiv');
    temp.offset = 0;
    slideArray[siteStatsSlideIndex].internalEls.push(temp);
    temp = new IntElSlideInfo();
    temp.internalElement = gID('latestContentDiv');
    temp.offset = 0;
    slideArray[siteStatsSlideIndex].internalEls.push(temp);
    temp = new IntElSlideInfo();
    temp.internalElement = gID('historyContentDiv');
    temp.offset = 0;
    slideArray[siteStatsSlideIndex].internalEls.push(temp);
}

function explorerPanelResize(inWidth, inHeight)
{
    var area = gID('ExplorerPanelDiv');   
    inHeight = inHeight - parseInt(area.style.top) - 10;
    area.style.height = inHeight + "px";
    gID('explorerRepeaterDiv').style.height = (inHeight - 254) + 'px';
    gID('explorerContentDiv').style.height = (inHeight) + 'px';
    gID('latestContentDiv').style.height = (inHeight) + 'px';
    gID('historyContentDiv').style.height = (inHeight) + 'px';    
}

function explorerPanelLogin()
{
    if(curUser == null)
    {
        var area = gID('historyContentDiv');
        if(area.style.display == "")
        {
            explorerTabClicked(gID('tabExplorer'));        
        }
        else
        {
            gID('tabHistory').style.cursor = 'default';
        }
        area.innerHTML = "";
    }
    else
    {
        var url = queryURL + '?QType=List&IDImage=';
        var first = true;
        for(var i in curUser.HistoryArray)
        {
            for(var j in curUser.HistoryArray[i])
            {
                if(j == "Name")
                    continue;
                
                if(first)
                {
                    url += j;
                    first = false;
                }
                else
                {
                    url += '.' + j;
                }
            }
        }
        var xmlObj = createXMLObject();
        if(xmlObj != null){
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                fillHistoryPanel(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
        }
    }
}

function fillHistoryPanel(response)
{
    var imgArray = eval('(' + response + ')');
    for(var i =0; i<imgArray.length; i++)
    {
        addImageLocal(imgArray[i],false);
    }
    var histArray = curUser.HistoryArray;
    var curImage = null;
    var htmlString = '<font style="font-size:2pt;">&nbsp;</font><br/>';
    var curName = "";
    var curID = "";
    
    var innerString = "";
    var count = 0;
    for(var i in histArray)
    {
        count = 0;
        curID = i;
        curName = histArray[i]["Name"];
        innerString = '<div style="padding-left:3px;"><table style="display:inline;border-collapse:collapse;vertical-align:middle;"><tr><td><div style="height:9px;overflow:hidden;width:9px;background-image:url(Images/WebGraphics/combined_100x283.gif);background-position:-75px -30px;cursor:pointer;" onclick="histNodeClicked(\''+curID+'\');" id="PlusMinusHist'+curID+'"></div></td><td style="padding-left:2px;"><div style="overflow:hidden;cursor:pointer;width:16px;height:14px;background-image:url(Images/WebGraphics/combined_100x283.gif);background-position:-84px -30px;" onclick="histNodeClicked(\''+curID+'\');" id="FolderIconHist'+curID+'"></div></td><td style="padding-left:2px;">'+curName+'</td></tr></table><div style="display:none;padding-left:19px;" id="HolderHistory'+curID+'">';
        for(var j in histArray[i])
        {
            if(j == "Name")
                continue;
            innerString += createFolderNodeString(GLOBAL_imageTable[''+j], curID, 'History');
			count++;
	    }
	    
	    if(count == 0)
	    {
	        innerString +=  '<div style="padding-left:13px;" id="BlankHistory'+curID+'">No history for this period.&nbsp;</div>';
	    }
	    
	    innerString += '</div></div>';
	    
	    htmlString += innerString;
    }
    gID('historyContentDiv').innerHTML = htmlString;
    gID('tabHistory').style.cursor = 'pointer';
}

function createFolderNodeString(img, curID, tab)
{
    return '<div style="padding-left:12px;" id="'+img.IDImage+tab+curID+'"><table style="border-collapse:collapse;border-spacing:0px;display:inline;vertical-align:middle;white-space:nowrap;"><tbody><tr><td><a href="index.php?IDImage='
            +img.IDImage+'" onclick="imageClicked('+img.IDImage+');return false;" style="text-decoration:none;"><img src="'+imageURL+'?IDImage='
            +img.IDImage+'" style="height:16px;width:16px;border:0px;"/></td><td style="padding-left:2px;"><span style="white-space:nowrap;"><a href="index.php?IDImage='
            +img.IDImage+'" onclick="imageClicked('+img.IDImage+');return false;" style="text-decoration:none;color:#666666">'+img.Name
            +'</span></td></tr></tbody></table></a>&nbsp;</div>'
}

function histNodeClicked(curID)
{
    changeNodeIcons(gID('HolderHistory' + curID), gID('PlusMinusHist'+curID), gID('FolderIconHist'+curID))
}

function explorerTabClicked(e)
{
    if(e==null){return;}
    if(e.id == 'tabExplorer')
    {
        e.style.backgroundPosition = '-60px -169px';
        e.style.cursor = 'default';
        e = gID('tabLatest');
        e.style.backgroundPosition = '-20px -94px';
        e.style.cursor = 'pointer';
        e = gID('tabHistory');
        e.style.backgroundPosition = '-40px -94px';
        if(curUser != null)
            e.style.cursor = 'pointer';
        else
            e.style.cursor = 'default';
        gID('explorerContentDiv').style.display = '';
        gID('latestContentDiv').style.display = 'none';
        gID('historyContentDiv').style.display = 'none';
    }
    else if(e.id == 'tabLatest')
    {
        loadLatestTab();
        e.style.backgroundPosition = '-20px -169px';
        e.style.cursor = 'default';
        e = gID('tabExplorer');
        e.style.backgroundPosition = '-60px -94px';
        e.style.cursor = 'pointer';
        e = gID('tabHistory');
        e.style.backgroundPosition = '-40px -94px';
        if(curUser != null)
            e.style.cursor = 'pointer';
        else
            e.style.cursor = 'default';
        gID('explorerContentDiv').style.display = 'none';
        gID('latestContentDiv').style.display = '';
        gID('historyContentDiv').style.display = 'none';
    }
    else if(e.id == 'tabHistory')
    {
        if(curUser != null)
        {    
            e.style.backgroundPosition = '-40px -169px';
            e.style.cursor = 'default';
            e = gID('tabLatest');
            e.style.backgroundPosition = '-20px -94px';
            e.style.cursor = 'pointer';
            e = gID('tabExplorer');
            e.style.backgroundPosition = '-60px -94px';
            e.style.cursor = 'pointer';
            gID('explorerContentDiv').style.display = 'none';
            gID('latestContentDiv').style.display = 'none';
            gID('historyContentDiv').style.display = '';
        }
        else
        {
            histErrorPanel = gID('tabHistoryError');
        
            if(histErrorPanelIntervalID != -1)
                clearInterval(histErrorPanelIntervalID);
            
            histErrorPanel.style.display = "";
            histErrorPanelIntervalID = setInterval('histErrorPanelSlideOut()', 20);
        }
    }
}

function loadLatestTab()
{
    if(gID('latestLoadingSpan') == null)
        return;
    
    var url = latestURL;
    var xmlObj = createXMLObject();
        
    if(xmlObj != null)
    {
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                loadLatestCallback(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
}

function loadLatestCallback(response)
{
    var latestDiv = gID('latestContentDiv');
    latestDiv.innerHTML = response;
}

function histErrorPanelSlideOut()
{
    var num = parseInt(histErrorPanel.style.width);
    if(num + slideSpeed < 145)
    {
        histErrorPanel.style.width = (num + slideSpeed) + 'px';
    }
    else
    {
        histErrorPanel.style.width = (145) + 'px';
        clearInterval(histErrorPanelIntervalID);
        histErrorPanelIntervalID = -1;
        histErrorPanelIntervalID = setTimeout('histErrorPanelSlideInStart()', 2000);
    }
}

function histErrorPanelSlideInStart()
{
    histErrorPanelIntervalID = setInterval('histErrorPanelSlideIn()', 20);
}


function histErrorPanelSlideIn()
{
    var num = parseInt(histErrorPanel.style.width);
    if(num - slideSpeed > 0)
    {
        histErrorPanel.style.width = (num - slideSpeed) + 'px';
    }
    else
    {
        histErrorPanel.style.display = "none";
        histErrorPanel.style.width = (0) + 'px';
        clearInterval(histErrorPanelIntervalID);
        histErrorPanelIntervalID = -1;  
    }
}

function changeNodeIcons(holder, plusMinus, folderIcon)
{
    if(holder == null)
        return false;
        
    if(holder.style.display == 'none')
    {
        holder.style.display = '';
        plusMinus.style.backgroundPosition = '-75px -39px';
        folderIcon.style.backgroundPosition = '-84px -44px';
    }
    else
    {
        holder.style.display = 'none';
        plusMinus.style.backgroundPosition = '-75px -30px';
        folderIcon.style.backgroundPosition = '-84px -30px';   
    }
    return true;
}

function explorerNodeClicked(catID)
{
    var plusMinus = gID('PlusMinusCat' + catID);
    var folderIcon = gID('FolderIconCat' + catID);
    var holder = gID('expChildNode' + catID);
    
    if(changeNodeIcons(holder, plusMinus, folderIcon))
        return;
    
    var parent = gID('catHolder' + catID);
    var loading = gID('loadingSpanFor' + catID);
    if(loading != null)
    {
        parent.removeChild(loading);
        plusMinus.style.backgroundPosition = '-75px -30px';
        folderIcon.style.backgroundPosition = '-84px -30px';
        return;
    }
    else
    {      
        plusMinus.style.backgroundPosition = '-75px -39px';
        folderIcon.style.backgroundPosition = '-84px -44px';
    }
        
    parent.innerHTML += '<div style="padding-left:32px;" id="loadingSpanFor'+catID+'">Loading....&nbsp;</div>';
        
    var url = queryURL + '?IDCat=' + catID + '&QType=NextChildren';
    var xmlObj = createXMLObject();
    if(xmlObj != null){
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                expandNode(xmlObj.responseText, parent, catID);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }       
}

function expandNode(responseText, parent, parentCatID)
{
    var node = gID('expChildNode' + parentCatID);
    if(node != null)
        return;
        
    var responseArray = eval('(' + responseText + ')');
    var catArray = responseArray[0];
    var imageArray = responseArray[1];
    var loadingSpan = gID('loadingSpanFor' + parentCatID);
    
    var newText = '<div id="expChildNode'+parentCatID+'" style="padding-left:19px;';
    if(loadingSpan == null)
    {   
        newText += 'display:none;">';
    }
    else
    {
        newText += '">';
    }
    
    for(var i = 0; i < catArray.length; i++)
    {
        newText +=  '<div id="catHolder'+catArray[i].IDCategory+'"><table style="display:inline;border-collapse:collapse;vertical-align:middle;"><tr><td><div style="height:9px;overflow:hidden;width:9px;background-image:url(Images/WebGraphics/combined_100x283.gif);background-position:-75px -30px;cursor:pointer;" onclick="explorerNodeClicked(\''+catArray[i].IDCategory+'\');" id="PlusMinusCat'+catArray[i].IDCategory+'"></div></td><td style="padding-left:2px;"><div style="overflow:hidden;cursor:pointer;width:16px;height:14px;background-image:url(Images/WebGraphics/combined_100x283.gif);background-position:-84px -30px;" onclick="explorerNodeClicked(\''+catArray[i].IDCategory+'\');" id="FolderIconCat'+catArray[i].IDCategory+'"></div></td><td style="padding-left:2px;">'+catArray[i].CatName+'</td></tr></table></div>';
    }
    
    var img = null;
    for(var i = 0; i < imageArray.length; i++)
    {
        newText += createFolderNodeString(imageArray[i], parentCatID, 'Explorer');
    }
    if(catArray.length == 0 && imageArray.length == 0)
    {
        newText +=  '<div style="padding-left:13px;">Category is empty.&nbsp;</div>';
    }
    
    newText += '</div>';
    
    if(loadingSpan != null)
        parent.removeChild(loadingSpan); 
        
    parent.innerHTML += newText;
    
    for(var i = 0; i < imageArray.length; i++)
    {
        addImageLocal(imageArray[i],false);
    } 
}

function addImageToHistory(img)
{
    if(curUser == null)
        return;
        
    var el = gID('HolderHistoryToday');
    if(el == null)
        return;    
        
    var childEl = gID(img.IDImage + 'HistoryToday');
    if(childEl != null)
    {
        el.removeChild(childEl);
    }
    else
    {
        childEl = gID('BlankHistoryToday');
        if(childEl != null)
        {
            el.removeChild(childEl);
        }
    }
   
    el.innerHTML = createFolderNodeString(img, 'Today', 'History') + el.innerHTML;
}

function imageClicked(imageID)
{
    setupPreviewPane(imageID, null);
}

function setupPreviewPane(imageID, search)
{
    gID('imagePreviewMessageCell').innerHTML = "Image Preview <br> Loading Image...";
    gID('previewImageDiv').search = search;
    
    getImage(imageID, loadImagePreview, false);
}

function loadImagePreview(img)
{
    var selType=null;
    if(loadTypeOnPageLoad!='')
    {
        selType=loadTypeOnPageLoad;
        loadTypeOnPageLoad='';
    }
    previewSelectedId = -1;  
    if(typeof(img) == "string")
    {
        alert(img);
        return;
    }
    gID('previewInfoDiv').innerHTML = '<center><b>' + img.Name + '</b><br/>'+img.Description
            +'<br/><span style="font-size:4pt;">&nbsp;<br/></span>'
            + '<a class="loginLnk" style="font-weight:normal;" href="index.php?Tree='
            +img.Name+'&IDImage='+img.IDImage+'" onclick="getImage('+img.IDImage
            +',createTreeFromImage,false);return false;"><table style="display:inline;border-collapse:collapse;width:13px;height:13px;"><tr><td><div style="width:13px;height:13px;background-image:url(Images/WebGraphics/combined_100x283.gif);background-position:-56px -264px;background-repeat:no-repeat;"></div></td></tr></table></a>'
            
            
            +'&nbsp;&nbsp;<a class="loginLnk" style="font-weight:normal;" href="index.php?Tree='
            +img.Name+'&IDImage='+img.IDImage+'" onclick="getImage('+img.IDImage
            +',createTreeFromImage,false);return false;">Start Tree from Image</a></center>';
            
    gID('previewInfoDiv').scrollTop = 0;
    var html = '';
    var currentLeft = 0;    
    var initView = null;
    var curTypes = checkTypes(img); 
    for(var key in curTypes)
    {
        if(!curTypes[key].hasType)
            continue;
            
        html += '<a href="index.php?IDImage='+img.IDImage+'&IDType='+TFSs[curTypes[key].IDTFS].IDType
                    +'" onclick="previewTabClicked(this,'+img.IDImage+','+curTypes[key].IDTFS
                    + ');return false;"><div class="unPreTab" style="left:'+currentLeft+'px;" id="'
                    +curTypes[key].id+'"><center>'+curTypes[key].dispName+'</center></div></a>';
        
        if(initView==null || (selType!=null&&TFSs[curTypes[key].IDTFS].IDType==selType))
        {
            initView = key;
        }
        currentLeft += 49;   
    }
    gID('previewTypesDiv').innerHTML = html;
    
    if(initView != null)
        previewTabClicked(gID(curTypes[initView].id), img.IDImage, curTypes[initView].IDTFS);
    
    if(gID('previewContentDiv').style.display == "none")
        searchTabClicked(gID('tabPreview'));
}

function previewTabClicked(element, imageID, idtfs)
{
    if(element.tagName == 'A')
        element = element.childNodes[0];
        
    if(element.style.cursor == 'Default'){return;}
    
    if(previewSelectedId!=-1)
    {
        gID(previewSelectedId).className = 'unPreTab';
        previewSelectedId = -1;
    }
        
    previewSelectedId = element.id;
    element.className = 'selPreTab';
        
    var preview = gID('previewImageDiv');
    preview.style.backgroundImage = 'url(' + imageURL + '?IDImage=' + imageID + '&IDTFS=' + idtfs + ')';
    preview.style.cursor = 'pointer';
    preview.title = 'Click Here to Enlarge';
   
    preview.ImageID = imageID;
    preview.Type = TFSs[idtfs].IDType;
    
    gID('previewImageLink').href = "index.php?IDImage="+imageID+'&IDType='+preview.Type;
    gID('previewImageEnlarge').href = "index.php?IDImage="+imageID+'&IDType='+preview.Type;
}

function checkTypes(imageObject)
{
    var types = new ImgTypesObject();
    var reg;
    for(var key in types)
    {
        reg = new RegExp(types[key].fullName, "i");
        for(var IDTFS in imageObject.AvailableTFS)
        {
            tfs = TFSs[IDTFS];
            if(reg.exec(TYPES[parseInt(tfs.IDType)].TypeExplanation) && tfs.Size == 145)
            {
                types[key].hasType = true;
                types[key].IDTFS = tfs.IDTFS;
                break;
            }
        }
    }
    return types;
}
var advSearchHolder = null;
var dispSearchHolder = null;
var incSearchHolder = null;
var slideAdvSearchIntervalId = -1;
var slideDispSearchIntervalId = -1;
var dispSearchHolderHeight = 50;
var advSearchHolderHeight = 125;
var incSearchHolderHeight = 25;
var currentHighImgTypeTab = -1;
var current512DivImage = null;
var current512DivQuery = null;
var agreeToEULA = -1;
var colorSelectorArray = null;

function previewPanelInit()
{
    slideArray[userStatsSlideIndex].bottomElement = gID('PreviewPanelDiv');
    var temp = new IntElSlideInfo();
    temp.internalElement = gID('searchRepeaterDiv');
    temp.offset = 179;
    slideArray[userStatsSlideIndex].internalEls.push(temp);   
    temp = new IntElSlideInfo();
    temp.internalElement = gID('searchContentDiv');
    temp.offset = 0;
    slideArray[userStatsSlideIndex].internalEls.push(temp);  
    temp = new IntElSlideInfo();
    temp.internalElement = gID('previewContentDiv');
    temp.offset = 0;
    slideArray[userStatsSlideIndex].internalEls.push(temp);
    showHideAd(false);
}

function previewPanelResize(inWidth,inHeight)
{
    var area = gID('rightPusher');
    if(inWidth == 970)
        area.style.left = '970px';
    else
        area.style.left = '0px';
    if(inHeight==630)
        area.style.top = '630px';
    else        
        area.style.top = '0px';
    area = gID('PreviewPanelDiv');
    var adArea = gID('AdAreaDiv');
    area.style.left = (inWidth - 190) + "px";
    adArea.style.left = (inWidth - 190) + "px";
    if(!(adArea.style.display == 'none'))
    {
        inHeight = inHeight - 158;
        adArea.style.top = (inHeight) + 'px';
    }
    inHeight = (inHeight - parseInt(area.style.top) - 10);
    area.style.height = inHeight + "px";
    gID('searchRepeaterDiv').style.height = (inHeight - 179) + 'px';
    gID('searchContentDiv').style.height = (inHeight) + 'px';
    gID('previewContentDiv').style.height = (inHeight) + 'px';
    gID('previewInfoDiv').style.height = inHeight - 201 + 'px';
}

function showHideAd(resize)
{
    var adArea = gID('AdAreaDiv');
    var iadArea = gID('InnerAdAreaDiv');
    var previewArea = gID('PreviewPanelDiv');
    if(curUser == null || curUser.FullAuthValue <= 1)
    {
        adArea.style.display = ''; 
        //iadArea.innerHTML = '<iframe scrolling="no" frameborder="0" style="width:180px;height:150px;border:0px;" src="Callbacks/ad_callback.php?pos=brc"></iframe>';
        slideArray[userStatsSlideIndex].bottomElementOffset = 399;
    }
    else
    {
        adArea.style.display = 'none'; 
        //iadArea.innerHTML = '';
        slideArray[userStatsSlideIndex].bottomElementOffset = 241;
    }
    
    if(resize)
        mainResize();
}

function searchTabClicked(e)
{
    if(e==null){return;}
    if(e.id == 'tabPreview')
    {
        e.style.backgroundPosition = '0px -169px';
        e.style.cursor = 'default';
        e = gID('tabSearch');
        e.style.backgroundPosition = '-80px -94px';
        e.style.cursor = 'pointer';
        
        gID('searchContentDiv').style.display = 'none';
        gID('previewContentDiv').style.display = '';
    }
    else if(e.id == 'tabSearch')
    {
        e.style.backgroundPosition = '-80px -169px';
        e.style.cursor = 'default';
        e = gID('tabPreview');
        e.style.backgroundPosition = '0px -94px';
        e.style.cursor = 'pointer';
        
        gID('searchContentDiv').style.display = '';
        gID('previewContentDiv').style.display = 'none';
    }
}

function colorPickerClicked(e, el)
{  
    var area = gID('ColorPickerCrosshair');
        
    if(browser.isIE || browser.isOP)
    {
        if(window.event.srcElement != el)
            return;
        e.layerX = e.offsetX;
        e.layerY = e.offsetY;
    }
    else if(e.target != el)
    {
        return;
    }
    
    gID('ColorPickerArrows').style.left = '60px';
        
    area.style.left = e.layerX - 8 + 'px';
    area.style.top = e.layerY - 8 + 'px';
    
    findColor(e.layerX-8, e.layerY-8);
    
    dragStartFull(e, null, area, 'findColor', -7, -8, 136, 147, 'default')
}

function findColorStart(a)
{
    findColor(64,69);
}

function findColor(posX, posY)
{
    if(!posX || !posY){return;}   
    posX+=8;posY+=8;
    var r = 0, g = 0, b = 0;
    
    if(posX > 0 && posX <= 24)
    {
        r = 255;
        b = 0;
        g = Math.round(10.625 * posX);
    }
    else if(posX > 24 && posX <= 48)
    {
        r = 255 - Math.round(10.625 * (posX - 24));
        g = 255;
        b = 0;
    }
    else if(posX > 48 && posX <= 72)
    {
        r = 0;
        g = 255;
        b = Math.round(10.625 * (posX - 48));
    }
    else if(posX > 72 && posX <= 96)
    {
        r = 0;
        g = 255 - Math.round(10.625 * (posX - 72));
        b = 255;
    }
    else if(posX > 96 && posX <= 120)
    {
        r = Math.round(10.625 * (posX - 96));
        g = 0;
        b = 255;
    }
    else
    {
        r = 255;
        g = 0;
        b = 255 - Math.round(10.625 * (posX - 120));
    }
    
    var newR = r - (((r - 127) / 155) * posY);
    var newG = g - (((g - 127) / 155) * posY);
    var newB = b - (((b - 127) / 155) * posY);
    
    r = Math.round(newR);
    g = Math.round(newG);
    b = Math.round(newB);
    selectColor(r,g,b);
        
    var colorSlices = 60;
    var cs2 = colorSlices / 2;
    var subR = (255 - newR) / cs2;
    var subG = (255 - newG) / cs2;
    var subB = (255 - newB) / cs2;
    var currentR = newR, currentG = newG, currentB = newB;
    
    if(colorSelectorArray==null)
        fillColorSelectorArray(colorSlices);
        
    var cSA = colorSelectorArray;
    for(var i = cs2 - 1; i > -1; i--)
    {
        cSA[i].red=Math.round(currentR);
        cSA[i].green=Math.round(currentG);
        cSA[i].blue=Math.round(currentB);
        cSA[i].style.backgroundColor = 'rgb('+cSA[i].red+','+cSA[i].green+','+cSA[i].blue+')';

        currentR+=subR;
        currentG+=subG;
        currentB+=subB;
    }
    
    subR = newR / cs2;
    subG = newG / cs2;
    subB = newB / cs2;
    currentR = newR;
    currentG = newG;
    currentB = newB;
    
    for(var i = cs2; i < colorSlices; i++)
    {
        currentR-=subR;
        currentG-=subG;
        currentB-=subB;
        cSA[i].red=Math.round(currentR);
        cSA[i].green=Math.round(currentG);
        cSA[i].blue=Math.round(currentB);
        cSA[i].style.backgroundColor = 'rgb('+cSA[i].red+','+cSA[i].green+','+cSA[i].blue+')';
    } 
}

function fillColorSelectorArray(slices)
{
    colorSelectorArray = new Array();
    var els = '';
    for(var i=0; i<slices; i++)
    {
        els += '<div style="position:absolute;width:2px;height:20px;z-index:1;left:'
                + (i * 2) + 'px;top:0px;" onmousedown="selectColorEl(event,this);" id="colorSelectorIndex'+i+'"></div>';
    }
    gID('ColorSelectorDiv').innerHTML += els;
    for(var i=0;i<slices; i++)
    {
        colorSelectorArray.push(gID('colorSelectorIndex'+i));
    }
}

function selectColorDrag(x,y)
{
    if(!x){return;}
    if(null==colorSelectorArray){return;}
    var a=colorSelectorArray[Math.floor((x+2)/2)]
    selectColor(a.red,a.green,a.blue);
}

function selectColorEl(event,e)
{
    var a=gID('ColorPickerArrows');
    a.style.left = (parseInt(e.style.left)-1) + 'px';
    selectColor(e.red,e.green,e.blue);
    dragStartFull(event, null, a, 'selectColorDrag', -2, -4, 117, -4, 'default');
}

function selectColor(r,g,b)
{
    var a=gID('ColorSelectedDiv');
    a.style.backgroundColor = 'rgb('+r+','+g+','+b+')';
    a.red=r;
    a.green=g;
    a.blue=b;
    gID('ColorPickerRed').innerHTML = '<b>Red:</b><br />' + r;
    gID('ColorPickerGreen').innerHTML = '<b>Green:</b><br />' + g;
    gID('ColorPickerBlue').innerHTML = '<b>Blue:</b><br />' + b;
}

function setSearchColorsFromPicker()
{
    var a=gID('ColorSelectedDiv');
    gID('SearchColorRedBox').value = a.red;
    gID('SearchColorGrnBox').value = a.green;
    gID('SearchColorBluBox').value = a.blue;
    closeDragWindow('ColorPickerArea');
}

function setSearchErrorMsg(message)
{
    gID('SearchErrorMsgBox').innerHTML = message;
}

function clearKeywordSearch()
{
    gID('keywordBox').value = "";
    gID('SearchImgTypeTex').checked = false;
    gID('SearchImgTypeObj').checked = false;
    gID('SearchImgTypeScn').checked = false;
    gID('SearchImgTypeAll').checked = true;
    gID('SearchImgTypeNor').checked = false;
    gID('SearchImgTypeHgt').checked = false;
    gID('SearchColorRedBox').value = '';
    gID('SearchColorGrnBox').value = '';
    gID('SearchColorBluBox').value = '';
    gID('SearchColorRangeBox').value = 100;
    gID('SearchImgRsltTree').checked = false;
    gID('SearchImgRsltStnd').checked = true;
    setSearchErrorMsg("");
    if(gID('advancedSearchOptionsDiv').style.display == '')
    {
        slideAdvSearch(gID('slideAdvSearchBut'));
    }
    if(gID('displaySearchOptionsDiv').style.display == '')
    {
        slideDispSearch(gID('slideDispSearchBut'));
    }
}

function fillSearchFromTab(tabNum)
{
    var tab = gID('treePanel' + tabNum);
    
    var search = tab.query;
    
    if(gID('searchContentDiv').style.display == "none")
        searchTabClicked(gID('tabSearch'));
    
    fillKeywordSearch(search);
}

function fillKeywordSearch(search)
{
    var showAdvDiv = false;
    var showDispDiv = false;
    
    setSearchErrorMsg("");
    
    gID('keywordBox').value = search.keywords;
    
    if(!(search.textures && search.objects && search.scenes))
    {
        showAdvDiv = true;
        gID('SearchImgTypeTex').checked = search.textures;
        gID('SearchImgTypeObj').checked = search.objects;
        gID('SearchImgTypeScn').checked = search.scenes;
        gID('SearchImgTypeAll').checked = false;    
    }else{
        gID('SearchImgTypeTex').checked = false;
        gID('SearchImgTypeObj').checked = false;
        gID('SearchImgTypeScn').checked = false;
        gID('SearchImgTypeAll').checked = true;    
    }
    
    if(search.normals || search.heights)
    {
        showAdvDiv = true;   
    }
    gID('SearchImgTypeNor').checked = search.normals;
    gID('SearchImgTypeHgt').checked = search.heights;
    
    if(search.red != '' && search.green != '' && search.blue != '')
    {
        showAdvDiv = true;   
    }
    
    gID('SearchColorRedBox').value = search.red;
    gID('SearchColorGrnBox').value = search.green;
    gID('SearchColorBluBox').value = search.blue;
    gID('SearchColorRangeBox').value = search.range;
    
    if(search.qType != "List")
    {
        showDispDiv = true;
        gID('SearchImgRsltTree').checked = true;
        gID('SearchImgRsltStnd').checked = false;
    }
    else
    {
        gID('SearchImgRsltTree').checked = false;
        gID('SearchImgRsltStnd').checked = true;
    }
    
    if(gID('advancedSearchOptionsDiv').style.display == '')
    {
        if(!showAdvDiv)
        {
            slideAdvSearch(gID('slideAdvSearchBut'));
        }
        else
        {
            if(search.normals || search.heights)
            {
                slideIncSearch(true);
            }
            else
            {
                slideIncSearch(false);    
            }
        }    
    }
    else if(showAdvDiv)
    {
        slideAdvSearch(gID('slideAdvSearchBut'));  
    }
    
    if(gID('displaySearchOptionsDiv').style.display == '')
    {
        if(!showDispDiv)
        {
            slideDispSearch(gID('slideDispSearchBut'));
        }
    }else if(showDispDiv){
        slideDispSearch(gID('slideDispSearchBut'));  
    }
}

function keywordSearch()
{
    var box = gID('keywordBox');

    if(box.value == "")
    {
        setSearchErrorMsg("Please enter a search query.");
        return;
    }

    var search = new SearchObject(box.value);

    var url = '';
    var req = (gID('includeSearchOptionsDiv').style.display == '');

    var type = 0;
    if(gID('SearchImgTypeAll').checked)
    {
        type = 1;
    }
    else
    {
        search.textures = false;
        search.objects = false;
        search.scenes = false;

        if(gID('SearchImgTypeTex').checked)
        {
            type+=2;
            search.textures = true;
        }
        if(gID('SearchImgTypeObj').checked)
        {
            search.objects = true;
            type+=3;
        }
        if(gID('SearchImgTypeScn').checked)
        {
            search.scenes = true;
            type+=4;
        }
        
        if(type == 9)
            type = 1;

        if(type == 0)
        {
            setSearchErrorMsg("Please choose a type of image to search for.");
            return;
        }

        url += "&ImgTypes=" + type;
    }
     
    if(req)
    {
        type = 0;
        if(gID('SearchImgTypeNor').checked)
        {
            search.normals = true;
            type+=1;
        }
        if(gID('SearchImgTypeHgt').checked)
        {
            search.heights = true;
            type+=2;
        }

        url += "&ReqTypes=" + type;
    }
     
    var red = gID('SearchColorRedBox').value;
    var green = gID('SearchColorGrnBox').value;
    var blue = gID('SearchColorBluBox').value;
    var range = gID('SearchColorRangeBox').value;
     
    if(red != "" || green != "" || blue != "")
    {
        red = parseInt(red);
        blue = parseInt(blue);
        green = parseInt(green);
        range = parseInt(range);
        if(red<0 || red>255 || green<0 || green>255 || blue<0 || blue>255 || range<0
            || range>255 || isNaN(red) || isNaN(green) || isNaN(blue) || isNaN(range))
        {
            setSearchErrorMsg("Please either fill in all the color fields with numbers between 0 and 255 or leave them all blank.");
            return;            
        }

        search.red = red;
        search.green = green;
        search.blue = blue;
        search.range = range;

        url += '&Red=' + red + '&Green=' + green + '&Blue=' + blue + '&Range=' + range;         
    }
    
    if(gID('SearchImgRsltTree').checked)
    {
        url += '&QType=Tree';
        search.qType = "Tree";
    }
    else
    {
        url += '&QType=List';
        search.qType = "List";
    }
    
    keywordSearch2(search, url);
}

function keywordSearch2(search, url)
{
    url = queryURL + '?Keywords=' + search.keywords + url;

    search.tabNum = createTab(search.keywords,search);
    
    var tree = null;
    if(search.qType == "Tree")
        tree = new Tree(gID('treePanel' + search.tabNum));    
        
    var xmlObj = createXMLObject();
    if(xmlObj != null){
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                if(search.qType == "List")
                    showSearchResultsStandard(search, xmlObj.responseText);
                else
                    tree.resetTree(xmlObj.responseText,true);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
    
    setSearchErrorMsg("");
}

function createUrlFromSearchObj(search, useQtype)
{
    var url = "";
    var type = 0;
    if(search.textures)
        type+=2;
    if(search.objects)
        type+=3;
    if(search.scenes)
        type+=4;
    if(type == 9)
        type = 1;
    url += "&ImgTypes=" + type;
    type = 0;
    if(search.normals)
        type+=1;
    if(search.heights)
        type+=2;
    url += "&ReqTypes=" + type;
    if(search.red != "" && search.green != "" && search.blue != "")
    {
        url += '&Red=' + search.red + '&Green=' + search.green + '&Blue=' + search.blue + '&Range=' + search.range;    
    }
    if(useQtype)
        url += '&QType=' + search.qType;
    return url;
}

function duplicateTab(tabNum)
{
    var tab = gID('treePanel' + tabNum);
    
    var search = tab.query;
    var nSearch = new SearchObject(search.keywords);
    nSearch.textures = search.textures;
    nSearch.objects = search.objects;
    nSearch.scenes = search.scenes;
    nSearch.normals = search.normals;
    nSearch.heights = search.heights;
    nSearch.red = search.red;
    nSearch.green = search.green;
    nSearch.blue = search.blue;
    nSearch.range = search.range;
    nSearch.qType = search.qType;
    
    keywordSearch2(nSearch, createUrlFromSearchObj(nSearch, true));
}

function showSearchResultsStandard(search, results)
{
    var tab = gID('treePanel' + search.tabNum).innerPanel;
    
    var error = '<font style="font-size:2pt;">&nbsp;</font><br><table style="color:#666666; border-collapse: collapse; width:100%;"><tr><td style="text-align:center;">';
    
    if(results == null || results == '')
    {
        tab.innerHTML = error + 'Unable to connect to server.</td></tr></table>';
        return;
    }
    
    var imgArray = eval('(' + results + ')');
    if(typeof(imgArray) == "string")
    {
        tab.innerHTML = error + imgArray + '</td></tr></table>';
        return;
    }   

    if(imgArray.length == 0)
    {
        tab.innerHTML = error + 'No matching results found.</td></tr></table>';
        return;
    }                    
    
    var html = '<font style="font-size:2pt;">&nbsp;</font><br>';
    var img = null;
    
    for(var i=0; i<imgArray.length; i++)
    {
        img = imgArray[i];
        addImageLocal(img,false);
        
        html += '<table style="display:inline;width:144px;color:#666666;border-collapse:collapse;">'
                +'<tr style="height:64px;"><td style="text-align:center;width:144px;"><a href="index.php?IDImage='
                +img.IDImage+'" onclick="keywordSearchImgClicked('+img.IDImage+','+search.tabNum+');return false;"><img border="0" src="'
                +imageURL+'?IDTFS=3&IDImage='+img.IDImage+'" height="64px" width="64px"></a></td></tr>'
			    +'<tr style="height:5px;"><td></td></tr><tr><td height="30px" valign="top" style="width:144px;text-align:center;">' 
			    +img.Name+'</td></tr><tr height="15px"><td></td></tr></table>';
    }
    
    tab.innerHTML = html + '<font style="font-size:2pt;">&nbsp;</font><br>';
}

function keywordSearchImgClicked(imgID, tabNum)
{
    setupPreviewPane(imgID, gID('treePanel' + tabNum).query);
}

function displayFullImage(previewDiv, setPrev)
{
    var i = previewDiv.ImageID;
    if(isNaN(i) || i < 0)
        return;
    gID('ImageDisplayAreaTag').innerHTML = '';
    
    var area;
    for(var j=0; j<2; j++)
    {
        gID('Relationship512Msg'+j).innerHTML = 'Loading Image...';
        area = gID('Relationship512Pic'+j);
        area.style.backgroundImage = '';
        area.title = "";
        area.style.cursor = 'default';
        area = gID('Relationship512Link'+j);
        area.href = '';
        area.ImageID = -1;
    }
        
    if(setPrev)
        setupPreviewPane(i,current512DivQuery);
    getImage(i, displayFullImage2, false);    
}

function displayFullImage2(currentImage)
{
    if(typeof(currentImage) == "string")
    {
        alert(currentImage);
        return;
    }
    
    current512DivImage = currentImage;
    
    var preDiv = gID('previewImageDiv');
    var selectedType = preDiv.Type;
    current512DivQuery = preDiv.search;
    var selectedTFS = 0;
    
    currentHighImgTypeTab = -1;
    
    var area = gID('ImageTabHolder');
    area.innerHTML = "";
    var currentPos = 0;
    for(var IDTFS in currentImage.AvailableTFS)
    {
        var currentTFS = TFSs[IDTFS];
        
        if(currentTFS.Size != 512 || currentTFS.IDFormat != 1)
            continue;
            
        if(currentTFS.IDType == selectedType)
            selectedTFS = currentTFS;                                     
        
        area.innerHTML += '<a href="index.php?IDImage='+currentImage.IDImage+'&IDType='+currentTFS.IDType
                +'" onclick="imageTypeTabClicked(this, ' + currentTFS.IDTFS
                + ');return false;"><div class="unBigDiv" id="ImageTypeTab' + currentTFS.IDTFS 
                + '" style="left:' + currentPos + 'px;"><table style="position:absolute;left:0px;top:0px;width:49px;height:18px;"><tr><td style="vertical-align:middle;">' + TYPES[currentTFS.IDType].TypeName + '</td></tr></table></div></a>';
        
	    currentPos+=49;
    }   
    
    imageTypeTabClicked(gID('ImageTypeTab' + selectedTFS.IDTFS), selectedTFS.IDTFS);
    
    genericShowDragDiv('ImageDisplayArea', currentImage.Name, 655, null);
    area = gID('ImageDisplayAreaContainer')
    area.style.height = "544px";
    
    setUp512AdSpace(currentImage.IDImage);

    gID('ImageDisplayAreaTitle').innerHTML = '&nbsp;' + currentImage.Name;
    
    addImageToHistory(currentImage);
}

function setUp512AdSpace(imgID)
{
    if(curUser != null && curUser.FullAuthValue > 1)
    {
        gID('Google512Ads').style.display = 'none';
        gID('Relationship512Area').style.display = '';
        gID('512BottomAd').innerHTML = '';
        
        var url = queryURL + '?IDImage=' + imgID + '&QType=Tree&Level1Num=2&Level2Num=0';
        if(current512DivQuery != null)
        {
            url += '&'+createUrlFromSearchObj(current512DivQuery, false);
        }        
        var xmlObj = createXMLObject();
        if(xmlObj != null){
            xmlObj.onreadystatechange = function(){
                if(xmlObj.readyState == 4){
                    setRelated512Images(xmlObj.responseText);
                }
            }
            xmlObj.open ('GET', url, true);
            xmlObj.send ('');
        }
    }
    else
    {
        gID('Relationship512Area').style.display = 'none';
        gID('Google512Ads').style.display = '';
        var area = gID('512TopAd');
        if(area.innerHTML == '')
            area.innerHTML = '<iframe scrolling="no" frameborder="0" style="width:125px;height:125px;border:0px;" src="Callbacks/ad_callback.php?type=picasa"></iframe>';
        gID('512BottomAd').innerHTML = '<iframe scrolling="no" frameborder="0" style="width:120px;height:240px;border:0px;" src="Callbacks/ad_callback.php?pos=512b"></iframe>';
    }
}

function loginSetup512Div()
{
    var a = gID('ImageDisplayArea');
    if(a == null || a.style.display == 'none')
    {
        return;
    }
    imageTypeTabClicked(gID('ImageTypeTab' + currentHighImgTypeTab), currentHighImgTypeTab);
    setUp512AdSpace(current512DivImage.IDImage);
    showHide512ErrorAd();
}

function setRelated512Images(response)
{
    if(!response){return;}
    var imageArray = eval('(' + response + ')');
    var area,img;
    
    for(var i=0; i<2; i++)
    {
        if(null==imageArray[1] || i>=imageArray[1].length || null==imageArray[1][i])
        {
            gID('Relationship512Msg'+i).innerHTML = 'No Related Image<br/>Found';
        }
        else
        {
            img = imageArray[1][i];
            addImageLocal(img,false);
            area = gID('Relationship512Pic'+i);
            area.style.backgroundImage = 'url('+ imageURL + '?IDImage=' + img.IDImage + '&IDTFS=4)';
            area.title = img.Name;
            area.style.cursor = 'pointer';
            area = gID('Relationship512Link'+i);
            area.href = 'index.php?IDImage='+img.IDImage;    
            area.ImageID = img.IDImage;
        }
    }
}

function displayDownloadLinks(currentImage)
{
    if(currentHighImgTypeTab == -1)
        return;
        
    var userAuthLevel = 0;
    if(curUser != null)
    {
        userAuthLevel = curUser.FullAuthValue;
    }
        
    var linkStrings = new Object();  
    var currentType = TFSs[currentHighImgTypeTab].IDType;
    var picSize = '';
        
    for(var IDTFS in currentImage.AvailableTFS)
    {
        var cTFS = TFSs[IDTFS];
        
        if(cTFS.Size < 512 || cTFS.IDType !=  currentType)
            continue;
        
        if(linkStrings[cTFS.IDFormat] == null)
            linkStrings[cTFS.IDFormat] = '';    
        
        picSize = cTFS.Size + 'x' + cTFS.Size;
        
        if(userAuthLevel >= cTFS.RequiredAuthLevel)
        {
            if(!exceededDownloadLimit(cTFS.Size))
            {
                linkStrings[cTFS.IDFormat] += '<a onclick="addDownAmt('+currentImage.AvailableTFS[IDTFS]+','+IDTFS+');" href="'+imageURL+'?IDImage='+currentImage.IDImage+'&IDTFS='+cTFS.IDTFS+'&Download=true"><u style="color:#666666;"><b>'+picSize+'</b></u></a> &nbsp;(' + Number((Number(currentImage.AvailableTFS[IDTFS])/1024.0)).toFixed(2) + 'MB)<br/>';            
            }
            else
            {
                linkStrings[cTFS.IDFormat] += '<span style="cursor:default;color:#666666;" onclick="imgUpgradeClicked();" ';
                if(browser.isOP)
                {
                    linkStrings[cTFS.IDFormat] += 'title="Exceeded Bandwidth"';
                }
                else
                {
                    linkStrings[cTFS.IDFormat] += 'onmouseover="this.innerHTML=\'Exceeded Bandwidth\';" onmouseout="this.innerHTML=\''+picSize+'\';"'
                } 
                linkStrings[cTFS.IDFormat] += '>'+picSize+'</span><br/>';
            }
        }
        else
        {
            linkStrings[cTFS.IDFormat] += '<span style="cursor:default;color:#666666;" onclick="imgUpgradeClicked();" ';
            if(browser.isOP)
            {
                linkStrings[cTFS.IDFormat] += 'title="Please Upgrade Your Account"';
            }
            else
            {
                linkStrings[cTFS.IDFormat] += 'onmouseover="this.innerHTML=\'Upgrade Account\';" onmouseout="this.innerHTML=\''+picSize+'\';"'
            } 
            linkStrings[cTFS.IDFormat] += '>'+picSize+'</span><br/>';
        }      
    }
    
    picSize = '';
    for(format in linkStrings)
    {
        picSize += '<b style="font-size:9pt;color:#333333;">'
                    +FORMATS[format].FormatName+'</b><br/>'+linkStrings[format]+'<br/>';    
    }
    
    gID('ImageDownloadHolder').innerHTML = picSize;
}

function slideAdvSearch(element)
{
    if(slideAdvSearchIntervalId != -1)
        clearInterval(slideAdvSearchIntervalId);
        
    advSearchHolder = gID('advancedSearchOptionsDiv');
        
    if(advSearchHolder.style.display == 'none')
    {
        advSearchHolder.style.display = '';
        slideAdvSearchIntervalId = setInterval('advSearchSlideOut()', 15);
        element.style.backgroundPosition = '-18px -244px';
    }
    else
    {
        slideAdvSearchIntervalId = setInterval('advSearchSlideIn()', 15);
        element.style.backgroundPosition = '0px -244px';
    } 
}

function fixSearchDivScroll()
{
    if(!browser.isFF){return;}
    gID('searchContentDiv').style.overflow='hidden';
    setTimeout("gID('searchContentDiv').style.overflow='auto';",5);
}

function advSearchSlideOut()
{
    var num = parseInt(advSearchHolder.style.height);
    if(num + slideSpeed < advSearchHolderHeight)
    {
        advSearchHolder.style.height = (num + slideSpeed) + 'px';
    }
    else
    {
        advSearchHolder.style.height = "";
        advSearchHolderHeight = parseInt(gID('advancedSearchOptionsTable').clientHeight) + 5;
        advSearchHolder.style.height = (advSearchHolderHeight) + 'px';
        clearInterval(slideAdvSearchIntervalId);
        slideAdvSearchIntervalId = -1;

        if(gID('SearchImgTypeTex').checked || gID('SearchImgTypeAll').checked)
        {
            slideIncSearch(true);
        }
        else
        {
            slideIncSearch(false);    
        }
    }
}

function advSearchSlideIn()
{
    var num = parseInt(advSearchHolder.style.height);
    if(num - slideSpeed > 0)
    {
        advSearchHolder.style.height = (num - slideSpeed) + 'px';
    }
    else
    {
        advSearchHolder.style.display = "none";
        advSearchHolder.style.height = (0) + 'px';
        clearInterval(slideAdvSearchIntervalId);
        slideAdvSearchIntervalId = -1;
        fixSearchDivScroll();
    }
}

function slideDispSearch(element)
{
    if(slideDispSearchIntervalId != -1)
        clearInterval(slideDispSearchIntervalId);
        
    dispSearchHolder = gID('displaySearchOptionsDiv');
        
    if(dispSearchHolder.style.display == 'none')
    {
        dispSearchHolder.style.display = '';
        slideDispSearchIntervalId = setInterval('dispSearchSlideOut()', 15);
        element.style.backgroundPosition = '-18px -244px';
    }
    else
    {
        slideDispSearchIntervalId = setInterval('dispSearchSlideIn()', 15);
        element.style.backgroundPosition = '0px -244px';
    } 
}

function dispSearchSlideOut()
{
    var num = parseInt(dispSearchHolder.style.height);
    if(num + slideSpeed < dispSearchHolderHeight)
    {
        dispSearchHolder.style.height = (num + slideSpeed) + 'px';
    }
    else
    {
        dispSearchHolder.style.height = "";
        dispSearchHolderHeight = parseInt(gID('displaySearchOptionsTable').clientHeight) + 5;
        dispSearchHolder.style.height = dispSearchHolderHeight + 'px';
        clearInterval(slideDispSearchIntervalId);
        slideDispSearchIntervalId = -1; 
    }
}

function dispSearchSlideIn()
{
    var num = parseInt(dispSearchHolder.style.height);
    if(num - slideSpeed > 0)
    {
        dispSearchHolder.style.height = (num - slideSpeed) + 'px';
    }
    else
    {
        dispSearchHolder.style.display = "none";
        dispSearchHolder.style.height = (0) + 'px';
        clearInterval(slideDispSearchIntervalId);
        slideDispSearchIntervalId = -1;
        fixSearchDivScroll();
    }
}

function slideIncSearch(out)
{
    if(slideAdvSearchIntervalId != -1)
        clearInterval(slideAdvSearchIntervalId);
        
    advSearchHolder = gID('advancedSearchOptionsDiv');
    incSearchHolder = gID('includeSearchOptionsDiv');
        
    if(out && incSearchHolder.style.display == 'none')
    {
        incSearchHolder.style.display = '';
        slideAdvSearchIntervalId = setInterval('incSearchSlideOut()', 15);
    }
    else if(!out && incSearchHolder.style.display == '')
    {
        slideAdvSearchIntervalId = setInterval('incSearchSlideIn()', 15);
    }
}

function incSearchSlideOut()
{
    var num1 = parseInt(incSearchHolder.style.height);
    var num2 = parseInt(advSearchHolder.style.height);
    if(num1 + slideSpeed < incSearchHolderHeight)
    {
        advSearchHolder.style.height = (num2 + slideSpeed) + 'px';
        incSearchHolder.style.height = (num1 + slideSpeed) + 'px';
    }
    else
    {
        incSearchHolder.style.height = "";
        incSearchHolderHeight = parseInt(gID('includeSearchOptionsTable').clientHeight) + 5;
        incSearchHolder.style.height = incSearchHolderHeight + 'px';
        advSearchHolder.style.height = "";
        advSearchHolderHeight = parseInt(gID('advancedSearchOptionsTable').clientHeight) + 5;
        advSearchHolder.style.height = (advSearchHolderHeight) + 'px';
        clearInterval(slideAdvSearchIntervalId);
        slideAdvSearchIntervalId = -1;   
    }
}

function incSearchSlideIn()
{
    var num1 = parseInt(incSearchHolder.style.height);
    var num2 = parseInt(advSearchHolder.style.height);
    if(num1 - slideSpeed > 0)
    {
        incSearchHolder.style.height = (num1 - slideSpeed) + 'px';
        advSearchHolder.style.height = (num2 - slideSpeed) + 'px';
    }
    else
    {
        incSearchHolder.style.display = "none";
        incSearchHolder.style.height = (0) + 'px';
        advSearchHolder.style.height = "";
        advSearchHolderHeight = parseInt(gID('advancedSearchOptionsTable').clientHeight) + 5;
        advSearchHolder.style.height = (advSearchHolderHeight) + 'px';
        clearInterval(slideAdvSearchIntervalId);
        slideAdvSearchIntervalId = -1;
        fixSearchDivScroll(); 
    }
}

function searchBoxKeyPressed(e)
{
    genericKeyPress(e, keywordSearch);
}

function searchImgTypeChkbox(el, isAll)
{
    var all = gID('SearchImgTypeAll');
    var tex = gID('SearchImgTypeTex');
    
    if(isAll && el.checked)
    {
        tex.checked = false;
        gID('SearchImgTypeObj').checked = false;
        gID('SearchImgTypeScn').checked = false;
    }
    else if(!isAll && el.checked)
    {
        all.checked = false;
    }
    
    if(tex.checked || all.checked)
    {
        slideIncSearch(true);
    }
    else
    {
        slideIncSearch(false);    
    }
}

function showHide512ErrorAd()
{
    var ads = '';
    if((curUser == null) || (curUser.FullAuthValue < 2))
    {
        ads = '<iframe scrolling="no" frameborder="0" style="width:468px;height:60px;border:0px;" src="Callbacks/ad_callback.php?pos=512bar"></iframe>'; 
    }
    var area;
    if(gID('ImageDisplayUpgrade').style.display == '')
    {
        area = gID('ImageDisplayUpgradeAd');
        area.innerHTML = ads;
    }
    if(gID('ImageDisplayEULA').style.display == '')
    {
        area = gID('ImageDisplayEULAAd');
        area.innerHTML = ads;
    }
    if(gID('ImageDisplayDownloadExceeded').style.display == '')
    {
        area = gID('ImageDisplayDownloadExceededAd');
        area.innerHTML = ads;
    }
}

function imageTypeTabClicked(tabElement, selectedTFSID)
{
    if(tabElement.tagName == 'A')
        tabElement = tabElement.childNodes[0];
        
    if(tabElement.style.cursor == 'Default'){return;}
    
    if(currentHighImgTypeTab != -1)
    {
        gID('ImageTypeTab' + currentHighImgTypeTab).className = 'unBigDiv';
    }
    
    currentHighImgTypeTab = -1;
    
    var area = gID('ImageDisplayLoading');
    var areaEula = gID('ImageDisplayEULA');
    var areaUpgrade = gID('ImageDisplayUpgrade');
    var areaExceed = gID('ImageDisplayDownloadExceeded');
    var imgArea = gID('ImageDisplayAreaTag');
    var showLinks = true;
    
    area.style.display = '';
    areaEula.style.display = 'none';
    areaUpgrade.style.display = 'none';
    areaExceed.style.display = 'none';
    imgArea.style.display = 'none';
    imgArea.innerHTML = "";
        
    var userAuth = 0;
    if(curUser != null)
    {
        userAuth = curUser.FullAuthValue;
    }
    
    if(userAuth < TFSs[selectedTFSID].RequiredAuthLevel)
    {
        area.style.display = 'none';
        areaUpgrade.style.display = '';
    } 
    else if(exceededDownloadLimit(512))
    {
        area.style.display = 'none';
        areaExceed.style.display = '';
        showLinks = false;
    }
    else if(curUser == null && agreeToEULA == -1)
    {
        area.style.display = 'none';
        areaEula.style.display = '';
    }
    else
    {
        imgArea.style.display = '';
    }
    
    showHide512ErrorAd();
    
    var curImg = current512DivImage;
    
    if(userAuth >= TFSs[selectedTFSID].RequiredAuthLevel)
    {
        if(curImg.imgEls[''+selectedTFSID] == null)
        {
            curImg.imgEls[''+selectedTFSID] = createImgEl(selectedTFSID, curImg.IDImage, "");
            addDownAmt(curImg.AvailableTFS[selectedTFSID],selectedTFSID);
        }
        addElement(curImg.imgEls[''+selectedTFSID], imgArea);      
    }
               
    tabElement.className = 'selBigDiv';
    
    currentHighImgTypeTab = selectedTFSID;
    if(showLinks)
        displayDownloadLinks(curImg);
    else
        gID('ImageDownloadHolder').innerHTML = '';
}

function addDownAmt(fSize,tfsID)
{
    fSize = Number(fSize);
    if(curUser == null)
    {
        ipAmtDown = Number(ipAmtDown) + fSize;
        gID('USMBUsedLogOut').innerHTML = Number((ipAmtDown/1024.0)).toFixed(2);
        return;    
    }
    
    if((TFSs[tfsID].DownloadsCount == 1 && TFSs[tfsID].Size != 512) || (curUser.FullAuthValue <= 1 && TFSs[tfsID].Size == 512))
    {
        curUser.TotalDownloads++;
        curUser.TotalAmountDownloaded = fSize + Number(curUser.TotalAmountDownloaded);
        curUser.MegsUsedToday = fSize + Number(curUser.MegsUsedToday);
        populateDownUserStats();    
    }  
}

function imageEULAAgree()
{
    gID('ImageDisplayEULA').style.display = 'none';
    gID('ImageDisplayLoading').style.display = '';
    gID('ImageDisplayAreaTag').style.display = '';
    agreeToEULA = 1;
    setCookie('agreeToEULA',1);
}

function imgUpgradeClicked()
{
    if(curUser != null)
        upgradeAccountClicked()
    else
        registerClicked();
}
var topErrorPanelIntervalID = -1;
var topErrorPanel = null;

function topPanelInit()
{
    fillProfilePanel();
}

function topPanelResize(inWidth, inHeight)
{
    var area;
    dragDivStartYPos = dragDivStartYPosO;
    for(var i=0; i<createdDragDivs.length; i++)
    {
        area = gID(createdDragDivs[i]);
        area.style.left = ((inWidth / 2) - (parseInt(area.style.width)/2)) + "px";
        area.style.top = dragDivStartYPos+'px';
        dragDivStartYPos += dragDivYPosMod;    
    }
    gID('TopPanelDiv').style.width = (inWidth-20) + "px";
}

function registerClicked()
{
    if(curUser!=null){return;}
	genericShowDragDiv('RegisterArea', 'Create An Account', 275, registerClicked2);
}
function registerClicked2(a){setRegisterErrorMessage("");}

function storeClicked()
{
	genericShowDragDiv('StoreInfoArea', 'Online Store', 500, null);
}

function requestClicked()
{
	genericShowDragDiv('RequestArea', 'Request a Texture', 325, requestClicked2);
}
function requestClicked2(a)
{
    setRequestErrorMsg("");
    if(curUser != null)
    {
        var email = gID('requestEmail');
        email.value = curUser.Email;
    }
}

function aboutClicked()
{
    genericShowDragDiv('AboutInfoArea', 'About Gaming Textures', 500, null);
}

function contactClicked()
{
    genericShowDragDiv('ContactInfoArea', 'Contact Us', 400, null);
}

function subInfoClicked()
{
    genericShowDragDiv('SubscriptionInfoArea', 'Subscriptions Explained', 525, null);    
}

function faqClicked()
{
    genericShowDragDiv('FAQArea', 'GamingTextures.com FAQ', 560, null);    
}

function faqLoadonPageLoad()
{
    genericShowDragDiv('FAQArea', 'GamingTextures.com FAQ', 560, function(){setTimeout('goToFAQAnswer('+loadQuesOnPageLoad+');',10);});
}

function showNoSubThankYou()
{
    var area = gID('AccountTypeArea');
    area.style.display='none';
    genericShowDragDiv2('NoSubThanksArea', 'Thank You!', 325, null, area.style.left, area.style.top);
}

function myProfileClicked()
{
    if(null==curUser){return;}
    genericShowDragDiv('ProfileArea', 'Update Profile Info', 334, myProClicked2);	
}
function myProClicked2(a)
{
    switchProfilePanel('detailProfileInfo');
    var area = gID('ProfileAreaContainer');
    area.style.height = "";
    area.style.height = (parseInt(area.clientHeight) + 10) + 'px';
}

function subThankClicked()
{
    genericShowDragDiv('PayPalSubResultArea', 'Thank You!', 300, null);
}

function purThankClicked()
{
    genericShowDragDiv('PayPalPurResultArea', 'Thank You!', 300, null);  
}

function setRegisterErrorMessage(msg)
{
    setErrorMsg(msg, 'registerErrorMessage', 'RegisterArea', true);
}

function setChangePassErrorMessage(msg)
{
    setErrorMsg(msg, 'changePassMessage', 'ProfileArea', false);
}

function setUpdateInfoErrorMessage(msg)
{
    setErrorMsg(msg, 'updateInfoMessage', 'ProfileArea', false);
}

function setAccountTypeErrorMsg(msg)
{
    setErrorMsg(msg, 'accountTypeMessage', 'AccountTypeArea', true);
}

function setRequestErrorMsg(msg)
{
    if(msg != "")
        msg += "<br/><br/>";
    setErrorMsg(msg, 'requestErrorMessage', 'RequestArea', true);
}

function setErrorMsg(msg, msgID, areaID, resize)
{
    gID(msgID).innerHTML = msg;
    if(resize)
    {
        var area = gID(areaID+'Container');
	area.style.height = "";
	area.style.height = (parseInt(area.clientHeight) + 10) + 'px';
    }
}

function adFirefoxAd(a)
{
    gID('firefoxAdSpot').innerHTML = '<iframe scrolling="no" frameborder="0" style="width:120px;height:240px;border:0px;" src="Callbacks/ad_callback.php?type=firefox"></iframe>';
}

function fillProfilePanel()
{
    if(null==curUser){return;}
    if(null==gID('ProfileArea')){return;}
    
    gID('updateHandle').innerHTML = curUser.Handle;
	gID('updateEmail').value = curUser.Email;
	gID('updateFName').value = curUser.NameFirst;
	gID('updateLName').value = curUser.NameLast;
	
	gID('profileJoinDate').innerHTML = curUser.JoinDate;
	gID('profileLastLogin').innerHTML = curUser.LastLogin;
	gID('profileSubLevel').innerHTML = curUser.SubLevelName;
	gID('profileDownLimit').innerHTML = (curUser.FullDownAmt/1024.0) + "MB";
    fillDownProfilePanel();
    
    gID('updatePassOld').value = "";
    gID('updatePass1').value = "";
    gID('updatePass2').value = "";
    
    var a = gID('SubAgrProfileLink');
    if(curUser.FullAuthValue > 1)
    {
        a.style.display = '';
    }
    else
    {
        a.style.display = 'none';
    }
}

function fillDownProfilePanel()
{
    gID('profileDownTotal').innerHTML = Number((curUser.TotalAmountDownloaded/1024.0)).toFixed(2) + "MB";
	gID('profileDownImg').innerHTML = curUser.TotalDownloads;
}

function switchProfilePanel(id)
{
    fillProfilePanel();
    
    area = gID('ProfileArea');
    var pArea = gID('profilePassChange');
    var uArea = gID('profileInfoUpdate');
    var dArea = gID('detailProfileInfo');
    var pLink = gID('profilePassChangeLink');
    var uLink = gID('profileInfoUpdateLink');
    var dLink = gID('detailInfoProfileLink');
    
    uArea.style.display = 'none';
    uLink.className = "unProTab";
    dArea.style.display = 'none';
    dLink.className = "unProTab";
    pArea.style.display = 'none'; 
    pLink.className = "unProTab";
    
    if(id == 'profilePassChange')
    {
        gID('changePassMessage').innerHTML = ""; 
        pLink.className = "selProTab";       
        pArea.style.display = '';
    }
    else if(id == 'profileInfoUpdate')
    {
        gID('updateInfoMessage').innerHTML = "";
        uLink.className = "selProTab"; 
        uArea.style.display = '';       
    }
    else
    {
        dLink.className = "selProTab";
        dArea.style.display = '';  
    }
}

function logoutClicked()
{
	var url = loginURL + "?Logout";
	var xmlObj = createXMLObject();
    if(xmlObj != null)
    {
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                logoutResponse(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
}

function logoutResponse()
{
    curUser = null;
    closeDragWindow2('ProfileArea', false);
    var area = gID('loginArea');
    area.style.display = "";
    area = gID('logoutArea');
    area.style.display = "none";
    area = gID('registerLinkArea');
    area.style.display = "";
    area = gID('profileLinkArea');
    area.style.display = "none";
    area = gID('usernameSpan');
    area.innerHTML = "";
    showHideAd(true);
    populateUserStats(); 
    explorerPanelLogin();
    loginSetup512Div();    
}

function loginClicked()
{
    var handle = gID('loginHandle');
    var pass = gID('loginPass');
	
	if(handle == null || handle.value == "")
	{
		topErrorPanelSlideOutStart("Please enter a username.");
		return;
	}
	
	if(pass == null || pass.value == "")
	{
		topErrorPanelSlideOutStart("Please enter a password.");
		return;
	}
	
	gID('usernameSpan').innerHTML = "Working...&nbsp;&nbsp;&nbsp;&nbsp;";
	handle.disabled = true;
	pass.disabled = true;

	var url = loginURL + "?handle=" + handle.value + "&pass=" + sha1Hash(sha1Hash(pass.value)+challenge);
	var xmlObj = createXMLObject();
    if(xmlObj != null)
    {
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                loginResponse(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
}

function loginKeyPressed(e)
{
    genericKeyPress(e, loginClicked);
}

function loginResponse(response)
{
    gID('usernameSpan').innerHTML = "";
    gID('loginHandle').disabled = false;
    gID('loginPass').disabled = false;
    if(response == null || response == '')
    {
        topErrorPanelSlideOutStart("Connection Error.");
        return;    
    }
    var user = eval('(' + response + ')');
    if(typeof(user) == "string")
    {
        topErrorPanelSlideOutStart(user);
        return;
    }
    
    curUser = user;
    closeDragWindow2('RegisterArea',false);
    var area = gID('loginArea');
    area.style.display = "none";
    area = gID('logoutArea');
    area.style.display = "";
    area = gID('registerLinkArea');
    area.style.display = "none";
    area = gID('profileLinkArea');
    area.style.display = "";
    area = gID('loginPass');
    area.value = "";
    area = gID('usernameSpan');
    area.innerHTML = '<a href="index.php?page=myProfile" onclick="myProfileClicked();return false;" class="topBar">'+curUser.Handle+'</a>&nbsp;&nbsp;&nbsp;&nbsp;';    
    showHideAd(true);
    populateUserStats();
    explorerPanelLogin();
    fillProfilePanel();
    loginSetup512Div();
    
}

function doAccountCreation()
{  
    //registerResponse();return;  
    var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var email = gID('registerEmail');
	var handle = gID('registerHandle');
	var firstname = gID('registerFName');
	var lastname = gID('registerLName');
	var pass1 = gID('registerPass1');
	var pass2 = gID('registerPass2');
			
	if(handle.value == "")
	{
		setRegisterErrorMessage("<font color=red>Please enter a username.</font>");
		return;
	}
	
	if(handle.value.length > 16)
	{
		setRegisterErrorMessage("<font color=red>Please enter a username with 16 characters or less.</font>");
	    return;
	}
	
	if(email.value == "")
	{
		setRegisterErrorMessage("<font color=red>Please enter an email address.</font>");
		return;
	}
	
	if(email.value.length > 255)
	{
		setRegisterErrorMessage("<font color=red>Email address must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(!emailFilter.test(email.value))
	{
		setRegisterErrorMessage("<font color=red>Please enter a valid email address.</font>");
		return;
	}
	
	if(firstname.value.length > 255)
	{
		setRegisterErrorMessage("<font color=red>First name must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(lastname.value.length > 255)
	{
		setRegisterErrorMessage("<font color=red>Last name must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(pass1.value.length < 6)
	{
		setRegisterErrorMessage("<font color=red>Password must be at least 6 characters.</font>");
		return;	
	}
	
	if(pass1.value.length > 255)
	{
		setRegisterErrorMessage("<font color=red>Password must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(pass1.value == "" || pass2.value == "" || pass1.value != pass2.value)
	{
		setRegisterErrorMessage("<font color=red>Passwords do not match, please re-enter them.</font>");
		return;
	}
	
	if(!gID('registerEULA').checked)
	{
	    setRegisterErrorMessage("<font color=red>You must accept the terms of the EULA before you can register.</font>");
		return;
	}
		
	var url = loginURL + "?email=" + email.value + "&pass=" + sha1Hash(pass1.value) + "&handle=" + handle.value 
				+ "&namefirst=" + firstname.value + "&namelast=" + lastname.value + "&Register"; 
	
	setRegisterErrorMessage("Working...");
    	
	var xmlObj = createXMLObject();
    if(xmlObj != null){
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                registerResponse(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
}

function subscriptionClick(radioButton)
{
    var area;
    area = gID('PremiumChoice');
    area.checked = false;
    area = gID('PlusChoice');
    area.checked = false;
    area = gID('StandardChoice');
    area.checked = false;
    area = gID('NoneChoice');
    area.checked = false;
    
    radioButton.checked = true;
    
    if('NoneChoice'==radioButton.id)
    {
        gID('AccountTypeAgreementRow').style.display='none';
        gID('AccountTypeSubButton').style.display='none';
        gID('AccountTypeNoSubButton').style.display='';
    }
    else
    {
        gID('AccountTypeAgreementRow').style.display='';
        gID('AccountTypeSubButton').style.display='';
        gID('AccountTypeNoSubButton').style.display='none';
    }
    setAccountTypeErrorMsg('');    
    area=gID('AccountTypeAreaContainer');
    area.style.height='';
    area.style.height=(area.clientHeight+10)+'px';
    
    changeSubscriptionHiddenForm(radioButton.id, false);
}

function changeSubscriptionHiddenForm(id, modify)
{
    var modV = 0;
    if(modify)
        modV = 2;
    gID('paypalModifyField').value = modV;
    
    var sid = gID('paypalSIDField');
    var sname = gID('paypalSNameField');
    var sprice = gID('paypalSPriceField');
    if(id == "PremiumChoice")
    {
        sid.value = "3";
        sname.value = "GamingTextures.com Premium Subscription";
        sprice.value = "7.99";
    }
    else if(id == "PlusChoice")
    {
        sid.value = "2";
        sname.value = "GamingTextures.com Plus Subscription";
        sprice.value = "4.99";
    }
    else if(id == "StandardChoice")
    {
        sid.value = "1";
        sname.value = "GamingTextures.com Standard Subscription";
        sprice.value = "1.99";
    }
    else
    {
        sid.value = "";
        sname.value = "";
        sprice.value = "";
    }
}

function accountTypeButtonClicked(from)
{
    if(gID('paypalSIDField').value == ""){return;}
    
    var msg = 'If you wish to subscribe, you must agree to the terms of the Subscription Agreement first.<br/><br/>';
    
    if(from == 'Register')
    {
        if(!gID('actTypeSubAgr').checked)
        {
            setAccountTypeErrorMsg(msg);
            return;
        }
    }
    else if(from == 'Upgrade')
    {
        if((curUser == null || curUser.FullAuthValue <= 1) && !gID('upgradeSubAgr').checked)
        {
            setErrorMsg(msg, 'UpgradeAccountMessage', 'UpgradeAccountArea', true);
            return;
        }
    }

    gID('paypalForm').submit();
}

function registerKeyPressed(e)
{
    genericKeyPress(e, doAccountCreation);
}

function registerResponse(response)
{	
	var user = eval('(' + response + ')');
	
	if(typeof(user) == "string")
    {
        setRegisterErrorMessage("<font color=red>" +  user + "</font>");  
        return;
    }
    
    gID('registerEmail').value = "";
	gID('registerHandle').value= "";
	gID('registerFName').value = "";
	gID('registerLName').value = "";
	gID('registerPass1').value = "";
	gID('registerPass2').value = "";    
        
    var area = gID('RegisterArea');
    area.style.display='none';
    genericShowDragDiv2('AccountTypeArea', 'Choose Your Account Type', 325, registerResponse2, area.style.left, area.style.top);

    gID('paypalUIDField').value = user.IDUser;
    
    loginResponse(response);
}
function registerResponse2(a){setAccountTypeErrorMsg('');}

function topErrorPanelSlideOutStart(message)
{
    var el = gID('topErrorMsg');
    el.innerHTML = message;
    topErrorPanel = gID('topErrorDiv');
    el = gID('loginHandle');
    topErrorPanel.style.top = (el.offsetTop + el.offsetHeight) + 'px';
    var num = el.offsetLeft;
    topErrorPanel.style.left = (el.offsetLeft + 302) + 'px';
    el = gID('loginPass');
    topErrorPanel.style.width = ((el.offsetLeft - num) + el.offsetWidth - 2) + 'px';
    if(topErrorPanelIntervalID != -1)
        clearInterval(topErrorPanelIntervalID);        
    topErrorPanel.style.display = "";
    topErrorPanelIntervalID = setInterval('topErrorPanelSlideOut()', 20);
}

function topErrorPanelSlideOut()
{
    var num = parseInt(topErrorPanel.style.height);
    if(num + slideSpeed < 40)
    {
        topErrorPanel.style.height = (num + slideSpeed/2) + 'px';
    }
    else
    {
        topErrorPanel.style.height = (40) + 'px';
        clearInterval(topErrorPanelIntervalID);
        topErrorPanelIntervalID = -1;
        topErrorPanelIntervalID = setTimeout('topErrorPanelSlideInStart()', 2000);
    }
}

function topErrorPanelSlideInStart()
{
    topErrorPanelIntervalID = setInterval('topErrorPanelSlideIn()', 20);
}

function topErrorPanelSlideIn()
{
    var num = parseInt(topErrorPanel.style.height);
    if(num - slideSpeed > 0)
    {
        topErrorPanel.style.height = (num - slideSpeed/2) + 'px';
    }
    else
    {
        topErrorPanel.style.display = "none";
        topErrorPanel.style.height = (0) + 'px';
        clearInterval(topErrorPanelIntervalID);
        topErrorPanelIntervalID = -1;
        gID('loginHandle').focus();
        gID('loginPass').focus();  
    }
}

function updatePassKeyPressed(e)
{
    genericKeyPress(e, updatePasswordButtonClicked);
}

function updateInfoKeyPressed(e)
{
    genericKeyPress(e, updateUserInfoButtonClicked);
}

function updatePasswordButtonClicked()
{
    var oldPass = gID('updatePassOld');
	var pass1 = gID('updatePass1');
	var pass2 = gID('updatePass2');
	
	if(oldPass.value == "")
	{
	    setChangePassErrorMessage("<font color=red>Please enter your current password.</font>");
	    return;	
	}
	
	if(pass1.value.length < 6)
	{
		setChangePassErrorMessage("<font color=red>Password must be at least 6 characters.</font>");
		return;	
	}
	
	if(pass1.value.length > 255)
	{
		setChangePassErrorMessage("<font color=red>Password must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(pass1.value == "" || pass2.value == "" || pass1.value != pass2.value)
	{
		setChangePassErrorMessage("<font color=red>Passwords do not match, please re-enter them.</font>");
		return;
	}
		
	var url = loginURL + "?handle=" + curUser.Handle + "&oldpass=" + sha1Hash(sha1Hash(oldPass.value)+challenge) + "&newpass=" + sha1Hash(pass1.value) + "&ChangePass";
				
    setChangePassErrorMessage("Working...");
    	
	var xmlObj = createXMLObject();
    if(xmlObj != null){
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                passChangeResponse(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
}

function passChangeResponse(response)
{
    var user = eval('(' + response + ')');
    
    if(typeof(user) == "string")
    {
        setChangePassErrorMessage("<font color=red>" + user + "</font>");
        return;
    }
    
    setChangePassErrorMessage("Password successfully changed.");
	
	gID('updatePassOld').value = "";
	gID('updatePass1').value = "";
	gID('updatePass2').value = "";
}

function updateUserInfoButtonClicked()
{
    var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var email = gID('updateEmail');
	var firstname = gID('updateFName');
	var lastname = gID('updateLName');
	
	if(email.value == "")
	{
		setUpdateInfoErrorMessage("<font color=red>Please enter an email address.</font>");
	    return;	
	}
	
	if(email.value.length > 255)
	{
		setUpdateInfoErrorMessage("<font color=red>Email address must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(!emailFilter.test(email.value))
	{
		setUpdateInfoErrorMessage("<font color=red>Please enter a valid email address.</font>");
		return;
	}
	
    if(firstname.value.length > 255)
	{
		setUpdateInfoErrorMessage("<font color=red>First name must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(lastname.value.length > 255)
	{
		setUpdateInfoErrorMessage("<font color=red>Last name must be fewer than 255 characters.</font>");
	    return;
	}
	
	var url = loginURL + "?email=" + email.value + "&handle=" + curUser.Handle 
				+ "&namefirst=" + firstname.value + "&namelast=" + lastname.value + "&Update";
				
    setUpdateInfoErrorMessage("Working...");
    	
	var xmlObj = createXMLObject();
    if(xmlObj != null){
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                updateInfoResponse(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
}

function updateInfoResponse(response)
{
    var user = eval('(' + response + ')');
	   
    if(typeof(user) == "string")
    {
        setUpdateInfoErrorMessage("<font color=red>" + user + "</font>");
        return;
    }
        
    setUpdateInfoErrorMessage("Successfully updated your info.");
    
    curUser.Email = user.Email;
    curUser.NameFirst = user.NameFirst;
    curUser.NameLast = user.NameLast;
        
    populateUserStats();
    fillProfilePanel();
}

function eulaClicked()
{
    genericShowDragDiv('EULAArea', 'GamingTextures.com EULA', 500, null);
}

function subAgreeClicked()
{
    genericShowDragDiv('SubAgreeArea', 'GamingTextures.com Subscription Agreement', 500, null);
}

function goToFAQAnswer(id)
{
    gID('FAQAnswers').scrollTop = 0;
    gID('FAQAnswers').scrollTop = gID('FAQQ'+id+'Answer').offsetTop;
}

function requestKeyPressed(e)
{
    genericKeyPress(e, doTextureRequest);
}

function doTextureRequest()
{
    var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var req = gID('requestTextArea');
    var email = gID('requestEmail');
    
    if(req.value == "")
    {
        setRequestErrorMsg("<font color=red>Please enter a description for your request.</font>");
        return;
    }
    
    if(email.value == "")
    {
        setRequestErrorMsg("<font color=red>Please enter an email address.</font>");
        return;
    }
    
    if(email.value.length > 255)
	{
		setRequestErrorMsg("<font color=red>Email address must be fewer than 255 characters.</font>");
	    return;
	}
	
	if(!emailFilter.test(email.value))
	{
		setRequestErrorMsg("<font color=red>Please enter a valid email address.</font>");
		return;
	}
    
    var url = requestURL + "?email=" + email.value + "&request=" + escape(req.value);
				
    setRequestErrorMsg("Working...");
    	
	var xmlObj = createXMLObject();
    if(xmlObj != null){
        xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
                requestResponse(xmlObj.responseText);
            }
        }
        xmlObj.open ('GET', url, true);
        xmlObj.send ('');
    }
}

function requestResponse(response)
{
    setRequestErrorMsg(eval('(' + response + ')'));
    gID('requestTextArea').value = "";    
}
function userStatsPanelInit()
{
    populateUserStats();
    slideArray[userStatsSlideIndex].topElement = gID('UserStatsPanelDiv');
}

function userStatsPanelResize(inWidth, inHeight)
{
    gID('UserStatsPanelDiv').style.left=(inWidth-190)+"px";
}

function upgradeAccountClicked()
{
    if(curUser==null){return;}
    if(curUser.FullAuthValue>3)
    {
        genericShowDragDiv('PremiumUpgradeArea', 'Premium Upgrade', 275, null);
        return;
    }
    
    genericShowDragDiv('UpgradeAccountArea', 'Upgrade Account', 325, upgradeAccountClicked2);
    gID('paypalUIDField').value = curUser.IDUser;
}
function upgradeAccountClicked2(a)
{
    gID('subAgrUpgradeRow').style.display = (curUser.FullAuthValue<=1)?'':'none';
    setErrorMsg('', 'UpgradeAccountMessage', 'UpgradeAccountArea', true);
    var r=gID('UpgradePremiumChoice');
    var p=gID('UpgradePlusChoice');
    var s=gID('UpgradePlusChoice');
    r.disabled=false;
    p.disabled=true;
    s.disabled=true;
    
    if(curUser.FullAuthValue<=1)
    {
        s.disabled=false;
        p.disabled=false;
        upgradeChoiceSelected(s);
    }
    else if(curUser.FullAuthValue<=2)
    {
        p.disabled=false;
        upgradeChoiceSelected(p);
    }
    else
    {
        upgradeChoiceSelected(r);
    }
}

function upgradeChoiceSelected(e)
{
    gID('UpgradePremiumChoice').checked=false;
    gID('UpgradePlusChoice').checked=false;
    gID('UpgradeStandardChoice').checked=false;
    e.checked=true;
    changeSubscriptionHiddenForm(e.value,curUser.FullAuthValue>1);
}

function populateUserStats()
{
    if(curUser == null)
    {
        gID('USMainTable').style.display = "none";
        gID('USLogOutTable').style.display = "";    
    }
    else
    {
        populateDownUserStats();
        gID('USActLev').innerHTML = curUser.SubLevelName;
        gID('USMemSince').innerHTML = curUser.JoinDateFormated;
        var area = gID('USUpLnk');
        if(curUser.FullAuthValue < 4)
            area.style.display = "";
        else
            area.style.display = "none";
        gID('USLogOutTable').style.display = "none";
        gID('USMainTable').style.display = "";
    }
}

function populateDownUserStats()
{
    gID('USMBUsed').innerHTML = Number((curUser.MegsUsedToday/1024.0)).toFixed(2);
    gID('USTotDown').innerHTML = curUser.TotalDownloads;
}
