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 = 'Yellow';
        error = "Please enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validateName(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your name.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validateMessage(fld){
	  var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter a message.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validateContact(fld){
    	var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

    if(fld.value != ""){
    if (isNaN(parseInt(stripped))) {
        error = "The contact number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    }
	}
    return error;
}

function validateFax(fld){
	    	var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, ''); 
	   
    if(fld.value != ""){
    if (isNaN(parseInt(stripped))) {
        error = "The fax number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    }
	}
    return error;
}

function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateName(theForm.name);
  reason += validateContact(theForm.contact);
  reason += validateFax(theForm.fax);
  reason += validateEmail(theForm.email);
  reason += validateMessage(theForm.enquiry);
      
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }else{
     theForm.submit(); 
  }

  return true;
}




