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

	initialize: function(){
		this.form = document.id('theform');

		this.elements = this.form.getElements('input,textarea').associate($obj_keys(this.attributes));
		this.elements.mensaje.addEvent('keyup', this.checkLimit.bind(this));

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

		this.limit = 1000;
		this.counter = this.form.getElement('p.counter span').set('html', this.limit);

		this.bubble = new Element('div', {'class': 'bubbleInfo'}).setStyle('display', 'none').addEvent('click', this.hideBubbleInfo.bind(this)).inject(document.body);
	},

	checkLimit: function(){
		var	value = this.elements.mensaje.value.trim(),
			chars = value.length;

		if(chars > this.limit){
			this.elements.mensaje.value = value.substr(0, this.limit);
			this.counter.set('html', '0');
		}else{
			this.counter.set('html', this.limit - chars);
		}
	},

	validate: function(){
		var k, attribute, value, title, message, error = false;

		for(k in this.attributes){
			attribute = this.attributes[k];
			value = this.elements[k].value;

			if(
				(empty(value) && attribute[1]) ||
				(!empty(value) && !value.test(iRules[attribute[0]].regex))
			){
				title = empty(value) ? Messages.required : Messages.invalid;
				message = iRules[attribute[0]].message;

				this.setBubblePosition(k);
				this.showBubbleInfo(title, message);

				this.elements[k].focus();

				error = true;

				break;
			}
		}

		return !error;
	},

	send: function(){
		if(this.validate()){
			var data = {}, request = new Request({onSuccess: this.onSend.bind(this), onFailure: onRequestFailure}), k;

			for(k in this.attributes){
				data[k] = this.elements[k].value;
			}

			this.hideBubbleInfo();

			Loading.show();

			request.send({
				url: BASE.ajax + 'contact.ajax',
				data: 'action=Send&data=' + encodeURIComponent(JSON.encode(data))
			});
		}
	},

	onSend: function(response){
		if(response == 'true'){
			this.form.empty().set('html', Messages.form.success);
			Loading.hide();
			try{
				pageTracker._trackPageview(LNG.code + '/contact_success');
			}catch(e){}
		}else{
			Loading.set(Messages.form.error);
		}
	},

	setBubblePosition: function(k){
		var ref = this.elements[k].getCoordinates();
		this.bubble.setStyles({
			left: (ref.right + 5) + 'px',
			top: (ref.top - 10) + 'px'
		});
	},

	showBubbleInfo: function(title, message){
		this.bubble.set('html', '<div><h3>' + title + '!</h3><p>' + message + '</p></div><div class="foot"></div>').setStyle('display', 'block');
	},

	hideBubbleInfo: function(){
		this.bubble.setStyle('display', 'none');
	}
};

ContactForm.initialize();

