// ***************************************************************************************** \\
function localValidateFields(theForm, lang)
{
    var field_check18       = theForm["question(AGE_18)"];
    var errMessage          = "";
    var englishMessage      = true;

    if ((typeof lang != 'undefined') && (lang.toLowerCase() == 'es'))
    {
         englishMessage=false;
    }

    // Make sure the age 18 check box is selected
    if (((field_check18 != null) && (field_check18 != 'undefined')) && (field_check18.checked == false))
    {
        if (englishMessage)
        {
            errMessage += "You must be at least 18 years or older to recieve reminders.\r\n";
        }
        else
        {
            errMessage += "Debes tener por lo menos 18 anos de edad para recibir estos recordatorios.\r\n";
        }
    }

    var monthValue="";
    var dayValue="";
    var yearValue="";
    var theList = document.getElementsByName('question(dose_month)');
    if (theList != undefined)
    {
        if (theList[0].selectedIndex > 0)
        {
            monthValue = theList[0].options[theList[0].selectedIndex].value;
        }
    }
    theList = document.getElementsByName('question(dose_day)');
    if (theList != undefined)
    {
        if (theList[0].selectedIndex > 0)
        {
            dayValue = theList[0].options[theList[0].selectedIndex].value;
        }
    }
    theList = document.getElementsByName('question(dose_year)');
    if (theList != undefined)
    {
        if (theList[0].selectedIndex > 0)
        {
            yearValue = theList[0].options[theList[0].selectedIndex].value;
        }
    }

    var doseDateString = monthValue + "/" + dayValue + "/" + yearValue;
    if (!isDate(doseDateString,false))
    {
        if (englishMessage)
        {
            errMessage += "Date the first dose was received.\r\n";
        }
        else
        {
            errMessage += "Fecha de la Primera Dosis Recibida\r\n";
        }
    }
    else
    {
        var doseDate = new Date(yearValue, monthValue-1, dayValue);

        var pastDate = new Date();                       //apply difference
        pastDate.setDate(pastDate.getDate() - 154);

        var futureDate = new Date();                       //apply difference
        futureDate.setDate(futureDate.getDate() + 14);

        if ((doseDate < pastDate) || (doseDate > futureDate))
        {
            if (englishMessage)
            {
                errMessage += "A valid date of the first dose received is needed to send reminders.\r\n";
            }
            else
            {
                errMessage += "Se necesita una fecha válida de la primera cita de la vacuna para poder enviar recordatorios.\r\n";
            }
        }
        else
        {
            pastDate = new Date();                       //apply difference
            pastDate.setDate(pastDate.getDate() - 35);

            if (doseDate < pastDate)
            {
                if (englishMessage)
                {
                    var reply = confirm("Based on the date of the first dose, it is too late to send a reminder for the second dose.\n\nPress OK to receive a reminder for the third dose.");
                }
                else
                {
                    var reply = confirm("Debido a la fecha de su primera cita medica, es muy tarde para enviar un recordatorio para su segunda cita.\n\nOprima 'ok' para recibir un recordatorio para su tercera cita.");
                }
                if (reply == false)
                {
                    if (englishMessage)
                    {
                        errMessage += "Based on the date of the first dose, it is too late to send a reminder for the second dose.\r\n";
                    }
                    else
                    {
                        errMessage += "Debido a la fecha de su primera cita medica, es muy tarde para enviar un recordatorio para su segunda cita.\r\n";
                    }
                }
            }
        }
    }

    return errMessage;
}

