var SHOW_ERRORS = false;

/************************************************
* This function will validate all elements in
* a given form which have a class value 
* containing the word required.
* For select boxes, it will require the user to
* select something other than the first (default)
* option.  Change: If there is a
* parent node surrounding the select, then it will
* be highlighted  --Gene
* For radio buttons, it will require that one of
* the options has been selected. If there is a
* parent node surrounding the set of radio buttons
* (that is not the form itself), then it will be
* highlighted.
* For text boxes, it will do an additional check
* to see if the element name contains the word
* "email". If it does, it will try to validate
* the email address using another function called
* validateEmail().
* This does not cover "file-select" fields.
*************************************************/
function validateForm(theForm)
{
   var isValid = true;  // Give the user the benefit of the doubt.

   var errorMessage = "Please fill out all required fields.\nMissing or unselected items are marked in red.\nThank you.";

   for(a = 0; a < theForm.elements.length; a++)
   {
      var thisField = theForm.elements[a];   // Get the element.
      var thisClass = thisField.className;   // Get the class name.

      // If it's required...
      if(thisClass.indexOf("required") != -1)
      {
         // ... make sure it's valid!
         if(thisField.type == "select-one")
         {
            if(thisField.selectedIndex == 0)
            {
               thisField.parentNode.style.border = "1px solid red";
               isValid = false;
            }
         }
         else if(thisField.type == "text")
         {
              if(trimAll(thisField.value) == "")
              {
            thisField.style.border = "1px solid red";             
            isValid = false;
              }
              else 
              {
               var fieldName = thisField.name;
               var mailpat =/email/i;
               if (fieldName.match(mailpat) != null )
               {
                  var emailStr = thisField.value;
                  if(!validateEmail(emailStr, SHOW_ERRORS))
                  {
                     isValid = false;
                     errorMessage = "Please enter a valid email address.";
                  }
               }
              }
         }
         else if(thisField.type == "textarea")
         {
              if(thisField.value == "")
              {
            thisField.style.border = "1px solid red";
            isValid = false;
              }
         }
         else if(thisField.type == "radio")
         {
               var radiogroup = theForm.elements[thisField.name]; // get the whole set of radio buttons.
            var isChecked = false;

            for (i=0; i<radiogroup.length; i++)
            {
               if (radiogroup[i].checked)
                  isChecked = true;
            }
            if(!isChecked)
            {
               isValid = false;
               if(thisField.parentNode.tagName != "FORM")
                                        {
                  thisField.parentNode.style.border = "1px solid red";
                                        }
            }
         }
      }
   }
   if(!isValid)
      alert(errorMessage);
   return isValid;
}


/*********************************************
* This is a rewrite of the common trim
* function native to many programming
* languages, but not to Javascript!
**********************************************/
function trimAll(sString)
{
   while (sString.substring(0,1) == ' ')
      { sString = sString.substring(1, sString.length); }

   while (sString.substring(sString.length-1, sString.length) == ' ')
      { sString = sString.substring(0,sString.length-1); }

   return sString;
}


/*********************************************
* This is a massive email validation script!
* It uses lots of regular expressions
* and covers a lot of bases.
* Read comments for further detail.
*********************************************/
function validateEmail(emailStr, showErrors)
{
   var checkTLD=1;
   
   var knownDomainsPattern=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

   // Specify user@domain format
   var emailPattern=/^(.+)@(.+)$/;

   // Things we don't want ...
   var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

   // (allow everything but the above)
   var validChars="\[^\\s" + specialChars + "\]";

   // allow for quoted user names
   var quotedUser="(\"[^\"]*\")";

   // allow for domains in IP format
   var ipDomainPattern=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;


   /* The following string represents an atom (basically a series of non-special characters.) */

   var atom=validChars + '+';

   /* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */

   var word="(" + atom + "|" + quotedUser + ")";

   // The following pattern describes the structure of the user

   var userNamePattern = new RegExp("^" + word + "(\\." + word + ")*$");

   /* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPattern, shown above. */

   var domainNamePattern = new RegExp("^" + atom + "(\\." + atom +")*$");

   /* Finally, let's start trying to figure out if the supplied address is valid. */

   /* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */

   var matchArray=emailStr.match(emailPattern);

   if (matchArray==null)
   {
      /* Too many/few @'s or something; basically, this address doesn't
      even fit the general mould of a valid e-mail address. */
      if(showErrors)
         alert("Email address seems incorrect (check @ and .'s)");
      return false;
   }

   var user=matchArray[1];
   var domain=matchArray[2];

   // Start by checking that only basic ASCII characters are in the strings (0-127).

   for (i=0; i<user.length; i++)
   {
      if (user.charCodeAt(i)>127)
      {
         if(showErrors)
            alert("Ths username contains invalid characters.");
         return false;
      }
   }

   for (i=0; i<domain.length; i++)
   {
      if (domain.charCodeAt(i)>127)
      {
         if(showErrors)
            alert("Ths domain name contains invalid characters.");
         return false;
      }
   }

   // See if "user" is valid 

   if (user.match(userNamePattern)==null) 
   {
      // user is not valid
      if(showErrors)
         alert("The username doesn't seem to be valid.");
      return false;
   }


   /* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */

   var IPArray=domain.match(ipDomainPattern);
   if (IPArray!=null) 
   {

      // this is an IP address

      for (var i=1; i<=4; i++) 
      {
         if (IPArray[i]>255)
         {
            if(showErrors)
               alert("Destination IP address is invalid!");
            return false;
         }
      }
      return true;
   }

   // Domain is symbolic name.  Check if it's valid.

   var atomPat=new RegExp("^" + atom + "$");
   var domArr=domain.split(".");
   var len=domArr.length;

   for (i=0;i<len;i++) 
   {
      if (domArr[i].search(atomPat)==-1) 
      {
         if(showErrors)
            alert("The domain name does not seem to be valid.");
         return false;
      }
   }

   /* domain name seems valid, but now make sure that it ends in a
   known top-level domain (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

   if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomainsPattern)==-1) 
   {
      if(showErrors)
         alert("The address must end in a well-known domain or two letter country.");
      return false;
   }

   // Make sure there's a host name preceding the domain.
   if (len<2) 
   {
      if(showErrors)
         alert("This address is missing a hostname!");
      return false;
   }

   // If we've gotten this far, everything's valid!
   return true;

}