/**----------------------------------------------------------------------------------
This is a generic set of functions for validating form fields before submitting the
form.  The main function is validateField().  In most cases you simply pass the 
field's name as a string, the label you want to use for the field as a string and
an array of function names you want the field validated against.

Example:

validateField("myFieldName", "Really Cool Field", ["zeroLength","justWhiteSpace"])

This call would check to see if the field's value was zero length or just white space.
If the validation finds any of these conditions to be true, if returns a string with
the field label and an error message for each error.

Example:

Really Cool Field - Cannot be empty.

Adding new functions to check for more conditions is easy.  Just create a function
with a nice descriptive name that returns a string indicating the error message if
the condition fails the test. The naming convention is to name the function for the 
state that would cause an error.  "zeroLength" errors if the value of the field has
a length of zero.  "notStateAbbreviation" errors if the value of the field is not a 
valid State abbreviation. The following functions already exist, please add your
functions to the list as you create them. 

zeroLength
justWhiteSpace
notJustLettersAndSpaces
notJustLetters
notJustNumbers
notJustCapitalLetters
notStateAbbreviation
notCanadaOrUSAZipCode
notValidEmailAddress
notValidPhone
notValidMoney
isChooseCity
badFileExtensions
badEmailList 
badPROList
badLinearFeet
badShipmentWeight
checkBoxNotEmpty


I've also created some standard validation checks for common fields.  These should
be fairly standard throughout the application.  The arrays are global to the page
and can be put in the validateField() call. The names of these arrays follow.

simplyRequired
standardValidCompanyName
standardValidAddress
standardValidCity
standardAttachmentExtensions
standardValidState
standardValidZipCode
standardValidName
standardValidEmail
standardValidPhone
standardValidMoney
standardValidPRO
standardListOfEmails
standardListOfPROs
standardDate
standardLinearFeet
------------------------------------------------------------------------------------**/
var standardValidCompanyName = ["zeroLength","justWhiteSpace"];
var standardValidAddress = ["zeroLength","justWhiteSpace"];
var standardValidCity = ["zeroLength","justWhiteSpace","isChooseCity"];
var standardValidState = ["zeroLength","notJustCapitalLetters","notStateAbbreviation"];
var standardAttachmentExtensions = ["badFileExtensions"];
var standardValidZipCode = ["notCanadaOrUSAZipCode"];
var standardValidName = ["zeroLength","justWhiteSpace","notJustLettersAndSpaces"];
var standardValidEmail = ["notValidEmailAddress"];
var standardValidPhone = ["notValidPhone"];
var standardValidMoney = ["zeroLength","notValidMoney"];
var standardValidPRO = ["notJustNumbers"];
var standardListOfEmails = ["badEmailList"];
var standardListOfPROs = ["badPROList"];
var simplyRequired = ["zeroLength"];
var standardWholeNumber = ["isWholeNumber"];
var standardDate = ["isStandardDate"];
var standardLinearFeet = ["zeroLength","isWholeNumber","badLinearFeet"];
var standardShipmentWeight = ["zeroLength","isWholeNumber","badShipmentWeight"];

var regexSpace=/\S/;
var regexLettersAndSpaces = /[^a-zA-Z\s?]/;
var regexLetter = /[^a-zA-Z]/;
var regexNumber = /[^0-9]/;
var regexFloat = /^[0-9]*\.?[0-9]*?$/;
var regexCapLetters = /[^A-Z]/;
var regexZip = /(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/i;
var regexEmail = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
var regexPhone = /^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}/;
var regexMoney = /^\$?[0-9]+(,[0-9]{3})*(\.[0-9]{2})?$/;
var regexWholeNumber = /^[1-9]+[0-9]*$/;
var regexDate = /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/;

// Use this to test for valid state abbreviations.
var stateAbbreviations = ["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA",
							"KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ",
							"NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT",
							"VA","WA","WV","WI","WY"];
							
function validateField(fieldName, fieldLabel, validations)
{
	var errorMessage = "";
	var field = $(fieldName);
	var tempMessage = "";
	var validationArray = $A(validations);
	var currentValidation = "";

	try
	{
		for (var index = 0; index < validationArray.size(); index++)
		{
			currentValidation = validationArray[index] + "(field)";
			tempMessage = eval(currentValidation);
			
			if (tempMessage != null && tempMessage.length > 0)
			{
				errorMessage += createErrorMessage(fieldLabel, tempMessage);
			}
		}
	}
	catch (ex)
	{
		return "\r\nvalidateField Exception: " + ex.name + " - " + ex.description + "\r\n"
				+ "FieldName: " + fieldName + "\r\n"
				+ "FieldValue: " + field.inspect() + "\r\n"
				+ "Validations: " + validationArray.inspect() + "\r\n"
				+ "Function: " + currentValidation + "\r\n\r\n";
	}
	
	if (errorMessage.length > 0)
	{
		setFieldAsInvalid(field);
	}
	else
	{
		setFieldAsValid(field);
	}
	return errorMessage;
}

function setFieldAsInvalid(field)
{
	field.style.backgroundColor ='palegoldenrod';
}

function setFieldAsValid(field)
{
	field.style.backgroundColor ='white';
}

function justWhiteSpace(field)
{
	var msg = "";
	
	if (field == null) return "Error: justWhiteSpace Null field.\r\n";
	
	if (!regexSpace.test(field.getValue()))
	{
		msg = "Cannot be just blank spaces.";
	}
	return msg;
}

function zeroLength(field)
{
	var msg = "";
	
	if (field == null) return "Error: zeroLength Null field.";
	
	if (field.getValue().length < 1)
	{
		msg = "Cannot be empty.";
	}
	return msg;
}

