// JavaScript Document

var regEx = new RegExp("")

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

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

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

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

	//check required fields - Email Address
	if(!checkFilled(form1.email, "email")) return
	if(!validateEmail(form1.email)) return
	
	//check for address if sample checkbox is selected
	if(form1.request_sample.checked == true){
		if(!checkStreetFilled(form1.street, "street")) return
		if(!checkCityFilled(form1.city, "city")) return
		if(!checkStateFilled(form1.state, "state")) return
		if(!checkZipFilled(form1.zip, "zip")) return
	}
	form1.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
	}
}

function checkStreetFilled(ctl, str){
	if(ctl.value.length == 0){
		alert("Please fill in the street name and number to receive our free sample")
		ctl.focus()
		return false
	}
	return true
}

function checkCityFilled(ctl, str){
	if(ctl.value.length == 0){
		alert("Please fill in the city field to receive our free sample")
		ctl.focus()
		return false
	}
	return true
}

function checkStateFilled(ctl, str){
	if(ctl.value.length == 0){
		alert("Please fill in the state field to receive our free sample")
		ctl.focus()
		return false
	}
	return true
}

function checkZipFilled(ctl, str){
	if(ctl.value.length == 0){
		alert("Please fill in the Zipcode field to receive our free sample")
		ctl.focus()
		return false
	}
	return true
}