// JavaScript Document

//trim function from http://snippets.dzone.com/posts/show/701
// Removes leading whitespaces
function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}
// Removes ending whitespaces
function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}
// Removes leading and ending whitespaces--trimming function
function trim( value ) {
	return LTrim(RTrim(value));
}


function isEmpty(strng, fieldname, id) {
  if (strng == null || strng == "") {
  	  strng = "";
  }
  if (fieldname=="") {
	  fieldname="Name"
  }
  var error = "";
	  strng = trim(strng);
  if (strng.length == 0) {
  	fieldname.style.border = '1px solid red'; 
	error = "-" + id + " is a required field.\n";
  }
  if (strng.length > 0){
	   fieldname.style.border = '1px solid #AAD6EC';
  }
  return error;	  
}

function validatePhone (strng, fieldname) {
  var error = "";
  var stripped = strng.replace(/[\(\)\.\+\/\-\ ]/g, ''); //strip out acceptable non-numeric characters
  if (isNaN(parseInt(stripped))) {
    fieldname.style.border = '1px solid red';
	error = "- The phone number contains illegal characters.\n";
  }
  if (!(stripped.length >= 10)) {
    fieldname.style.border = '1px solid red';
	error = "- Please make sure the phone number is at least 10 digits.\n";
  } 
  return error;
}

function validateEmail (strng, fieldname) {
  var error="";
  
  var emailFilter=/^.+@.+\..{2,3}$/;
  if (!(emailFilter.test(strng))) { 
    fieldname.style.border = '1px solid red';
	error = "- Please enter a valid email address.\n";
  } else {
    //test email for illegal characters
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
    if (strng.match(illegalChars)) {
      fieldname.style.border = '1px solid red';
	  error = "- The email address contains illegal characters.\n";
    }
  }
  return error;    
}


//process form, call all validations
function validateForm(theForm, which) {
	var reason = "";
	switch (which) {
		case 'Contact Page':
  			reason += isEmpty(theForm.cfname.value, theForm.cfname, theForm.cfname.id);
 			reason += isEmpty(theForm.clname.value, theForm.clname, theForm.clname.id);
  			reason += isEmpty(theForm.cfemail.value, theForm.cfemail, theForm.cfemail.id);
 			reason += validateEmail(theForm.cfemail.value, theForm.cfemail);
			break;
		case 'left':
			reason += isEmpty(theForm.fname.value, theForm.fname, theForm.fname.id);
 			reason += isEmpty(theForm.fphone.value, theForm.fphone, theForm.fphone.id);
			reason += validatePhone(theForm.fphone.value, theForm.fphone);
  			reason += isEmpty(theForm.femail.value, theForm.femail, theForm.femail.id);
 			reason += validateEmail(theForm.femail.value, theForm.femail);
			break;
		}
  if (reason != "") {
   // alert("Some fields need correction:\n" + reason);
    return false;
  }

  return true;
}