// ContactForm.js

function validateForm(theForm) {
	var reason ="";
	
	reason += validateEmpty(theForm.name, "Name");
	reason += validatePhone(theForm.phone);
	reason += validateEmail(theForm.email);
	reason += validateEmpty(theForm.address, "Address");
	reason += validateEmpty(theForm.city, "City");
	reason += validateZip(theForm.zip);
	reason += validateEmpty(theForm.helpText, "helpText");
	
	if (reason != "")
	{
		alert("Some fields need correction:\n" + reason);
		return false;
	}
	
	return true;
	
}

function validateEmpty(fld, fldName) {
	
	var error ="";
	
	if (fld.value.length == 0) 
	{
		fld.style.background =  '#FF8080';
		
		if (fldName == 'helpText') {
			error = "You did not enter anything in the \"How can we help filed\".\n";
		}
		
		else {
			error = "Please enter your " + fldName + ".\n";
		}
		
		
	}
	else {
		fld.style.background = '#FF9';
	}
	return error;
}


function trim(s)
{
	return s.replace(/^\s+|\s+$/, '')
}

function validateEmail(fld) {
	var error ="";
	var tfld = trim(fld.value);
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
	
	if (fld.value =="") {
		fld.style.background = '#FF8080';
		error = "You didn't enter an email address.\n";
	}
	else if (!emailFilter.test(tfld)) {
		fld.style.background = '#FF8080';
		error = "Please enter a valid email address.\n";
	}
	else if (fld.value.match(illegalChars)) {
		fld.style.background = '#FF8080';
		error = "The email address contains illegal characters.\n";
	}
	else {
		fld.style.background = '#FF9';
	}
	return error;
}


function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (fld.value == "") {
        error = "You didn't enter a phone number.\n";
        fld.style.background = '#FF8080';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        fld.style.background = '#FF8080';
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = '#FF8080';
    } 
    return error;
}

function validateZip(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (fld.value == "") {
        error = "You didn't enter a zip code.\n";
        fld.style.background = '#FF8080';
    } else if (isNaN(parseInt(stripped))) {
        error = "The zip code contains illegal characters.\n";
        fld.style.background = '#FF8080';
    } else if (!(stripped.length == 5)) {
        error = "The zip code is the wrong length.\n";
        fld.style.background = '#FF8080';
    } 
    return error;
}


