/*jshint browser:true */
/*global SiteOptions */
(function ($, Twitch) {

  $.forceLogIn = function () {
    window.location = '/user/login?redirect_on_login=' + window.location.pathname + window.location.search;
  };

  $.loggedInAjax = function (url, settings) {
    // For ajax requests that require special permissions,
    // redirect to the login page in the case where you're not logged in.
    if (typeof(settings) === 'undefined') {
      settings = url;
      url = null;
    } else {
      settings.url = url;
    }
    var oldErrback = settings.error;
    var errback = function (jqXHR, textStatus, errorThrown) {
      if (jqXHR.status === 403) {
        $.forceLogIn();
      }
      if (oldErrback) oldErrback.apply(this, arguments);
    };
    settings.error = errback;
    return $.ajax(settings);
  };

  window.BoxartImage = {
    setPlaceholder: function (element) {
      var placeholder = element.getAttribute('data-placeholder');
      if (placeholder && element.src !== placeholder) {
        element.src = placeholder;
      }
    }
  };

  $(function () {

    Twitch.notify.flash();

    $('.header_nick').popup($('#self_actions'));
    $('input[placeholder]').placeholder();


    // The click event on these selectors now displays a login overlay. See login.js
    $('#broadcast_login').login({mpSourceAction: "broadcast-login-link"});
    $('#partnersignup_login').login({mpSourceAction: "partnersignup-login-link"});
    $('#header_login').login({mpSourceAction: "login-button"});
    $('#channel_login').login({mpSourceAction: "login-button"});

    $('#partnersignup_signup').signup({mpSourceAction: "partnersignup-signup-link"});
    $('#header_signup').signup({mpSourceAction: "signup-button"});

    $('#left_col #language_select').popup($('#languages_popup'), {'side': 'right', 'above': true});
    $('#site_footer #language_select').popup($('#languages_popup'), {'side': 'left', 'above': true});

    Twitch.user(function (info) {
      Twitch.emailNotifier.init({
        forgetDuration: 3600,
        delay: 5
      });
    }, function(e) {
      if (e && e.status === 401) {
        /* Silence known error: unauthenticated */
        return;
      }
      throw e;
    });

    if (!Twitch.user.isLoggedIn()) {
      $('#user_display_name').hide();
      $('#user_login').show();
    }

    if (typeof PP !== "undefined") {

      // Directory is responsible for sending tracking itself
      if (window.SitePageType !== 'directory') {
        if (['channel', 'video'].indexOf(window.SitePageType) === -1) {
          Twitch.tracking.gaq.trackPageView();
        }
        Twitch.tracking.mixpanel.trackDiscovery();
      }
    }
  });

})(jQuery, Twitch);
