;(function($) {

	$.fn.adderror = function() {
		$(this).next('label').addClass('error');
		$(this).focus();
		return false;
	}

})(jQuery);

function isValidEmail(value)
{
	// Verrrrry simplified email validation as it would never know that "iam@faker.cx" is never going to be genuine.
	apos=value.indexOf("@");
	dotpos=value.lastIndexOf(".");
	if (apos<1||dotpos-apos<2)
	{return false;}
	else {return true;}
}

$(function(){
	$('#contactform').submit(function(){
	
		var items = new Array(
			new Array('firstname', 'first name'),
			new Array('lastname', 'last name'),
			new Array('phone', 'phone number'),
			new Array('email', 'e-mail address'),
			new Array('captcha', 'validation code'),
			new Array('notes', 'notes')
		);
	
		$('#contactform label').removeClass('error');
		
		for (i=0; i < items.length; i++) {
			var elemtype = $('#contactform #'+items[i][0]).attr('tagName').toLowerCase();
			var itemvalue = "";
			
			itemvalue = $('#contactform #'+items[i][0]).val();

			if (itemvalue == "" && items[i][1] != "")
			{
				$('#contactform #'+items[i][0]).adderror();
				return false;
			}
		}
				
		if (isValidEmail($('#contactform #email').val()) == false)
		{
			$('#contactform #email').adderror();
			return false;
		}
		
		/* submit the page (through ajax, do not use "browser post" ) ... */
		
		var posturl = $("#contactform").attr("action");
		var dataString = "";
		
		for (i=0; i < items.length; i++) {
			if (dataString != "") { dataString += "&"; }
			dataString += items[i][0] + "=" + $('#contactform #'+items[i][0]).val();
		}
		
		$.ajax({
      type: "POST",
      url: posturl,
      data: dataString,
	  beforeSend: function() {
		$('#contactform input[type=submit]').attr("disabled", "true").val('Submitting...');
	  },
      success: function(xhr) {
		if (xhr == "OK") {
			$('#contactform').html("<div id='message'></div>");
			$('#contactform #message').html("<h2>Thank you.</h2>")
			.append("<p>Thank you for your message. You will be contacted shortly.</p>")
			.hide()
			.fadeIn(1500, function() {
			  $('#contactform #message').append("<img id='checkmark' src='images/check.png' />");
			});
		}
		else
		{
			$('#contactform input[type=submit]').attr("disabled", "").val('Submit');
			if (xhr == 'CAPTCHA_FAILED') alert("The validation code is incorrect.");
			else alert('There has been an error.\nPlease try again later.\nError:'+xhr);
		}
      },
	  timeout: function() {
		alert("A timeout has occurred during your request.\nPlease try again.");
	  },
	  error: function (xhr, ajaxOptions, thrownError) {
		$('#prizeform input[type=submit]').attr("disabled", "").val('Submit');
		if (xhr.status == '404') alert("Ajax Error - Requested file not found.");
		else alert("Ajax Error" + xhr.status);
		//alert(thrownError);
      }
     });
    return false;
	});
});