
(function (d) {
  //Initial object preparation & message events
  var pp = window.presspatron;
  var host_url = "http://dashboard.presspatron.com";
  var currentOrigin = window.location.origin || window.location.protocol + "//"
  + window.location.hostname
  + (window.location.port ? ':' + window.location.port : '');

  if(pp == null){
    pp = window.presspatron = {};
    pp.receiveMessage = handleIframeMessages;
    window.addEventListener("message", pp.receiveMessage, false);
  }

  function handleIframeMessages(event){
      if (extractDomain(event.origin) !== extractDomain(host_url)){
        return;
      }
      else{
        switch (event.data) {
          case "modal":
            var modal = d.getElementById("pp-modal");
            if(modal == null) {
              setupDonationModal();
              document.documentElement.classList.add("pp-modal-open");
            }
            else{
              document.documentElement.classList.remove("pp-modal-open");
              tearDownDonationModal();
            }
            break;
          case "updateBanner":
            var bannerFrame = document.querySelector("iframe[name=banner-frame]");
            bannerFrame.contentWindow.postMessage("update",host_url);
            break;
          case "hide":
            var banner = document.getElementById("pp-banner");
            if(banner) {
              banner.style.display = "none";
              setHideCookie();
            }
          default:
            return;
        }
      }
  }

  function setHideCookie() {
      var date = new Date(),
          days = 7;
      date.setTime(date.getTime() + (days*24*60*60*1000));
      var expires = "expires="+ date.toUTCString();
      document.cookie = "_presspatron-hide_banner=true;" + expires + ";path=/";
  }

  function checkHideCookie() {
    var value = "; " + document.cookie;
    var parts = value.split("; " + "_presspatron-hide_banner" + "=");
    return (parts.length >= 2);
  }

  function createStyles() {
    var styles = document.createElement("style");
    styles.id = "pp-styles";
    styles.innerText = "html.pp-modal-open,.pp-modal-open body {overflow:hidden;}"
    document.body.appendChild(styles);
  };

  function createButton(buttonCont){
      var button = d.createElement("iframe"), bStyle = button.style;;
      button.name = button.id = "button-frame";
      button.frameborder = "0";
      button.scrolling = "no";
      button.allowtransparency="true";
      bStyle.width = "180px"; bStyle.height="34px"; bStyle.border="none";
      button.src = "//dashboard.presspatron.com/websites/28/get_button?origin="+encodeURIComponent(currentOrigin);
      buttonCont.appendChild(button);

      return button;
  }

  function onAhrefClick (e){
    e.preventDefault();
    showModal();
  }

  function showModal(){
    presspatron.receiveMessage({ 'data': 'modal', 'origin': host_url });
  }

  function addTracking(element){
    var analyticsFrame = d.createElement("iframe"), aStyle = analyticsFrame.style;
    analyticsFrame.frameborder = "0";
    analyticsFrame.scrolling = "no";
    analyticsFrame.allowtransparency= "true";
    aStyle.width = "1px"; aStyle.height = "1px"; aStyle.border = "none";
    analyticsFrame.src = "//dashboard.presspatron.com/websites/28/custom_button";
    element.appendChild(analyticsFrame);
  }

  function setupComponents() {
    //create the required styles
    createStyles();
    //banner iframe setup
    var banner, bannerCont = d.getElementById("pp-banner");
    if(bannerCont && !(checkHideCookie())){

      banner = d.createElement("iframe");
      banner.className = "pp-banner-cont";
      banner.src = "//dashboard.presspatron.com/websites/28?origin="+encodeURIComponent(currentOrigin);
      banner.frameborder="0";
      banner.scrolling = "no";
      banner.name = "banner-frame";
      s = banner.style
      var elStyle = banner.style;
      elStyle.width = "100%"; elStyle.height = "44px"; elStyle.display = "block";
      elStyle.border = "none";
      bannerCont.appendChild(banner);

    }
    
    //button iframe setup
    var deprecatedReference=d.getElementById("pp-donate-button");
    var references = d.getElementsByClassName("pp-donate-button");
    if(deprecatedReference)createButton(deprecatedReference);
    for(var i = 0; i < references.length ; i++){
      var ref = references[i];
      if(ref !== deprecatedReference)createButton(ref);
    }
    
    //create calbacks to open modal manually
    var elements = d.querySelectorAll('.pp-trigger-modal');
    for (var i = 0; i < elements.length; i++) {
      addTracking(elements[i]);
      if (document.addEventListener) {                // For all major browsers, except IE 8 and earlier
        elements[i].addEventListener("click", showModal);
      } else if (document.attachEvent) {              // For IE 8 and earlier versions
        elements[i].attachEvent("click", showModal);
      }
    }

    // check for a hrefs that contain a link to the donation form and capture their click event
    var customButtonLinks=d.querySelectorAll("a[href*='presspatron.com/donations/new']")
    for (var i = 0; i < customButtonLinks.length; i++) {
      addTracking(customButtonLinks[i]);
      if (document.addEventListener) {                // For all major browsers, except IE 8 and earlier
        customButtonLinks[i].addEventListener("click", onAhrefClick);
      } else if (document.attachEvent) {              // For IE 8 and earlier versions
        customButtonLinks[i].attachEvent("click", onAhrefClick);
      }
     }
  }

  function setupDonationModal() {
    // Basic iframe modal setup
    var modalContainer = d.createElement("div");
    modalContainer.classList.add("pp-modal-container");
    var modalContainerStyle = "width: 100%; height: 100%; position: fixed; z-index: 9999; top: 0; left: 0;";
    modalContainerStyle += "background: rgba(0, 0, 0, 0.82) no-repeat 50% 25% url(https://dashboard.presspatron.com/assets/loading-modal-69f4148533c471654c225bfc674a131749b855c7dffb8138d27f8ac63e97d522.gif);";
    modalContainer.setAttribute("style", modalContainerStyle);

    var modal = d.createElement("iframe"), s = modal.style;
    modal.id = "pp-modal";
    modal.name = "donation-frame";
    modal.src = "//dashboard.presspatron.com/donations/new?frame=1&t=Y8ic5UC4MY2Q5s698Re1YRwA&origin="+encodeURIComponent(currentOrigin);
    var modalStyle = "width: 100%; height: 100%; position: fixed; z-index: 9999; top: 0; left: 0;";
    modalStyle += "border: none; opacity: 0; transition: opacity 0.2s ease-out;";
    modal.setAttribute("style", modalStyle);
    modal.allowtransparency="true";
    modal.scrolling = "no";
    
    modalContainer.appendChild(modal);
    modal.addEventListener("load", function() {
      modal.style.opacity = 1;
    })
    d.body.appendChild(modalContainer);
  }

  function tearDownDonationModal() {
    var donationFrame = document.querySelector(".pp-modal-container");
    d.body.removeChild(donationFrame)
  }

  function extractDomain(url) {
    urlParts = url.match(/^https?:\/\/(.*)$/);
    return urlParts.length >= 1 ? urlParts[1] : null;
  }

  // if both divs are ready, ELSE if the whole DOM is ready, ELSE wait until DOM loads
  // the first check is for speed, the second catches this script loading after DOM,
  // the final catches everything else

 if (document.readyState.match(/^(ready|loaded|interactive|complete)$/)) {
    setupComponents();
  } else {
    document.addEventListener('DOMContentLoaded', function () {
      setupComponents();
    });
  }
}(document));
