/* SCRIPTS */

// function to validate phone number
function checkPhone(field) {
	var pNum = field.value;
	var cleanNum=""; 
	var index = 0; 
	var LimitCheck;

 	//Get the length of the inputted string, to know how many characters to check
 	LimitCheck = pNum.length;
 
 	//Walk through the inputted string and collect only number characters, appending them to cleanNum
 	while (index != LimitCheck) { 
  		if (isNaN(parseInt(pNum.charAt(index)))) { } 
  		else { cleanNum = cleanNum + pNum.charAt(index); } 
  		index = index + 1; 
 	}
 
 	//If cleanNum is exactly 10 digits long, then format it and allow form submission
 	if (cleanNum.length == 10) { 
  		field.value = cleanNum.substring(0,3) + "-" + cleanNum.substring(3,6) + "-" + cleanNum.substring(6,10); 
		return true;
	 } else { 
  		cleanNum = pNum;
		return false;
	}
}

// function to validate email
function checkEmail(str) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)){
		return true;
	} else {
		return false;
	}
}

// function to validate form
function checkForm(theForm){
	var errorMsg = "Please correct these errors:\n\n";
	var errorCount = 0;
	// check for firstname
	if (theForm.elements['firstname'].value == ""){
		errorCount++;
		errorMsg += "- Enter your first name\n";
	}
	// check for lastname
	if (theForm.elements['lastname'].value == ""){
		errorCount++;
		errorMsg += "- Enter your last name\n";
	}
	// check for email
	if ((theForm.elements['email'].value == "") || (!checkEmail(theForm.elements['email'].value))){
		errorCount++;
		errorMsg += "- Enter a valid email address\n";
	}
	// check for phone
	if (!checkPhone(theForm.elements['phone'])){
		errorCount++;
		errorMsg += "- Enter a 10-digit phone number\n";
	}
	// check for price selection
	var priceField = theForm.elements['price'];
	var priceValue = priceField.options[priceField.selectedIndex].value;
	if (priceValue < 1 || priceValue == ""){
		errorCount++;
		errorMsg += "- Please select a price range\n";
	}
	// check for timeframe selection
	var timeField = theForm.elements['time'];
	var timeValue = timeField.options[timeField.selectedIndex].value;
	if (timeValue < 1 || timeValue == ""){
		errorCount++;
		errorMsg += "- Please select a time range\n";
	}
	// are there errors?
	if (errorCount > 0){
		errorMsg += "\nThen resubmit the form. Thank you.";
		alert(errorMsg);
		return false;
	} else {
		return true;
	}
}