
var Gallery = Class.create({
	
	initialize: function(divId) {
		
		this.divId				= divId;
		this.images				= $$("#" + this.divId + " img");
		this.nav				= $$("#" + this.divId + " li a");
		this.numOfImages		= this.images.length;
		this.index				= 0;
		this.intervalPlaying	= false;
		this.nextImage			= this.images[0];
		this.addListeners();
		
	},
	
	
	autoPlayNext: function(){
		var currImage = $$("#" + this.divId + " img.currentImage")[0];
		if (this.index >= this.numOfImages - 1) {
			this.index = -1;
		}
		this.index++;
		var nextImage = this.images[this.index];
		this.updateNumber();
		this.playFade(currImage, nextImage);
	},
	
	playFade: function(imgFrom, imgTo){
		
		this.nextImage = imgTo;
		new Effect.Fade(imgFrom, {
			duration: 0.3, 
			queue: 'end', 
			limit: 1, 
			afterFinish: function(){
				this.images.each(function(item){
					item.className = '';
				}.bind(this))
				//imgFrom.className = '';
				imgTo.className = 'queuedImage';
			}.bind(this)
		});
		new Effect.Appear(imgTo, {
			duration: 0.3, 
			queue: 'end', 
			limit: 1, 
			afterFinish: function(){
				imgTo.className = 'currentImage';
			}.bind(this)
		});
	}, 
	
	updateNumber: function() {
		this.nav.each(function(item){
			item.className = '';
		})
		this.nav[this.index].className = 'active';
	}, 
	
	addListeners: function(){
		
		this.nav.each(function(item, index){
			Event.observe(item, 'click', function(event){
				this.index = index;
				var currImage = this.nextImage; //$$("#" + this.divId + " img.currentImage")[0];
				var nextImage = this.images[index];
				if (this.intervalPlaying == true) {
					this.stopAutoPlay();
				}
				if (currImage != nextImage) {
					this.updateNumber();
					this.playFade(currImage, nextImage);
				}
			}.bindAsEventListener(this))
		}.bind(this))
	}
	
})