ImgGallery = new Class({
	Implements: Events,
	images: [],
	autoLoop: false,
	loopDelay: 5, // in seconds
	currentIndex: 0,
	timer: false,
	currentEl: false,
	
	init: function(els) {		
		this.images = els;
		this.currentEl = els[0];	
		
		for (var i = 1; i < els.length; i++) {
			$(els[i]).setStyles({opacity: 0, display: 'block'});
		}
			
		if (this.images.length > 1) {
			this.setupPagination();
		
		
			if (this.autoLoop == true) {
				this.timer = this.doLoop.periodical(this.loopDelay * 1000);
			}
		}
	},
	
	setupPagination: function()
	{			
		var a = new Element('a');
		a.rel = 'previous';
		a.addEvent('click', img_gallery.showImage);
		a.addClass('slider_left');
		a.inject('paginator');
		
		for (var i = 0; i < this.images.length; i++) {
			a = new Element('a');
			a.rel = i;
			a.addEvent('click', img_gallery.showImage);
			a.addClass('slider_inactive');
			
			if (i == 0) {
				a.addClass('slider_active');
			}
			
			a.inject('paginator');
		}
		
		a = new Element('a');
		a.rel = 'next';
		a.addEvent('click', img_gallery.showImage);
		a.addClass('slider_right');
		a.inject('paginator');
	},
	
	showImage: function()
	{
		var index = this.rel;
		
		if (index == 'previous') {
			index = img_gallery.currentIndex - 1;
			if (index < 0) {
				index = img_gallery.images.length - 1;
			}
		}
		if (index == 'next') {
			index = img_gallery.currentIndex + 1;
			if (index == img_gallery.images.length) {
				index = 0;
			}
		}
		
		if (index < img_gallery.images.length) {
			$clear(img_gallery.timer);
			img_gallery.timer = false;
			
			$(img_gallery.currentEl).fade('out');
			img_gallery.currentEl = img_gallery.images[index];
			img_gallery.currentIndex = index;
			img_gallery.changeState();
			$(img_gallery.currentEl).fade('in');
			
			img_gallery.timer = img_gallery.doLoop.periodical(img_gallery.loopDelay * 1000);
		}
	},
	
	doLoop: function()
	{
		$(img_gallery.currentEl).fade('out');
	
		(function() {
			img_gallery.currentIndex++;
			if (img_gallery.currentIndex == img_gallery.images.length) {
				img_gallery.currentIndex = 0;
			}
			
			img_gallery.currentEl = img_gallery.images[img_gallery.currentIndex];
			img_gallery.changeState();
			
		}).delay(500);
		
		(function() { $(img_gallery.currentEl).fade('in'); }).delay(1000);
	},
	
	changeState: function()
	{
		$$('.slider_inactive').each(function(el, i) {
			el.removeClass('slider_active');
			
			if (i == img_gallery.currentIndex) {
				el.addClass('slider_active');
			}
		})
	}
});
