$(document).ready(function(){ // Bind validation functions to the forms if jQuery is available
	$("form").submit( function() { return validate(); } );
});

//---------------------------------------------------------------------------------------------------------

function allValidChars(email) {
	var validchars										= "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
	for (var i=0; i < email.length; i++) {
		var letter										= email.charAt(i).toLowerCase();
		if (validchars.indexOf(letter) == -1) {
			return false;
		}
	}
	return true;
}

function isValidEmail(email) {
	if (email == null) { return false; }
	if (email.length < 9) { return false; }          								// there must be at least 9 characters
	if (!allValidChars(email)) { return false; }									// all characters must be valid
	if (email.indexOf("@") < 1) { return false; }    							// must contain @, and it must not be the first character
			
	// There must not be more than one @		
	var atcount											= 0;
	for (var i=0; i < email.length; i++) {
		var letter										= email.charAt(i).toLowerCase();
		if (letter == "@") { atcount++; }
	}
	if (atcount > 1) { return false; }																	
																					
	if (email.lastIndexOf("@") == email.length-1) { return false; }				// @ must not be the last character
	if (email.indexOf(".") < 1) { return false; }								// dot must not be the first character
	if (email.indexOf("..") >= 0) { return false; }                              // two dots in a row is not valid
    if (email.lastIndexOf(".") <= email.indexOf("@")) { return false; }         	// last dot must be after the @
    if (email.lastIndexOf(".") == email.length-1) { return false; }              // dot must not be the last character
    return true;
}

//--------------------------------------------------------------------------------------------------------- Contact

function checkField(field,type,limit) {
	$err												= "";
	if ($(field).val() == ''){ $err = "Please complete this field"; }
	if (type == 2 && !isValidEmail($(field).val())) { $err = "Please provide a valid email address"; } // Type 1 is a generic field, 2 is an email address
	if (limit > 0 && $(field).val().length > limit) { $err = "Please make this <strong>"+limit+" characters or less</strong>"; } // limit 0 is a field with no limit
	if ($err != "") { $(field).addClass("err").after("<p class=\"err\"><em>"+$err+"</em></p>"); $errNo++; }
}

function validate() {
	
	$errNo												= 0;
	$("p.err").remove();
	$(".err").removeClass("err");
	
	checkField("#name_first",1,30);
	checkField("#name_last",1,30);
	checkField("#email",2,50);
	checkField("#message",1,0);
	
	//$("form").find("p.err").fadeIn("slow");
	
	$("p.err").fadeIn("normal");
	
	if ($errNo > 0) { return false; }
	
}
