var Gallery = Class.create();

Gallery.prototype = {
	initialize:function(id, counter){
	
		this.id = id;
		this.imageListWidth = 0;
		var sumWidth = 0;
		$$('ul#' + this.id + ' li a').each(function(imageContainer){
			sumWidth += imageContainer.offsetWidth + 2;
		}.bind(this));
		this.imageListWidth = sumWidth;
		this.contentGroup = $(this.id).parentNode.parentNode.parentNode;
		this.contentGroup.id = "contentGroup_" + counter;
		$(this.id).style.width = this.imageListWidth + "px";
		
		this.showButtons(this.id);
		
		this.forwardButton = $$('#' + this.contentGroup.id + ' a.forward')[0];
		this.reverseButton = $$('#' + this.contentGroup.id + ' a.reverse')[0];

		Event.observe(this.forwardButton, 'mousedown', function(){ this.forward(this.id); }.bind(this));
		Event.observe(this.forwardButton, 'mouseup', function(){ this.cancel(this.id); }.bind(this));
		Event.observe(this.reverseButton, 'mousedown', function(){ this.reverse(this.id); }.bind(this));
		Event.observe(this.reverseButton, 'mouseup', function(){ this.cancel(this.id); }.bind(this));

	},
	showButtons:function(id){
		this.distance = $(this.id).offsetWidth - this.contentGroup.offsetWidth;
		if(this.distance > 0) {
			$$('#' + this.contentGroup.id + ' .buttons').each(function(button){
				button.show();
			});
		} else {
			$$('#' + this.contentGroup.id + ' .buttons').each(function(button){
				button.hide();
			});
		}
		$(id).style.left = "0px";
	},
	forward:function(id){
			if(parseInt($(this.id).style.left) <= -this.distance) {
				this.effect.cancel();
				$(this.id).style.left = -this.distance + 2 + "px";
			} else { 
				this.effect = new Effect.Move($(this.id), {
					x: -8, 
					mode: 'relative', 
					duration: 0, 
					afterFinish:function(){
						this.forward(this.id)
					}.bind(this)
				});
			}
	},
	reverse:function(id){
			if(parseInt($(this.id).style.left) >= 0) {
				this.effect.cancel();
				$(this.id).style.left = "0px";
			} else { 
				this.effect = new Effect.Move($(this.id), {
					x: 8, 
					mode: 'relative', 
					duration: 0, 
					afterFinish:function(){
						this.reverse(this.id)
					}.bind(this)
				});
			}
	},
	cancel:function(id){
		this.effect.cancel();
	}
};


Event.observe(window, 'load', function(){

	var counter = 0;
	$$('.imageGroup ul').each(function(imageList){
		imageList.id = "imageList_" + counter;
		gallery = new Gallery(imageList.id, counter);
		Event.observe(window, 'resize', function(){
			gallery.showButtons(imageList.id);
		});
		
		counter++;
		
	});


});
