  // FORMHANDLING.JS

  // THE FIRST CODE SECTION MAKES SURE THAT ALL OF THE FORMS "REQUIRED" FIELDS 
  // HAVE BEEN FILLED IN.
  //
  // THE SECOND CODE SECTION TRIGGERS AN ALERT MESSAGE INDICATING WHERE THE DEALER
  // IS LOCATED IF THE PHONE NUMBERS AREA CODE IS NOT WITHIN A DEFINED LIST OF AREA
  // CODES.
  //
  // THE THIRD CODE SECTION EVALUATES WHETHER AN E-MAIL ADDRESS ENTERED ON THE FORM
  // IS A VALID E-MAIL ADDRESS FORMAT. OTHERWISE THE INPUT IS IGNORED AND AN ALERT IS 
  // SHOWN PROMPTING THE USER FOR A VALID E-MAIL ADDRESS.
  //
  // THE FOURTH CODE SECTION ALLOWS THE ENTER KEY ON FORM INPUT FIELDS TO MOVE THE
  // CURSOR TO THE NEXT FIELD IN THE SAME WAY THAT THE TAB KEY DOES.
  //
  // THE FIFTH CODE SECTION SUPPORTS A FUNCTION TO RETURN A STANDARD ADF 1.0
  // (AUTO-LEAD DATA FORMAT FOR AUTOMOTIVE DEALER CUSTOMER LEADS) TIME AND
  // DATE STAMP FORMATTED STRING AS REQUIRED BY THE ADF STANDARD.


  // THIS FIRST CODE SECTION MAKES SURE THAT ALL OF THE FORMS "REQUIRED" FIELDS 
  // HAVE BEEN FILLED IN.
  
  // This function is called by the CheckRequiredFields function below. It changes the
  // displayed text on the submit button to "PLEASE WAIT . . ." only if the required 
  // fields have been filled in and the submit button has been pressed.
  //
  function ChgSubmitBttn() {

    document.theform.submitbutton.value = "PLEASE WAIT . . .";
    return true;
  };
  
  // This is the code that check to make sure that all of the required fields (which all
  // have names starting with "r_") have been filled in before the submit button is changed
  // and the information is submitted.
  //
  function CheckRequiredFields(input) {

   // Check that the required fields have been entered.

    // Define the required form fields that must be entered.
    //
    // NOTE: This is remarked out as it is now defined in the calling page code.
    // var requiredFields = new Array("r_Model","r_Name","r_Phone","r_City","r_Email");

    // Text to display the label that describes any missing but required form fields.
    //
    // NOTE: This is remarked out as it is now defined in the calling page code.
    // var fieldNames = new Array("    Desired Model","    Name","    Phone Number","    City","    E-Mail Address");

    var fieldCheck = true;
    var fieldsNeeded = "Please fill in the following field(s):\n\n";
    for (var fieldNum=0; fieldNum < requiredFields.length; fieldNum++)
       {
        if ((input.elements[requiredFields[fieldNum]].value == "") ||
            (input.elements[requiredFields[fieldNum]].value == " "))
          {
           fieldsNeeded += fieldNames[fieldNum] + "\n";
           fieldCheck = false;
          };
       };
    fieldsNeeded += "\n    -Thank you." + "\n";
    if (fieldCheck == true)
      {
       // All the required fields have been filled.
       ChgSubmitBttn();
       return true;
      } else {
              // Some required fields have not been filled.
              alert(fieldsNeeded);
              return false;
             };
  };


  // THIS SECOND CODE SECTION TRIGGERS AN ALERT MESSAGE INDICATING WHERE THE DEALER
  // IS LOCATED IF THE PHONE NUMBERS AREA CODE IS NOT WITHIN A DEFINED LIST OF AREA
  // CODES.

  // This code is called when the user clicks on and leaves the main phone number field.
  // If a phone number has been entered with an area code, this code verifies that it is an
  // area code from one of the designated regions. If not, the user is prompted with a
  // reminder of where the dealer is located and given the option of continuing or not.
  // The calling Phone form field must contain the following code:
  // onblur="isValidAreaCode(this.value)"

  // NOTE: Tests that start with a "1" but only have 10 digits will not be rejected. This is because
  // "1" is a valid option before the area code number. This is not a problem as there are no real
  // area codes that actually start with a "1".

  function isValidAreaCode(PhoneInfoEntered) {
    
    // NOTE: This is remarked out as it is now defined in the calling page code.
    //
    // var MasterAreaCodeString = "604-778-250"; // BC
    // MasterAreaCodeString = MasterAreaCodeString + "-800-888-877-866-855-900"; // Toll free
    // MasterAreaCodeString = MasterAreaCodeString + "-867"; // Yukon, NWT and Nunavut
    // MasterAreaCodeString = MasterAreaCodeString + "-403-780"; // Alberta
    // MasterAreaCodeString = MasterAreaCodeString + "-306"; // Saskatchewan
    // MasterAreaCodeString = MasterAreaCodeString + "-204"; // Manitoba
    // // Northern Washington State below (NOT including the Vancouver Washington area)
    // MasterAreaCodeString = MasterAreaCodeString + "-425-253-206-509";

    // NOTE: This is remarked out as it is now defined in the calling page code.
    //
    // var AreaCodeAlertMessage = "Just a reminder that we are located in the Greater Vancouver area of BC, Canada!";

    var PhoneString = "";
    var PhoneStringAsNumber = 0;
    var AreaCodeString = "";
    var AreaCodeOK = false;
    PhoneInfoEntered = PhoneInfoEntered + ""; // Convert to string

    if (Version4Plus)
      {   
       if (PhoneInfoEntered.length >= 1)
         {
          PhoneString = PhoneInfoEntered;
          while ((PhoneString.length >= 1) && (PhoneString.indexOf(" ") != -1))
               {
                // Remove all spaces.
                PhoneString = PhoneString.replace(" ","");
               };
          while ((PhoneString.length >= 1) && (PhoneString.indexOf("-") != -1))
               {
                // Remove all phone number separator hyphens.
                PhoneString = PhoneString.replace("-","");
               };
          while ((PhoneString.length >= 1) && (PhoneString.indexOf("(") != -1))
               {
                // Remove any opening brackets around the area code.
                PhoneString = PhoneString.replace("(","");
               };
          while ((PhoneString.length >= 1) && (PhoneString.indexOf(")") != -1))
               {
                // Remove any closing brackets around the area code.
                PhoneString = PhoneString.replace(")","");
               };
          if (PhoneString.length >= 1)
            {
             if (PhoneString.indexOf("1") == 0) 
               {
                // If the phone number starts with a 1 for long distance, remove it.
                PhoneString = PhoneString.replace("1","");
               };
            };
          if (PhoneString.length == 10)
            {
             // If the string (after removing any leading number 1) is 10 digits long, then
             // confirm that it is a number and if so, check the first 3 digit area code.
             PhoneStringAsNumber = parseInt(PhoneString);
             if (isNaN(PhoneStringAsNumber) != false)
               {
                // Nothing further is done as this is not a number.
               } else {
                       // This is a number so check the area code which are the first 3 digits.
                       AreaCodeString = PhoneString.substring(0,3);
                       if (MasterAreaCodeString.indexOf(AreaCodeString) != -1)
                         {
                          AreaCodeOK = true;
                         }; 
                       // There is an area code listed but it is NOT a valid BC area code.
                       // Display a warning explanation to the user.
                       if (AreaCodeOK != true)
                         {
                          alert(AreaCodeAlertMessage);
                         };
                      };
            };
         };
      };
  };


  // THIS THIRD CODE SECTION EVALUATES WHETHER AN E-MAIL ADDRESS ENTERED ON THE FORM
  // IS A VALID E-MAIL ADDRESS FORMAT. OTHERWISE THE INPUT IS IGNORED AND AN ALERT IS 
  // SHOWN PROMPTING THE USER FOR A VALID E-MAIL ADDRESS.

  // The calling E-Mail form field must contain the following code:
  // onblur="IsThisAnEmailAddress(this.value);"
  //
  function IsThisAnEmailAddress (emailstring) {

    // Simply pass a tentative e-mail address string to the function, and it'll tell you if
    // you've got a valid email address by returning a boolean value of true or false.  Note
    // that it checks the syntax, not the actual existence of the address. This function
    // works with all JavaScript-enabled browsers, but provides a more advanced algorithm
    // for fourth-generation browsers (Navigator 4.0x, Internet Explorer 4.0x, and above).
    //
    // Are regular expressions supported?
    var IsAnEmail = false; // Default false value before testing below.
    var supported = false; // Default false value before testing below.
    if (window.RegExp)
      {
       var tempStr = "a";
       var tempReg = new RegExp(tempStr);
       if (tempReg.test(tempStr))
         { 
          supported = true;
         };
      };
    if (!supported)
      { 
       IsAnEmail = ((emailstring.indexOf(".") > 2) && (emailstring.indexOf("@") > 0));
      };
    var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
    var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
    IsAnEmail = ((!r1.test(emailstring) && r2.test(emailstring)));
    if ((IsAnEmail != true) && (emailstring > ""))
      {
       // This is not a valid email address format.
       alert("Please enter a valid e-mail address so\r\nthat we may respond to your request.\r\n\r\nNote that we do NOT collect them!");      
       document.theform.r_Email.value = "";
       eval('document.theform.r_Email.focus()');
      };
    return IsAnEmail; // Returns true or false.
  };


  // THIS FOURTH CODE SECTION ALLOWS THE ENTER KEY ON FORM INPUT FIELDS TO MOVE THE
  // CURSOR TO THE NEXT FIELD IN THE SAME WAY THAT THE TAB KEY DOES.

  // NOTE: This is remarked out as it is now defined in the calling page code.
  //
  //  nextfield = "_IAmInterestedIn"; // name of the first input box on the page.

  //  The following should be added to each input box:
  //  onFocus="nextfield='NameOfNextFieldBoxGoesHere';"
  // the last input box should have "nextfield='done';"
  // the form should also have added the name: NAME="theform"
  //
  NavigatorUserAgent = navigator.userAgent;
  NavigatorUserAgent = NavigatorUserAgent.toLowerCase();
  // ThisIsWindows must be defined as IsWindows has not yet been declared as it is loaded
  // in the external niscode.js file which hasn't yet been loaded.
  var ThisIsWindows = (NavigatorUserAgent.indexOf("win") != -1);
  //
  if (Version4Plus)
    {
     // ThisIsWindows is used instead of IsWindows as IsWindows is declared in the niscode.js
     // file which hasn't yet been loaded. So ThisIsWindows was declared at the start of this
     // code.
     if (ThisIsWindows)
       {
        netscape = "";
        ver = navigator.appVersion;
        len = ver.length;
        for (iln = 0; iln < len; iln++) 
           {
            if (ver.charAt(iln) == "(")
              {
               break;
              };
           };
        netscape = (ver.charAt(iln+1).toUpperCase() != "C");
        document.onkeydown = keyDown; // Work together to analyze keystrokes.
        if (netscape)
          {
           document.captureEvents(Event.KEYDOWN|Event.KEYUP);
          };
       };
    };
  //
  function keyDown(DnEvents) {

    // The keypress code. 
    if (Version4Plus)
      {
       // ThisIsWindows is used instead of IsWindows as IsWindows is declared in the niscode.js
       // file which hasn't yet been loaded. So ThisIsWindows was declared at the start of this
       // code.
       if (ThisIsWindows)
         {
          k = (netscape) ? DnEvents.which : window.event.keyCode;
          if (k == 13) 
            { 
             // enter key pressed
             if (nextfield == 'done')
               {
                return true; // submit, we finished all fields
               } else {
                       // we're not done yet, send focus to next box
                       eval('document.theform.' + nextfield + '.focus()');
                       return false;
                      };
            };
         };
      };
  };
  //
  if (Version4Plus)
    { 
     // ThisIsWindows is used instead of IsWindows as IsWindows is declared in the niscode.js
     // file which hasn't yet been loaded. So ThisIsWindows was declared at the start of this
     // code.
     if (ThisIsWindows)
       {
        document.onkeydown = keyDown; // work together to analyze keystrokes.
        if (netscape) 
          {
           document.captureEvents(Event.KEYDOWN|Event.KEYUP);
          };
       };
    };


  // THIS FIFTH CODE SECTION SUPPORTS A FUNCTION TO RETURN A STANDARD ADF 1.0
  // (AUTO-LEAD DATA FORMAT FOR AUTOMOTIVE DEALER CUSTOMER LEADS) TIME AND
  // DATE STAMP FORMATTED STRING AS REQUIRED BY THE ADF STANDARD.

  // Functions required to return a standard ADF 1.0 time and date stamp formatted string.
  //
  // Note that the required Date and Math JavaScript objects are supported by just about any browser
  // that supports JavaScript, including Netscape 3, etc.
  //
  // A typical hidden form ADF time and date stamp field (in brackets) would be:
  // input type="hidden" name="_adf_time_date_stamp" value="0000-00-00T00:00:00-00:00"
  //
  // A typical call to get the ADF time and date string would be:
  // TheFullADFTimeDateStampString = ReturnTheFullADFTimeDateStampString();
  //
  // Afterwards the JavaScript code to populate the hidden field would be something like:
  // document.theform._adf_time_date_stamp.value = TheFullADFTimeDateStampString;
  //
  // The string that the ReturnTheFullADFTimeDateStampString function returns looks like this:
  // "2004-11-27T18:41:48-08:00"
  // "[4 digit year]-[2 digit month]-[2 digit day]T[2 digit hour]:[2 digit minute]:[2 digit second]["+" or "-" symbol depending on the time zone offset][2 digit hour offset]:[2 digit minute offset]"
  // Note that single digit values such as "8" MUST be 2 digit values, i.e. "08".
  // Also note that all hours are based on a 24 hour clock, i.e. 5:25 PM is "17:25"
  //
  //
  // Function to return the 4 digit current year.  A typical call is:
  // The4DigitYear = Return4DigitYear();
  //
  function Return4DigitCurrentYear() {
    
    TodaysDate = new Date();
    Current4DigitYear = TodaysDate.getFullYear();
    return Current4DigitYear;
  };

  // Function to return the 2 digit current month string.
  // For example, June would be "06".
  // A typical call is:
  // The2DigitMonth = Return2DigitCurrentMonth();
  //
  function Return2DigitCurrentMonth() {
    
    TodaysDate = new Date();
    Current2DigitMonth = parseInt(TodaysDate.getMonth() + 1);
    if (Current2DigitMonth < 10)
      {
       Current2DigitMonth = "0" + Current2DigitMonth;
      };
   return Current2DigitMonth;
  };

  // Function to return the 2 digit current day string.
  // For example, March 8, 2004 would be "08".
  // A typical call is:
  // The2DigitDay = Return2DigitCurrentDay();
  //
  function Return2DigitCurrentDay() {
    
    TodaysDate = new Date();
    Current2DigitDay = TodaysDate.getDate();
    if (Current2DigitDay < 10)
      {
       Current2DigitDay = "0" + Current2DigitDay;
      };
   return Current2DigitDay;
  };

  // Function to return the 2 digit current hour.
  // For example, 8:30 would be "08".
  // A typical call is:
  // The2DigitHour = Return2DigitCurrentHour();
  //
  function Return2DigitCurrentHour() {
    
    TodaysDate = new Date();
    Current2DigitHour = TodaysDate.getHours();
    if (Current2DigitHour < 10)
      {
       Current2DigitHour = "0" + Current2DigitHour;
      };
   return Current2DigitHour;
  };

  // Function to return the 2 digit current minutes.
  // For example, 8:08 would be "08".
  // A typical call is:
  // The2DigitMinute = Return2DigitCurrentMinute();
  //
  function Return2DigitCurrentMinute() {
    
    TodaysDate = new Date();
    Current2DigitMinute = TodaysDate.getMinutes();
    if (Current2DigitMinute < 10)
      {
       Current2DigitMinute = "0" + Current2DigitMinute;
      };
   return Current2DigitMinute;
  };

  // Function to return the 2 digit current seconds.
  // For example, 8:18:02 would be "02".
  // A typical call is:
  // The2DigitSecond = Return2DigitCurrentSecond();
  //
  function Return2DigitCurrentSecond() {
    
    TodaysDate = new Date();
    Current2DigitSecond = TodaysDate.getSeconds();
    if (Current2DigitSecond < 10)
      {
       Current2DigitSecond = "0" + Current2DigitSecond;
      };
   return Current2DigitSecond;
  };

  // Function to return the full time zone offset from Greenwich Mean Time
  // i.e. "+08:30", etc.   For Vancouver it would return "-08:00"
  // A typical call is:
  // TheTimeZoneOffsetString = ReturnFullCurrentTimeZoneOffsetString();
  //
  function ReturnFullCurrentTimeZoneOffsetString() {

    TodaysDate = new Date();
    OffsetTimeInMinutes = TodaysDate.getTimezoneOffset();
    OffsetTimeString = "-00:00"; // Default setting
    OffsetMinutesOnlyPortion = "00";
    if (Math.abs(OffsetTimeInMinutes) >= 60)
      {
       OffsetTimeHours = Math.abs(parseInt(OffsetTimeInMinutes/60));
       OffsetMinutesOnlyPortion = Math.abs(OffsetTimeInMinutes) - (OffsetTimeHours * 60);
       if (OffsetMinutesOnlyPortion < 10)
         {
           OffsetMinutesOnlyPortion = "0" + OffsetMinutesOnlyPortion;
         };
       if (Math.abs(OffsetTimeHours) < 10)
         {
          OffsetTimeHours = "0" + Math.abs(OffsetTimeHours);
         };
       OffsetTimeString = OffsetTimeHours;
      } else {
                 OffsetTimeString = "00";
               };
    if (OffsetTimeInMinutes < 0)
      {
       OffsetTimeString = "+" + OffsetTimeString;
      } else {
                OffsetTimeString = "-" + OffsetTimeString;
               };
    OffsetTimeString = OffsetTimeString + ":" + OffsetMinutesOnlyPortion;
    return OffsetTimeString;
  };

  //
  function ReturnTheFullADFTimeDateStampString() {

    FullADFTImeDateStampString = Return4DigitCurrentYear() + "-" + Return2DigitCurrentMonth() + "-" + Return2DigitCurrentDay() + "T" + Return2DigitCurrentHour() + ":" + Return2DigitCurrentMinute() + ":" + Return2DigitCurrentSecond() + ReturnFullCurrentTimeZoneOffsetString();
    return FullADFTImeDateStampString;
  };

  // Now actually create the full time and date string.
  TheFullADFTimeDateStampString = ReturnTheFullADFTimeDateStampString();
