/*
*	Dependencies:
*		MooTools 1.2.1
*		MooTools Plugin: Hash: Assets
*/

var PhotoGallery = new Class({
	Implements: Options,
	options: {
		active: 1,
		prev: '.prev',
		next: '.next'
	},
	initialize: function(container, options){
		this.setOptions(options);
		this.container = $(container) || false;
		this.togglerPrev = $$(this.options.prev);
		this.togglerNext = $$(this.options.next);
		this.image = this.container.getElement('div.image img');
		this.pages = this.container.getElements('div.pages a');
		this.title = this.container.getElement('div.description h2');
		this.description = this.container.getElement('div.description p');
		this.count = this.pages.length;
		this.active = this.options.active;
		this.setup();
	},
	setup: function(){
		this.gallery = {};
		this.show(this.active);
		this.togglerPrev.addEvent('click', this.prev.bindWithEvent(this));
		this.togglerNext.addEvent('click', this.next.bindWithEvent(this));
		this.pages.each(function(el, i){
			el.addEvent('click', function(e){
				e.stop();
				this.show((i+1));
			}.bind(this));
		}.bind(this));
	},
	show: function(pos){
		if(pos != this.active) this.deactivate(this.active);
		this.activate(pos);
		this.active = pos;
		(this.active == 1) ? this.togglerPrev.addClass('disable') : this.togglerPrev.removeClass('disable');
		(this.active == this.count) ? this.togglerNext.addClass('disable') : this.togglerNext.removeClass('disable');
		this.image.fade('out');
		if(this.gallery[pos - 1]){
			this.gallery[pos - 1].replaces(this.image);
			this.image = this.gallery[pos - 1];
			this.image.fade('show');
		} else {
			this.gallery[pos - 1] = new Asset.image(this.pages[pos - 1].getProperty('href'), {
				title: this.pages[pos - 1].getProperty('title'),
				onload: function(img){
					img.replaces(this.image);
					this.image = img;
					this.image.fade('in');
				}.bind(this),
				onerror: function(error){
					alert(this.title + ' image not found');
				}
			});
		}
		this.title.set('html', this.pages[pos-1].getProperty('title'));
		this.description.set('html', this.pages[pos-1].getProperty('rel'));
	},
	activate: function(pos){
		pos -= 1;
		this.pages[pos].addClass('active');
	},
	deactivate: function(pos){
		pos -= 1;
		this.pages[pos].removeClass('active');
	},
	prev: function(e){
		if(e) e.stop();
		if(e && e.target.hasClass('disable')) return false;
		var active = this.active;
		(active > 1 ) ? active -= 1 : active = 1;
		this.show(active);
	},
	next: function(e){
		if(e) e.stop();
		if(e && e.target.hasClass('disable')) return false;
		var active = this.active;
		(active < this.count ) ? active += 1 : active = this.count;
		this.show(active);
	}
});