var SHIT = 0;
if (window.ActiveXObject){
  SHIT = 1;
}


function cE(name){
    return document.createElement(name);
}
function gE(name){
    return document.getElementById(name);
}
function cT(val){
    return document.createTextNode(val);
}
function cEC(tag,cn,ob){
    var el = cE(tag);
    el.className = cn;
    if (ob) for (var k in ob) el.setAttribute(k,ob[k]);
    return el;
}

function FC(){
    var b = gE("body");
    //this.l = cE("div");
    //b.appendChild(this.l);
    this.log = function(a,b,c,d){
        //var txt = cE("p");
        //txt.textContent = a + b + c + d;
        //this.l.appendChild(txt);
    };
}

if (window.console == null){
    window.console = new FC();
}

var docEl = document.documentElement,IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;
docEl = null;
function isDocumentElementHeightOff(){
    var d = document,div = d.createElement('div');
    div.style.height = "2500px";
    d.body.insertBefore(div, d.body.firstChild);
    var r = d.documentElement.clientHeight > 2400;
    d.body.removeChild(div);
    return r;   }
    // Safari 2 uses document.clientWidth (default). 
function getHeight(){
    if(typeof document.clientWidth == "number")
    {      // use document.clientHeight/Width.
    return document.clientHeight;   }
    else if(IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
    // use document.body.clientHeight/Width.       
    return document.body.clientHeight;   } else {       
    // use document.documentElement.clientHeight/Width.
    return document.documentElement.clientHeight;   } 
}

function mouseCoords(ev){
    //alert(window.event == ev);
    if (window.event){
        ev = window.event;
        return [
        ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        ev.clientY + document.body.scrollTop  - document.body.clientTop
        ];
    }
    var res = (ev.pageX || ev.pageY) ? [ev.pageX,ev.pageY] : [
        ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        ev.clientY + document.body.scrollTop  - document.body.clientTop
        ];
    //document.getElementById("coords").textContent = String(res);
    return res;
}

function associateObjWithEvent(obj, methodName){
    return (function(e){
        e = e||window.event;
        return obj[methodName](e, this);
    });
}

function bind(ob,func,args){
    return function(ev){
        //console.log(ob,func,args,ev);
        ob[func](args,ev);
        return false;
    }
}

function clear(el){while(el.childNodes.length){el.removeChild(el.firstChild);}}


function replace(old,neu){
    old.parentNode.replaceChild(neu,old);
}

function picurl(){
    this.pre = "base/fs/";
    this.sidx = -1;
    this.setPGS = function()
    {
        if (getHeight() < 760) {
            this.pxPGS =  this.px400;
            gE("content_mid").style.height = "400px";
            this.sidx = 2;
        }else{
            this.pxPGS = this.px530;
            gE("content_mid").style.height = "530px"
            this.sidx = 3;
        }
    }
    this.getIDX = function(){
        return this.sidx;
    }
    this.px30 = function(pic){
        return this.pre+"30px/"+pic.id.toString()+"." + pic.tpe;
    }
    this.px530 = function(pic){
        return this.pre+"530px/"+pic.id.toString()+"." + pic.tpe;
    }
    this.pxPGS = function(pic){
        //return this.pre + "530px/" + pic.id.toString() + "." + pic.tpe;
    }
    this.px400 = function(pic){
        return this.pre+"400px/"+pic.id.toString()+"." + pic.tpe;
    }
    this.px200 = function(pic){
        return this.pre+"200px/"+pic.id.toString()+"." + pic.tpe;
    }
    this.original = function(pic){
        return this.pre+"original/"+pic.id.toString()+"." + pic.tpe;
    }
}
var URL = new picurl();
/*
cats = [{name:"Landscape",cats:[{name:"uk0",pics:['0x0', '0x1', '0x2', '0x3', '0x4']},
                    {name:"uk1",pics:['0x5', '0x6', '0x7', '0x8', '0x9']},
                    {name:"uk2",pics:['0xa', '0xb', '0xc', '0xd', '0xe']}]},
        {name:"People",cats:[
                {name:"uk3",pics:['0xf', '0x10', '0x11', '0x12', '0x13','0x14', '0x15', '0x16', '0x17', '0x18']},
//                 {name:"uk4",pics:['0x14', '0x15', '0x16', '0x17', '0x18']},
                {name:"uk5",pics:['0x19', '0x1a', '0x1b', '0x1c', '0x1d']}]},
        {name:"Works",cats:[{name:"uk6",pics:['0x1e', '0x1f', '0x20', '0x21', '0x22']},
                {name:"uk7",pics:['0x23', '0x24', '0x25', '0x26', '0x27']},
                {name:"uk8",pics:['0x28', '0x29', '0x2a', '0x2b', '0x2c']}]}
        ];*/

