var Form = {
	initialize: function(){
		this.form = document.getElement('form').addEvent('submit',this.submit.bindWithEvent(this));
		var inputs = this.form.getElements('input,select,textarea');
		this.inputs = inputs.associate(inputs.get('name'));

		this.tip = {delay:0,el:false,container:new Element('div',{'class':'iVtip hidden'}).addEvent('click',this.hideTip.bind(this)).inject(document.body)};
		this.request = new Request({url:this.form.action,onSuccess:function(r){this['on'+this.request.action](r);}.bind(this),onFailure:onError});

		inputs[0].focus();
	},

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

	submit: function(e){
		new Event(e).stop();
		if(this.checkForm()){
			var data = {};
			for(var i in this.inputs){
				data[i] = this.inputs[i].value;
			};
			this.requestSubmit('Submit','data='+encodeURIComponent(JSON.encode(data)));
			this.form.disabled = true;
		}
	},

	onSubmit: function(response){
		switch(response){
			case 'true':
				redirect(gracias);
				break;
			case 'false':
				//Loading.set('','');
				//Loading.hide();
				break;
			default:
				alert(response);
		}
	},

	checkForm: function(){
		var els = [];
		for(var el in this.inputs){
			els.push(el);
		}
		return this.checkInputs(els,true);
	},

	checkInputs: function(els,tip){
		this.hideTip();
		for(var i=0;i<els.length;i++){
			var el = this.inputs[els[i]];
			var value = el.value = el.value.trim();
			var rule = iRules[el.className.split(' ')[0]];
			var required = !el.hasClass('norequired');
			if((empty(value) && required) || (!empty(value) && !value.test(rule.regx))){
				if(tip){
					this.showTip(els[i],(empty(value) ? _jlng.requerido : rule.msg),{x:4,y:-12});
				}
				return false;
			}
		}
		return true;
	},

	showTip: function(el,msg,offset,position){
		$clear(this.tip.delay);

		var position = position || {x:'right',y:'top'};
		var offset = offset || {x:0,y:0};
		var coordinates = this.inputs[el].addClass('invalid').getParent().getCoordinates();
		var style = {'left':(coordinates[position.x]+offset.x)+'px','top':(coordinates[position.y]+offset.y)+'px'};

		this.tip.el = el;
		this.tip.container.set('html','<div><h3>Error!</h3><p>'+msg+'</p></div><div class="foot"></div>').setStyles(style).removeClass('hidden');
		this.tip.delay = this.hideTip.delay(5000,this);

		this.inputs[el].focus();
		window.scroll(0,coordinates.top-50);
	},

	hideTip: function(){
		if(this.tip.el){
			this.inputs[this.tip.el].removeClass('invalid');
			this.tip.container.addClass('hidden');
			this.tip.el = false;
		}
	}
};

window.addEvent('domready',Form.initialize.bind(Form));