// validate.js
// McAdoo   - 05/15/2003 - form validation code

function ValidateBrackets ( tform, currentList )
  // McAdoo - 05/01/2001 - validate a quote
  {
    // local vars
    var i, j;
    
    // reset the flag
    ErrorFound = false;

    // loop through the form elements
    for ( i = 0; i < tform.elements.length; i++ )
      {
        // loop through the list elements
        for (j = 0; j < currentList.length; j++ )
          {
            if ( currentList [j].fname == tform.elements [i].name )
              {
                // run validation on the field
                validField ( tform.elements [i], currentList [j] );
              }
          }
      }

    // return the error flag
    return ( !ErrorFound );
  }

function validField ( formElement, listEntry )
  // McAdoo - 05/01/2001 - run validation on this field
  {

    // check for:
    //   * Required Field
    //   * NOT proper length
    if ( (formElement.value.length <  listEntry.minlength ) && listEntry.req ) 
      { 
        // throw an error
        Error (formElement, listEntry.msg + " that is at least " + listEntry.minlength + " characters in length"); 
      } 
    else
      {
        // check for:
        //   * provided data
        //     OR
        //   * required field
        if ( ( formElement.value.length > 0 ) || ( listEntry.req ) )
          {
            // check against various types
            switch ( listEntry.ftype )
              {
                // [START] Select
                case "date" :
                  // fix the e-mail address
                  formElement.value = fixDate ( formElement.value );                            

                  // run date validation
                  validateDate ( listEntry, formElement );
                break;

                case "integer" :
                  // run integer validation
                  validateInteger ( listEntry, formElement);
                break;

                case "currency" :
                  // clean out commas, etc
                  formElement.value = cleanNumbers ( formElement.value );
                        
                  // run currency validation
                  validateCurrency ( listEntry, formElement );
                break;

                case "decimal" :
                  // clean out commas, etc
                  formElement.value = cleanNumbers ( formElement.value );
                        
                  // run currency validation
                  validateDecimal ( listEntry, formElement );
                break;

                case "number" :
                  // clean out commas, etc
                  formElement.value = cleanNumbers ( formElement.value );
  
                  // run number validation
                  validateNumber ( listEntry, formElement );
                break;

                case "phone" :
                  // run phone validation
                  validatePhone ( listEntry, formElement );
                break;

                case "email" :
                  // fix the e-mail address
                  formElement.value = fixEmail ( formElement.value );                            

                  // run email validation
                  validateEmail ( listEntry, formElement );
                break;
    
              }

          }
 
      }

  }

function Validate ( tform, currentList )
  // McAdoo - 04/27/2001 - perform validation
  // McAdoo - 05/01/2001 - fixed name references
  //                     - added e-mail domain pre-fill w/memach.com
  {
    // local vars
    var i;

    // set the (global) error flag
    ErrorFound = false;
    
    // loop through the list of required elements
    for (i = 0; i < currentList.length; i++)

      // check for NULLed out elements (not needed later)
      if (currentList [i] != null)
        {
          // check for a form element with this name
          if ( document.forms [ tform.name ].elements [ currentList [i].fname ] )
            {       
              // run validation on the field
              validField ( document.forms [ tform.name ].elements [currentList [i].fname ], currentList [i] );
            }
        }    

    // return results
    return (!ErrorFound);
  }

function cleanNumbers ( str )
  // McAdoo - 04/30/2001 - clean-up numbers
  {
    // allocate
    var tstr = str;

    // strip out the commas
    tstr = tstr.replace ( ",", "" );

    // return the revised version
    return ( tstr );
  }

