/*global ich, FB */
(function ($) {
  $(function () {

    var body = $('body'),
        $cachedOverlay,
        $cachedOverlayType,
        $cachedOverlayContainer;

    body.bind('login.overlay.show', function (e, options) {
      if ($cachedOverlay && options.id === $cachedOverlayType) {
        $cachedOverlay.show();
        $cachedOverlayContainer.show();
        return;
      }
      body.overlay(options.url,
        function ($overlay, $container) {
          $cachedOverlay = $overlay;
          $cachedOverlayContainer = $container;
          $cachedOverlayType = $overlay.attr('id');

          $('#subwindow_close').click(function (e) {
            e.preventDefault();
            $(this).trigger('overlay.hide');
          });

          $('#signup_form .birthday_fields select').dropdownify();
          $overlay.find('input[name="follow"]').val(options.follow);
          $overlay.find('input[name="mp_source_action"]').val(options.mpSourceAction);

          // The signup form contains ICanHaz templates for
          // the LoginValidator's spinner. They're usually
          // loaded in document.ready, but since they're
          // rendered via the popup, we need to do this
          // manually.
          ich.grabTemplates();
        },
        options);
    });
    $('#signup_form .birthday_fields select').dropdownify();
  });

  // Listen for a "height" message from the passport iframe.
  //
  // 1) We receive a "loaded" message once the passport iframe page has loaded. At this
  //    point, we notify the passport iframe of the current width of the modal. The passport
  //    iframe will then scale it's height accordingly and report that height back to us.
  // 2) We receive a "height" value from the passport iframe. We manually resize the modal
  //    height to appropriately match the passport card height.
  // 3) We receive a "passportCallback" redirect_uri for a callback to complete OIDC flow.
  window.addEventListener('message', function (e) {
    var parsedData;
    if (e.data && e.data[0] === "{") {
      parsedData = JSON.parse(e.data);
    } else {
      parsedData = e.data;
    }
    switch (parsedData.messageType) {
      case 'loaded':
        var $iframe = $('iframe[name=passport]')[0];
        var iframeMessage = {"width": $('#passport_iframe_container').width()};
        $iframe.contentWindow.postMessage(JSON.stringify(iframeMessage), "*");
        return;
      case 'height':
        $('#passport_iframe_container').css({'height': parsedData.height + 25});
        $('#passport_modal').css({'visibility': 'visible'});
        $iframe = $('iframe[name="passport"]').contents()[0];
        if (parsedData.focus) { $($iframe).find("#username").focus(); };
        return;
      case 'passportCallback':
        window.location.assign(parsedData["redirectURI"]);
        return;
    }
  });

  var trackLoginSignupEvent = function (eventName, mpSourceAction) {
    var trackingOptions = {};
    if (window.SitePageType) trackingOptions.source = window.SitePageType;
    if (mpSourceAction) trackingOptions['source_action'] = mpSourceAction;
    Twitch.tracking.spadeAndMixpanel.trackEvent(eventName, trackingOptions);
  };

  // We should remove $.login and $.follow at some point and change this to a function on $.
  $.showAuthenticationOverlay = function (formType, options) {
    var id = formType + '_subwindow',
        url = '/user/' + formType + '_popup',
        eventName = formType + '-click',
        focusOnLoad = formType === 'login' ? '#login_user_login' : '#user_login',
        overlayOptions;

    options = options || {};

    if (options.params) {
      url += '?' + $.param(options.params);
    }

    overlayOptions = {
      'url': url,
      'width': '420px',
      'id': id,
      'focusOnLoad': focusOnLoad,
      'destroyOnHide': false,
      'follow': options.follow,
      'mpSourceAction': options.mpSourceAction,
      'formType': formType
    };

    $('body').trigger('login.overlay.show', [overlayOptions]);
    trackLoginSignupEvent(eventName, options.mpSourceAction);
  };

  /**
   * Use this to trigger displaying the login overlay - it will determine whether
   * or not to show a full login box or a smaller one useful for embeds
   */
  $.signup = function (options) {
    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
    if (SiteOptions.maintenance_mode) {
      // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
      $.showAuthenticationOverlay('maintenance', options);
    } else {
      $.showAuthenticationOverlay('signup', options);
    }
  };

  $.login = function (options) {
    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
    if (SiteOptions.maintenance_mode) {
      // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
      $.showAuthenticationOverlay('maintenance', options);
    } else {
      $.showAuthenticationOverlay('login', options);
    }
  };

  /**
   * Binds the login overlay logic to the provided nodes, you can set the
   * events to any of the jquery events by passing in options.events = 'foo bar'.
   *
   * Defaults to listening to click.
   */
  $.fn.login = function (options) {
    options = $.extend({}, options, {'events': 'click'});

    return this.each(function () {
      $(this).bind(options.events, function (e) {
        e.preventDefault();
        $.login(options);
      });
    });
  };

  $.fn.signup = function (options) {
    options = $.extend({}, options, {'events': 'click'});

    return this.each(function () {
      $(this).bind(options.events, function (e) {
        e.preventDefault();
        $.signup(options);
      });
    });
  };

})(jQuery);
