/*
 * Copyright (c) 2005-2015 RevX Systems, Corp.,  All Rights Reserved.
 *
 * All Rights Reserved.  Unpublished rights reserved under
 * the copyright laws of the United States.
 *
 * The software contained on this media is proprietary to
 * and embodies the confidential technology of RevX Systems
 * Possession, use, duplication or dissemination of
 * the software and media is authorized only pursuant to
 * a valid written license from RevX Systems.
 *
 * RESTRICTED RIGHTS LEGEND  Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set
 * forth in Subparagraph (c)(1)(ii) of DFARS 252.227-7013,
 * or in FAR 52.227-19, as applicable.
 *
 */

/************************************************************************/
/*      Function:       fnValidateKit                                   */
/*                                                                      */
/*      Summary:        Make sure a valid kit is selected if displayed  */
/*                                                                      */
/************************************************************************/
function fnValidateKit()
{
    if ( document.getElementById('kit_id').value != '*' )
    {  document.getElementById('kit_id').className = 'Valid';
        fnToggleButtonStatus();
        return true;
    }
    else
    {  document.getElementById('kit_id').className = 'Invalid';
        fnToggleButtonStatus();
        return false;
    }
}

/************************************************************************/
/*      Function:       fnEmptyOk                                       */
/*                                                                      */
/*      Summary:        Generic catch all for fields which are allowed  */
/*                      to be empty (not required).                     */
/*                                                                      */
/************************************************************************/
function fnEmptyOk(objField)
{
  objField.className = 'Valid';
  fnToggleButtonStatus();
  return true;
}

