var Gallery = Class.create();

Gallery.prototype = {
	initialize: function(wrapper)
	{
		this.wrapper = $(wrapper) || false;
		this.photo_wrapper = $('photo_wrapper') || false;
		this.photo;
		this.loader = $('photo_loading') || false;
		this.thumbs_selector = 'a.gallery';
		this.thumbs = $A();
		this.obs;
		this.currentPhoto = 0;
	},
	getElements: function()
	{
		if (this.wrapper && this.photo_wrapper && this.loader) 
		{
			this.thumbs = this.wrapper.select(this.thumbs_selector);
			return this.thumbs.length > 0 || false;
		}
		else 
			return false;
	},
	setNewPhoto: function()
	{
		this.photo = new Element('img', { 'src': this.thumbs[this.currentPhoto].getAttribute('href'), 'display':'none' });
		this.photo.src = this.thumbs[this.currentPhoto].getAttribute('href'); 
		this.photo_wrapper.update(this.photo);
		that = this;
		Event.observe(this.photo, 'load', this.obs);
		that.thumbs[that.currentPhoto].addClassName('active');
		/*
		Event.observe(this.photo, 'load', this.showPhoto.bindAsEventListener(this.photo, that));
		Event.observe(this.photo, 'load', this.showPhoto.bind(this.photo, that));
		this.photo.stopObserving();
		this.photo.observe('load', function(ev){
			new Effect.Fade(that.loader, {delay: 0.3, duration: 0.3});
			new Effect.Appear(that.photo_wrapper, {duration: 0.3, queue: 'end', afterFinish: function(){}});
		});
		*/
	},
	unsetPhoto: function()
	{
		if(this.photo)
		{
		//	Event.stopObserving(this.photo, 'load', this.obs);
			Element.remove(this.photo);
		}
	},
	prevPhoto: function(){
		// Figure out which photo is previous
		(this.currentPhoto == 0) ? this.currentPhoto = this.thumbs.length - 1 : this.currentPhoto--;
		this.swap();
	},
	nextPhoto: function()
	{
		// Figure out which photo is next
		(this.currentPhoto == (this.thumbs.length - 1)) ? this.currentPhoto = 0 : this.currentPhoto++;
		this.swap();
	},
	showPhoto: function(ev, that)
	{
		new Effect.Fade(that.loader, {delay: 0.3, duration: 0.3});
		new Effect.Appear(that.photo_wrapper, {duration: 0.3, queue: 'end', afterFinish: function(){
			// 
		}});
		Event.stopObserving(that.photo, 'load', that.obs);
	},
	swap: function()
	{
		Element.show(this.loader);
		Element.hide(this.photo_wrapper);
		this.unsetPhoto();
		this.thumbs.invoke('removeClassName', 'active');
		this.setNewPhoto();
	},
	registerObservers: function()
	{
		that = this;
		this.photo_wrapper.observe('click', function(ev)
		{
			ev.stop();
			that.nextPhoto()
		});
		this.obs = this.showPhoto.bindAsEventListener(this.photo, that);
		this.thumbs.each(function(thumb, i)
		{
			thumb.observe('click', function(ev)
			{
				ev.stop();
				that.currentPhoto = i;
				that.swap()
			});
		});
	},
	init: function()
	{
		if (!this.getElements()) 
		{
			if (this.wrapper) 
				Element.hide(this.wrapper);
			return false;
		}
		this.registerObservers();
		this.swap();
	}
}


