var Authorization = (function () {
  'use strict';

  var loginForm = $('.js-login-form');

  return {
    show: show,
    isLoggedIn: isLoggedIn,
    logout: logout,
    setRequestHeaders: setRequestHeaders
  };

  function show() {
    Util.trackPage('login');
    Tabs.hide();
    Search.hide();
    LoadingBar.hide();
    $('.js-size').text('');
    $('.js-photos').addClass('hidden');
    $('.js-authorization').removeClass('hidden');
    $(document).off('scroll');
    loginForm.on('submit', login);
  }

  function hide() {
    Search.show();
    $('.js-photos').removeClass('hidden');
    $('.js-authorization').addClass('hidden');
  }

  function login(event) {
    event.preventDefault();
    var email = $(this).serializeArray()[0].value;
    var password = $(this).serializeArray()[1].value;

    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: API_BASE_URL + 'knock/auth_token',
      beforeSend: function (xhr) {
        xhr.setRequestHeader('x-auth-api', API_KEY);
      },
      data: {
        auth: {
          email: email,
          password: password
        }
      },
      success: loginSuccess,
      error: loginError
    });
  }

  function setRequestHeaders(xhr) {
    var jwt = getJwt();

    xhr.setRequestHeader('x-auth-api', API_KEY);
    if (jwt) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + jwt);
    }
  }

  function loginError(data) {
    if (data.status === 402) {
      BuyPro.show();
    } else {
      $('.js-login-error').removeClass('hidden');
    }
  }

  function loginSuccess(data) {
    localStorage.setItem('jwt', data.jwt);
    Tabs.openTabByName('recent');
    hide();
  }

  function logout() {
    localStorage.removeItem('jwt');
    show();
  }

  function getJwt() {
    return localStorage.getItem('jwt');
  }

  function isLoggedIn() {
    return !!getJwt();
  }

}());