function isChooseCity(field)
{
	msg = "";
	
	if (field.getValue() == "Choose City" ||field.getValue() == "Enter Zip Code")
	{
		msg = "Must choose a City.";
	}
	return msg;
}

function notJustLettersAndSpaces(field)
{
	msg = "";
	
	if (regexLettersAndSpaces.test(field.getValue()))
	{
		msg = "Can only contain letters and spaces.";
	}
	return msg;
}

function notJustLetters(field)
{
	msg = "";
	
	if (regexLetter.test(field.value))
	{
		msg = "Can only contain letters.";
	}
	return msg;
}

function notJustNumbers(field)
{
	
	msg = "";
	
	if (regexNumber.test(field.value))
	{
		msg = "Can only contain numbers.";
	}
	return msg;
}

function isWholeNumber(field)
{
	
	msg = "";
	
	if (!regexWholeNumber.test(field.value))
	{
		msg = "Can only contain whole numbers.";
	}
	return msg;
}

function isFloat(field)
{
	
	msg = "";
	
	if (!regexFloat.test(field.value))
	{
		msg = "Must contain valid decimals.";
	}
	return msg;
}

function badLinearFeet(field)
{	
	var msg = "";
	var feet = field.value;
	
	if(!(feet > 0 && feet <= 53))
	{		
		msg = "Linear Feet should be between 1 and 53";
	}
	return msg;
}

function badShipmentWeight(field)
{	
	var msg = "";
	var weight = field.value;
	
	if(!(weight > 0 && weight <= 48000))
	{
		msg = "Weight should be between 1 and 48000";
	}

	return msg;
}

function isStandardDate(field)
{
	
	msg = "";
	
	if (!regexDate.test(field.value))
	{
		msg = "Date is not in MM/DD/YYYY format, or a valid date has not been entered.";
	}
	return msg;
}

function notJustCapitalLetters(field)
{
	msg = "";
	
	if (regexCapLetters.test(field.value))
	{
		msg = "Can only contain capital letters.";
	}
	return msg;
}

function notStateAbbreviation(field)
{
	msg = "";
	
	field.value = field.value.toUpperCase();
	if (stateAbbreviations.indexOf(field.value) < 0)
	{
		msg = "Must be a state abbreviation.";
	}
	return msg;
}

function notCanadaOrUSAZipCode(field)
{
	msg = "";
	
	if (!regexZip.test(field.value))
	{
		msg = "Not a valid US or Canadian zip code.";
	}
	return msg;
}

function notValidEmailAddress(field)
{
	var msg = "";
	
	if (!regexEmail.test(field.value))
	{
		msg = "Not a valid email address.";
	}
	return msg;
}

function notValidPhone(field)
{
	var msg = "";
	
	if (!regexPhone.test(field.value))
	{
		msg = "Not a valid phone number.";
	}
	return msg;
}

function notValidMoney(field)
{
	var msg = "";
	
	if (!regexMoney.test(field.value))
	{
		msg = "Not a valid monetary value.";
	}
	return msg;
}

// badFileExtensions is a little different from the other functions here.
// It gets the regular expression to match against off the field that is 
// being checked.  Add a property called "validExtensions" to the field in the
// HTML or JSP file.  It should look like this: 
// validExtensions="^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$"
function badFileExtensions(field)
{
	if (field.value != null && !field.value.empty())
	{
		var regex = new RegExp(field.getAttribute("validExtensions"));
		if (!regex.test(field.value)) 
		{ 
	     	return  "Invalid file extension.";
	    } 
	}
	return "";
}

function badEmailList(field)
{
	var tempField = new Object;
	var emailArray = splitByLine(field.value);
	var msg = "";
	var tempMsg = "";
	var x;
	
	for (x = 0; x < emailArray.size(); x++)
	{
		tempField.value = emailArray[x].strip();
		tempMsg = notValidEmailAddress(tempField);
		if (!tempMsg.blank())
		{
			if (x == 0)
			{
				msg += tempField.value + ": " + tempMsg + "; ";
			}
			else
			{
				msg += "\r\n   " + tempField.value + ": " + tempMsg + "; ";
			}
		}
	}

	return msg.substring(0, msg.length - 2);
}

function checkBoxNotEmpty(field)
{
	var somethingChecked = false; // = "";
	var checkFields = $A(document.getElementsByName(field));
	
	for (x = 0; x < checkFields.length; x++)
	{
		if ($(checkFields[x]).getValue() != null)
		{
			somethingChecked = true;
			break;
		}
	}
	
	if (somethingChecked)
	{
		return "";
	}
	else
	{
		return "You must check at least 1 option.";
	}
}

function badPROList(field)
{
	var tempField = new Object;
	var proArray = splitByLine(field.value);
	var msg = "";
	var tempMsg = "";
	var x;
	
	for (x = 0; x < proArray.size(); x++)
	{
		tempField.value = proArray[x].strip();
		tempMsg = notJustNumbers(tempField);
		if (!tempMsg.blank())
		{
			if (x == 0)
			{
				msg += tempField.value + ": " + tempMsg + "; ";
			}
			else
			{
				msg += "\r\n   " + tempField.value + ": " + tempMsg + "; ";
			}
		}
	}

	return msg.substring(0, msg.length - 2);
}

function splitByLine(strVal)
{
	var localVal = strVal.replace(new RegExp("\\n", "g"), "~");
	return localVal.split("~");
}

function createErrorMessage(fieldLabel, message)
{
	return fieldLabel + " - " + message + "\r\n";
}

