/*  Universal Favourite Image Gallery Script v0.1
 *  (c) 2007 James Nicol www.enilsson.com.au
 *
 *--------------------------------------------------------------------------*/

var Site = {

	start : function() {
		Site.behaviour();
	},
	
	behaviour : function() {
		$$('#img_gallery').each(function(el){ new Gallery('img_gallery'); });
	}

}

document.observe('dom:loaded', Site.start);

var Gallery = Class.create();

Gallery.prototype = {
	
	defaultOptions : {
		thumbnails 	: 'thumbnails',
		duration 	: 0.7
	},

	initialize: function(container) {
		this.container = $(container);
		options = arguments[1] || {};
		this.options = Object.extend(Object.extend({},this.defaultOptions), options || {});
		this.options.thumbnails = $(this.options.thumbnails);
		this.start();
	},

	start: function() {
		this.options.thumbnails.getElementsBySelector('a').each(function(el,item){
			el.onclick = function(){ this.reveal(item); return false; }.bind(this);
		}.bind(this));	
	},

	getCurrItem : function() {
		var items = this.container.getElementsByClassName('main_img');
		var iter = 0;
		$A(items).each(function(el,i){
			if(el.style.display != 'none'){ iter = i; }
		});
		return iter;
	},

	reveal : function(i) {
		this.images = this.container.getElementsByClassName('main_img');
		this.currItem = this.getCurrItem();
		
		var after_finish = function(){
			this.images.each(function(b, iter){ if(iter != i){ b.hide(); } });
		}.bind(this);
		
		if(this.currItem == i){ return; }
		
		this.images[this.currItem].style.zIndex = 1;
		new Effect.Fade(this.images[this.currItem],{ duration: this.options.duration });
		
		this.images[i].style.zIndex = 2;
		new Effect.Appear(this.images[i],{ duration: this.options.duration, afterFinish: after_finish });
	}
		
}