/** Photo Album Carousel
* @author Russ Tennant
* @require 
*/
if(typeof pa_carousel_inited == 'undefined') {
var pa_carousel_inited = true;
var counter=0;


PACarousel = function(photo, caption, ol, tn_w, tn_h, ap, an){
    this.ol = ol;
    this.ie = !!(window.attachEvent && !window.opera);
    this.photo = photo;
    this.caption = caption;
    this.tnWidth = tn_w;
    this.tnHeight = tn_h;
    this.ap = ap;
    this.an = an;
    this.nextFunc = this.next.bindAsEventListener(this);
    this.prevFunc = this.prev.bindAsEventListener(this);
    try{Element.cleanWhitespace(this.ol);}catch(e){}
    this.initPA();
};
PACarousel.prototype = {
    isDisplayed: function(el) {
        if(el.style && el.style.display == "none") return false;
        if(el.parentNode) return this.isDisplayed(el.parentNode);
        return true;
    },
    initPA: function() {
        if(!this.isDisplayed(this.ol)) {
            this.ol.style.visibility = "hidden";
            window.setTimeout(this.initPA.bind(this), 1000);
            return;
        } else {
            this.ol.style.visibility = "visible";
        }
        if(this.tnHeight == 0 || this.tnWidth == 0) {
            // Recalculate
            var dim = Element.getDimensions(this.getTNs()[0]);
            this.tnHeight = dim.height;
            this.tnWidth = dim.width;
        }
        var olw = Element.getWidth(this.ol.parentNode) - Element.getWidth(this.ap)  - Element.getWidth(this.an);
        olw -= (olw % this.tnWidth);
        var vc = parseInt(olw / this.tnWidth);
        Element.setStyle(this.ol, 
            {
                height: this.tnHeight + "px",
                width: olw + "px", 
                overflow: 'hidden'
            }, 
            true);
        
        this.ap.className += " disabled";
        var i, ib, el, tns = this.getTNs();
        if(vc < tns.length) {
            this.an.onclick = this.nextStart.bindAsEventListener(this);
            this.ap.onclick = this.prevStart.bindAsEventListener(this);
        }else{
            this.an.style.visibility = "hidden";
        }
        var uif = this.updateImg.bindAsEventListener(this);
        this.updateImg(null, tns[0]);
        for(i=0,ib=tns.length;i<ib;i++){
            el = tns[i];
            el.id ="p_" + (counter++);
            Event.observe(el, "click", uif, false);
            if((i+1) > vc){el.style.display="none";}
            else el.style.display="block";
            el.style.overflow='hidden';
        } 
    },
    getTNs:function(){
       return Element.getElementsBySelector(this.ol, "li.thumbnail"); 
    },
    getChangingTNs:function(forward){
       var el, prev, next, vc, i, ib, list = this.getTNs();
       vc = parseInt(Element.getDimensions(this.ol).width / this.tnWidth);
       for(i=0,ib=list.length;i<ib;i++){
           el = list[i];
           if(el.style.display == 'none'){continue;}
           if(forward){
               prev = el;
               next = (i+vc <ib) ? list[i+vc] : null;
           }else{
               prev = (i > 0) ? list[i-1] : null;
               next = (i+vc <ib) ? list[i+vc-1] : null;
           }
           break;
       }
       return {prev:prev,next:next};
    },
    nextStart:function(){
        if(this.els){return;}
        this.ap.className=this.ap.className.replace("disabled", "");
        this.els = this.getChangingTNs(true);
        if(!(this.els.next && this.els.prev)){this.els=null;return;}
        this.els.next.style.width='0px';
        this.els.next.style.display='block';
        window.setTimeout(this.nextFunc, 10);
    },
    next:function(){
        try{
            var ps = this.els.prev.style;
            var ns = this.els.next.style;
            var cd = parseInt(ps.marginLeft?ps.marginLeft.replace('px',''):0);
            if(Math.abs(cd) >= this.tnWidth){this.nextStop();}
            else{
                //cd-=parseInt(this.tnWidth < 25 ? 1 : (this.tnWidth/25));
                var v = parseInt(Math.pow(this.tnWidth + cd, 0.5));
                cd-=v;
                ps.marginLeft=cd+'px';
                ns.width=Math.abs(cd) + 'px';
                window.setTimeout(this.nextFunc, 15);
            }
        }catch(e){this.els=null;}
    },
    nextStop:function(){
        if(this.getTNs().pop()===this.els.next){this.an.className+=" disabled";}
        this.els.prev.style.display='none';
        this.els=null;
    },
    prevStart:function(){
        if(this.els){return;}
        this.els = this.getChangingTNs(false);
        if(!(this.els.prev)){this.els=null;return;}
        this.els.prev.style.display='block';
        window.setTimeout(this.prevFunc, 10);
    },
    prev:function(){
        try{
            var ps = this.els.prev.style;
            var ns = (this.els.next ? this.els.next.style : null);
            var cd = parseInt(ps.marginLeft?ps.marginLeft.replace('px',''):-this.tnWidth);
            if(cd >= 0){;this.prevStop();}
            else{
                //cd+=parseInt(this.tnWidth < 25 ? 1 : (this.tnWidth/25));
                var v = parseInt(Math.pow(Math.abs(cd), 0.5));
                cd+=v
                ps.marginLeft=cd+'px';
                if(ns){ns.width=Math.abs(cd) + 'px'};
                window.setTimeout(this.prevFunc, 15);
            }
        }catch(e){this.els=null;}
    },
    prevStop:function(){
        this.an.className=this.an.className.replace("disabled", "");
        if(this.getTNs()[0]===this.els.prev) {this.ap.className += " disabled";}
        this.els.prev.style.marginLeft='0px';
        var ns = (this.els.next ? this.els.next.style : null);
        if(ns){ns.display='none';ns.width=this.tnWidth+'px';}
        this.els = null;
    },
    getConfig:function(tn){
       var el,config={}, codes = Element.getElementsBySelector(tn, "code");
       while( (el=codes.pop()) ){
           if(el.className  && el.firstChild){
             config[el.className]=el.firstChild.nodeValue;  
           }
       }
       return config;
    },
    clear:function(el){
        while(el.firstChild){el.removeChild(el.firstChild);}
    },
    getTN:function(el){
        var parent = el;
        while((parent && parent.nodeName.toLowerCase() != 'li')){
            parent = parent.parentNode;
        }
        return parent;
    },
    updateImg:function(evt, tn){
        var li = tn || this.getTN(Event.element(evt));
        var img, dim, config = this.getConfig(li);
        dim = config.image_dim.split(",");
        img = new Image();
        img.src = config.image_url;
        img.title = config.image_title;
        img.alt = config.image_title;
        img.width = dim[0].replace('px','');
        img.height = dim[1].replace('px','');
        img.align="middle";
        var pac = this;
        
        var ci = this.photo.getElementsByTagName("img");
        ci = (ci.length == 1 ? ci[0] : {transition:true})
        var interval = window.setInterval(function(){
            if(img.complete) {
                window.clearInterval(interval);
                pac.clear(pac.photo);
                pac.photo.appendChild(img);
                img = pac.photo.childNodes[0];
                if(pac.ie) {
                    img.style.position = "absolute";
                    img.style.top = "50%";
                    img.style.left = "50%";
                    img.style.marginTop = "-" + parseInt(parseInt(img.height)/2) + "px";
                    img.style.marginLeft = "-" + parseInt(parseInt(img.width)/2) + "px";
                }
                var els = pac.getChangingTNs();
                var test = li;
                if(li == els.next){
                    pac.nextStart();
                }else if(li.previousSibling == els.prev){
                    pac.prevStart();
                }
            }else if(!ci.transition){
                ci.transition=true;
                pac.clear(pac.photo);
                pac.photo.update('<div  style="height: ' 
                 + ci.height
                 + 'px;" class="image_loading">Loading...</div>');
            }
        },10);
        this.clear(this.caption)
        this.caption.update('<span class="caption">' + config.image_caption + '</span>');
        var i, ib, tns = this.getTNs();
        for(i = 0, ib = tns.length; i < ib; i++) {
            tns[i].className = tns[i].className.replace("selected", "");
        }
        li.className += " selected";
    }
};

pac_getBySel = function(start, sel){
    var l = Element.getElementsBySelector(start,sel);
    if(!!l && l.length == 1){return l[0];}
    else return null;
};
pac_inited = false;
pac_init = function() {
    if(pac_inited){return;}
    pac_inited=true;
    var el, list = $$("div.carousel");
    while( (el = list.pop()) ) {
        var p, c, ol, dim, tnList, ap, an;
        p = pac_getBySel(el,"div.photo");
        c = pac_getBySel(el,"div.caption");
        ol = pac_getBySel(el,"ol");
        ap = pac_getBySel(el,"span.previous");
        an = pac_getBySel(el,"span.next");
        tnList = Element.getElementsBySelector(ol, "li.thumbnail");
        if(tnList.length == 0){continue;}
        if(!(p && c && ol)){continue;}
        dim = Element.getDimensions(tnList[0]);
        new PACarousel(p, c, ol, dim.width, dim.height, ap, an);
    }
    Event.stopObserving(window, 'load'. pac_init);
};

try { // "Activate" asap.
	var ua = navigator.userAgent;
	if (document.addEventListener && (ua.match(/Firefox/) || ua.match(/SeaMonkey/))) {
		document.addEventListener("DOMContentLoaded", pac_init, false);
	} else if(document.attachEvent &&  !window.opera) {
        document.write("<script id=__pac_ocl defer " + "src='//:'><\/script>");
        document.getElementById("__pac_ocl").onreadystatechange = function() {
            if (this.readyState == "complete") {
                this.onreadystatechange = null;
                pac_init();
            }
        };
    } else { 
		pac_timer = setInterval(function() {
            var drs = document.readyState;
			if ((drs && /complete|loaded/.test(drs))
			    || pac_inited ) {
				clearInterval(pac_timer);
				delete pac_timer;
				pac_init();
			}
		}, 1);
	}
} catch(e) {}
// Fallback in case, we didn't get an onContentLoad event.
Event.observe(window, 'load', pac_init);


}
