// checks that an input string looks like a valid email address.
var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
var passed = true;
var validEmail = true;
var validFields = true;
var currentField;

// Check if a string matches the email reg ex
function isEmail(s) {
	return String(s).search (isEmail_re) != -1;
}
// Validate an email field and append error
function validateEmail(s){
	validEmail = isEmail(s);
	if (!validEmail) {
		$("#errors").append("&bull; Please provide a valid email address.<br />");
	}	
}
// Test if a field is empty, append error or strip semi colons and percent signs
function validateForEmpty(fieldValue, fieldDesc, fieldRel){
	if (fieldValue.length == 0 || fieldValue == fieldRel){
		$("#errors").append("&bull; Please provide your " + fieldDesc +".<br />");
		validFields = false;
	} 
}	
// Sanitize a string replacing semi colons and percent signs
function stripSemiColonsPercent(fieldValue){
	fieldValue=fieldValue.replace(/;/g, ",");
	fieldValue=fieldValue.replace(/%/g, " percent");	
	return fieldValue;
}
// Sanitize any number of fields - use this if there are multiple fields which are not required on a form
function sanitizeInputs(){
	for(var i=0; i<arguments.length; i++){
		document.getElementById(arguments[i]).value = stripSemiColonsPercent(document.getElementById(arguments[i]).value);
	}
}
// Check any number of fields from a form to see if they are blank
function validateForm(){
	$("#errors").css("display", "none"); // Initially hide errors	
	$("#errors").html(""); // Clear the div
	passed = true;
	validEmail = true;
	validFields = true;	
	for(var i=0; i<arguments.length; i++){
		elemName = arguments[i]; 
		currentField = document.getElementById(elemName);
		$(currentField).val(stripSemiColonsPercent($(currentField).val())); // Sanitize input
		if (elemName == "email"){
			validateEmail(document.getElementById(elemName).value); // Check for a valid email address 
		} else {
			validateForEmpty($(currentField).val(), $(currentField).attr("title"), $(currentField).attr("rel")); // Check for a blank field
		}
	}
	if (!validEmail || !validFields){
		passed = false;
	}
	if (passed){
		return true;
	} else { // Slide the error div in, animate a yellow to white fade on the background
		$("#errors").css("background-color", "#FFFFCC");
		$("#errors").slideDown(250);
		//$('#errors').animate({ backgroundColor: "#ffffff" }, 'slow');
		return false;
	}
}
