// -----------------------------------------------------------------------------------
// 
// This page coded by Scott Upton
// http://www.uptonic.com | http://www.couloir.org
//
// This work is licensed under a Creative Commons License
// Attribution-ShareAlike 2.0
// http://creativecommons.org/licenses/by-sa/2.0/
//
// Associated APIs copyright their respective owners
//
// -----------------------------------------------------------------------------------
// --- version date: 11/28/05 --------------------------------------------------------


// get current photo id from URL
var thisURL = document.location.href;
var splitURL = thisURL.split("#");
var photoId = 0;
if (splitURL.length > 1) {
    photoId = parseInt(splitURL[1]) - 1;
}

// if no photoId supplied then set default
var photoId = (!photoId)? 0 : photoId;

// CSS border size x 2
var borderSize = 10;

var thumbHeight     = 88;
var topThumbMask    = 'http://wbond.net/images/slideshow/up_mask.png';
var bottomThumbMask = 'http://wbond.net/images/slideshow/down_mask.png';

// Number of photos in this gallery
var photoNum = photoArray.length;

var myPhoto = false;

/*--------------------------------------------------------------------------*/

// Additional methods for Element added by SU, Couloir
Object.extend(Element, {
	getWidth: function(element) {
   	element = $(element);
   	return element.offsetWidth; 
	},
    getTop: function(element) {
       element = $(element);
       return element.style.top.replace(/px/, '');
    },
	setTop: function(element,t) {
        element = $(element);
        element.style.top = t +"px";
    },
    setWidth: function(element,w) {
   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   	element = $(element);
    	element.style.height = h +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	},
    addThumbnail: function(element,id,src) {
        element = $(element);
        var a   = document.createElement('a');
        a.setAttribute('href', '#' + (parseInt(id)+1));
        a.selfPhotoId = id + 1;
        a.onclick = function() {
            myPhoto.moveTo(this.selfPhotoId);   
        }
        var img = document.createElement('img');
        img.src = src;
        a.appendChild(img);
        element.appendChild(a);    
    },
    findLeftEdge: function(element) {
        object = $(element);
        var top = 0;
        if (object.offsetParent) {
            while (object.offsetParent) {
                top += object.offsetTop
                object = object.offsetParent;
            }
        } else if (object.y) {
            top += object.y;
        }
        return top;
    },
    findMouseY: function(e) {
        if (document.layers) {
            return e.pageY;
        } else if (document.all) {
            return window.event.y+document.body.scrollTop;
        } else if (document.getElementById) {
            return e.pageY;
        }    
    }
});

/*--------------------------------------------------------------------------*/

var Slideshow = Class.create();

var myPhoto = false;