//cats = [{"cats":[],"name":"asd"},{"cats":[{"name":"please give me a desc","pics":[45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]}],"name":"people"},{"cats":[{"name":"please give me a desc","pics":[62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79]}],"name":"landscape"},{"cats":[{"name":"please give me a desc","pics":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]}],"name":"people"},{"cats":[{"name":"please give me a desc","pics":[23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]}],"name":"landscape"}];

function getWidth(theElt){
        if(SHIT){
                tmphght = theElt.offsetWidth;
        }
        else{
                docObj = theElt;
                var tmphght1 = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("width");
                tmphght = tmphght1.split('px');
                tmphght = tmphght[0];
        }
        return tmphght;
}

var STS = null;

function indexOf(arr,ob){
    for(var idx in arr){
        if (arr[idx] == ob)
            return idx;
    }
    return -1;
}

function states(){
    STS = this;
    this.first = true;
    this.init = function(cats){
        URL.setPGS();
        this.rarrow = cE("img");
        this.rarrow.src = "img/arrow.png";
        this.rarrow.style.display = "none";
        this.rarrow.style.position = "fixed";
        this.larrow = cE("img");
        this.larrow.src = "img/larrow.png";
        this.larrow.style.display = "none";
        this.larrow.style.position = "fixed";
        
        this.larrow.onmousemove = bind(this,"onmove");
        this.rarrow.onmousemove = bind(this,"onmove");
        this.rarrow.onmouseout = bind(this,"onmove");
        this.larrow.onmouseout = bind(this,"onmove");
        this.larrow.onclick = bind(s,"norp");
        this.rarrow.onclick = bind(s,"norp");
        
        gE("body").appendChild(this.larrow);
        gE("body").appendChild(this.rarrow);
        this.cats = cats;
        this.mn = cats.length;
        
        this.sn = [];
        for (var idx in cats){
            this.sn.push(cats[idx].cats.length);
        }
        //cats.map(function(x){return x.cats.length;});
        this.mcats = [];
        this.scats = [];
        this.thumbs = [];
        this.mcl   = [];
        this.act = [0,0,0];
//         var ths = gE("thumbs");
//         this.thumbs = [];
//         for (var tri in ths.childNodes){
//             var tr = ths.childNodes[tri];
//             if (tr.tagName == "TR"){
//                 for (var tdi in tr.childNodes){
//                     var td = tr.childNodes[tdi];
//                     if (td.tagName == "TD"){
//                         this.thumbs.push(td);
//                     }
//                 }
//             }
//         }
        var mc = this.mc = gE("cats");
        
        for (var tri in mc.childNodes){
            var tr = mc.childNodes[tri];
            
            if (tr.tagName == "TR"){
                //console.log(tr);
                var lst = [];
                for (var tdi in tr.childNodes){
                    var td = tr.childNodes[tdi];
                    if (td.tagName == "TD"){
                        lst.push(td);
                    }
                }
                //alert(lst.length);
                this.mcats.push(lst[0]);
                var scats = lst.splice(1,lst.length - 1);
                //alert(scats.length);
                this.scats.push(scats);
            }
        }
        
        console.log(this.mcats);
        console.log(this.scats);
        for (var mci in this.mcats){
            mci = Number(mci);
            var mc = this.mcats[mci];
            console.log(mci,"<<");
            if (cats[mci]){
                mc.textContent = cats[mci].name;
                if(SHIT)
                    mc.innerText = cats[mci].name;
                //alert(cats[mci].name);
                //alert(mc.textContent);
                console.log(mc,mci,"<<");
                mc.className   = "exs";
                mc.onclick     = bind(this,"showPIC",[mci,0,0]);
                console.log(mc,mci,"<<");
                for (var sci in cats[mci].cats){
                    var scat = cats[mci].cats[sci];
                    var sc = this.scats[mci][sci];
                    sc.setAttribute("title",title = scat.name);
                    sc.className = "exs";
                    sc.onclick = bind(this,"showPIC",[mci,sci,0]);
                }
            }
        }
    }
    
    this.initShow = function (){
        
        var desc = [0,0,0];
        if (location.hash){
        var lst = location.hash.substr(1).split('/');
        console.log(lst);
        var cat = lst[0];
        
        for (var i in cats){
            if (cats[i].name == cat){
                desc[0] = i;
            }}
            try {
                var p1 = parseInt(lst[1]);
                var p2 = parseInt(lst[2]);
                desc[1] =  isNaN(p1) ? 0 : (p1-1 > -1) ? (p1-1) : 0;
                desc[2] =  isNaN(p2) ? 0 : (p2-1 > -1) ? (p2-1) : 0;;
            }catch(e){console.log(e);}
            console.log("desc is ",desc);
        }
        
        this.allPics();
        this.act = desc; // IMPORTANT !!!!
        this.showPIC(desc);
        
        //gE("allpics").onmouseover = bind(this,"follow");
        //gE("allpics").onmouseout = bind(this,"unfollow");
        //gE("allpics").onmousemove = bind(this,"onmove");
    }
    
    this.unfollow = function(){
        
        //console.log("UNFOLLOW");
        
        //var c = mouseCoords(ev);
        //if (Math.abs(this.ox-c[0]) > 5 || Math.abs(this.oy-c[1]) > 5){
        //if (this.arrow && this.arrow.style)
        //this.arrow.style.display = "none";
        //}
    }
    
    this.follow = function(args,ev){
        var c = mouseCoords(ev);
        if (c[0] < W()/2){
          this.larrow.style.display = "";
        }else{
          this.rarrow.style.display = "";
        }
        //console.log(c);
        //this.arrow.style.left = c[0];
        //this.arrow.style.top  = c[1];
    }
    
    this.ox = 0;
    this.oy = 0;
    
    this.onmove = function(args,ev){
            var c = mouseCoords(ev);
        
        
        //if (Math.abs(this.ox-c[0]) > 1 || Math.abs(this.oy-c[1]) > 1){
            
            //var cx = parseInt();
            //var cy = c[1];
            var cnt = gE("content_mid");
            if (c[1] > cnt.offsetTop && c[1] < (cnt.offsetTop + cnt.offsetHeight)){
            
            var hsc = (!SHIT) ? (pageXOffset) : document.documentElement.scrollLeft;
            var vsc = (!SHIT) ? (pageYOffset) : document.documentElement.scrollTop;
            
            if (c[0] < W()/2){
            
            
                this.rarrow.style.display = "none";
                this.larrow.style.display = "";
                this.larrow.style.position = "fixed";
                
            
            
            //this.larrow.style.left = (c[0] - 45 - hsc) + "px";
            this.larrow.style.left = (c[0] - 36 - hsc) + "px";
            //this.larrow.style.top  = (c[1] - 20 - vsc) + "px";
            this.larrow.style.top  = (c[1] - 78 - vsc) + "px";
            this.arrow = this.larrow;
            this.ox = c[0];
            this.oy = c[1];   
           }else{
            
                this.larrow.style.display = "none";
                this.rarrow.style.display = "";
                this.rarrow.style.position = "fixed";
            
            
            this.rarrow.style.left = (c[0] - 36  - hsc)  + "px";
            this.rarrow.style.top  = (c[1] - 78  - vsc) + "px";
            
            this.arrow = this.rarrow;
            this.arrow.style.zIndex = 100000;
            this.ox = c[0];
            this.oy = c[1];
           }
        }else(this.arrow.style.display = "none");
    }
    
    this.showMC = function(desc){
        var mci = desc[0];
        this.mcats[this.act[0]].className = "exs";
        this.mcats[mci].className = "act";
        
        this.act = desc;
    }
    
    this.showSC = function(desc){
        var mci = desc[0];
        var sci = desc[1];
        this.scats[this.act[0]][this.act[1]].className = "exs";
        this.scats[mci][sci].className = "act";
        
        this.showMC(desc);
        console.log("mci,sci",mci,sci);
        gE("sctxt").textContent = this.cats[mci].cats[sci].name;
        if(SHIT) gE("sctxt").innerText = this.cats[mci].cats[sci].name;
        gE("sctxt").title = this.cats[mci].cats[sci].name;
    }
    
    this.showPIC = function(desc){
        var d = this.act;
        try{this.thumbs[d[2]].className = "";}catch(e){}
        
        
        
        //alert(desc);
        //alert(desc[1]);
        //alert(desc[2]);
        var pic = desc[2];
        var sci = desc[1];
        var mci = desc[0];
        try{
        //if (pic + sci + mci == 0)
        //    location.hash = "";
        if (sci + pic == 0)
            location.hash = "#" + cats[mci].name;
        else if (pic == 0)
            location.hash = "#" + cats[mci].name + "/" + (Number(sci) + 1);
        else
            location.hash = "#" + [cats[mci].name,Number(sci)+1,Number(pic)+1].join("/");
        }catch(e){}
        var jump = false;
        if (mci != d[0] || sci != d[1] || this.first ){
            this.first = false;
            var ap = gE("allpics");
            console.log(mci,sci,this.picdivs);
            replace(ap,this.picdivs[mci][sci]);
            //this.picdivs[mci][sci].id = "allpics";
            console.log("pleaseload",this.scload[mci][sci]);
            if (this.scload[mci][sci] == 0){
                console.log("pleaseload");
                this.loadsc(mci,sci);
                jump = true;
            }
        }
        this.showSC(desc);
        this.showThumbs(desc);
        this.thumbs[desc[2]].className = "actth";
        
        /// don't change the order of these and the above. gE("allpics") could be different //
        
        div = gE("allpics");
        var a = desc;
        var pc = this.pictree[a[0]][a[1]][a[2]];
        console.log(a," <- show desc ");
        //var idx = this.allpics.indexOf(pc);
        //console.log( this.mcpics , this.mcpics[a[0]] );
        var idx = a[2]; //indexOf(this.scpics[a[0]][a[1]],pc);// .indexOf(pc);
        
        console.log(idx," <- show idx ");
        var img = div.childNodes[idx];
        
        var offset = img.offsetLeft;
        console.log(offset," <- show offset ");
        var w = getWidth(img);
        var npos = (new String(((W()/2)-(w/2))-offset)) + "px";
        
        gE("lupe").setAttribute("href",URL.original(pc));
        gE("dwld").setAttribute("href","download.php?pic="+String(pc.id)+"."+pc.tpe);
        if (jump){gE("allpics").style.left = npos;}
        else {
            $("#allpics").animate( { left:npos }, { queue:true, duration:45 } );
        }
    }
    
    this.showThumbs = function(desc){
        
        var mci = desc[0];
        var sci = desc[1];
        var lst = []
        for (var thi in this.cats[mci].cats[sci].pics){
            var th = this.cats[mci].cats[sci].pics[thi];
            //var thumb = this.thumbs[thi];
            var img = cE("img");
            img.src = URL.px30(th);
            //'/pics/'+th+'.png';
            lst.push(img);
            //thumb.appendChild(img);
            img.onclick = bind(this,"showPIC",[mci,sci,thi]);
            img.className = "thumb";
        }
        var first = lst.splice(0,Math.ceil(lst.length / 2.) );
        var ul1 = gE("ul1");
        var ul2 = gE("ul2");
        
        this.clearThumbs();
        this.thumbs = [];
        for (var img in first){
            var li = cE("li");
            li.appendChild(first[img]);
            ul1.appendChild(li);
            this.thumbs.push(li);
        }
        for (var img in lst){
            var li = cE("li");
            li.appendChild(lst[img]);
            ul2.appendChild(li);
            this.thumbs.push(li);
        }
    }
    
    this.allPics = function(){
        var allpics = this.allpics = [];
        var scpics  = this.scpics  = [];
        var pictree = this.pictree = [];
        var alldescs = this.alldescs = [];
        for (var mc in this.cats){
            mc = Number(mc);
            pictree.push([]);
            scpics.push([]);
            for (var sc in this.cats[mc].cats){
                sc = Number(sc);
                pictree[mc].push([]);
                scpics[mc].push([]);
                for (var pic in this.cats[mc].cats[sc].pics){
                    pic = Number(pic);
                    var pc = this.cats[mc].cats[sc].pics[pic];
                    pictree[mc][sc].push(pc);
                    allpics.push(pc);
                    scpics[mc][sc].push(pc);
                    alldescs.push([mc,sc,pic]);
                }
            }
        }
        
        //try{
        this.placeholders();
        //}catch(e){console.log(e);}
        return allpics;
    }
    
    //this.csize = 0;
    
    this.placeholders = function(){
        this.picdivs = [];
        this.scload  = [];
        for (var mc in this.scpics){
            var scs = this.scpics[mc];
            this.scload.push([]);
            this.picdivs.push([]);
            for (var sc in scs){
                var pics = scs[sc];
                var cdiv = cEC("div","cntdiv",{id:"allpics"});
                cdiv.onmouseover = bind(this,"onmove");
                cdiv.onmouseout = bind(this,"onmove");
                cdiv.onmousemove = bind(this,"onmove");
                var cdw = 500;
                for (var pic in pics){
                    var div = cEC("div","picdiv");
                    var wd = pics[pic].size[URL.getIDX()] + 6;
                    div.style.width = ( wd ) +"px";
                    cdw += wd;
                    var pp = new progressp(pic,pics[pic]);
                    div.appendChild(pp.p);
                    cdiv.style.width = cdw + "px";
                    cdiv.appendChild(div);
                }
                this.picdivs[mc].push(cdiv);
                this.scload[mc].push(0);
            }
        }
        gE("content_mid").appendChild(this.picdivs[0][0]);
        
        //this.loadmc(0);
        //replace(gE("a"));
    }
    
    this.loadsc = function(mci,sci){
        this.scload[mci][sci] = 1;
        for (var p in this.scpics[mci][sci]){
            console.log("loading");
            this.scpics[mci][sci][p].pp.start();
        }
    }
    
    this.norp = function(args,ev){
        var c = mouseCoords(ev);
        if (c[0] < W()/2){this.prevPic();}else{this.nextPic();}
    }
    
    this.nextPic = function(){
        var a = this.act;
        var pic = this.pictree[a[0]][a[1]][a[2]];
        //var idx = indexOf(this.allPics,pic);
        var idx = SHIT ? indexOf(this.allpics,pic) : this.allpics.indexOf(pic);
        idx = Number(idx); 
        if (idx > -1 && (idx+1) < this.allpics.length ){
            //alert(idx + 1);
            var next = this.alldescs[idx+1];
            //alert(next);
            this.showPIC(next);
        }
        else{
            console.log("nextPic failed");
        }
    }
    this.prevPic = function(){
        var a = this.act;
        var pic = this.pictree[a[0]][a[1]][a[2]];
        var idx = SHIT ? indexOf(this.allpics,pic) : this.allpics.indexOf(pic); // (!SHIT)
        //var idx = indexOf(this.allPics,pic);
        if (idx > -1 && (idx-1) > -1){
            var next = this.alldescs[idx-1];
            this.showPIC(next);
        }
        else{
            console.log("prevPic failed");
        }
    }
    
    this.clearThumbs = function(){
        clear(gE("ul1"));
        clear(gE("ul2"));
    }
    
    this.unset = function(pic){
        
    }
    
    this.setact = function(pic){
        if (this.act){
            this.unset(this.act)
        }
    }
    
}

