

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}

/* --------------------------------------------------------------*/
/* DIRTY                                                         */

var isDirty=false;
var suppressIsDirty=false;

function confirmExit() {
   if (!suppressIsDirty && isDirty)
      return "Your changes have not been saved and will be lost if you leave this page.";
}

function confirmChangeData() {
   if (!suppressIsDirty && isDirty)
      return confirm("Your changes have not been saved.  Discard your changes?");
   return true;
}

function setIsDirty() {
   isDirty=true;
}

function addFormIsDirtyFunctions(formIndex) {
   var theForm = document.forms[formIndex];
   for(i=0; i<theForm.elements.length; i++){
      //b/c on change only triggers when focus is lost
      if(theForm.elements[i].type=='text')
         theForm.elements[i].onkeypress=setIsDirty;
      else
         theForm.elements[i].onchange=setIsDirty;
   }
   window.onbeforeunload=confirmExit;

   isDirty=false;
   suppressIsDirty=false;
}


/* --------------------------------------------------------------*/
/* VALIDATION                                                    */

function isValidEmail(elem, userFriendlyName) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = elem.value;
   if(reg.test(address) == false) {
     alert('"' + userFriendlyName + '" is not valid.');
     focusElement(elem);
     return false;
   }
   return true;
}

function validateFileExtension(elem) {
   var str = elem.value.toLowerCase();
   if (str.trim()=='')
      return true;

   if(!/(\.|\.gif|\.jpg|\.jpeg|\.png|\.gif|\.doc|\.txt|\.rtf|\.pdf|\.zip)$/i.test(str)) {
      alert("Invalid attachment file type. File attachments must be of type: JPG (or JPEG), PNG, GIF, DOC, TXT, RTF, PDF, or ZIP.");
      elem.focus();
      return false;
   }
   return true;
}


function isNotEmpty(elem, userFriendlyName) {
   var str = elem.value;
   if (str.trim()=='') {
     alert('"' + userFriendlyName + '" is required.');
     focusElement(elem);
     return false;
   }
   return true;
}

function focusElement(elem) {
    elem.focus();
    elem.select();
}

function validateForm() {
   return (validateFileExtension(document.forms[0].attachment) && isNotEmpty(document.forms[0].name, 'Your Name') && isNotEmpty(document.forms[0].email, 'Your Email') && isValidEmail(document.forms[0].email, 'Your Email') &&  isNotEmpty(document.forms[0].message, 'Message') );
}