function fixDate ( str )
  // Stricker - 08/14/2001 - format slashes where needed in the date
  {
    // allocate
    var tstr = str;
    var slashes = tstr.match ( /\//g );
    var slashquantity;

    // store number of existing slashes in an array to avoid checks against null
    if ( slashes != null )
      {
        slashquantity = slashes.length;
      }

    // if number of slashes is not correct for valid format
    if ( slashquantity != 2 )
      {
        // take out all current slashes
        tstr = tstr.replace ( "/", "" );

        // if eight numbers were not entered just return the original string
        if ( tstr.length != 8 ) return ( str );

        // otherwise add slashes in the correct places
        tstr = tstr.slice ( 0, 2 ) + "/" + tstr.slice ( 2, 4 ) + "/" + tstr.slice ( 4, 8 );
      }

    // return the corrected date
    return ( tstr );
  }

function fixEmail ( str )
  // McAdoo - 05/01/2001 - add @memach.com, when needed
  {
    
    // allocate
    var tstr = str;
    var atindex = tstr.indexOf ('@');

    // check for an entry
    if ( atindex < 0 )
      {
        // append '@nettek.com'
        tstr = tstr + '@nettek.com';
      }

    // return the revised version
    return ( tstr );
  }

function validateDate ( ffield, elem )
  // McAdoo - 04/30/2001 - do date validation ##/##/####
  // McAdoo - 05/01/2001 - added handling of 20 to dates
  // McAdoo - 06/08/2001 - fixed problem with ParseInt using wrong radix
  {
    // allocate
    var datelist = elem.value.split ( "/" );
    var month, day, year;

    // flags
    var acceptmonth = false;
    var acceptday   = false;
    var acceptyear  = false;

    // check for at least one entry
    if ( datelist.length != 3 )
      {
        // not properly formatted
        Error ( elem, ffield.msg + ' that is in the format mm/dd/yyyy' );
      }
    else
      {
        // pull out the month, day, year
        month = parseInt ( datelist [0], 10 );
        day   = parseInt ( datelist [1], 10 );
        year  = parseInt ( datelist [2], 10 );

        // check month formatting
        if ( isNaN ( month ) )
          {
            // Invalid number
            Error ( elem, ffield.msg + ' with a month that is a number' );
          }
        else
          {
            // check range
            if ( ( month < 1 ) || ( month > 12 ) )
              {
                // error
                Error ( elem, ffield.msg + ' with a month that is between 01 and 12' );
              }
            else
              {
                // set the flag
                acceptmonth = true;
              }
          }

        // check day formatting
        if ( isNaN ( day ) )
          {
            // Invalid number
            Error ( elem, ffield.msg + ' with a day that is a number' );
          }
        else
          {
            // check range
            if ( ( day < 1 ) || ( day > 31 ) )
              {
                // error
                Error ( elem, ffield.msg + ' with a day that is between 01 and 31' );
              }
            else
              {
                // set the flag
                acceptday = true;
              }
          }

        // check year formatting
        if ( isNaN ( year ) )
          {
            // Invalid number
            Error ( elem, ffield.msg + ' with a year that is a number' );
          }
        else
          {
            // check if there are only two digits
            if ( datelist [2].length == 2 )
              {
                // add 2000 to the year
                year = year + 2000;
              }

            // check range
            if ( ( year < 2000 ) || ( year > 9999 ) )
              {
                // error
                Error ( elem, ffield.msg + ' with a year that is between 2000 and 9999');
              }
            else
              {
                // set the flag
                acceptyear = true;
              }
          }
      }

    // check the flags
    if ( acceptmonth && acceptday && acceptyear )
      {
        // reset the values
        elem.value = month + "/" + day + "/" + year;
      }
  }

function validateInteger ( ffield, elem )
  // McAdoo - 04/30/2001 - validate on integers
  // McAdoo - 05/01/2001 - fixed minus location logic flaw
  {
    // pattern
    var notinteger_pattern = /[^0-9-]/
    var integer = elem.value;
    var firstminus  = integer.lastIndexOf ( '-' );

    // check for non-numbers
    if ( notinteger_pattern.test ( integer ) )
      {
        // error message
        Error ( elem, ffield.msg + ' that only contains numbers');
      }
    else
      {
        // check for minus not first character
        if ( firstminus > 0 )
          {
            // error message
            Error ( elem, ffield.msg + ' that only has a negative sign at the front' );
          }
      }
  }

function validateCurrency ( ffield, elem )
  // McAdoo - 04/30/2001 - make sure that there is a match for proper currency
  // McAdoo - 05/01/2001 - fixed minus location logic flaw
  {
    // pattern(s)
    var currency_pattern = /[^0-9-]/
    var currency = elem.value; 
    var firstminus  = currency.lastIndexOf ( '-' );
    var numberparts = currency.split ('.');

    // flag(s)
    var valid = false;
    
    // check for non-numbers
    if ( numberparts.length != 2 )
      {
        // error message
        Error ( elem, ffield.msg + ' that only contains numbers and at most one decimal point');
      }
    else
      {
        // check for minus only on the first entry
        if ( firstminus > 0 )
          {
            // error message
            Error ( elem, ffield.msg + ' that only has a negative sign at the front' );
          }
        else
          {
 
            // check for first half
            if ( currency_pattern.test ( numberparts [0] ) )
              {
                // error message
                Error ( elem, ffield.msg + ' that only contains numbers before the decimal point');
              }
            else
              {
                // check for first half
                if ( currency_pattern.test ( numberparts [1] ) )
                  {
                    // error message
                    Error ( elem, ffield.msg + ' that only contains numbers after the decimal point');
                  }
                else
                  {
                    // checks for blanks
                    if ( numberparts [1].length == 0)
                      {
                        numberparts [1] = "00";

                        // set the valid flag
                        valid = true;
                      }
                  }
              }

          }
      }

    // use the valid flag
    if ( valid )
      {
        // rebuild the "final" version
        elem.value = numberparts [0] + "." + numberparts [1];
      }
  }

function validateDecimal ( ffield, elem )
  {
    // pattern(s)
    var currency_pattern = /[^0-9-]/
    var currency = elem.value; 
    var firstminus  = currency.lastIndexOf ( '-' );
    var numberparts = currency.split ('.');

    // flag(s)
    var valid = false;
    
    // check for non-numbers
    if ( numberparts.length != 2 )
      {
        // error message
        Error ( elem, ffield.msg + ' that only contains numbers and at most one decimal point');
      }
    else
      {
        // check for minus only on the first entry
        if ( firstminus > 0 )
          {
            // error message
            Error ( elem, ffield.msg + ' that only has a negative sign at the front' );
          }
        else
          {
 
            // check for first half
            if ( currency_pattern.test ( numberparts [0] ) )
              {
                // error message
                Error ( elem, ffield.msg + ' that only contains numbers before the decimal point');
              }
            else
              {
                // check for first half
                if ( currency_pattern.test ( numberparts [1] ) )
                  {
                    // error message
                    Error ( elem, ffield.msg + ' that only contains numbers after the decimal point');
                  }
                else
                  {
                    // checks for blanks
                    if ( numberparts [1].length == 0)
                      {
                        numberparts [1] = "0";

                        // set the valid flag
                        valid = true;
                      }
                  }
              }

          }
      }

    // use the valid flag
    if ( valid )
      {
        // rebuild the "final" version
        elem.value = numberparts [0] + "." + numberparts [1];
      }
  }

function validateNumber ( ffield, elem )
  // McAdoo - 04/30/2001 - validates any "normal" number
  // McAdoo - 05/01/2001 - fixed minus location logic flaw
  {
    // pattern
    var number_pattern = /[^0-9-]/
    var number = elem.value; 
    var firstminus  = number.lastIndexOf ( '-' );
    var numberparts = number.split ( '.' );

    // flag(s)
    var valid = false;

    // check for non-numbers
    if ( numberparts.length > 2 )
      {
        // error message
        Error ( elem, ffield.msg + ' that only contains numbers and at most one decimal point');
      }
    else
      {
        // check for minus only on the first entry
        if ( firstminus > 0 )
          {
            // error message
            Error ( elem, ffield.msg + ' that only has a negative sign at the front' );
          }
        else
          {

            // check for first half
            if ( number_pattern.test ( numberparts [0] ) )
              {
                // error message
                Error ( elem, ffield.msg + ' that only contains numbers before the decimal point');
              }
            else
              {

                // check if there is a second half
                if ( numberparts.length == 2 )
                  {
                    // check for second half
                    if ( number_pattern.test ( numberparts [1] ) )
                      {
                        // error message
                        Error ( elem, ffield.msg + ' that only contains numbers after the decimal point');
                      }
                    else
                      {
                        // set the flag
                        valid = true;
                      }
                  }
                else
                  {
                    // set the flag
                    valid = true;
                  }
              }

          }
      }

    // check for a need to update
    if ( valid ) 
      {
        // check for a second half to the number
        if ( numberparts.length == 2)
          {
            // check for no decimal needed
            if ( numberparts [1].length == 0 )
              {
                // set the value in the field w/o the decimal
                elem.value = numberparts [0];
              }
          }
      }
  }

function validatePhone ( ffield, elem )
  {
    // pattern
    var phone_num = elem.value;
    var phone_pattern = /^\d{3}-\d{3}-\d{4}/;

    // check length
    if ( phone_num.length != 12 ) 
      {
        // error out
        Error ( elem, ffield.msg + ' that is in the format ###-###-####' );
      }
    else
      {
        // match the pattern
        if ( ! phone_pattern.test ( phone_num ) )
          {
            // error out
            Error ( elem, ffield.msg + ' that is only numbers in the format ###-###-####' );
          }
      }

  }

function validateEmail ( ffield, elem )
  // McAdoo - 04/30/2001 - this does validation on the e-mail address
  {
    // allocate
    var username = "";
    var domain   = "";
    var domainlist;
    var i = 0;

    // flags
    var acceptusername  = false;
    var acceptdomain    = false;
    var done            = false;

    // split out the e-mail address
    var address = elem.value.split ( "@" );

    // build the patterns
    var user_pattern      = /^([a-zA-Z])(\w*)$/;
    var subdomain_pattern = /^(\w+)/
    var domain_pattern    = /^(cc)|(com)|(org)|(edu)|(gov)|(mil)|(net)/;

    // check for at least one entry
    if ( address.length != 2 )
      {
        // error message
        Error ( elem, ffield.msg + ' that is in the format username@domain' );
      }
    else
      {
        // set the username
        username = address [ 0 ].toLowerCase ();

        // set the domain
        domain   = address [ 1 ].toLowerCase ();

        // run the pattern match on username
        if ( ! user_pattern.test ( username ) )
          {
            // print the error message
            Error ( elem, ffield.msg + ' with a valid username' );
          }
        else
          {
            // set the flag
            acceptusername = true;
          }

        // get the domain list
        domainlist = domain.split ( '.' );

        // loop through all but last
        for ( i = 0; (i < domainlist.length - 1) && ! done; i++ )
          {
            // run the pattern match on domain
            if ( ! subdomain_pattern.test ( domainlist [i] ) )
              {
                // print the error message
                Error ( elem, ffield.msg + ' with a valid domain name' );

                // set the flag
                done = true;
              }
          }

//        window.alert ( domainlist [ domainlist.length - 1] + ";" + domain_pattern.test ( domainlist [ domainlist.length - 1 ] ) );

        // check for:
        //   * okay domain
        //   * okay subdomain(s)
        if ( ! domain_pattern.test ( domainlist [ domainlist.length - 1 ] ) || done )
          {
            // print the error message
            Error ( elem, ffield.msg + ' with a valid domain' );
          }
        else
          {
            // set the flag
            acceptdomain = true;
          }

        // check the flags
        if ( acceptusername && acceptdomain )
          {
            // refresh the username@domain
            elem.value = username + '@' + domain;
          }
      }
  }

