// Note: Making this script a separate file allows HTML validation to work without changing < to &lt;
//  This regular expression will validate the email address format
function validateEmail(em) {
  var empat = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
  return empat.test(em);
}

var emailSent = false;

function validateForm(frm) {
   if (emailSent) {
      alert("Please do not click SEND more than once.\nTry reloading the form first.");
      return false;
   }
   var mWork = frm.from.value;
   var messages = new Array();
   var spltEmail;
   var emailError = false;
   emailError = ! validateEmail(mWork);

   if (emailError)
       messages[messages.length] = "A non-blank Email Address in correct" +
              " Internet format is required.";

   var mWorkT;
   mWork = frm.subject.value;
   mWorkT = trimIt(mWork);
   if (mWork != mWorkT) frm.subject.value = mWorkT; // stick in the trimmed value
   if (mWorkT.length < 4)
       messages[messages.length] = "The Email subject must not be blank and" +
              " it must include at least 4 characters.";

   mWork = frm.body.value;
   mWorkT = trimIt(mWork);
   if (mWork != mWorkT) frm.body.value = mWorkT; // stick in the trimmed value
   if (mWorkT.length < 4)
       messages[messages.length] = "The Email message body must not be blank and" +
              " it must include at least 4 characters.";

   if (messages.length > 0) {
      alert("Invalid Email request:\n\n" + messages.join("\n"));
      return false;
   } else {
     emailSent = true;
     return true;
   }
}

function trimIt(inp) {
   var cW;
   var first = 0, last = inp.length;
   for (;first < last; first ++) {
     cW = inp.charAt(first);
     if (cW != ' '
         && cW != '\t'
         && cW != '\n'
         && cW != '\r') break;
   }
   for (;first < last; last --) {
     cW = inp.charAt(last-1);
     if (cW != ' '
         && cW != '\t'
         && cW != '\n'
         && cW != '\r') break;
   }

   return inp.substring(first,last);
}

