// JavaScript Document

var regEx = new RegExp("")

function validateForm(){
	var form2 = document.form2;

	//check required fields - Requestor Name
	if(!checkNameFilled(form2.name, "name")) return

	//check required fields - Phone
	if(!checkFilled(form2.phone, "phone")) return

	if(form2.phone.value.length != 0) {
		if(!checkPhoneNum(form2.phone, "phone")) return
	}

	//check required fields - Email Address
	if(!checkFilled(form2.email, "email")) return
	if(!validateEmail(form2.email)) return
	
	
	form2.submit();
}

//functions

function checkNameFilled(ctl, str){
	if(ctl.value.length == 0){
		alert("Please fill in the Name field before submitting your information")
		ctl.focus()
		return false
	}
	return true
}

function checkFilled(ctl, str){
	if(ctl.value.length == 0){
		alert(str + " is a required field. Please fill it in prior to submitting your information.")
		ctl.focus()
		return false
	}
	return true
}

function validateEmail(ctl){
	regEx = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/
	if(!regEx.test(ctl.value)){
		alert("The email address you entered is invalid.")
		return false
	}
	return true
}

function checkPhoneNum(ctl, desc) {
	var str = ctl.value;
	var phoneNum = "";
	var i = 0;


	while (i != str.length) {
		if(!isNaN(parseInt(str.charAt(i)))){ 
			phoneNum = phoneNum + str.charAt(i); 
		}
		i = i + 1;
	}
	if(phoneNum.length == 10) {
		ctl.value = "(" + phoneNum.substring(0,3) + ") " + phoneNum.substring(3,6) + "-" + phoneNum.substring(6,10);
		return true
	}else{
		ctl.value = str;
		alert("The " + desc + " you have entered is invalid.");
		ctl.focus()
		return false
	}
}

