/***********************************************************************************/
/*  FILE          : chkform.js                                                     */
/*  CREATED       :                                                                */
/*  LANGUAGE      :                                                                */
/*                                                                                 */
/*  This file contains all the common funtions used to validate a form             */
/*                                                                                 */
/***********************************************************************************/


/**
 * trim left spaces
 *
 * @param   String   the string to be trimmed
 * @return  String  the trimmed string
 */

  function lTrim(str)
   {
     return (new String(str)).replace(/^\s*/, "")
   }



/**
 * trim right spaces
 *
 * @param   String   the string to be trimmed
 * @return  String  the trimmed string
 */

  function rTrim(str)
  {
     return (new String(str)).replace(/\s*$/, "")
  }



/**
 * trim left and right spaces
 *
 * @param   String   the string to be trimmed
 * @return  String  the trimmed string
 */

  function trim(str)
  {
     return lTrim(rTrim(new String(str)))
  }



/**
 * check whether a string is empty or not
 *
 * @param   String   the string to be checked
 * @return  boolean  true if is empty, false if not
 */

  function isEmpty(inputVal)
  {
     return (inputVal == null || inputVal == "");
  }



/**
 * check whether a string contains only wanted characters or not
 *
 * @param   String   the string to be checked
 * @param   String   the string that contains valid chars
 * @return  boolean  whether the string is corret or not
 */

  function valid_char(str, valid)
  {
     for(var i = 0; i < str.length; i++)
     {
        temp = "" + str.substring(i, i + 1);
        if(valid.indexOf(temp) == "-1")
          return false;
     }

     return true;
  }



/**
 * check whether a string contains only integers or not
 *
 * @param   String   the string to be checked
 * @return  boolean  whether the string is corret or not
 */


  function chk_int(field)
  {
     var s = new String(field);
     s = trim(s);

     // validita' caratteri campo
     if (!valid_char(s, "0123456789") || isNaN(s))
       return false;
     else
       return true;
  }



/**
 * check whether a string contains only double or not (dot as decimal separator)
 *
 * @param   String   the string to be checked
 * @return  boolean  whether the string is corret or not
 */

  function chk_double(f)
  {
     var t = new String(f);
     t = trim(t);

     // change comma decimal separator (for italian numbers) whith dot separator (international)
     re = /,/gi;
     var s = t.replace(re, '.');

     if (!valid_char(s, "01234567890.") || isNaN(s))
       return false;

     return true;
  }





/**
 * validate an email address
 *
 * @param   String   the email address to be validated
 * @return  boolean  whether the email address is corret or not
 */


  function emailCheck(emailStr, errorMsg)
  {
      var checkTLD     = 1;
      var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

      var checkNTLD       = 1;
      var knownNatDomsPat = /^(af|al|dz|as|ad|ao|ai|aq|ag|ar|am|aw|au|at|az|bs|bh|bd|bb|by|be|bz|bj|bm|bt|bo|ba|bw|bv|br|io|bn|bg|bf|bi|kh|cm|ca|cv|ky|cf|td|cl|cn|cx|cc|co|km|cg|cd|ck|cr|ci|hr|cu|cy|cz|dk|dj|dm|do|tp|ec|eg|sv|gq|er|ee|et|eu|fk|fo|fj|fi|fr|fx|gf|pf|tf|ga|gm|ge|de|gh|gi|gr|gl|gd|gp|gu|gt|gn|gw|gy|ht|hm|va|hn|hk|hu|is|in|id|ir|iq|ie|il|it|jm|jp|jo|kz|ke|ki|kp|kr|kw|kg|la|lv|lb|ls|lr|ly|li|lt|lu|mo|mk|mg|mw|my|mv|ml|mt|mh|mq|mr|mu|yt|mx|fm|md|mc|mn|ms|ma|mz|mm|na|nr|np|nl|an|nc|nz|ni|ne|ng|nu|nf|mp|no|om|pk|pw|pa|pg|py|pe|ph|pn|pl|pt|pr|qa|re|ro|ru|rw|kn|lc|vc|ws|sm|st|sa|sn|sc|sl|sg|sk|si|sb|so|za|gs|es|lk|sh|pm|sd|sr|sj|sz|se|ch|sy|tw|tj|tz|th|tg|tk|to|tt|tn|tr|tm|tc|tv|ug|ua|ae|gb|us|um|uy|uz|vu|ve|vn|vg|vi|wf|eh|ye|yu|zm|zw)$/;

      var emailPat     = /^(.+)@(.+)$/;
      var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
      var validChars   = "\[^\\s" + specialChars + "\]";
      var quotedUser   = "(\"[^\"]*\")";
      var ipDomainPat  = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

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

      var userPat      = new RegExp("^" + word + "(\\." + word + ")*$");
      var domainPat    = new RegExp("^" + atom + "(\\." + atom +")*$");
      var matchArray   = emailStr.match(emailPat);


      if(matchArray == null)
      {
        //alert("Email address seems incorrect (check @ and .'s)");
        alert(errorMsg + " (mancano @ e/o .)");
        return false;
      }


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

      for(i=0; i<user.length; i++)
      {
        if(user.charCodeAt(i)>127)
        {
          //alert("This username contains invalid characters.");
          alert(errorMsg + ": il nome utente contiene caratteri non validi.");
          return false;
        }
      }


      for(i=0; i<domain.length; i++)
      {
        if(domain.charCodeAt(i)>127)
        {
          //alert("This domain name contains invalid characters.");
          alert(errorMsg + ": il nome del dominio contiene caratteri non validi.");
          return false;
        }
      }


      if(user.match(userPat) == null)
      {
        //alert("The username doesn't seem to be valid.");
        alert(errorMsg + ": il nome utente non sembra valido.");
        return false;
      }


      var IPArray = domain.match(ipDomainPat);

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


      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)
        {
          //alert("The domain name does not seem to be valid.");
          alert(errorMsg + ": il nome del dominio non sembra valido.");
          return false;
        }
      }


      if(len < 2)
      {
        //alert("This address is missing a hostname!");
        alert(errorMsg + ":\nmanca il dominio.");
        return false;
      }



      if(checkTLD && checkNTLD)
      {
        if(domArr[domArr.length-1].length < 2)
        {
          //alert("The address must end in a well-known domain or two letter " + "country.");
          alert(errorMsg + ":\nl'indirizzo deve terminare con un dominio valido.");
          return false;
        }

        if(domArr[domArr.length-1].search(knownDomsPat) == -1 && domArr[domArr.length-1].search(knownNatDomsPat) == -1)
        {
          //alert("The address must end in a well-known domain or two letter " + "country.");
          alert(errorMsg + ":\nl'indirizzo deve terminare con un dominio valido.");
          return false;
        }
      }


      return true;
  }
 
