var Gallery = new Class({
	initialize: function(container_id, prev_id, next_id, counter_id, hidden_class, sketch) {
		this.prev_link = $(prev_id);
		this.next_link = $(next_id);
		this.counter = $(counter_id);
		this.items = $$('#' + container_id + ' div');
		this.current = 0;
		this.hidden_class = hidden_class;
		this.allow_switch = true;
		this.sketch = $$('.' + sketch);
		
		this.setActionHandlers();
		
	}
});

Gallery.implement({
	
	setActionHandlers: function() {
		
		var obj = this;
		
		this.prev_link.addEvent('click', function(e){
			new Event(e).stop();
			
			if(obj.allow_switch) {
				
				var prev = obj.current;
				
				if(obj.current <= 0) {
					obj.current = obj.items.length - 1;
				}
				else {
					obj.current--;
				}
				
				obj.change(prev);
			}
		});
		
		this.next_link.addEvent('click', function(e){
			new Event(e).stop();
			
			if(obj.allow_switch) {
				
				var prev = obj.current;
				
				if(obj.current >= obj.items.length - 1) {
					obj.current = 0;
				}
				else {
					obj.current++;
				}
				
				obj.change(prev);
			}
		});
	
		if (this.sketch.length) {
			
			obj.initSketches();
		}
	}, 
	
	change: function(prev) {
		
		var obj = this;
		
		new Fx.Morph(this.items[prev], {
			duration: 100, 
			onComplete: function() {
				
				obj.items[obj.current].setStyle('opacity', 0);
				obj.items[prev].addClass(obj.hidden_class);
				obj.items[obj.current].removeClass(obj.hidden_class);
				
				new Asset.image(obj.items[obj.current].getFirst('img').src, {onload: function(){
					
					new Fx.Morph(obj.items[obj.current], {
						duration: 250, 
						onComplete: function(){
							obj.allow_switch = true;
						}
					}).start({
						opacity: [0, 1]
					});
				}});
			}
		}).start({
			opacity: [1, 0]
		});
		
		obj.counter.set('text', obj.current + 1);
	},
	 
	initSketches: function() {
		
		var obj = this;
		
		this.sketch.each(function(el) {
			
			var img = el.getChildren('img');
			
			img.addEvent('click', function(e){
				new Event(e).stop();
				
				if(obj.allow_switch) {
					
					var prev = obj.current;
					
					obj.current = parseInt(img.get('rel'));
					obj.change(prev);
				}
			});
		})
	} 
});