$(function () {

  //------------------------------------------------------------------------------------
  // This section is for the page that will open the popup form
  if ($(".hearingaid-optin").length > 0) {

    if (jQuery().fancybox) {
      // Set event handler to show the popup
      $(".hearingaid-optin").fancybox({
        'autoScale': false,
        'width'   : 800,
        'height'  : 640,
        'type'    : 'iframe',
        'href'    : '/_layouts/Energizer/popup/hearingaid-optinform.html'
      });

      // Set cursor style
      $(".hearingaid-optin").css("cursor","pointer");
          
      // Check for cookie
      var ENRHAcookieName = "Energizer_sawHearingAidOptInForm";
      if (getCookie(ENRHAcookieName) != "true") {
      
        $(".hearingaid-optin").click();
        
        // Set cookie once the popup has been shown
        setCookieWithPath(ENRHAcookieName, "true", null);
      }
    }
  }
  
  //------------------------------------------------------------------------------------
  // This section is for the popup form itself
  
  if (jQuery().AnyTime_picker) {
    $("#frm-bdate").AnyTime_picker({
      format: "%M %e, %Y",
      labelTitle: "Birth Date"
    });  
  }
  
  $("#btn-submit").click( function(e) {
    e.preventDefault();

    if (_validateEntries()) {
      try {
        var soapmessage =
          '<?xml version="1.0" encoding="utf-8"?>'
          + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
            + '<soap:Body>'
              + '<UpdateHearingAidOptIn xmlns="http://www.energizer.com/webservices/UpdateLists/">'
                + '<lastName>' + $("#frm-lname").val() + '</lastName>'
                + '<firstName>' + $("#frm-fname").val() + '</firstName>'
                + '<email>' + $("#frm-email").val() + '</email>'
                + '<birthDate>' + $("#frm-bdate").val() + '</birthDate>'
                + '<optInHearingAid>' + $("#frm-optin-hearingaid").is(":checked") + '</optInHearingAid>'
                + '<optInAll>' + $("#frm-optin-energizer").is(":checked") + '</optInAll>'
              + '</UpdateHearingAidOptIn>'
            + '</soap:Body>'
          + '</soap:Envelope>';
            
        $.ajax({
          url: "/_vti_bin/EnergizerUpdateLists.asmx",
          type: "POST",
          dataType: "text",
          data: soapmessage,
          beforeSend:
            function (xhr) {
              // Pass the action onto the proxy.
              xhr.setRequestHeader("SOAPAction", "http://www.energizer.com/webservices/UpdateLists/UpdateHearingAidOptIn");
            },
          /*
          complete:
            function (xhr) {
              alert(xhr.responseText);  //debug
            },
          */
          contentType: "text/xml; charset=\"utf-8\""
        });          
      } catch(err) {
      }
      
      // Close the popup
      $("#fieldscontainer").hide();
      if (jQuery.support.opacity) {
        $("#confirmed").fadeIn(400);
      } else {
        $("#confirmed").show();
      }
      setTimeout("parent.$.fancybox.close()", 1000);
    }
    
  });

  function _validateEntries() {
    $("#cstm-messages").hide();
    var messages = "";

    // Check required fields
    if ($("#frm-bdate").val() === ""
      || $("#frm-fname").val() === ""
      || $("#frm-lname").val() === ""
      || $("#frm-email").val() === ""
      || $("#frm-confirmemail").val() === ""
      || !$("#frm-optin-hearingaid").is(":checked")) {
      messages = "Please enter required information.  ";
    }

    if ($("#frm-email").val() !== "" && !_isValidEmailAddress($("#frm-email").val())) {
      messages += "Please enter a valid email address.  ";
    }
    else if ($("#frm-email").val() != $("#frm-confirmemail").val()) {
      messages += "Confirm Email does not match Email.  "
    }

    if (messages != "") {
      $("#cstm-messages").html(messages).show();
      return false;
    }

    return true;
  }

  function _isValidEmailAddress(emailAddress) {
    // see http://stackoverflow.com/questions/2855865/jquery-validate-e-mail-address-regex
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
  }

})
