////////////////////////////////////////////////////////////////////////////////////////

/*/
	VERIFIES:
		EMPTY FIELDS ON REQUIRED ITEMS
		EMAIL ADDRESSES
		ZIP CODES (US and CA) 
		PHONE NUMBERS ON ANY FORM.  
				
	USAGE:
		1) ATTACH validate.js: 
			<script language="JavaScript1.2" src="validate.js" type="text/javascript"></script>
		2) CALL FUNCTION: 
			<form... onSubmit="return validateForm(this);">
		3) MARK REQUIRED FORM ELEMENTS 
			<TAG... name="rqd_NAME">

/*/

////////////////////////////////////////////////////////////////////////////////////////

var specialType = false; // Used in detectTypeFromName - email, phone and zip validation

//Display an error message, jump to the field and select the contents
function showError(item,msg)
{
	alert(msg);
	if (item.focus) item.focus();
	
	if (item.select) item.select();
}

//Check to see if a form field is empty
function isEmpty(item)
{
	if (item.value.length < 1)
		return true
	else
		return false;
}

//Check for a properly formatted email address
function isInvalidEmail(item)
{
	var email_pattern = /[\S|\.]+@\S\S+\.\D\D+/gi;
	var result = item.value.match(email_pattern);
	if (result || isEmpty(item)) 
		return false
	else
		return true;
}

//Check for a properly formatted United States Zip Code
function isInvalidUSZip(item)
{
	var zipcode_pattern = /^\d{5}$|^\d{5}[\-\s]?\d{4}$/;
	var result = item.value.match(zipcode_pattern);
	if (result || isEmpty(item)) 
		return false
	else
		return true;
}

//Check for a properly formatted Canadian Zip Code
function isInvalidCanadianZip(item)
{
	var zipcode_pattern = /[A-Z]{1}[0-9]{1}[A-Z]{1}\s{1}[0-9]{1}[A-Z]{1}[0-9]{1}/;
	var result = item.value.match(zipcode_pattern);
	if (result || isEmpty(item)) 
		return false
	else
		return true;
}

function isInvalidUSPhone(phoneNumber)
{
	var rawNumber = phoneNumber.value;
	// Strip the possible garbage: hyphens, parens, etc.
	rawNumber = rawNumber.replace(/-/g,"");		//remove hyphens
	rawNumber = rawNumber.replace(/\s/g,"");	//remove whitespace
	rawNumber = rawNumber.replace(/\./g,"");	//remove periods
	rawNumber = rawNumber.replace(/\(/g,"");	//remove left parens
	rawNumber = rawNumber.replace(/\)/g,"");	//remove right parens

	var ten_numbers = /[0-9]{10}$/;
	var result = rawNumber.match(ten_numbers);
	if (result || isEmpty(phoneNumber)) 
		return false
	else
		return true;
}

function detectTypeFromName(theInputName)
{
	if (theInputName.indexOf("email") > -1) {
		specialType = "email";
	}
	else if (theInputName.indexOf("phone") > -1) {
		specialType = "phone";
	}
	else if (theInputName.indexOf("zip") > -1) {
		specialType = "zip";
	}
	else specialType = false
}

function properCase(text)
{
	// Capitalize the first letter of each distinct word, lowercase the rest
	var words = text.split(' ');
	for (x=0; x<words.length; x++) {
		var first_letter = words[x].charAt(0);
		var upper_first_letter = first_letter.toUpperCase();
		var len = words[x].length -1;
		var complete_word = upper_first_letter + words[x].substr(1,len).toLowerCase();
		words[x] = complete_word;
	}
	var sentence = words.join(' ');
	return sentence;
}

function niceAlert(theInputName)
{
	// Used in the alert box - take the input.name and clean it up
	// Strip rqd_, rqd, replace "_" with " ", Proper Case 
	theInputName = theInputName.replace(/rqd_/gi,"") // Strip rqd_
	theInputName = theInputName.replace(/rqd/gi,"") // Strip rqd
	theInputName = theInputName.replace(/_/gi," ") // Replace "_" with " "
	theNiceInput = properCase(theInputName) // Proper Case 
	niceMessage = "Please enter your ";
	niceMessage += theNiceInput;
	return niceMessage;
}

function validateForm(theForm)
{
	for (var i=0; i<theForm.elements.length; i++) {
		var emptyOK = false; // assume required 

		// Check to see if it's a special case - if so, set specialType
		detectTypeFromName(theForm.elements[i].name);

		if (specialType=="email") {
			if ((isInvalidEmail(theForm.elements[i]))) {
				showError(theForm.elements[i],'Please enter a valid email address.');
				return false;
			}
		}
		
		if (specialType=="phone") {
			if (isInvalidUSPhone(theForm.elements[i])) {
				showError(theForm.elements[i],'Please enter a valid 10 digit phone number.');	
				return false;
			}
		}
		
		if (specialType=="zip") {
			if (isInvalidUSZip(theForm.elements[i]) && isInvalidCanadianZip(theForm.elements[i])) {
				showError(theForm.elements[i],'Please enter a valid email US or Canadian zip code.');	
				return false;
			}
		}
		
		// Check to see if the field is required 		
		if (theForm.elements[i].name.indexOf("rqd") == -1) {
			emptyOK = true;
		}
		// If not required, check the next item
		if (emptyOK == true) {
			continue;
		}
		// Check to see if empty
		if (theForm.elements[i].type.indexOf("select") > -1) { // Selects work differently...
			if (isEmpty(theForm.elements[i].options[theForm.elements[i].selectedIndex])) { // need to check 'select.OPTION[X].value'
				showError(theForm.elements[i],niceAlert(theForm.elements[i].name));
				return false;
			}
		}
		else if (isEmpty(theForm.elements[i]) && theForm.elements[i].type.indexOf("select") == -1) {
			showError(theForm.elements[i],niceAlert(theForm.elements[i].name));	
			return false;
		}		
	}
	return true; 	// we're all done
}
