/****************************************************************
 * Validate forms
 */
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateName(theForm.contact_name);
  reason += validateEmail(theForm.email);
  reason += validatePhone(theForm.contact_number);
      
  if (reason != "") {
    alert("The fields highlighted in red need correction:\n\n" + reason);
    return false;
  }

  return true;
}

// Check if form is empty

function validateName(fld) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Crimson'; 
        error = "Please enter a contact name.\n\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

// Check if email is valid

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Crimson';
        error = "Please enter an email address.\n\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Crimson';
        error = "Please enter a valid email address.\n\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Crimson';
        error = "The email address contains illegal characters.\n\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter a phone number.\n";
        fld.style.background = 'Crimson';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n\n";
        fld.style.background = 'Crimson';
    } else if (!(stripped.length == 11)) {
        error = "The phone number is the wrong length.\nPlease type the pnone number including the area code.\n\n";
        fld.style.background = 'Crimson';
    }
    return error;
}