function MailIt_CloseDialog() {
    if ($(".mailit-popup").length) {
        $(".mailit-popup").remove();
        $(".mailit-overlay").remove();
    }
}

function MailIt_ButtonClickCallback(event) {
    // prevent auto scroll
    event.preventDefault();

    // open the modal dialog
    MailIt_OpenDialog();

    // when the user clicks off of the popup (anywhere on the overlay)
    // exit the modal
    $(".mailit-overlay").click(MailIt_OverlayClickCallback);
}

function MailIt_OverlayClickCallback(event) {
    // we only want to do it if the user did not click the popup
    if ($(event.target).is(".mailit-popup")
            || $(event.target).parents(".mailit-popup").length) {
        return;
    }

    // close the modal dialog
    MailIt_CloseDialog();
}

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

function MailIt_MailItButtonClickCallback(event)
{

  emails = $("#recomendee").val();
  emails_array = emails.split(",");
  proceed = true;
  $.each(emails_array, function(index, value)
  {
    email = emails_array[index].trim();
    if(!validateEmail(email))
    {
      proceed = false;
    }
  });
  if(proceed)
  {
    // send the mail
    $.ajax({type: "POST",
            url: CWIS_BASE_URL + "index.php?P=P_MailIt_SendFullRecordEmail&ID=" + MailItResourceId,
            data: {email: $("#recomendee").val() },
            dataType: "html",
            success: function(data) {
              dataobject = JSON.parse(data);
              response = dataobject["status"]["message"];
              if(response.length > 0){
                $("#MailItErrors").html("<br/>" + dataobject["status"]["message"] + "<br/>");
              }
              else
              {
                $("#MailItSuccess").html("<br/>Email successfully sent!<br/>");
              }
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus, errorThrown);
            }
            });

    // close the popup
    MailIt_CloseDialog();
  }
  else
  {
    if(!$("#alert").length)
    {
      $("<p style='color: red' id='alert'> Please enter a valid email address.</p>").insertBefore("#email-label");
    }
  }
}

function MailIt_CancelButtonClickCallback(event) {
    // close the popup
    MailIt_CloseDialog();
}

function MailIt_OpenDialog() {
    if (!($(".mailit-popup").length) && !($(".mailit-overlay").length)) {
        // create the overlay to make the popup modal
        var overlay = document.createElement("div");
        overlay.className = "mailit-overlay";
        $("body").append(overlay);

        // create the popup
        var popup = document.createElement("div");
        popup.className = "mailit-popup";
        $("body").append(popup);
        $(".mailit-popup").html(
                "<div class=\"mailit-popup-titlebar\">" +
                  "<h1 class=\"mailit-popup-title\">" + MailItHeaderText + "</h1>" +
                "</div>" +
                "<div class=\"mailit-popup-body\">" +
                  "<p class=\mailit-popup-bodytext\">" +
                    MailItBodyText +
                  "</p>" +
                  "<label id='email-label'>Email Address:</label>" +
                  '<input id="recomendee" type="text" name="recomendee" value="'+ MailItDefaultEmail + '" placeholder="email@email.com" />' +
                "</div>" +
                "<div class=\"mailit-popup-buttons\">" +
                  "<button class=\"cw-button cw-button-elegant mailit-popup-button mailit-button-mailit\">Send</button>" +
                  "<button class=\"cw-button cw-button-elegant mailit-popup-button mailit-button-cancel\">Cancel</button>" +
                "</div>");
        $(".mailit-button-mailit").click(MailIt_MailItButtonClickCallback);
        $(".mailit-button-cancel").click(MailIt_CancelButtonClickCallback);
    }
}


$(document).ready(function() {
    // clicking the button brings up the popup
    $("#MailItButton").click(MailIt_ButtonClickCallback);
});