var IE6SetInterval = [];

function next(tid){
    //alert(tid);
    IE6SetInterval[tid].next();
}

function progressp(idx,pic){
    this.tid = IE6SetInterval.length;
    IE6SetInterval.push(this);
    this.idx = idx;
    this.pic = pic;
    pic.pp   = this;
    this.n = 3;
    this.cnt = 0;
    this.p = cEC("div","progress");
    for (var i=0;i<this.n;++i){
        var s = cE("span","prpoint");
        s.textContent = "◌"; //codepoint 9676
        this.p.appendChild(s);
    }
    this.start = function(){
        this.state = 0;
        if (!SHIT)
            {this.iv = window.setInterval(bind(this,"next"),250);}
        else
            {this.iv = window.setInterval('next('+this.tid+')',250);}
            
        this.next();
    }
    this.next = function(){
        if (this.cnt == this.idx){
            this.img = cEC("img","");
            
            this.img.onload = bind(this,"done");
            this.img.src = URL.pxPGS(this.pic);
            //if(SHIT)this.img.addEvent("domready", bind(this,"done"));
        }
        this.cnt++;
        this.p.childNodes[this.state].className = "prpoint";
        this.state = (this.state + 1) % this.n;
        this.p.childNodes[this.state].className = "pract";
    }
    
    this.done = function(){
        this.stop();
        replace(this.p,this.img);
    }
    this.stop = function(){
        window.clearInterval(this.iv);
    }
}