/*------------------------------------------------------------------
   complianceValidation.js

   This file contains the submittal validation logic for Gardasil
   3-is-Key form.

   This function returns:
      - true if all data entry is valid;
      - false otherwise (to cancel form submittal)
   -----------------------------------------------------------------*/

  function _3isKey_doClientSidedValidation(theForm, lang)
  {

     ////// "Global" variables //////

     var string_age18           = lang=="en" ?
                                     "You must be 18 years or older to receive reminders." :
                                     "Debes ser mayor de 18 años para poder recibir información";
     var string_dosedatewarning = lang=="en" ?
                                     "Based on the date of the first dose, it is too late to send a reminder for the second dose.\n\nPress OK to receive a reminder for the third dose." :
                                     "Debido a la fecha de su primera cita medica, es muy tarde para enviar un recordatorio para su segunda cita.\n\nOprima 'ok' para recibir un recordatorio para su tercera cita.";
     var string_postaladdress   = lang=="en" ?
                                     "You have not entered a complete postal address.\nDo you only want email reminders?\n\nPress OK if you only want email reminders." :
                                     "No has incluido una dirección postal válida.\n¿Desea recibir recordatorios solamente por e-mail?\n\nOprima \'ok\' para recibir recordatorios solamente por e-mail.";
     var string_requiredinfo    = lang=="en" ?
                                     "The following information is required" :
                                     "Se requiere llenar las siguientes secciones";
     var string_emailvalid      = lang=="en" ?
                                     "A valid email address is needed to send reminders." :
                                     "Se necesita una dirección de e-mail válida para poder enviar recordatorios.";
     var string_validdate       = lang=="en" ?
                                     "A valid date of the first dose received is needed to send reminders." :
                                     "Se necesita una fecha válida de la primera cita de la vacuna para poder enviar recordatorios.";

     var string_firstname  = lang=="en" ? "Patient first name" : "Nombre de la Paciente";
     var string_lastname   = lang=="en" ? "Patient last name" : "Apellido de la Paciente";
     var string_zip        = lang=="en" ? "ZIP code" : "Código postal";
     var string_email      = lang=="en" ? "E-mail address" : "Dirección de E-mail";
     var string_dosedate   = lang=="en" ? "Date the first dose was received" : "Fecha de la Primera Dosis Recibida";

     var field_check18       = theForm["question(AGE_18)"];
     var field_firstname     = theForm.firstname;
     var field_lastname      = theForm.lastname;
     var field_address1      = theForm.address1;
     var field_address2      = theForm.address2;
     var field_city          = theForm.city;
     var field_state         = theForm.state;
     var field_zip           = theForm.postalcode;
     var field_email         = theForm.email;
     var field_dosemonth     = theForm["question(dose_month)"];
     var field_doseday       = theForm["question(dose_day)"];
     var field_doseyear      = theForm["question(dose_year)"];
     var field_contactoption = theForm["question(CONTACT_OPTION)"];

   /*----------------------------------------------------
      Utility function.  Return a string to indicate the
        level of data entry in the postal address fields
      Assumes zip code field contains valid data.
     ----------------------------------------------------*/
     function postalAddressEntry()
     {
        var addrlen  = field_address1.value.length;
        var citylen  = field_city.value.length;
        var statelen = field_state.value.length;

        if (addrlen==0 && citylen==0 && statelen==0)
           return "not entered";
        else
        if (addrlen>0 && citylen>0 && statelen>0)
           return "complete";
        else
           return "partial";
     }

   /*------------------------------------------------------
      Utility function. Returns a date adjusted by
      a number of days. Number of days can be a negative
      number to get a date in the past.
      Returned date is set to midnight.
     ------------------------------------------------------*/
     function getCurrentDatePlusDays(days)
     {
        var myDate = new Date();

        myDate = new Date(myDate.setDate(myDate.getDate() + days));                    //apply difference
        myDate = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());  //remove time element (set to midnight)

        return myDate;
     }

   /*----------------------------------------------------------------
      Check required fields.
      =====================
      Returns: false if required data is missing; otherwise true.
     ----------------------------------------------------------------*/
     function checkRequiredFields()
     {
        var focusField = null;    //used to set focus, and indicates return value
        var message = string_requiredinfo + ":\n";
        var doseDate = new Object();

        doseDate.value = "" + field_dosemonth.value + "-" + field_doseday.value + "-" + field_doseyear.value;
        doseDate.value = /[0-9]+\-[0-9]+\-[0-9]/.test(doseDate.value) ? doseDate.value : "";  //blank it out if it's incomplete
        doseDate.focus = function() { field_dosemonth.focus(); }

        var fields =
            [
              [field_firstname, string_firstname],
              [field_lastname,  string_lastname],
              [field_zip,       string_zip],
              [field_email,     string_email],
              [ doseDate,       string_dosedate]
            ];

        //look for missing data...
        for (var i=0; i<fields.length; i++)
        {
           if (fields[i][0].value == "")
           {
              if (focusField == null) focusField = fields[i][0];
              message += "\n    " + fields[i][1];
           }
        }

        //check zip code format (invalid zip code is treated as missing data)...
        if ( field_zip.value.length > 0 )
        {
           var re = /(^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$)/;
           if (re.test(field_zip.value) == false)
           {
              if (focusField == null) focusField = field_zip;
              message += "\n    " + "ZIP code";
           }
        }

        if (focusField != null)   //if a focus field was identified, it means missing data was found
        {
           alert( message + "\n " );
       focusField.focus();
       return false;
        }

        return true;
     }


   /*-----------------------------------------------------------------------------
      Check e-mail address format.
      ===========================
      Returns: false if required email address has invalid format; otherwise true.
     ------------------------------------------------------------------------------*/
     function checkEmailFormat()
     {
        //this regex was found on RegExLib.com//
        var re = /([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;

        var test = re.test(field_email.value);

        if (test == false)
        {
           alert(string_emailvalid);
           field_email.focus();
        }

        return test;
     }


   /*---------------------------------------------------------------------
      Check for valid date of first dose.
      ==================================

      Check if dose date is a real date (e.g.: not 4/31/2008 or 2/29/2007),
      and is in range (154days -> today -> 14days)

      Returns: false if the dose date is incorrect or out of range;
               otherwise true.
      Assumes: date fields are all entered.
     ---------------------------------------------------------------------*/
     function checkDoseDate()
     {
        var m = { feb:1, apr:3, jun:5, sep:8, nov:10 };

        var month = parseInt(field_dosemonth.value) - 1;  //zero-based
        var day   = parseInt(field_doseday.value);
        var year  = parseInt(field_doseyear.value);

        var bad = false;

        if ( (month==m.feb || month==m.apr || month==m.jun || month==m.sep || month==m.nov) && (day>30) )
           bad = true;
        else
        if ( (month == m.feb) && ((year%4==0 && day>29) || (year%4!=0 && day>28)) )
    bad = true;
        else
        {
           var doseDate = new Date(year, month, day);
           var pastDate = getCurrentDatePlusDays(-154);
           var futrDate = getCurrentDatePlusDays(14);

           if ((doseDate < pastDate) || (doseDate > futrDate))
           {
              alert(string_validdate);
              field_dosemonth.focus();
              bad = true;
           }
        }

        return !bad;
     }


   /*---------------------------------------------------------------------------------------
      Warn if dose date is more than 35 days in the past.
      ==================================================
      Assumes dose date fields contain valid data.
      Returns: true if dose date is within 35 days, or user clicks "OK"
               false if the dose date more than 35 days in the past and user clicks "Cancel"
     ---------------------------------------------------------------------------------------*/
     function doseDateWarning()
     {
        var month = parseInt(field_dosemonth.value) - 1;  //zero-based
        var day   = parseInt(field_doseday.value);
        var year  = parseInt(field_doseyear.value);

        var doseDate = new Date(year, month, day);
        var pastDate = getCurrentDatePlusDays(-35);

        if (doseDate < pastDate)
        {
           var reply = confirm(string_dosedatewarning);
           if (reply == false)
           {
              field_dosemonth.focus();
              return false;
           }
        }

        return true;
     }

   /*-------------------------------------------------------------------------------------
      Warn on incomplete entry of postal address.
      ==========================================
      Checks the level of data entry in the postal address fields.
      Returns: true to continue processing
               false to cancel processing
     --------------------------------------------------------------------------------------*/
     function postalAddressWarning()
     {
        if (postalAddressEntry() == "partial")
        {
           var reply = confirm(string_postaladdress);
           if (reply == false)
           {
              field_address1.focus();
              return false;
           }
        }

        return true;
     }

  /* -----------------------------------------------------
      Main processing logic...
     -----------------------------------------------------*/

  /* STEP 1: test the 18-years-or-older flag */

     if (field_check18.checked == false)
     {
        alert(string_age18);
        field_check18.focus();
        return false;
     }

  /* STEP 2: test required fields  */

     if (checkRequiredFields() == false)
        return false;

  /* STEP 3: test data validity  */

     if (checkEmailFormat() == false)
        return false;

     if (checkDoseDate() == false)
        return false;

  /* STEP 4: test if dose date is more than 21 days in the past */

     if (doseDateWarning() == false)
        return false;

  /* STEP 5: check for partial address */

     if (postalAddressWarning() == false)
        return false;

  /* STEP 6: set CONTACT_OPTION */

     if (postalAddressEntry() == "complete")
        field_contactoption.value = "A3";    //will send both regular mail and email
     else
     {
        field_contactoption.value = "A2";    //will send email only
        if (postalAddressEntry() == "partial")
        {
           field_address1.value = "";        //clean it up
           field_address2.value = "";
           field_city.value = "";
           field_state.value = "";
        }
     }

     return true;
  }

