var ImageMenu = new Class({

	options : {
		selected: -1,
		duration: 400,
		itemWidth: false,
		openWidth: false,
		smallWidth: false,
		transition: Fx.Transitions.quadOut,
		onSelect: Class.empty
	},
	
	initialize: function(elements, options){
		this.setOptions(options);
		this.elements = $$(elements);
		
		this.itemWidth = this.options.itemWidth || this.elements[0].getStyle('width').toInt();
		this.smallWidth = this.options.smallWidth || Math.round(((this.itemWidth * this.elements.length) - this.options.openWidth) / (this.elements.length - 1));
		
		this.fx = new Fx.Elements(this.elements, {wait: false, duration: this.options.duration, transition: this.options.transition });
		
		this.elements.each(function(el, i){
			el.addEvents({
				'mouseover' : function(e){ e = new Event(e).stop(); this.show(i); this.elements[i].setStyle('background-position', '-5px bottom'); }.bind(this),
				'mouseout' : function(e){ e = new Event(e).stop(); this.hide(i); this.elements[i].setStyle('background-position', '-5px top'); }.bind(this),
				'click' : function(e){ this.select(i); }.bind(this)
			});
		}, this);
		
		if(this.options.selected != -1){
			this.show(this.options.selected);
			this.select(this.options.selected);
		}
	},
	
	show: function(index) {
		var obj = {};
		obj[index] = {'width': [this.elements[index].getStyle('width').toInt(), this.options.openWidth]};
		
		this.elements.each(function(el, i){
			if (i != index){
				var w = el.getStyle('width').toInt();
				if (w != this.smallWidth) obj[i] = {'width': [w, this.smallWidth]};
			}
		}, this);
		
		this.fx.start(obj);
	},
	
	hide: function(index) {
		var obj = {};
		if(this.options.selected == -1){
			this.elements.each(function(el,i){
				obj[i] = {'width': [el.getStyle('width').toInt(), this.itemWidth]};
			}, this);
		}
		
		else{
			this.elements.each(function(el,i){
				if(i != this.options.selected){
					var w = el.getStyle('width').toInt();
					if(w != this.smallWidth){obj[i] = {'width': [w, this.smallWidth]}};
				}
				else obj[i] = {'width': [el.getStyle('width').toInt(), this.options.openWidth]};
			}, this);
		}
		
		this.fx.start(obj);
	},
	
	select: function(index) {
		this.options.selected = this.options.selected == index ? -1 : index;
		this.fireEvent('onSelect', this.options.selected);
	},
	
	reset: function(){
		this.options.selected = -1;
		this.myElements.each(function(el, i){ this.hide(i); }, this);
	}
	
});

ImageMenu.implement(new Events);
ImageMenu.implement(new Options);
