var Nav = {
	initialize: function(){
		this.container = $('navTop');
		this.prepare();
	},

	prepare: function(){
		var size = this.container.getSize();
		var first_links = this.container.removeClass('preload').getFirst().getChildren()
		this.build();
	},

	build: function(){
		this.container.getElements('ul').each(function(ul){
			var li = ul.getParent();
			if(li.get('tag')=='li'){
				ul.addClass('hidden');
				li.addEvents({
					mouseenter: function(){
						var ul = this.addClass('hover').getElement('ul');
						if(this.getParent().getParent().get('tag')=='li'){
							ul.setStyle('margin-top','-'+this.getFirst().getHeight()+'px');
						}
						ul.removeClass('hidden');
					},
					mouseleave: function(){
						this.removeClass('hover').getElement('ul').addClass('hidden');
					}
				});
			}else{
				ul.className = '';
			}
		});
	}
};


var Search = {
	initialize: function(){
		this.inputs = $('search').getChildren().associate(['label','words','send']);
		this.inputs.send.addEvent('click',this.submit.bind(this));
		if (this.inputs.words.value=='' || this.inputs.words.value.length==1) this.inputs.words.value="Búsqueda avanzada de productos";
		this.inputs.words.addEvent('click', function(){
          this.inputs = $('search').getChildren().associate(['label','words','send']);
		  if (this.inputs.words.value=='Búsqueda avanzada de productos') this.inputs.words.value='';
	     }
		); 
		this.inputs.words.addEvent('blur', function(){
          this.inputs = $('search').getChildren().associate(['label','words','send']);
		  if (this.inputs.words.value=='') this.inputs.words.value='Búsqueda avanzada de productos';
	     }
		); 
		this.inputs.words.addEvent('keyup',function(e){
			var e = new Event(e);
			if(e.key=='enter'){
				this.submit();
			}
		}.bind(this));
	},

	submit: function(){
		var words = this.inputs.words.value = this.inputs.words.value.trim();
		if(words.length>1 && this.inputs.words.value!='Búsqueda avanzada de productos'){
			redirect(BASE.web+'?s='+words.replace(/\s+/g,'+')+'&i=0');
		}
	}
};

var BrandSearch = {
	initialize: function(){
		var select = $('search_brand');
		if(select){
			this.input = select.getFirst().addEvent('change',this.brandFilter.bind(this));
		}
	},

	brandFilter: function(){
		if(!empty(this.input.value)){
			redirect(this.url.replace('%',this.input.value));
		}
	}
};

var ContactPopUp = {
	initialize: function(){
		this.build();
		this.link = $('navtop_contacto').addEvent('click',function(e){
			new Event(e).stop();
			this.showWin();
		}.bind(this));
	},

	build: function(){
		this.win = $('wcontact').setStyle('top','-654px').removeClass('hidden');
		this.content = $('wcontact_left');
		this.close = $('wcontact_close').addEvent('click',this.hideWin.bind(this));

		this.map = $('wmapa');
		this.map_link = $('wmapa_link').addEvent('click',this.toggleMap.bind(this));
		this.map_loaded = false;

		this.fx = new Fx.Tween(this.win);
	},

	showWin: function(){
		if(!this.win){
			this.build();
		}
		ContactForm.reset();
		this.showMap(false);
		//Overlay.show();
		this.fx.options.duration = 1000;
		this.fx.options.transition = Fx.Transitions.Back.easeOut;
		this.fx.start('top',-654,32);
	},

	hideWin: function(){
		this.fx.options.duration = 500;
		this.fx.options.transition = Fx.Transitions.Expo.easeOut;
		this.fx.start('top',32,-654);
		//Overlay.hide();
	},

	showMap: function(mode){
		if(mode){
			ContactForm.hideTip();
			this.content.addClass('hidden');
			this.map_link.set('html','<span>ocultar mapa de ubicación</span>');
			this.map.removeClass('hidden');
		}else{
			this.content.removeClass('hidden');
			this.map_link.set('html','<span>ver mapa de ubicación</span>');
			this.map.addClass('hidden');
		}
	},

	toggleMap: function(){
		this.showMap(this.map.hasClass('hidden'));
	}
};

