/**
 * Gallery for mootools 1.2.1
 * @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: {
		slideWidth: 650,
		prevBtn: null,
		nextBtn: null,
		slidesBtn: [],
		showPopup: false
	},
	
	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.prevBtn = this.options.prevBtn;
		this.nextBtn = this.options.nextBtn;
		this.slidesBtn = this.options.slidesBtn;
		
		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));
			if(this.options.showPopup) {
				new Popup(el, el.getNext(), {tweak: {x: -20, y: -5}});
			}
		}.bind(this));
		
		this.prevBtn.addEvent('click', function(e) {
			new Event(e).stop();
			var index = this.iSelected - 1;
			if(index < 0) {
				index = 0;
			}
			this.show(index);
		}.bind(this));
		
		this.nextBtn.addEvent('click', function(e) {
			new Event(e).stop();
			var index = this.iSelected + 1;
			if(index >= this.slides.length) {
				index = this.slides.length-1;
			}
			this.show(index);
		}.bind(this));
	},
	
	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.options.slideWidth,-index*this.options.slideWidth]
				}).chain(function() {
					this.slidesBtn[index].focus();
					this.iSelected = index;
					this.loading = false;
				}.bind(this));
			}
		}
	}
	
});