function cImg(url){
    var img = cE("img");
    img.src = url;
    img.className = "flimg";
    return img;
}

function W(){return  document.body.clientWidth;}
function H(){return  document.body.clientHeight;}

CUR = [0,1]

function cRest(){
    var f = CUR[0];
    var t = CUR[1];
    var now = allpics.slice(f,t);
    div = gE("allpics");
    for (var pic in now){
        var url = ['pics/',now[pic],'.png'].join("");
        var url = URL.px530(now[pic]);
        div.appendChild(cImg(url));
    }
    CUR = [f+1,t+1];
    if (t < allpics.length){
        setTimeout(cRest,100);
    }
}




function cImgs(){
    s = new states();
    s.init(cats);
    s.initShow();
    
    
    //allpics = s.allPics();
    
    //var div = cE("div");
    //div.style.width = (800*allpics.length) + "px";
    //div.style.position = "relative";
    //div.style.left = (W()/2 - 400) + "px";
    //div.id = "allpics";
    //gE("content_mid").appendChild(div);
    
    //var now = allpics.slice(CUR[0],CUR[1]);
    //var f = CUR[0];
    //var t = CUR[1];
    //CUR = [t,t+1];
    //for (var pic in now){
        //var url = ['pics/',now[pic],'.png'].join("");
        
        //div.appendChild(cImg(URL.px530(now[pic])));
    //}
    
    
    //setTimeout(bind(s,"initShow"),30);
    
    $("#content_mid").mouseover(
        
    )
    gE("content_mid").onclick = bind(s,"norp");
    //$("#content_mid").click(function(){
    //    
    //  s.nextPic();
    //  //$("#allpics").animate( { left:"-=800" }, { queue:true, duration:700 } )
    //});
    //setTimeout(cRest,200);
}

window.onload = cImgs;

