var Gallery = new Class({
	initialize: function(el) {
		this.container = $(el);
		
		this.desc = new Element('p', {'class': 'caption'});
		this.container.appendChild(this.desc);
		
		this.images = this.container.getFirst().getChildren();
		
		this.images.each(function(item, i) {
			if (item.hasClass('img-current')) {
				this.currentImgIndex = i;				
				return;
			}
		}.bind(this));
		
		this.render();
	},
	
	render: function(e) {
		var list = new Element('ul').injectInside(this.container);
		
		var prevClick = this.prevImg.bindWithEvent(this);
		var nextClick = this.nextImg.bindWithEvent(this);
		
		new Element('img', {
			src: '../_ui/images/ico_arrow_left.gif', 
			alt: 'Previous Photo', 
			width: '18', 
			height: '18'
		}).injectInside(new Element('a', {
			href: '#',
			events: { click: prevClick },
			'class': 'previous-photo'
		}).injectInside(new Element('li').injectInside(list)));

		this.links = [];
		this.images.each(function(item, i) {
			var linkClick = function(e) {
				this.selectImg(i);
				e.preventDefault();
			}.bindWithEvent(this);
			
			var link = new Element('a', {
				href: '#',
				events: { click: linkClick }
			}).injectInside(new Element('li').injectInside(list)).setText(i + 1);
			
			this.links.push(link);
		}.bind(this));
		
		this.links[this.currentImgIndex].addClass('current');
		this.desc.setText(this.images[this.currentImgIndex].alt)

		new Element('img', {
			src: '../_ui/images/ico_arrow_right.gif', 
			alt: 'Next Photo', 
			width: '18',
			height: '18'
		}).injectInside(new Element('a', {
			href: '#',
			events: { click: nextClick },
			'class': 'next-photo'
		}).injectInside(new Element('li').injectInside(list)));
	},
	
	prevImg: function(e) {
		if (this.currentImgIndex > 0) {
			this.selectImg(this.currentImgIndex - 1);
		}
		if (e) e.preventDefault();
	},
	
	nextImg: function(e) {
		if (this.currentImgIndex < this.images.length - 1) {
			this.selectImg(this.currentImgIndex + 1);
		}
		if (e) e.preventDefault();
	},
	
	selectImg: function(index) {
		if (this.animationInProgress) return;
	
		this.animationInProgress = true;	
		this.images[index].setStyles({
			top: '0px',
			opacity: '0'
		}).effect('opacity', {
			duration: 700
		}).start(1).chain(function() {
			this.images[this.currentImgIndex].removeClass('img-current');
			this.images[index].addClass('img-current');			
			this.currentImgIndex = index;
			this.images[index].setStyle('top', '');
			this.animationInProgress = false;
		}.bind(this));
		
		this.desc.setText(this.images[index].alt);
		this.links[this.currentImgIndex].removeClass('current');
		this.links[index].addClass('current');

	}
});

window.addEvent('domready', function() {
	if ($('gallery')) new Gallery('gallery');
});