// JavaScript Document
//	Near perfect contact form
//		@Created: 	6 Jan 2008
//		@Author: 	Dan Kaltenbaugh
//		@Company:	www.Book27.com
//		@Email: 	Dan.K@Book27.com
//		@Modified: 	31 Jan 2008

function trim (inputString) {
	// Removes leading and trailing spaces from the passed string.  Also removes
	// consecutive spaces and replaces them with one space. If something besides
	// a string is passed in (null, custom object, etc.), then return the input.
	// Code from "Beginning AJAX with PHP: Lee Babin"
	if (typeof inputString != "string") {
		return inputString;
	}
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") { // Check for spaces at the beginning of the string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") { // check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) {
		// Note there are two spaces in the string
		// Therefore look for multiple spaces in the string
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
		// Again, there are two spaces in each of the strings
	}
	return retValue; // Return the trimmed string back to the user
}	// Ends the "trim function

function isEmpty(elem, helperMsg) {
	if (elem.value.length == 0) {
		alert(helperMsg);
		elem.focus();
		return true;
	} else {
		return false;
	}
}
function validate_email (elem, helperMsg) {
		var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
		if ( elem.value == 'Name@Domain.com') {  // Make sure they didn't leave the default setting in the box
			elem.value = "";
		}
		if ( elem.value.match(emailExp) ) {
			return true;
		}
		else {
			alert(helperMsg);
			elem.focus();
			return false;
		}							  
}

function validate_name (elem, helperMsg) {
	elem.value = trim(elem.value);
	return isEmpty(elem, helperMsg);
}

function validate_phone(isField){

	isPhone = isField.value;
	if (isPhone.length == 12)
	{isPhone = isPhone.replace(/\D/g,'').replace(/^(\d{3})(\d{3})/,'($1) $2-');isField.value = isPhone;}
	else if (isPhone.length > 12 && isPhone.length <= 16)
	{isPhone = isPhone.replace(/\D/g,' ').replace(/^(\d{3})( )(\d{3})/,'($1) $3-').replace(/- /,'-').replace(/( )(\d{1,3}$)/,' x $2');isField.value = isPhone;}
	else if (isPhone.length > 0 || isPhone.length < 12 || isPhone.length > 16 || isNaN(isPhone))
	{
		alert("Incorrect phone number, but it's not required anyway so let's continue :)");
		isField.value = "";
	}
}

function validate_text (elem, helperMsg) {
	elem.value = trim(elem.value);
	return isEmpty(elem, helperMsg);
}
