var form = {
	init: function(){
		this.validation = {nombre:['name',true],email:['mail',true],telefono:['telephone',false],mensaje:['content',true]};
		this.dom = {
			inputs: $('form').getElements('input[type=text],textarea').associate(['nombre','email','telefono','mensaje']),
			buttons: $('form').getElements('input[type=button]').associate(['submit'])
		};
		
		['nombre','email','telefono'].each(function(l){this.dom.inputs[l].addEvent('keyup',function(e){var ev=new Event(e);if(ev.key=='enter'){this.submit();}}.bind(this));},this);

		this.dom.buttons.submit.addEvent('click',this.submit.bind(this));
		this.request = new Request({url:BASE.WEB+'contact.ajax',onSuccess:this.onSuccess.bind(this),onFailure:onError});
	},

	onSuccess: function(){
		this['on'+this.action](this.request.response.text);
	},

	submit: function(){
		if(this.checkForm()){
			Loading.show();
			data = {};
			['nombre','email','telefono','mensaje'].each(function(l){data[l]=this.dom.inputs[l].value;},this);
			this.action = 'Submit';
			this.request.send({data:'action='+this.action+'&data='+encodeURIComponent(JSON.encode(data))});
		}
	},

	onSubmit: function(response){
		switch(response){
			case 'true':
				redirect(gracias);
				break;
			case 'false':
				alert('No se pudo enviar su mensaje.');
				Loading.hide();
				break;
			default:
				alert(response);
		}
	},

	checkForm: function(){
		this.hideTip();
		if(this.checkInputs(['nombre','email','telefono','mensaje'],true)){
			return true;
		}
		return false;
	},

	checkInputs: function(ls,tip){	
		for(var i=0;i<ls.length;i++){
			var value = this.dom.inputs[ls[i]].value = this.dom.inputs[ls[i]].value.trim();
			if((value=='' && this.validation[ls[i]][1]) || (value!='' && !value.test(iRules[this.validation[ls[i]][0]].regx))){
				if(tip){
					this.showTip(ls[i],(value==''?_jlng.required:false));
				}
				return false;
			}
		}
		return true;
	},

	showTip: function(l,msg){
		$clear(this._hideTip);
		if(!this.tip){
			this.tip = {cont:new Element('div',{'class':'iVtip hidden'}).inject(document.body)};
			this.tip.title = new Element('h3').set('html','Error!').inject(this.tip.cont);
			this.tip.text = new Element('p').inject(this.tip.cont);
		}
		this.tip.l = l;
		var pos = this.dom.inputs[l].addClass('fail').getPosition();
		this.tip.cont.setStyles({'left':(pos.x+200)+'px','top':(pos.y-16)+'px'});
		this.tip.text.innerHTML = msg ? msg : iRules[this.validation[l][0]].msg;
		this.tip.cont.removeClass('hidden');
		this._hideTip = this.hideTip.delay(5000,this);
		this.dom.inputs[l].focus();
		window.scroll(0,pos.y-50);
	},

	hideTip: function(){
		if(this.tip){
			this.dom.inputs[this.tip.l].removeClass('fail');
			this.tip.cont.addClass('hidden');
		}
	}
};

window.addEvent('domready',form.init.bind(form));