var ContactForm = {
	attributes: {
		nombre: ['text',true],
		empresa: ['text',false],
		email: ['email',false],
		direccion: ['text',true],
		telefono: ['phone',true],
		mensaje: ['text',true]
	},

	initialize: function(){
		//ref
		this.form = $('wcontact_form');
		
		//inputs
		var ls = [];
		for(var k in this.attributes){ls.push(k);}
		this.inputs = this.form.getElements('input,textarea').associate(ls);

		//buttons
		this.buttons = this.form.getElements('button').associate(['submit']);
		this.buttons.submit.addEvent('click',this.submit.bind(this));

		//tip
		this.tip = new Element('div',{'class':'vtip hidden'}).addEvent('click',this.hideTip.bind(this)).inject(document.body);
		this.tip_hide = 0;

		//request
		this.request = new Request({url:BASE.web+'contact.ajax',onSuccess:function(r){this['on'+this.request.action](r);}.bind(this),onFailure:onError});

		//init
		this.reset();
	},

	requestSubmit: function(action,data,loading){
		if(!$defined(loading) || loading===true){
			Loading.show();
		}
		this.request.action = action;
		this.request.send({data:'action='+action+'&'+data});
	},

	reset: function(){
		this.data = {};
		for(var k in this.attributes){
			this.inputs[k].value = this.data[k] = '';
		}
	},

	toForm: function(){
		for(var k in this.inputs){
			this.inputs[k].value = this.data[k];
		}
	},

	toData: function(){
		for(var k in this.inputs){
			this.data[k] = this.inputs[k].value = this.inputs[k].value.trim();
		}
	},

	checkData: function(){
		this.hideTip();
		this.toData();
		for(var k in this.data){
			var v = this.data[k];
			var attr = this.attributes[k];
			var rule = iRules[attr[0]];
			if((v=='' && attr[1]) || (v!='' && !v.test(rule.regx))){
				this.showTip(k,v=='' ? _jlng.requerido : rule.msg);
				return false;
			}
		}
		return true;
	},

	// form
	submit: function(){
		if(this.checkData()){
			this.requestSubmit('Submit','data='+encodeURIComponent(JSON.encode(this.data)));
		}
	},

	onSubmit: function(response){
		if(response=='true'){
			Loading.set('Recibimos su mensaje correctamente!','success');
			Loading.hide.delay(3000,Loading);
			ContactPopUp.hideWin.delay(3100,ContactPopUp);
		}else{
			Loading.set('Error!','error');
		}
	},

	// tool-tip
	showTip: function(l,msg){
		$clear(this.tip_hide);
		this.tipl = l;
		this.inputs[l].addClass('fail');
		var ref = this.inputs[l].getParent().getCoordinates();
		var increment = 0;
		this.tip.set('html','<div><h3>Error!</h3><p>'+msg+'</p></div><div class="foot"></div>').setStyles({'left':ref.right+'px','top':(ref.top+increment-16)+'px'}).removeClass('hidden');
		this.tip_hide = this.hideTip.delay(6000,this);
		(function(){
			//window.scroll(0,ref.top+increment-100);
			this.inputs[this.tipl].focus();
		}.bind(this)).delay(10);
	},

	hideTip: function(){
		$clear(this.tip_hide);
		this.tip.addClass('hidden');
		if(this.tipl){
			this.inputs[this.tipl].removeClass('fail');
		}
	}
};

var PresentSlide = {
	initialize: function(){
		this.el = document.getElement('#present_slide span');
		if(this.el){
			this._move = this.move.periodical(40,this);
		}
	},
	
	move: function(){
		var pos = this.el.getStyle('left').toInt();
		var width = this.el.getWidth();
		pos -= 2;
		if(pos<width*-1){
			pos = 300;
		}

		this.el.setStyle('left',pos+'px')
	}
};

var ProdcutPopUp = {
	initialize: function(){
		this.build();
		this.link = $('navtop_productos').addEvent('click',function(e){
			new Event(e).stop();
			this.showWin();
		}.bind(this));		
	},

	build: function(){
		this.win = $('wproduct').setStyle('top','-654px').removeClass('hidden');
		this.close = $('wproduct_close').addEvent('click',this.hideWin.bind(this));
		this.fx = new Fx.Tween(this.win);
		$('wproduct_search').addEvent('keyup',function(e){
			var e = new Event(e);
			if(e.key=='enter'){
				this.submit();
			}
		}.bind(this));
		$('wproduct_send').addEvent('click',this.submit.bind(this));
	},

	showWin: function(){
		if(!this.win){
			this.build();
		}
		this.fx.options.duration = 1000;
		this.fx.options.transition = Fx.Transitions.Back.easeOut;
		this.fx.start('top',-654,32);
	},

	hideWin: function(){
		this.fx.options.duration = 500;
		this.fx.options.transition = Fx.Transitions.Expo.easeOut;
		this.fx.start('top',32,-654);
	},
	
	submit: function(){
		var words = $('wproduct_search').value.trim();
		if(words.length>1){
			redirect(BASE.web+'?s='+words.replace(/\s+/g,'+')+'&i=0');
		}
	}
	
};

window.addEvent('domready',function(){
	//options disabled
	$$('option').each(function(el){
		if(el.disabled && el.innerHTML=='seleccione'){
			el.dispose();
		}
	});

	//busqueda
	Search.initialize();

	//menu
	Nav.initialize();
	
	//filtro marca
	BrandSearch.initialize();

	//ContactPopUp
	ContactPopUp.initialize();

	//ContactForm
	ContactForm.initialize();
	//productos
	ProdcutPopUp.initialize();
});

window.addEvent('load',function(){
	PresentSlide.initialize();
});