
Vn.Contact = new Class
({
	Extends: Vn.Module

	,activate: function ()
	{
		var self = this;
		var form = this.$('contact-form').onsubmit = function ()
			{ self.onSubmit (); return false; };

		this.refreshCaptcha ();
	}
	
	,refreshCaptcha: function ()
	{
		var url = 'forms/cms/contact/captcha.php';
		this.$('captcha-img').src = url +'?'+ new Date ().getTime ();
	}
	
	,onSubmit: function ()
	{
		var form = this.$('contact-form');
	
		var request = new Vn.FormRequest ();
		request.send (form, this.onResponse.bind (this));
	}
	
	,onResponse: function (response)
	{
		var form = this.$('contact-form');

		if (response)
		{
			form.reset ();
			Htk.Toast.showMessage (_('DataSentSuccess'));
		}
		else
			Htk.Toast.showError (_('ErrorSendingData'));

		form['captcha'].value = '';
		this.refreshCaptcha ();
	}
});

Vn.FormRequest = new Class
({
	send: function (form, callback)
	{
		var formData = '';
		var elements = form.elements;

		for (var i = 0; i < elements.length; i++)
		if (elements[i].name)
			formData += elements[i].name +'='+
				encodeURIComponent (elements[i].value) +'&';

		var request = new XMLHttpRequest ();
		request.open (form.method, form.action, true);
		request.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded');
		request.onreadystatechange = this.onSend.bind (this, request, callback);
		request.send (formData);
	}
	
	,onSend: function (request, callback)
	{
		if (request.readyState != 4)
			return;

		if (request.status == 200)
			callback (eval (request.responseText));
		else
			callback (null);
	}
});

