(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.CheckoutSignInScreen = function(app) {

    var logger = context.JK.logger;
    var rest = context.JK.Rest();

    var $screen = null;
    var $navigation = null;
    var $signinForm = null;
    var $self = $(this);
    var $email = null;
    var $password = null;
    var $signinBtn = null;
    var $signupBtn = null;
    var $inputElements = null;
    var $contentHolder = null;
    var $btnNext = null;
    var $btnFacebook = null;
    var checkoutUtils = context.JK.CheckoutUtilsInstance;

    function beforeShow(data) {
      renderNavigation();
      renderLoggedInState();
    }

    function afterShow(data) {
    }


    function renderLoggedInState(){
      if(isLoggedIn()) {
        $contentHolder.removeClass('not-signed-in').addClass('signed-in')
      }
      else {
        $contentHolder.removeClass('signed-in').addClass('not-signed-in')
      }
    }

    function isLoggedIn() {
      return !!context.JK.currentUserId;
    }

    function events() {
      $signinForm.on('submit', login);
      $signinBtn.on('click', login);
      $btnNext.on('click', moveNext);
      $btnFacebook.on('click', facebookSignup);
    }

    function reset() {
      $inputElements.removeClass('login-error');
    }

    function moveNext() {
      window.location = '/client#/checkoutPayment';

      return false;
    }

    function facebookSignup() {

      var $btn = $(this);

      if($btn.is('.disabled')) {
        logger.debug("ignoring fast attempt at facebook signup")
        return false;
      }

      $btn.addClass('disabled')

      rest.createSignupHint({redirect_location: '/client#/checkoutPayment'})
        .done(function() {
          // send the user on to facebook signin
          window.location = $btn.attr('href');
        })
        .fail(function() {
          app.notify({text:"Facebook Signup is not working properly"});
        })
        .always(function() {
          $btn.removeClass('disabled')
        })
      return false;
    }
    function login() {
      if($signinBtn.is('.disabled')) {
        return false;
      }

      var email = $email.val();
      var password = $password.val();

      reset();

      $signinBtn.text('TRYING...').addClass('disabled')

      rest.login({email: email, password: password, remember_me: true})
        .done(function(user) {
          // now determine where we should send the user
          rest.getShoppingCarts()
            .done(function(carts) {
              if(checkoutUtils.hasOneFreeItemInShoppingCart(carts)) {
                window.location = '/client#/redeemComplete'
                window.location.reload();
              }
              else {
                window.location = '/client#/checkoutPayment'
                window.location.reload();
              }
            })
            .fail(function() {
              window.location = '/client#/jamtrack/search'
              window.location.reload();
            })
        })
        .fail(function(jqXHR) {
          if(jqXHR.status == 422) {
            $inputElements.addClass('login-error')
          }
          else  {
            app.notifyServerError(jqXHR, "Unable to log in")
          }
        })
        .always(function() {
          $signinBtn.text('SIGN IN').removeClass('disabled')
        })

      return false;
    }

    function renderNavigation() {
      $navigation.html("");

      var navigationHtml = $(
        context._.template(
          $('#template-checkout-navigation').html(),
          {current: 1, purchases_disable_class: gon.global.purchases_enabled ? 'hidden' : ''},
          {variable: 'data'}
        )
      );

      $navigation.append(navigationHtml);
    }

    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow
      };
      app.bindScreen('checkoutSignin', screenBindings);

      $screen           = $("#checkoutSignInScreen");
      $navigation       = $screen.find(".checkout-navigation-bar");
      $signinForm       = $screen.find(".signin-form");
      $signinBtn        = $signinForm.find('.signin-submit');
      $email            = $signinForm.find('input[name="email"]');
      $password         = $signinForm.find('input[name="password"]');
      $inputElements    = $signinForm.find('.input-elements');
      $contentHolder    = $screen.find('.content-holder');
      $btnNext          = $screen.find('.btnNext');
      $btnFacebook      = $screen.find('.signin-facebook')

      if($screen.length == 0) throw "$screen must be specified";
      if($navigation.length == 0) throw "$navigation must be specified";

      events();
    }

    this.initialize = initialize;

    return this;
  }
})(window,jQuery);