
var ImageViewer = Class.create({
	initialize: function(container)
	{
		if ($(container)) {
			this.container = container;
		}
		else {
			return false;
		}
		
		this.start();
	},
	
	start: function() {
		this.toggleCaption();
		this.setup();
		this.registerEvents();
	},
	
	setup: function() {
		this.scrollWidth = ($('thumbs').select('.thumb').length) * 66;
		$('scrollContainer').setStyle({width: this.scrollWidth + 'px'});
	},
	
	registerEvents: function() {
		$('thumbs').select('.thumb').each(function(thumb){
			thumb.observe('click', this.thumbClicked.bindAsEventListener(this));
		}.bind(this));
		
		$('scrollLeft').observe('click', this.scrollLeft.bindAsEventListener(this));
		$('scrollRight').observe('click', this.scrollRight.bindAsEventListener(this));
	},
	
	scrollRight: function() {
		var left = parseInt($('scrollContainer').getStyle('left').replace('px', ''));
		
		if (this.scrollWidth + left >= parseInt($('scroll').getStyle('width').replace('px', '')))
		{
			left = left - 66;
			
			new Effect.Morph($('scrollContainer'), {
				style:'left: ' + left + 'px',
				duration: 0.4
			});
		}
	},
	
	scrollLeft: function() {
		var left = parseInt($('scrollContainer').getStyle('left').replace('px', ''));
		left = left + 66;
		
		if (left <= 0)
		{
			new Effect.Morph($('scrollContainer'), {
				style:'left: ' + left + 'px',
				duration: 0.4
			});
		}
	},
	
	thumbClicked: function(ev) {
		ev.stop();
			
		var link = ev.element().up();
		var image = new Element('img', {src: link.href, alt: link.title});
		
		this.resetThumbs();
		link.addClassName('selected');
		
		$('mainImage').update(image);
		$('caption').update(link.title);
		
		this.toggleCaption();
	},
	
	toggleCaption: function() {
		if (!$('caption').innerHTML.replace(/^\s*|\s*$/g, ""))
		{
			$('caption').removeClassName('caption');
		}
		else
		{
			$('caption').addClassName('caption');
		}
	},
	
	resetThumbs: function()
	{
		$('thumbs').select('.thumb').each(function(thumb){
			thumb.removeClassName('selected');
		}.bind(this));
	}
	
});

document.observe('dom:loaded', function(){
	if ($('imageViewer')) {
		imageViewer = new ImageViewer($('imageViewer'));
	}
});


