var validForm = new function()
{
	this.errors = {
		'required' : 'Value is required and can\'t be empty',
		'email' : 'This is not a valid email address in the basic format local-part@hostname',
		'length_less' : 'This is less than $ characters long',
		'length_more' : 'This is more than $ characters long'
	};
	
	this.valid = true;
	
	this.form = null;
	
	this.error = function(elm, errorName, val)
	{
		if (elm.parent().find('ul.errors').length)
			return;
		
		var _msg = this.errors[errorName];
		if (null !== val)
			_msg = _msg.replace('$', val);
	
		var _error = $('<ul>').addClass('errors');
		$('<li>').text(_msg).appendTo(_error);
		elm.parent().append(_error);
		
		this.valid = false;
	}
	
	this.cleanErrors = function()
	{
		$(this.form).find('ul.errors').remove();
	}
	
	this.checkRequired = function(fields)
	{
		for (i in fields)
		{
			var _elm = $('#' + fields[i]);
			if ('' == $.trim(_elm.val()))
			{
				this.error(_elm, 'required');
			}
		}
	}
	
	this.checkEmails = function(fields)
	{
		for (i in fields)
		{
			var _elm = $('#' + fields[i]);
			var _match = _elm.val().match(/[a-z0-9-_\.]*@[a-z0-9\.]*/i);
			if (null == _match || _match[0].length != _elm.val().length)
			{
				this.error(_elm, 'email');
			}
		}
	}
	
	this.checkLengths = function(fields)
	{
		for (e in fields)
		{
			var _elm = $('#' + e);
			var _length = _elm.val().length;
			if (_length < fields[e][0])
			{
				this.error(_elm, 'length_less', fields[e][0]);
			}
			else if (length > fields[e][1])
			{
				this.error(_elm, 'length_more', fields[e][1]);
			}
		}
	}
	
	this.go = function(form)
	{
		this.form = form;
		this.cleanErrors();
		
		this.checkRequired(['email', 'subject', 'message']);
		this.checkEmails(['email']);
		this.checkLengths({
							'subject' : [5, 70],
							'message' : [12, 2000]
						});
		
		// finish and focus
		if (!this.valid)
		{
			$(form).find('ul.errors:first').parent().find(':input').focus();
		}
		return this.valid;
	}
}

$(document).ready(function(){
	$('#contact_form form').submit(function()
	{
		return validForm.go(this);
	}).find(':input').focus(function()
	{
		$(this).addClass('active');
	}).blur(function()
	{
		$(this).removeClass('active');
	});
	
	var _error = $('ul.errors li');
	if (_error.text().match(/Captcha value is wrong/))
	{
		_error.text(_error.text().replace(/\:[\s\S]*/, ''));
	}
});