Slideshow.prototype = {
	initialize: function(photoId) {
		this.photoId          = photoId;
		this.photo            = 'slideshow_photo';
		this.photoBox         = 'slideshow_container';
		this.prevLink         = 'slideshow_prev_link';
		this.nextLink         = 'slideshow_next_link';
		this.captionBox       = 'slideshow_caption_container';
		this.caption          = 'slideshow_caption';
		this.counter          = 'slideshow_counter';
		this.loader           = 'slideshow_loading';
        this.thumbSlider      = 'slideshow_thumb_slider';
        this.thumbSliderInner = 'slideshow_thumb_slider_inner';
        this.bottomThumbMask  = 'slideshow_bottom_thumb_mask',
        this.topThumbMask     = 'slideshow_top_thumb_mask',
        this.sectionSize      = 248;
        this.maxSpeed         = 8;
        this.thumbnailHeight  = 0;
        this.allowSlide       = true;
        
        this.rate             = 0;
        this.pe               = false;
	},
    changeSliderRate: function(e) {
        mouseY = Event.pointerY(e);
        if (mouseY < myPhoto.stopTop) {
            myPhoto.rate = Math.floor((((100/(myPhoto.stopTop-myPhoto.topEdge)) * ((myPhoto.stopTop - mouseY)))/100) * myPhoto.maxSpeed);   
        } else if (mouseY >= myPhoto.stopTop && mouseY <= myPhoto.stopBottom) {
            myPhoto.rate = 0;    
        } else if (mouseY > myPhoto.stopBottom) {           
            myPhoto.rate = 0 - Math.floor((((100/(myPhoto.bottomEdge-myPhoto.stopBottom)) * (mouseY - myPhoto.stopBottom))/100) * myPhoto.maxSpeed);    
        }
    },
    startSlider: function() {
        Event.observe(this.thumbSlider, 'mousemove', myPhoto.changeSliderRate, false);
        this.pe = new PeriodicalExecuter(myPhoto.moveSlider, 0.01);
    },
    stopSlider: function() {
        if (this.pe) {
            this.pe.stop();
        }
    },
    moveSlider: function() {
        if (myPhoto.allowSlide) {
            var curTop = parseInt(Element.getTop(myPhoto.thumbSliderInner));
            if (myPhoto.rate < 0 && curTop != myPhoto.rangeMin) {
                if ((curTop + myPhoto.rate) < myPhoto.rangeMin) {
                    Element.setTop(myPhoto.thumbSliderInner, myPhoto.rangeMin);    
                } else {
                    Element.setTop(myPhoto.thumbSliderInner, curTop + myPhoto.rate);
                }
            } else if (myPhoto.rate > 0 && curTop != myPhoto.rangeMax) {
                if (curTop + myPhoto.rate > myPhoto.rangeMax) {
                    Element.setTop(myPhoto.thumbSliderInner, myPhoto.rangeMax);    
                } else {
                    Element.setTop(myPhoto.thumbSliderInner, curTop + myPhoto.rate);
                }
            }
        }
    },
    populateThumbnails: function() {
        for (i=0; i<photoArray.length; i++) {
            Element.addThumbnail(this.thumbSliderInner, i, photoDir + photoArray[i][1]);   
        }
        
        var offsets     = new Position.cumulativeOffset(this.thumbSlider);
        this.topEdge    = Element.findLeftEdge(this.thumbSlider);
        this.bottomEdge = this.topEdge + Element.getHeight(this.thumbSlider);
        
        this.stopTop    = Math.floor(this.topEdge + ((Element.getHeight(this.thumbSlider) - this.sectionSize)/2));
        this.stopBottom = this.stopTop + this.sectionSize;  
        
        this.thumbnailHeight = thumbHeight;
        this.rangeMax   = Math.floor((Element.getHeight(this.thumbSlider)/2)-(this.thumbnailHeight/2));
        this.rangeMin   = 0 - ((this.thumbnailHeight*photoNum) - this.rangeMax - this.thumbnailHeight);                                
        
        var ob1 = $(this.topThumbMask);
        var ob2 = $(this.bottomThumbMask);
        
        // Fix IE6 Opacity 
        if (!window.XMLHttpRequest && window.ActiveXObject &&  parseInt(parseFloat(navigator.appVersion.toLowerCase())) == 4) {
            ob1.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + topThumbMask + "', sizingMethod='scale')";
            ob2.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + bottomThumbMask + "', sizingMethod='scale')";
        } else {
            ob1.style.backgroundImage = 'url(' + topThumbMask + ')';
            ob2.style.backgroundImage = 'url(' + bottomThumbMask + ')';
        }
        
        Element.setTop(this.thumbSliderInner, this.rangeMax);
        Element.show(this.thumbSlider);
    },
	getCurrentSize: function() {
		// Get current height and width, subtracting CSS border size
		this.wCur = Element.getWidth(this.photoBox) - borderSize;
		this.hCur = Element.getHeight(this.photoBox) - borderSize;
	},
	getNewSize: function() {
		// Get current height and width
		this.wNew = photoArray[photoId][2]; 
		this.hNew = photoArray[photoId][3];
	},
	getScaleFactor: function() {
		this.getCurrentSize();
		this.getNewSize();
		// Scalars based on change from old to new
		this.xScale = (this.wNew / this.wCur) * 100;
		this.yScale = (this.hNew / this.hCur) * 100;
	},
	setNewPhotoParams: function() {
        // Set source of new image
		Element.setSrc(this.photo,photoDir + photoArray[photoId][0]);
		// Set anchor for bookmarking
		Element.setHref(this.prevLink, "#" + (photoId+1));
		Element.setHref(this.nextLink, "#" + (photoId+1));
        Element.setWidth(this.photo, photoArray[photoId][2]);
        Element.setHeight(this.photo, photoArray[photoId][3]);
	},
	setPhotoCaption: function() {
		// Add caption from gallery array
		Element.setInnerHTML(this.caption,photoArray[photoId][4]);
		Element.setInnerHTML(this.counter,((photoId+1)+'/'+photoNum));
	},
	resizePhotoBox: function() {
		this.getScaleFactor();
		new Effect.Scale(this.photoBox, this.yScale, {scaleX: false, duration: 0.3, queue: 'front'});
		new Effect.Scale(this.photoBox, this.xScale, {scaleY: false, delay: 0.5, duration: 0.3});
		// Dynamically resize caption box as well
		Element.setWidth(this.captionBox,this.wNew-(-borderSize));
	},
	showPhoto: function(){
		new Effect.Fade(this.loader, {delay: 0.5, duration: 0.3});
		// Workaround for problems calling object method "afterFinish"
		new Effect.Appear(this.photo, {duration: 0.5, queue: 'end', afterFinish: function(){Element.show('slideshow_caption_container');Element.show('slideshow_prev_link');Element.show('slideshow_next_link');}});
	},
	nextPhoto: function(){
		// Figure out which photo is next
		(photoId == (photoArray.length - 1)) ? photoId = 0 : photoId++;
		this.updateSlider();
        this.initSwap();
	},
	prevPhoto: function(){
		// Figure out which photo is previous
		(photoId == 0) ? photoId = photoArray.length - 1 : photoId--;
		this.updateSlider();
        this.initSwap();
	},
    moveTo: function(newId){
        photoId = parseInt(newId)-1;
        this.updateSlider();
        this.initSwap();    
    },
    updateSlider: function(newId){
        this.rate = 0;
        var curTop = parseInt(Element.getTop(this.thumbSliderInner));
        var newTop = this.rangeMax - (photoId * this.thumbnailHeight);
        var moveTop = newTop - curTop;
        this.allowSlide = false;
        new Effect.MoveBy(this.thumbSliderInner, moveTop, 0, {duration: 0.5, fps: 40, transition: Effect.Transitions.linear});
        setTimeout('myPhoto.allowSlide = true;', 1000);
    },
	initSwap: function() {
		// Begin by hiding main elements
		Element.show(this.loader);
		Element.hide(this.photo);
		Element.hide(this.captionBox);
		Element.hide(this.prevLink);
		Element.hide(this.nextLink);
		// Set new dimensions and source, then resize
		this.setNewPhotoParams();
		this.resizePhotoBox();
		this.setPhotoCaption();
	}
}

/*--------------------------------------------------------------------------*/

// Establish CSS-driven events via Behaviour script
var myrules = {
	'#slideshow_photo' : function(element){
		element.onload = function(){
			myPhoto.showPhoto();
		}
	},
	'#slideshow_prev_link' : function(element){
		element.onclick = function(){
			myPhoto.prevPhoto();
		}
	},
	'#slideshow_next_link' : function(element){
		element.onclick = function(){
			myPhoto.nextPhoto();
		}
	},
    '#slideshow_thumb_slider' : function (element){
        element.onmouseover = function(){
            myPhoto.startSlider();
        }
        element.onmouseout = function(){
            myPhoto.stopSlider();
        }
    },
	a : function(element){
		element.onfocus = function(){
			this.blur();
		}
	}
};

// Add window.onload event to initialize
Behaviour.addLoadEvent(init);
Behaviour.apply();
function init() {
	myPhoto = new Slideshow(photoId);
	myPhoto.populateThumbnails();
    myPhoto.initSwap();
}
