window.addEvent('domready', function(){
    //create gallery
    if(typeof photos != "undefined" && photos != null)
    {
    	var gallery = new PhotoGallery(photos,0,'photo','caption','prevToggle','nextToggle');
    	gallery.setCaption();
    }
});
	

function Photo(src,caption) {
    this.src = src;
    this.caption = caption;
}
function PhotoGallery(images,index,element,caption,prev,next) {
    this.index = index;
    this.images = images;
	
	this.element = $(element);
	this.caption = $(caption);
    
	this.preLoad  = new Image();
	
	
	
	this.fade = new Fx.Style(element,'opacity',{duration: 400});
	
	var self = this;
	
	$(prev).onclick = function() { clearInterval(self.timer); self.prev(); }
	$(next).onclick = function() { clearInterval(self.timer); self.next(); }
	
	this.timer = setInterval(function() { self.next(); }, 6500);
}
PhotoGallery.prototype.curImage = function() {
    return this.images[this.index];
}
PhotoGallery.prototype.prevIndex = function() {
    return this.index - 1 <= -1 ? this.images.length - 1 : this.index - 1;
}
PhotoGallery.prototype.nextIndex = function() {
    return this.index + 1 == this.images.length ? 0 : this.index + 1;
}
PhotoGallery.prototype.nextImage = function() {
    return this.images[this.nextIndex()];
}
PhotoGallery.prototype.next = function() {
    this.index = this.nextIndex();
    this.load();
}
PhotoGallery.prototype.prev = function() {
    this.index = this.prevIndex();
    this.load();
}
PhotoGallery.prototype.load = function() {
    var self = this;
    this.fade.stop();
    this.fade.set(0);
    this.preLoad.onload = function() { self.display() };
    this.preLoad.src = this.curImage().src;
}
PhotoGallery.prototype.display = function() {
    this.element.src = this.preLoad.src;
    this.setCaption();
    
    this.fade.stop();
    this.fade.start(1);

    this.preLoad.onload = null;
    this.preLoad.src = this.nextImage().src;
    
}
PhotoGallery.prototype.setCaption = function() {
	this.caption.innerHTML = this.curImage().caption;
}


