var menuAnimado = Class.create();
menuAnimado.prototype = {
	idAntiguo: '',
	animando: false,
	menus: [],
	cola: '',
	
	initialize: function(clase, opciones) {
		this.opciones = Object.extend(
			{	anchoGrande: '160px',
				anchoPequenyo: '80px',
				anchoNormal: '100px',
				capaPadre: 'capaMenuAnimado',
				evento: 'mousemove'
			}, opciones || {}
		);
		
    	this.menus=document.getElementsByClassName(clase);
    	for (var ii=0; ii< this.menus.length; ii++){
        	var menu = this.menus[ii];
        	Event.observe(menu, this.opciones.evento, this.ampliar.bind(this, menu.id));
    	};
		Event.observe($(this.opciones.capaPadre), 'mouseout', this.restaurar.bindAsEventListener(this));
	},
	
	ampliar: function(id){
		this.cola = id;
    	if(!this.animando && (id != this.idAntiguo)) {
       		var anim = new Animator({onComplete: this.animacionAcabada.bind(this)});
			if(this.idAntiguo!="") {
				anim.addSubject(new NumericalStyleSubject($(this.idAntiguo), 'width', $(this.idAntiguo).style.width, this.opciones.anchoPequenyo));
			} else {
    			for (var ii=0; ii< this.menus.length; ii++){
        			var menu = this.menus[ii];
					anim.addSubject(new NumericalStyleSubject(menu, 'width', menu.style.width, this.opciones.anchoPequenyo));
				}
			}
			anim.addSubject(new NumericalStyleSubject($(id), 'width', $(id).style.width, this.opciones.anchoGrande ))
			this.animando = true;
			anim.play();
			this.idAntiguo = id;
    	};
	},
	
	animacionAcabada: function() {
		this.animando = false;	
		if(this.cola!=this.idAntiguo) {
			if(this.cola == '') {
				this.restaurar(null);
			} else {
				this.ampliar(this.cola);
			}
		}
	},
	
	restaurar: function(event) {
		this.cola = '';
		var continuar = false;
		if(event) {
			/** El evento mouseout no se produce necesariamente al salir de la capa - prototype 1.6.1 deber&#8217;a incluir el evento mouseleave y hacer esta comprobación innecesaria **/
			if( event.toElement ) {
				var rel = event.fromElement, cur = event.toElement;
			} else {
				var rel = event.relatedTarget, cur = event.currentTarget;
			}
			
   			if (rel && rel !== cur && !rel.descendantOf(cur)) { continuar=true;}
		} else {
			continuar = true;
		}
	
		if(!this.animando && continuar) {
			var anim = new Animator({onComplete: this.animacionAcabada.bind(this)});
			for (var ii=0; ii< this.menus.length; ii++){
        		var menu = this.menus[ii];
				anim.addSubject(new NumericalStyleSubject(menu, 'width', menu.style.width, this.opciones.anchoNormal));
			};
			this.animando = true;
			anim.play();
			this.idAntiguo = '';
		}
	}
	
}

