/**
 * Gallery for mootools 1.2.1 (utilise Popup.js)
 * @license MIT-style license
 * @author Anquetil Manuel <manuel.anquetil [at] baphira.com>
 * @copyright Baphira - http://www.baphira.com
 */
var Gallery = new Class({

	Implements: [Options],

	options: {
		'next_delay': 0
	},

	width: 558,
	
	initialize: function(el, options) {
		this.setOptions(options);
		this.gallery = $(el);
		this.container = this.gallery.getElement('.slides').setStyle('overflow','hidden');
		this.scroller = this.gallery.getElement('.scrollContainer');
		this.slides = this.gallery.getElements('.slide');
		this.slidesBtn = this.gallery.getElements('.bottom-nav a');
		this.prevBtn = this.gallery.getElement('.top-nav .prev a');
		this.nextBtn = this.gallery.getElement('.top-nav .next a');
		
		this.iSelected = -1;
		this.loading = false;
		
		this.effect = new Fx.Morph (this.scroller, {
			transition: Fx.Transitions.Quad.easeInOut,
			duration: 1000
		});
				
		//default selection
		for(var i = 0; i < this.slides.length; i++) {
			if(this.slides[i].hasClass('defaultSelect')) {
				this.show(i);
			}
			this.slides[i].setStyle('display','block');
		}
		
		//links
		this.slidesBtn.each(function(el) {
			var index = el.id.replace('slide-nav','').toInt();
			el.addEvent('click', function(e) {
				new Event(e).stop();
				this.show(index);
			}.bind(this));
		}.bind(this));
		
		this.prevBtn.addEvent('click', function(e) {
			new Event(e).stop();
			var index = this.iSelected - 1;
			if(index < 0) {
				index = this.slides.length-1;;
			}
			this.show(index);
		}.bind(this));

		this.nextBtnFunc = function(e) {
			if(e) {
				new Event(e).stop();
			}
			if(this.iSelected == -1) {
				this.iSelected = 0;
			}
			var index = this.iSelected + 1;
			if(index >= this.slides.length) {
				index = 0;
			}
			this.show(index);
		}.bind(this);

		this.nextBtn.addEvent('click', this.nextBtnFunc);

		if(this.options.next_delay > 0) {
			this.nextBtnFuncDelay = this.nextBtnFunc.delay(this.options.next_delay);
		}
	},
	
	show: function(index) {
		if(!this.loading) {
			this.loading = true;
			
			if(this.iSelected < 0) {
				this.slidesBtn[index].focus();
				this.iSelected = index;
				this.loading = false;
			} else {
				this.effect.start({
					'margin-left':[-this.iSelected*this.width,-index*this.width]
				}).chain(function() {
					//this.slidesBtn[index].focus();
					this.iSelected = index;
					if(this.options.next_delay > 0) {
						$clear(this.nextBtnFuncDelay);
						this.nextBtnFuncDelay = this.nextBtnFunc.delay(this.options.next_delay);
					}
					this.loading = false;
				}.bind(this));
			}

			for(var i = 0; i < this.slidesBtn.length; i++) {
				if(i != index) {
					this.slidesBtn[i].removeClass('here');
				} else {
					this.slidesBtn[i].addClass('here');
				}
			}

		}
	}
	
});
