$(document).ready(function()
{
	if (!$('.contactform').length)
	{
		return false;
	}

	$('.contactform form').submit(CheckForm)
	$('#' + ReqdFields.join(', #')).blur(CheckField);
});

var ReqdFields = ['vards', 'epasts', 'komentars'];

function CheckForm(e)
{
	var FormFilled = true;
	var Focused = false;
	for (var i = 0, ReqdField; ReqdField = ReqdFields[i]; i++)
	{
		var Elem = $('#' + ReqdField);
		FormFilled = CheckField(Elem.get(0), true) && FormFilled;
		if (!FormFilled && !Focused)
		{
			Elem.focus();
			Focused = true;
		}
	}

	return FormFilled;
}

function CheckField(Field, ShowTopMessage)
{
	if (Field.target)
	{
		Field = Field.target;
	}
	Field = $(Field);

	var InvalidEmail = false;
	if (Field.attr('id') == 'epasts')
	{
		var MailValue = Field.val();
		if (MailValue)
		{
			EmailPattern = /^\w+([\.\w-])*@\w+(\.[\w-]+)+$/;
			var match = MailValue.match(EmailPattern);
			InvalidEmail = match ? false : true;
		}
	}

	var parent = (Field.attr('id') == 'komentars' ? $('#jautajums') : Field.parent('li'));
	if (!Field.val() || InvalidEmail)
	{
		$('#error-message').text(InvalidEmail ? i18n.invalid_email : i18n.empty_fields);
		parent.addClass('error');
		return false;
	}
	else if (Field.val() && !InvalidEmail)
	{
		if ($('.contactform form li.error').length <= 0)
		{
			$('#error-message').text('');
		}
		parent.removeClass('error');
		return true;
	}
	alert([Field.val(), InvalidEmail]);
}

