function validTelephone(str)
{
	// Strip all non-digits from the string
	str = str.replace(/[^\d]/g,"");
	// If there aren't 10 digits in the string
	if (str.length != 10)
	{
		// The phone number is invalid
		return false;
	}
	// Split the string into a properly formatted U.S. telephone number
	var areaCode = str.substring(0,3);
	var prefix = str.substring(3,6);
	var suffix = str.substring(6,10);
	return str = (areaCode + "-" + prefix + "-" + suffix);
}

function validZipCode(str)
{
	// Strip all non-digits from the string
	str = str.replace(/[^\d]/g,"");
	// If there aren't 10 digits in the string
	if (str.length != 5)
	{
		return false;
	}
	return str;
}

function validEmail(str)
{
	if (!str)
	{
		return false;
	}
	request = GetXmlHttpObject();
	var url = "/tests/validemail.php";
	url = url + "?email=" + str;
	request.open("POST",url,false);
	request.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8;');
	request.send(null);
	if (request.responseText == 0)
	{
		return true;
	}
	return false;
}

function validState(str)
{
	str = str.toUpperCase();
	str = str.replace(/[^A-Z]/g,"");
	if (str.length != 2)
	{
		return false;
	}
	return str;
}
function postContactForm(arr)
{
	var req = new XMLHttpRequest();
	req.open("POST","submit.php",false);
	req.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8;');
	req.send(arr);
	if (req.responseText == 1)
	{
		alert("Form submitted successfully. A representative will contact you shortly.");
		return true;
	} else {
		alert("There was an error submitting your form.");
			return false;
	}
}

function setInputError(field)
{
	field.setAttribute("class","error");
	field.setAttribute("className","error");
	field.focus();
}

function clearInputError(field)
{
	field.removeAttribute("class");
	field.removeAttribute("className");
}

//  Validate Billing Form
function validateForm()
{
	var form = document.forms["contact"];

	if (!form.company.value)
	{
		setInputError(form.company);
		alert("Please enter your company name");
		return false;
	} else {
		clearInputError(form.company);
	}
	// Make sure we get a first and last name
	if (!form.firstName.value)
	{
		setInputError(form.firstName);
		alert("Please enter your first name");
		return false;
	} else {
		clearInputError(form.firstName);
	}
	if (!form.lastName.value)
	{
		setInputError(form.lastName);
		alert("Please enter your last name");
		return false;
	} else {
		clearInputError(form.lastName);
	}

	// Validate email address
	var email = validEmail(form.email.value);
	if (!email)
	{
		setInputError(form.email);
		alert("Please enter a valid email address");
		return false;
	} else {
		clearInputError(form.email);
		form.email.value = email;
	}
	
	var telephone = validTelephone(form.telephone.value);
	if (!telephone)
	{
		setInputError(form.telephone);
		alert("Please enter a valid telephone number");
		return false;
	} else {
		clearInputError(form.telephone);
		form.telephone.value = telephone;
	}
}
