/*

     ______   ______   ______ 
    |  ____| |  ____| |  ____|
    | |__    | |__    | |__   
    |  __|   |  __|   |  __|  
    | |____  | |      | |     
    |______| |_|      |_|     
                              
  =============================================================================

  Support the NoGlobalWarrants.org campaign by installing this banner on your site.

  <sina@eff.org> for support

  =============================================================================

  @source: https://github.com/EFForg/ngw-banner

  @licstart  The following is the entire license notice for the
             JavaScript code in this page.

  Copyright (C) 2016 Electronic Frontier Foundation <https://eff.org>

  The JavaScript code in this page is free software: you can
  redistribute it and/or modify it under the terms of the GNU
  General Public License (GNU GPL) as published by the Free Software
  Foundation, either version 3 of the License, or (at your option) any
  later version.  The code is distributed WITHOUT ANY WARRANTY;
  without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU GPL for more details.

  As additional permission under GNU GPL version 3 section 7, you may
  distribute non-source (e.g., minimized or compacted) forms of that
  code without the copy of the GNU GPL normally required by section
  4, provided you include this license notice and a URL through which
  recipients can access the Corresponding Source.

 @licend  The above is the entire license notice for the JavaScript
          code in this page.

*/

// Wrap widget in function to protect scope
var _banner_config = (typeof banner_config  !== 'undefined') ? banner_config  : {};