/************************************************************************/
/*      Function:       fnValidateSubscription                          */
/*                                                                      */
/*      Summary:        Make sure a valid subscription plan is selected.*/
/*                                                                      */
/************************************************************************/
function fnValidateSubscription()
{
    if ( document.getElementById('subscription_id').value != '0' )
    {
        // Disable modalUI for auto complete
        $(document).unbind('ajaxStart');
        $(document).unbind('ajaxStop');

        $( "#pkgLongTextDesc" ).load( "/handlers/gui/Package.FullDescription.php?PackageId=" + document.getElementById('subscription_id').value );

        // Restore modalUI after autocomplete
        $(document).ajaxStart(function(){ fnShowModal();
        }).ajaxStop(function(){  fnCloseModal();
        });

        document.getElementById('subscription_id').className = 'Valid';
        fnToggleButtonStatus();
        return true;
    }
    else
    {
        $('#pkgLongTextDesc').html(null);
        document.getElementById('subscription_id').className = 'Invalid';
        fnToggleButtonStatus();
        return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateUsername                              */
/*                                                                      */
/*      Summary:        Make sure a username is provided                */
/*                                                                      */
/************************************************************************/
function fnValidateUsername(objUsername)
{
    objUsername.value = objUsername.value.toLowerCase();
    /* Verify the data is a valid E-mail address.  If so, glow the box green */
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    if ( emailPattern.test(objUsername.value) )
    { objUsername.className = 'Valid';
      fnToggleButtonStatus();
      return true;
    }
    else
    { objUsername.className = 'Invalid';
      fnToggleButtonStatus();
      return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateConfUsername                          */
/*                                                                      */
/*      Summary:        Make sure a username is provided                */
/*                                                                      */
/************************************************************************/
function fnValidateConfUsername(objConfUsername)
{
    objConfUsername.value = objConfUsername.value.toLowerCase();
    /* Verify the data is a valid E-mail address.  If so, glow the box green */
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    if ( emailPattern.test(objConfUsername.value) )
    {
      // If the entered username parses ok, and it matches, then OK.
      if ( $('#conf_username').val() == $('#username').val() )
      {
        objConfUsername.className = objConfUsername.className.replace('Invalid','Valid');
        fnToggleButtonStatus();
        return true;
      }
      else
      {
        objConfUsername.className = objConfUsername.className.replace('Valid','Invalid');
        fnToggleButtonStatus();
        return false;
      }
    }
    else
    {
      objConfUsername.className = objConfUsername.className.replace('Valid','Invalid');
      fnToggleButtonStatus();
      return false;
    }
}

/************************************************************************/
/*      Function:       fnValidatePassword                              */
/*                                                                      */
/*      Summary:        Make sure a valid password is provided          */
/*                                                                      */
/************************************************************************/
function fnValidatePassword(objPassword)
{
    /* Only allow Alphanumeric support plus a few legacy symbols. */
    // objPassword.value = objPassword.value.replace(/[\W_]+/g, '');
    objPassword.value = objPassword.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');


    if ( objPassword.value.length > 5 )
    {  objPassword.className = objPassword.className.replace('Invalid','Valid');
       fnToggleButtonStatus();
    }
    else
    {  objPassword.className = objPassword.className.replace('Valid','Invalid');
       fnToggleButtonStatus();
    }

    /* Make sure we haven't changed the primary password field thus */
    /* causing the confirmed and primary password to become         */
    /* mismatched.                                                  */
    if ( $('#vpassword').length > 0) {
      fnValidateConfPassword(document.getElementById('vpassword'));
    }
}

/************************************************************************/
/*      Function:       fnValidateConfPassword                          */
/*                                                                      */
/*      Summary:        Make sure the secondary password keyed in       */
/*                      the contents of the first password entry.       */
/*                                                                      */
/************************************************************************/
function fnValidateConfPassword(objConfPassword)
{
    /* Only allow Alphanumeric support plus a few legacy symbols. */
    //objConfPassword.value = objConfPassword.value.replace(/[\W_]+/g, '');
    objConfPassword.value = objConfPassword.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');

    var strPassword = document.getElementById('password').value;
    if ( objConfPassword.value.length > 0 && objConfPassword.value == strPassword )
    {  objConfPassword.className = objConfPassword.className.replace('Invalid','Valid');
       fnToggleButtonStatus();
       return true;
    }
    else
    {  objConfPassword.className = objConfPassword.className.replace('Valid','Invalid');
       fnToggleButtonStatus();
       return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateCardholder                            */
/*                                                                      */
/*      Summary:        Make sure a valid Cardholder is entered for the */
/*                      payment information.                            */
/*                                                                      */
/************************************************************************/
function fnValidateCardholder(objCardholder)
{
    objCardholder.value = objCardholder.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');

    // If a reasonable length is provided and two name elements are present.
    if ( objCardholder.value.length > 5 && objCardholder.value.trim().split(" ").length > 1 )
    {  objCardholder.className = objCardholder.className.replace('Invalid','Valid');
       fnToggleButtonStatus();
    }
    else
    {  objCardholder.className = objCardholder.className.replace('Valid','Invalid');
       fnToggleButtonStatus();
    }
}

/************************************************************************/
/*      Function:       fnValidateCardNumber                            */
/*                                                                      */
/*      Summary:        Make sure a mathematically correct CC number    */
/*                      has been provided.                              */
/*                                                                      */
/************************************************************************/
function fnValidateCardNumber(objCcnumber)
{
  // Define last char before cleaning
  var lastChar = objCcnumber.value[objCcnumber.value.length -1];

  // First remove any undesireable characters.
  objCcnumber.value = objCcnumber.value.replace(/[^\d-]/g, '');

  // Pull a digits only version of the field to see if it's on a 4-byte
  // boundary.
  var strNumber = objCcnumber.value.replace(/[^\d]/g, '');

  // If we're not empty, and not at the end, and at a 4-byte boundary, place a '-'
  // in the field.
  if ( strNumber.length > 1 && strNumber.length < 13 && (strNumber.length % 4 == 0)  )
  {
    // Make sure last value is not '-'
    if (lastChar != "-")
    {
      objCcnumber.value = objCcnumber.value + '-';
    }
  }

  $('#cardnumber').validateCreditCard(function(result) {
      if ( result.luhn_valid && result.length_valid && result.valid )
      {
          objCcnumber.className = objCcnumber.className.replace('Invalid','Valid');
        /*
          $('.log').html('Card type: ' + (result.card_type == null ? '-' : result.card_type.name)
              + '<br>Valid: ' + result.valid
              + '<br>Length valid: ' + result.length_valid
              + '<br>Luhn valid: ' + result.luhn_valid);
        */
        fnToggleButtonStatus();
      }
      else
      {
          objCcnumber.className = objCcnumber.className.replace('Valid','Invalid');
        /*
          $('.log').html('Card type: ' + (result.card_type == null ? '-' : result.card_type.name)
              + '<br>Valid: ' + result.valid
              + '<br>Length valid: ' + result.length_valid
              + '<br>Luhn valid: ' + result.luhn_valid);
        */
        fnToggleButtonStatus();
      }
  });

}

/************************************************************************/
/*      Function:       fnCheckLuhn                                     */
/*                                                                      */
/*      Summary:        Validation on the CC number.                    */
/*                                                                      */
/************************************************************************/
function fnCheckLuhn(ccnumber)
{
    var sum       = 0;
    var numdigits = ccnumber.length;
    var parity    = numdigits % 2;

    for(var i=0; i < numdigits; i++)
    {
      var digit = parseInt(ccnumber.charAt(i))
      if(i % 2 == parity) digit *= 2;
      if(digit > 9) digit -= 9;
      sum += digit;
    }
    return (sum % 10) == 0;
}

/************************************************************************/
/*      Function:       fnValidateBillingAddress                        */
/*                                                                      */
/*      Summary:        Do some basic sanity checking on the Billing    */
/*                      address provided.                               */
/*                                                                      */
/************************************************************************/
function fnValidateBillingAddress(objCcaddress)
{
    objCcaddress.value = objCcaddress.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');

    // If a reasonable length is provided and two name elements are present.
    if ( objCcaddress.value.length > 5 && objCcaddress.value.indexOf(' ') != -1 )
    {  objCcaddress.className = 'Valid';
       fnToggleButtonStatus();
    }
    else
    {  objCcaddress.className = 'Invalid';
       fnToggleButtonStatus();
    }
}

/************************************************************************/
/*      Function:       fnValidateBillingCity                           */
/*                                                                      */
/*      Summary:        Do some basic sanity checking on the Billing    */
/*                      City provided.                                  */
/*                                                                      */
/************************************************************************/
function fnValidateBillingCity(objCCcity)
{
    objCCcity.value = objCCcity.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');

    // If a reasonable length is provided.
    if ( objCCcity.value.length >= 2 )
    {  objCCcity.className = 'Valid';
       fnToggleButtonStatus();
    }
    else
    {  objCCcity.className = 'Invalid';
       fnToggleButtonStatus();
    }
}

/************************************************************************/
/*      Function:       fnValidateBillingState                          */
/*                                                                      */
/*      Summary:        Make sure a valid state code is selected for the*/
/*                      Credit Card Screen.                             */
/*                                                                      */
/************************************************************************/
function fnValidateBillingState(objState)
{
    if ( objState.value.value != '*' )
    {  objState.className = 'Valid';
       fnToggleButtonStatus();
       return true;
    }
    else
    {  objState.className = 'Invalid';
       fnToggleButtonStatus();
       return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateShipTo                                */
/*                                                                      */
/*      Summary:        Do some basic sanity checking on the shipping   */
/*                      contact name provided.                          */
/*                                                                      */
/************************************************************************/
function fnValidateShipto(objShipto)
{
    objShipto.value = objShipto.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');

    // If a reasonable length is provided and two name elements are present.
    if ( objShipto.value.length > 5 && objShipto.value.trim().split(" ").length > 1 )
    {  objShipto.className = 'Valid';
       fnToggleButtonStatus();
    }
    else
    {  objShipto.className = 'Invalid';
       fnToggleButtonStatus();
    }
}

/************************************************************************/
/*      Function:       fnValidateShipAddress                           */
/*                                                                      */
/*      Summary:        Do some basic sanity checking on the shipping   */
/*                      address provided.                               */
/*                                                                      */
/************************************************************************/
function fnValidateShipAddress(objShipaddress)
{
    objShipaddress.value = objShipaddress.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');

    // If a reasonable length is provided and two name elements are present.
    if ( objShipaddress.value.length > 5 && objShipaddress.value.indexOf(' ') != -1 )
    {  objShipaddress.className = 'Valid';
       fnToggleButtonStatus();
    }
    else
    {  objShipaddress.className = 'Invalid';
       fnToggleButtonStatus();
    }
}

/************************************************************************/
/*      Function:       fnValidateShipCity                              */
/*                                                                      */
/*      Summary:        Do some basic sanity checking on the Shipping   */
/*                      City provided.                                  */
/*                                                                      */
/************************************************************************/
function fnValidateShipCity(objShipcity)
{
    objShipcity.value = objShipcity.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');

    // If a reasonable length is provided.
    if ( objShipcity.value.length >= 2 )
    {  objShipcity.className = 'Valid';
       fnToggleButtonStatus();
    }
    else
    {  objShipcity.className = 'Invalid';
       fnToggleButtonStatus();
    }
}

/************************************************************************/
/*      Function:       fnValidateShipCountry                           */
/*                                                                      */
/*      Summary:        Do some basic sanity checking on the Shipping   */
/*                      Country Chosen.                                 */
/*                                                                      */
/************************************************************************/
function fnValidateShipCountry(objShipCountry)
{
    if ( objShipCountry.value != '*' )
    {  objShipCountry.className = 'Valid';
        fnToggleButtonStatus();

        // Populate the Ship States Drop-down with data.
        fnBindStateCodes(objShipCountry,"shipstate");
    }
    else
    {  objShipCountry.className = 'Invalid';
        fnToggleButtonStatus();

        // Clear the Shipping States Drop-down.
        fnUnbindStateCodes("shipstate");
    }
}

/************************************************************************/
/*      Function:       fnValidateBillCountry                           */
/*                                                                      */
/*      Summary:        Do some basic sanity checking on the Billing    */
/*                      Country Chosen.                                 */
/*                                                                      */
/************************************************************************/
function fnValidateBillCountry(objBillCountry)
{
    if ( objBillCountry.value != '*' )
    {  objBillCountry.className = 'Valid';
        fnToggleButtonStatus();

        // Populate the Billing States Drop-down with data.
        fnBindStateCodes(objBillCountry,"ccstate");

    }
    else
    {  objBillCountry.className = 'Invalid';
       fnToggleButtonStatus();

       // Clear the Credit Card States Drop-down.
       fnUnbindStateCodes("ccstate");
    }
}

/************************************************************************/
/*      Function:       fnValidateShipState                             */
/*                                                                      */
/*      Summary:        Make sure a valid state code is selected for the*/
/*                      Shipping Address.                               */
/*                                                                      */
/************************************************************************/
function fnValidateShipState(objShipState)
{
    if ( objShipState.value != '*' )
    {  objShipState.className = 'Valid';
       fnToggleButtonStatus();
       return true;
    }
    else
    {  objShipState.className = 'Invalid';
       fnToggleButtonStatus();
       return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateZipCode                               */
/*                                                                      */
/*      Summary:        Make sure a valid zip code has been entered     */
/*                                                                      */
/************************************************************************/
function fnValidateZipCode(objZip)
{
  //objZip.value = objZip.value.replace(/[^\d]/g, '');
  objZip.value = objZip.value.replace(/[^[a-z0-9]]/g, '');

  if ( objZip.value.length > 4 )
  {  objZip.className = objZip.className.replace('Invalid','Valid');
    fnToggleButtonStatus();
    return true;
  }
  else
  {  objZip.className = objZip.className.replace('Valid','Invalid');
    fnToggleButtonStatus();
    return false;
  }
}

/************************************************************************/
/*      Function:       fnValidateShippingOptions                       */
/*                                                                      */
/*      Summary:        Make sure a valid shipping has been chosen      */
/*                                                                      */
/************************************************************************/
function fnValidateShippingOptions(objShippingOptions)
{
    if ( objShippingOptions.value != '*' )
    {  objShippingOptions.className = 'Valid';
       fnToggleButtonStatus();
       return true;
    }
    else
    {  objShippingOptions.className = 'Invalid';
       fnToggleButtonStatus();
       return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateMEIDorICCID                           */
/*                                                                      */
/*      Summary:        For rare cases when a custom field is           */
/*                      marked for dual input like ICCID or MEID        */
/*                      check it's contents against both sets of rules. */
/*                                                                      */
/************************************************************************/
function fnValidateMEIDorICCID(objField)
{
  objField.value = objField.value.toUpperCase();
  objField.value = objField.value.replace(/\s+/g, ''); // Strip spaces.

  var meidPattern = /^[A1]{2}[0-9a-fA-F]{12}$/g;
  var iccidPattern = /^[0-9]{19,20}$/g;

  if ( meidPattern.test(objField.value) || iccidPattern.test(objField.value) )
  {  objField.className = 'Valid';
     fnToggleButtonStatus();
     return true;
  }
  else
  {  objField.className = 'Invalid';
     fnToggleButtonStatus();
     return false;
  }

}

/************************************************************************/
/*      Function:       fnValidateMEID                                  */
/*                                                                      */
/*      Summary:        Make sure a valid MEID has been entered         */
/*                                                                      */
/************************************************************************/
function fnValidateMEID(objMEID)
{
    objMEID.value = objMEID.value.toUpperCase();
    objMEID.value = objMEID.value.replace(/\s+/g, '');

    var meidPattern = /[A1]{2}[0-9a-fA-F]{12}/g;

    if ( objMEID.value.length == 14 && meidPattern.test(objMEID.value) )
    {  objMEID.className = 'Valid';
       fnToggleButtonStatus();
       return true;
    }
    else
    {  objMEID.className = 'Invalid';
       fnToggleButtonStatus();
       return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateIMEI                                  */
/*                                                                      */
/*      Summary:        Make sure a valid IMEI has been entered         */
/*                                                                      */
/************************************************************************/
function fnValidateIMEI(objIMEI, MinLength, MaxLength)
{
    /* Strip Non-Digits */
    objIMEI.value = objIMEI.value.replace(/[^\d]/g, '');

    var patternIMEI = /^(89)(1)(48[0-9])(\d{13})(\d)$/g;

    if ( objIMEI.value.length >= MinLength && objIMEI.value.length <= MaxLength )
    {  objIMEI.className = 'Valid';
        //fnToggleButtonStatus();
        return true;
    }
    else
    {  objIMEI.className = 'Invalid';
        //fnToggleButtonStatus();
        return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateICCID                                 */
/*                                                                      */
/*      Summary:        Make sure a valid ICCID has been entered        */
/*                      TMOBILE does not follow the standard 20         */
/*                      digits and prints the "F" on the card, but      */
/*                      KORE does not require the input of the "F"      */
/*                      so 19 characters are valid in this case.        */
/*                                                                      */
/************************************************************************/
function fnValidateICCID(objICCID, bIsTmobile )
{
    var iFieldLen = 20;

    /* Strip Non-Digits */
    objICCID.value = objICCID.value.replace(/[^\d]/g, '');

    /* Support for TMOBILE */
    if ( bIsTmobile ) iFieldLen = 19;

    if ( objICCID.value.length == iFieldLen )
    {  objICCID.className = 'Valid';
        //fnToggleButtonStatus();
        return true;
    }
    else
    {  objICCID.className = 'Invalid';
        //fnToggleButtonStatus();
        return false;
    }
}

/************************************************************************/
/*      Function:       fnValidateTerms                                 */
/*                                                                      */
/*      Summary:        Make sure a the terms checkbox is checked.      */
/*                                                                      */
/************************************************************************/
function fnValidateTerms(objTerms)
{
    if ( objTerms.checked == 1  )
    {  objTerms.className = 'Valid';
        fnToggleButtonStatus();
        return true;
    }
    else
    {  objTerms.className = 'Invalid';
        fnToggleButtonStatus();
        return false;
    }
}

/************************************************************************/
/*      Function:       fnToggleButtonStatus                            */
/*                                                                      */
/*      Summary:        Check all controls on the form, and set the     */
/*                      button state to allow or disallow the signup.   */
/*                                                                      */
/************************************************************************/
function fnToggleButtonStatus()
{
  var bAllValid = true;

  // Fetch all visible elements which still have the Invalid class.
  var visibleElements = $( ".Invalid:visible");
  if ( visibleElements.length > 0 )
  {
    document.getElementById('btn_send').value    = btnInvalidCaption;
    document.getElementById('btn_send').disabled = true;
  }
  else
  {
    document.getElementById('btn_send').value    = btnValidCaption;
    document.getElementById('btn_send').disabled = false;
  }

  return;

  /* OLD Validation Method replaced with a JQUERY selector query */

/*
  var inputs = document.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i += 1)
  {
    if ( inputs[i].className == 'Invalid' ) bAllValid = false;
  }

  var selects = document.getElementsByTagName('select');
  for (var i = 0; i < selects.length; i += 1)
  {
    if ( selects[i].className == 'Invalid' ) bAllValid = false;
  }

  if ( bAllValid )
  {
    document.getElementById('btn_send').value    = btnValidCaption;
    document.getElementById('btn_send').disabled = false;
  }
  else
  {
    document.getElementById('btn_send').value    = btnInvalidCaption;
    document.getElementById('btn_send').disabled = true;
  }
*/

}

/************************************************************************/
/*      Function:       fnValidateNonEmpty                              */
/*                                                                      */
/*      Summary:        Generic validator to check for non-empty        */
/*                      and set the class indicator accordingly.        */
/*                                                                      */
/************************************************************************/
function fnValidateNonEmpty(objField)
{

    objField.value = objField.value.replace(/[^a-z0-9$@ %#!.*_-]+/gi, '');

    // If a reasonable length is provided.
    if ( objField.value.length > 3 )
      objField.className = objField.className.replace('Invalid','Valid');
    else
      objField.className = objField.className.replace('Valid','Invalid');
}

/************************************************************************/
/*      Function:       fnValidateEmpty                                 */
/*                                                                      */
/*      Summary:        Apply some generic data entry constraints to an */
/*                      optional field.                                 */
/*                                                                      */
/************************************************************************/
function fnValidateEmpty(objField)
{
  objField.value = objField.value.replace(/[^a-z0-9$@ %#!.*_]+/gi, '');
  objField.className = objField.className.replace('Invalid','Valid');
}

/************************************************************************/
/*      Function:       fnValidateDropDown                              */
/*                                                                      */
/*      Summary:        Generic validator to check for non-default      */
/*                      selector in a Drop Down list.                   */
/*                                                                      */
/************************************************************************/
function fnValidateDropDown(objField)
{
    if ( objField.value != '*' )
      objField.className = objField.className.replace('Invalid','Valid');
    else
      objField.className = objField.className.replace('Valid','Invalid');
}

/************************************************************************/
/*      Function:       fnValidateEmailAddress                          */
/*                                                                      */
/*      Summary:        Make sure a valid email address was provided.   */
/*                                                                      */
/************************************************************************/
function fnValidateEmailAddress(objEmailAddress)
{
    objEmailAddress.value = objEmailAddress.value.toLowerCase();
    /* Verify the data is a valid E-mail address.  If so, glow the box green */
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    if ( emailPattern.test(objEmailAddress.value) )
      objEmailAddress.className = objEmailAddress.className.replace('Invalid','Valid');
    else
        objEmailAddress.className = objEmailAddress.className.replace('Valid','Invalid');
}

/************************************************************************/
/*      Function:       fnValidatePhoneNumber                           */
/*                                                                      */
/*      Summary:        Make sure a valid NON alpha phone number        */
/*                                                                      */
/************************************************************************/
function fnValidatePhoneNumber(objPhone)
{
    objPhone.value = objPhone.value.replace(/[^\d]/g, '');
    objPhone.className = objPhone.className.replace('Invalid','Valid');
}

/************************************************************************/
/*      Function:       fnLoadStateCodes                                */
/*                                                                      */
/*      Summary:        Based on a chosen country code, load the        */
/*                      available state/provinces.                      */
/*                                                                      */
/*      Arguments:      fldCountry - DOM object of the Country field.   */
/*                                                                      */
/*                      strState - string name of the DOM object for    */
/*                      easy jquery selection.                          */
/************************************************************************/
function fnLoadStateCodes(fldCountry, strState)
{
    // First clear our the contents and re-add the default.
    $('#' + strState).empty();
    $('#' + strState).append("<option value=\"*\" selected=\"selected\">State/Province</option>");

    // Replace Valid with Invalid since we're changing the country code.
    strClass = $('#' + strState).attr('class');
    strClass = strClass.replace('Valid','Invalid');
    $('#' + strState).attr('class', strClass );

    // If a valid country is chosen, then mark the control as valid.
    if ( fldCountry.value != '*' )
    {
        fldCountry.className = fldCountry.className.replace('Invalid','Valid');
        fnToggleButtonStatus();
    }
    else
    {
        fldCountry.className = fldCountry.className.replace('Valid','Invalid');
        fnToggleButtonStatus();
        return;
    }

    var selCountry = fldCountry.value;
    var objCountryStates = objCountries[selCountry];

    // Iterate over all selectable states in this country.
    for (var countryId in objCountryStates)
    {
        var newOptionText = objCountryStates[countryId];
        var newOptionId   = countryId;
        var newOption     = "<option value='"+newOptionId+"'>"+newOptionText+"</option>";
        $('#' + strState).append(newOption);
    }

}

/************************************************************************/
/*      Function:       fnLoadSubscriptions                             */
/*                                                                      */
/*      Summary:        Based on a provided Package Category, load the  */
/*                      selectable subscriptions into the drop-down     */
/*                                                                      */
/************************************************************************/
function fnLoadSubscriptions(objCategory)
{
    // First clear our the contents and re-add the default.
    $("#subscription_id").empty();
    $("#subscription_id").attr('class', 'Invalid');
    $('#pkgLongTextDesc').html(null);

    // If a valid Category is chosen, then mark the control as valid.
    if ( objCategory.value != '*' )
    {
        objCategory.className = objCategory.className.replace('Invalid','Valid');
    }
    else
    {
        objCategory.className = objCategory.className.replace('Valid','Invalid');

        return;
    }

    var selCategory = objCategory.value;
    var objCategory = objSubs[selCategory];

    // Iterate over all selectable packages in this category.
    for (var pkgId in objCategory)
    {
      var newOptionText = objCategory[pkgId];
      var newOptionId   = pkgId;
      var newOption     = '';

      if ( newOptionId != '0' )
      {
        newOption = "<option value='"+newOptionId+"'>"+newOptionText+"</option>";
      }
      else
      {
        newOption = "<option selected='selected' value='"+newOptionId+"'>"+newOptionText+"</option>";
      }

      $("#subscription_id").append(newOption);

    }

}

/************************************************************************/
/*      Function:       fnToggleShippingCheckbox                        */
/*                                                                      */
/*      Summary:        Will inspect the state of the checkbox used     */
/*                      to indicate if the Billing address should be    */
/*                      copied into the shipping fields so the user     */
/*                      doesn't have to type them again.                */
/*                                                                      */
/************************************************************************/
function fnToggleShippingCheckbox(objShippingCheckbox, bBindCountry )
{

  var $inputs1 = $('#cardholder, #shipto');
  var $inputs2 = $('#ccaddress, #shipaddress');
  var $inputs3 = $('#cccity, #shipcity');
  var $inputs4 = $('#ccstate, #shipstate');
  var $inputs5 = $('#cczip, #shipzip');
  var $inputs6;

  /* If Country Code Support activated, then bind it too */
  if ( bBindCountry )
  {
    $inputs6 = $('#cccountry, #shipcountry');
  }


  if($("#shippingcheckbox").is(':checked'))
  {
    // Disable the fields.
    $("#shipto").attr("disabled",      "disabled");
    $("#shipaddress").attr("disabled", "disabled");
    $("#shipcity").attr("disabled",    "disabled");
    $("#shipstate").attr("disabled",   "disabled");
    $("#shipzip").attr("disabled",     "disabled");

    if ( bBindCountry )
    {
      $("#shipcountry").attr("disabled", "disabled");
    }

    // Copy the current values from Cardholder data to the Shipping Fields.
    $("#shipto").val( $("#cardholder").val() );
    $("#shipaddress").val( $("#ccaddress").val() );
    $("#shipcity").val( $("#cccity").val() );
    $("#shipstate").val( $("#ccstate").val() );
    $("#shipzip").val( $("#cczip").val() );

    if ( bBindCountry )
    {
      $("#shipcountry").val( $("#cccountry").val() );
      fnLoadStateCodes( document.getElementById('shipcountry') , 'shipstate');
      $("#shipstate").val( $("#ccstate").val() );
    }

    // Copy over the current CSS status which controls the UI display.
    $("#shipto").attr('class',      $('#cardholder').attr('class') );
    $("#shipaddress").attr('class', $('#ccaddress').attr('class') );
    $("#shipcity").attr('class',    $('#cccity').attr('class') );
    $("#shipstate").attr('class',   $('#ccstate').attr('class') );
    $("#shipzip").attr('class',     $('#cczip').attr('class') );

    if ( bBindCountry )
    {
      $("#shipcountry").attr('class', $('#cccountry').attr('class') );
    }

    // Bind subsequent input events on the CC holder data so it will ensure the
    // shipping fields are kept updated.
    $inputs1.keyup(function(){$inputs1.val($(this).val()); $('#shipto').change() });
    $inputs2.keyup(function(){$inputs2.val($(this).val()); $('#shipaddress').change()});
    $inputs3.keyup(function(){$inputs3.val($(this).val()); $('#shipcity').change()});
    $inputs4.change(function(){$inputs4.val($(this).val()); $('#shipstate').change()});
    $inputs5.keyup(function(){$inputs5.val($(this).val()); $('#shipzip').change()});

    if ( bBindCountry )
    {
      $inputs6.change(function(){$inputs6.val($(this).val()); $('#shipcountry').change()});
    }

  }
  else
  {
    $("#shipto").removeAttr('disabled');
    $("#shipaddress").removeAttr('disabled');
    $("#shipcity").removeAttr('disabled');
    $("#shipstate").removeAttr('disabled');
    $("#shipzip").removeAttr('disabled');

    if ( bBindCountry )
    {
      $("#shipcountry").removeAttr('disabled');
    }

    $inputs1.unbind('keyup');
    $inputs2.unbind('keyup');
    $inputs3.unbind('keyup');
    $inputs4.unbind('change');
    $inputs5.unbind('keyup');

    if ( bBindCountry )
    {
      $inputs6.unbind('change');
    }
  }
}

/************************************************************************/
/*      Function:       fnChangePaymentType                             */
/*                                                                      */
/*      Summary:        Toggle the display for payment type selection   */
/*                                                                      */
/************************************************************************/
function fnChangePaymentType(objPaymentType)
{
  var curSelection = $( "#payment_type" ).val();
  if ( curSelection == 'cc')
  {
    $("#bank" ).hide();
    $("#cc" ).show();
    $("#addressbindcheckbox" ).show();
  }
  else if ( curSelection == 'bank')
  {
    $("#cc" ).hide();
    $("#addressbindcheckbox" ).hide();
    $("#bank" ).show();

    /* If the box is checked, and we're about to hide, then unbind the inputs to the
    ** fields, and uncheck the box.
    */
    if($("#shippingcheckbox").is(':checked'))
    {
      var $inputs1 = $('#cardholder, #shipto');
      var $inputs2 = $('#ccaddress, #shipaddress');
      var $inputs3 = $('#cccity, #shipcity');
      var $inputs4 = $('#ccstate, #shipstate');
      var $inputs5 = $('#cczip, #shipzip');

      $("#shipto").removeAttr('disabled');
      $("#shipaddress").removeAttr('disabled');
      $("#shipcity").removeAttr('disabled');
      $("#shipstate").removeAttr('disabled');
      $("#shipzip").removeAttr('disabled');

      $inputs1.unbind('keyup');
      $inputs2.unbind('keyup');
      $inputs3.unbind('keyup');
      $inputs4.unbind('click');
      $inputs5.unbind('keyup');

      // Un-check the box since we're hiding it and restoring access to the shipping fields.
      $('#shippingcheckbox').attr('checked', false);
    }
  }

  // Since we changed what's visible, the master submit button may need updating.
  fnToggleButtonStatus();

}

/************************************************************************/
/*      Function:       fnValidateBankRoutingNumber                     */
/*                                                                      */
/*      Summary:        Perform Bank Standard ABA Validation.           */
/*                                                                      */
/************************************************************************/
function fnValidateBankRoutingNumber(objBankRoutingNumber)
{
  var i, n, t, aba;

  // Replace all non-numeric characters.
  objBankRoutingNumber.value = objBankRoutingNumber.value.replace(/[^\d]/g, '');

  // Check the length, it should be nine digits.
  if ( objBankRoutingNumber.value.length == 9 )
      objBankRoutingNumber.className = objBankRoutingNumber.className.replace('Invalid','Valid');
  else
      objBankRoutingNumber.className = objBankRoutingNumber.className.replace('Valid','Invalid');

  // Perform basic ABA CRC.
  aba = objBankRoutingNumber.value;
  n   = 0;

  for (i = 0; i <  aba.length; i += 3)
  {
    n += parseInt(aba.charAt(i),     10) * 3
      +  parseInt(aba.charAt(i + 1), 10) * 7
      +  parseInt(aba.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.

  if (n != 0 && n % 10 == 0)
  {
    objBankRoutingNumber.className = objBankRoutingNumber.className.replace('Invalid','Valid');
  }
  else
  {
    objBankRoutingNumber.className = objBankRoutingNumber.className.replace('Valid','Invalid');
  }

  fnToggleButtonStatus();
}

/************************************************************************/
/*      Function:       fnValidateBankAccountNumber                     */
/*                                                                      */
/*      Summary:        Perform Bank Standard Account Number Validation.*/
/*                                                                      */
/************************************************************************/
function fnValidateBankAccountNumber(objBankAccountNumber)
{
  // Replace all non-numeric characters.
    objBankAccountNumber.value = objBankAccountNumber.value.replace(/[^\d]/g, '');

  // Arbitrary limit of 6 characters.
  if ( objBankAccountNumber.value.length > 6 )
  {
      objBankAccountNumber.className = objBankAccountNumber.className.replace('Invalid','Valid');
  }
  else
  {
      objBankAccountNumber.className = objBankAccountNumber.className.replace('Valid','Invalid');
  }

  fnToggleButtonStatus();
}

/************************************************************************/
/*      Function:       fnvalidatePrepaidCard                           */
/*                                                                      */
/*      Summary:        Perform Prepaid Card Number Validation.         */
/*                                                                      */
/************************************************************************/
function fnValidatePrepaidCard(objPrepaidCardNumber)
{
  // Replace all non alpha numeric
  objPrepaidCardNumber.value = objPrepaidCardNumber.value.replace(/[\W_]+/g," ");

  // Return nothing if less than 16 chars
  if (objPrepaidCardNumber.value.length < 16)
  {
      objPrepaidCardNumber.className = objPrepaidCardNumber.className.replace('Valid','Invalid');
      $("#verify").html("");
      return false;
  }
  else
  {
    // Check if code is valid
    $.post( 'handlers/myaccount/MyAccount.PrepaidCard.Verify.php',
        {   token:        document.getElementById('token').value,
            cardnumber:   document.getElementById('prepaidCardNumber').value },
        function(data)
        {
            //alert( fnXMLToString(data) ); // Debug

            var respCode    = data.getElementsByTagName('error')[0].firstChild.nodeValue;
            var respMessage = data.getElementsByTagName('description')[0].firstChild.nodeValue;
            var redirUrl    = data.getElementsByTagName('redir')[0].firstChild.nodeValue;

            switch(respCode)
            {
                case '0':
                    $("#verify").html("");
                    $("#verify").append(respMessage);
                    objPrepaidCardNumber.className = objPrepaidCardNumber.className.replace('Invalid','Valid');
                    $("#btn_prepaid").addClass('Valid').removeClass('Invalid');
                    $("#btn_prepaid").removeAttr('disabled');
                    break;

                case '5':
                    $("#verify").html(respMessage);
                    break;

                default:
                    $("#verify").html("");
                    $("#btn_prepaid").addClass('Invalid').removeClass('Valid');
                    $("#btn_prepaid").attr('disabled', 'disabled');
                    break;
            }
        });
  }

}


/************************************************************************/
/*      Function:       fnValidateLUT                                  */
/*                                                                      */
/*      Summary:        Make sure a valid IMEI has been entered         */
/*                      using a lookup table                            */
/*                                                                      */
/************************************************************************/
function fnValidateLUT(objIMEI, MinLength, MaxLength, Lut)
{
  // Replace all non alpha numeric
  objIMEI.value = objIMEI.value.replace(/[\W_]+/g," ");

  // Check to make sure value is within constraints
  if ( objIMEI.value.length >= MinLength && objIMEI.value.length <= MaxLength )
  {

    var postData = 'LutAlias='+Lut+'&Value='+objIMEI.value;
    var lutResponse = fnDoPostXML_SYNCH(postData,'handlers/myaccount/MyAccount.LookupTable.Verify.php')
    var respCode    = lutResponse.getElementsByTagName('error')[0].firstChild.nodeValue;

    if ( respCode !== '0' )
    {
      return false;
    }
    else
    {
      return true;
    }

  }
}

function fnEnterpriseDMValidateImei(objIMEI, MinLength, MaxLength)
{
  /* Strip Non-Digits */
  objIMEI.value = objIMEI.value.replace(/[^\d]/g, '');

  var patternIMEI = /^(89)(1)(48[0-9])(\d{13})(\d)$/g;

  if ( objIMEI.value.length >= MinLength && objIMEI.value.length <= MaxLength )
  {
    $(objIMEI).addClass('edmValid');
    $(objIMEI).removeClass('edmInvalid');
    return true;
  }
  else
  {
    $(objIMEI).addClass('edmInvalid');
    $(objIMEI).removeClass('edmValid');
    return false;
  }
}

function fnEnterpriseDMValidateICCID(objICCID, bIsTmobile)
{
  var iFieldLen = 20;

  /* Strip Non-Digits */
  objICCID.value = objICCID.value.replace(/[^\d]/g, '');

  /* Support for TMOBILE */
  if ( bIsTmobile ) iFieldLen = 19;

  if ( objICCID.value.length == iFieldLen )
  {
    $(objICCID).addClass('edmValid');
    $(objICCID).removeClass('edmInvalid');
    return true;
  }
  else
  {
    $(objICCID).addClass('edmInvalid');
    $(objICCID).removeClass('edmValid');
    return false;
  }
}