(function (window, widgetConfig) {

  // Do configuration
  widgetConfig.show_style = widgetConfig.show_style || 'banner';
  widgetConfig.debug = widgetConfig.debug || false;
  widgetConfig.localAssets = widgetConfig.localAssets || false;
  widgetConfig.callOnly = widgetConfig.callOnly || false;
  widgetConfig.startAsMinimized = widgetConfig.startAsMinimized || false;
  widgetConfig.disableDate = widgetConfig.disableDate || false;
  widgetConfig.campaign = widgetConfig.campaign || 'noglobalwarrants';
  widgetConfig.cookieTimeout = widgetConfig.cookieTimeout || null;

  function debug() {
    if (widgetConfig.debug) {
      if (this.console) {
        console.log.apply(console, arguments);
      }
    }
  }

  // Setup
  var activeCampaign;
  var ASSET_URL;

  if (widgetConfig.localAssets) {
    ASSET_URL = '../banner_content/';
  } else {
    ASSET_URL = 'https://www.eff.org/ngw/banner_content/';
  }

  // Cookie helpers, taken from w3schools
  function setCookie(c_name, value, seconds) {
    var exdate = new Date(new Date().getTime() + seconds * 1000);
    var c_value = escape(value) + ((seconds === null) ? '' : '; expires=' +
      exdate.toUTCString());
    document.cookie = c_name + '=' + c_value;
  }

  function getCookie(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(' ' + c_name + '=');

    if (c_start === -1) {
      c_start = c_value.indexOf(c_name + '=');
    }

    if (c_start === -1) {
      c_value = null;
    } else {
      c_start = c_value.indexOf('=', c_start) + 1;
      var c_end = c_value.indexOf(';', c_start);
      if (c_end === -1) { c_end = c_value.length; }
      c_value = unescape(c_value.substring(c_start, c_end));
    }

    return c_value;
  }

  // Define checks
  var checks = {
    correctDate: function (callback) {
      debug('correctDate()');

      // This used to check the date by getting it from a server, but now just uses the device's local date.

      window.dateCallBackFailSafe = setTimeout(function () {
        var today = new Date();
        if (today.getDate() === activeCampaign.runDate.day && today.getMonth() === activeCampaign.runDate.month - 1 && today.getFullYear() === activeCampaign.runDate.year) {
          callback({activeToday: true});
        } else {
          callback({activeToday: false});
        }
      }, 1);
    }
  };

  // Define campaigns
  var campaign = {
    noglobalwarrants: {
      cookieName: 'noglobalwarrants_hasseen',
      runDate: {
        day: 21,
        month: 6, // Use natural month, e.g. January = 1
        year: 2016
      },
      size: {
        desktop: {
          heightOpened: '300px',
          heightMinimized: '50px'
        },
        mobile: {
          heightOpened: '100px',
          heightMinimized: '0px'
        }
      },
      styles: {
        banner: {
          campaignSpacer: 'height: 50px;',
          campaignContainer: 'background: #000; position: fixed; ' +
            'width: 100%; bottom: 0; left: 0; z-index: 100000; padding: 0; ' +
            '-webkit-box-sizing: border-box; -moz-box-sizing: border-box;',
          iframeContainer: 'position: relative; height: 350px; width: 100%; ' +
            'margin: 0; background: #08A013; z-index: 1;',
          iframe: 'width: 100%; height: 100%; border: 0; margin: 0; ' +
            'padding: 0; background: #08A013;',
          footerOverlay: 'cursor: pointer; position: absolute; bottom: 0; ' +
            'height: 50px; width: 100%; margin: 0; background: none; ' +
            'z-index: 2;',
          closeButton: 'border: 0; height: 26px; width: 26px; ' +
            'cursor: pointer; position: absolute; top: 20px; right: 20px; ' +
            'background: url("' + ASSET_URL + 'imgs/close-button.png") no-repeat right top;',
          mobileCloseButton: 'border: 0; height: 20px; width: 20px; ' +
            'cursor: pointer; position: absolute;top: 10px; right: 10px; ' +
            'background: url("' + ASSET_URL +
            'imgs/close-button-mobile.png") no-repeat right top;',
          openButton: 'border: 0; height: 26px; width: 26px; ' +
            'cursor: pointer; position: absolute; bottom: 10px; ' +
            'right: 20px; background: url("' + ASSET_URL +
            'imgs/open-button.png") no-repeat right top;'
        }
      },
      minimized: false,
      show: function (options) {
        debug('show()', options);

        var cookie = getCookie(activeCampaign.cookieName);

        if (widgetConfig.startAsMinimized && cookie === null) {
          this.minimized = true;
        }

        var style = activeCampaign.styles[activeCampaign.config.show_style];

        if (style.overlay) {
          var overlay = document.createElement('div');
          overlay.style.cssText = style.overlay;
          document.body.appendChild(overlay);
        }

        // Create a spacer to prevent the container from covering up
        // parts of the containing page when minimized

        if(document.getElementById("campaign-spacer")){
          document.body.removeChild(document.getElementById("campaign-spacer"));
        }

        if(document.getElementById("campaign-container")){
          document.body.removeChild(document.getElementById("campaign-container"));
        }

        var campaignSpacer = document.createElement('div');
        window.campaignSpacer = campaignSpacer;
        campaignSpacer.style.cssText = style.campaignSpacer;
        campaignSpacer.setAttribute("id", "campaign-spacer");
        campaignSpacer.setAttribute("class", "campaign-spacer");
        // Create a container
        var campaignContainer = document.createElement('div');
        window.campaignContainer = campaignContainer;
        campaignContainer.style.cssText = style.campaignContainer;
        campaignContainer.setAttribute("id", "campaign-container");
        campaignContainer.setAttribute("class", "campaign-container");

        // Create a container for the iframe so we can do padding and
        // border-radius properly
        var iframeContainer = document.createElement('div');

        iframeContainer.style.cssText = style.iframeContainer;

        var e = document.documentElement,
            g = document.getElementsByTagName('body')[0],
            x = window.innerWidth || e.clientWidth || g.clientWidth;

        if (x < 767) {
          if (!this.minimized) {
            iframeContainer.style.height = '100px';
          } else {
            iframeContainer.style.height = '0px';
          }
        } else {
          // Find out if user has minimized via cookie
          if (this.minimized) {
            iframeContainer.style.height = '50px';
          } else {
            iframeContainer.style.height = activeCampaign.size.desktop.heightOpened;
          }
          var footerOverlay = document.createElement('div');
          footerOverlay.style.cssText = style.footerOverlay;
          campaignContainer.appendChild(footerOverlay);
        }

        // Append Iframe and campaign container to document
        campaignContainer.appendChild(iframeContainer);

        document.body.appendChild(campaignSpacer);
        document.body.appendChild(campaignContainer);

        var firstTime = true;

        if (cookie !== null) {
          firstTime = false;
        }

        // a Hack, if mobile set firsttime to false so splash page never shows
        if (x < 767) {
          firstTime = false;
        }

        var iframe = document.createElement('iframe');

        iframe.style.cssText = style.iframe;

        var us = iframe.src = ASSET_URL + activeCampaign.config.show_style +
          '.html?firstTime=' + firstTime;

        iframeContainer.appendChild(iframe);

        var that = this;

        if (x > 767) {
          that.fullSize = true;
          // Setup a close button
          var closeButton = document.createElement('button');
          closeButton.style.cssText = style.closeButton;
          iframeContainer.appendChild(closeButton);

          // Setup a open button
          var openButton = document.createElement('button');
          openButton.style.cssText = style.openButton;
          iframeContainer.appendChild(openButton);

          if (this.minimized) {
            openButton.style.display = 'block';
            closeButton.style.display = 'none';
            footerOverlay.style.display = 'block';
          } else {
            openButton.style.display = 'none';
            closeButton.style.display = 'block';
            footerOverlay.style.display = 'none';
          }

          var toggleDisplay = function () {
            if (!that.minimized) {
              iframeContainer.style.height = '50px';
              that.minimized = true;
              footerOverlay.style.display = 'block';
              closeButton.style.display = 'none';
              openButton.style.display = 'block';
              setCookie(activeCampaign.cookieName, '{"minimized": true}',
                widgetConfig.cookieTimeout);
            } else {
              iframeContainer.style.height = '300px';
              that.minimized = false;
              footerOverlay.style.display = 'none';
              openButton.style.display = 'none';
              closeButton.style.display = 'block';
              setCookie(activeCampaign.cookieName, '{"minimized": false}',
                widgetConfig.cookieTimeout);
            }
          };

          footerOverlay.onclick = toggleDisplay;
          closeButton.onclick = toggleDisplay;
        } else {
          that.fullSize = false;
          var mobileCloseButton = document.createElement('button');
          mobileCloseButton.style.cssText = style.mobileCloseButton;
          iframeContainer.appendChild(mobileCloseButton);
          debug(that.minimized);
          if (that.minimized) {

            mobileCloseButton.style.display = 'none';
          } else {
            mobileCloseButton.style.display = 'block';
          }
          mobileCloseButton.onclick = function () {
            setCookie(activeCampaign.cookieName, '{"minimized": true}',
              widgetConfig.cookieTimeout);
            document.body.removeChild(campaignContainer);
          };
        }
      },
      init: function (config) {
        activeCampaign.config = config;

        var cookie = getCookie(activeCampaign.cookieName);
        var that = this;

        if (cookie) {
          this.minimized = JSON.parse(cookie).minimized;
        }

        checks.correctDate(function (response) {
          debug('correctDate() callback', response);

          clearTimeout(window.dateCallBackFailSafe);

          if (response && (response.activeToday ||
              widgetConfig.disableDate || widgetConfig.debug)) {

              activeCampaign.show({
                location: null,
                widgetConfig: widgetConfig
              });

            if (window.addEventListener) window.addEventListener('resize', function() {
                var w = window,
                  d = document,
                  e = d.documentElement,
                  g = d.getElementsByTagName('body')[0],
                  x = w.innerWidth || e.clientWidth || g.clientWidth,
                  y = w.innerHeight|| e.clientHeight|| g.clientHeight;
               if((that.fullSize && x < 767) || (!that.fullSize && x > 767)) {
                  if(window.tdwfbResizeCallback) {
                    clearTimeout(window.tdwfbResizeCallback);
                  }
                  window.tdwfbResizeCallback = setTimeout(function () {
                      that.show({location: window.tdwfbLocation, widgetConfig: widgetConfig});
                      windowWidth = x;
                  }, 50);
                }
            }, false);
          }
        });
      }
    }
  };

  // Load campaign if it exists
  if (typeof campaign[widgetConfig.campaign] !== 'undefined') {
    activeCampaign = campaign[widgetConfig.campaign];
    activeCampaign.init(widgetConfig);
  } else {
    return false;
  }
})(window, _banner_config);