(function(context,$) {

  "use strict";

  context.JK = context.JK || {};

  context.JK.SigninHelper = function(app) {

    if(!app) throw "no app defined";

    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var $self = $(this);
    var $parent = null;
    var $signinBtn = null;
    var $signinForm = null;
    var $signinCancelBtn = null;
    var $email = null;
    var $password = null;
    var $rememberMe = null;
    var useAjax = false;
    var EVENTS = context.JK.EVENTS;
    var argRedirectTo = null;

    function reset(_redirectTo) {
      argRedirectTo = _redirectTo;
      clear();
    }

    function clear() {
      $signinForm.removeClass('login-error')

      $email.val('');
      $password.val('');
      $rememberMe.attr('checked', 'checked')
    }
    function login() {
      var email = $email.val();
      var password = $password.val();
      var rememberMe = $rememberMe.is(':checked')

      clear();

      $signinBtn.text('TRYING...');

      rest.login({email: email, password: password, remember_me: rememberMe})
        .done(function() {
          //app.layout.closeDialog('signin-dialog')

          if(argRedirectTo) {
            if(argRedirectTo instanceof Function) {
              argRedirectTo();
            }
            else {
              window.location.href = argRedirectTo;
            }
            return;
          }
          var redirectTo = $.QueryString['redirect-to'];
          if(redirectTo) {
            logger.debug("redirectTo:" + redirectTo);
            window.location.href = redirectTo;
          }
          else {
            logger.debug("default post-login path");
            window.location.href = '/client'
          }
        })
        .fail(function(jqXHR) {
          if(jqXHR.status == 422) {
            $signinForm.addClass('login-error')
          }
          else  {
            app.notifyServerError(jqXHR, "Unable to log in")
          }
        })
        .always(function() {
          $signinBtn.text('SIGN IN')
        })
    }


    function events() {
      $signinCancelBtn.click(function(e) {
        app.layout.closeDialog('signin-dialog', true);
        e.stopPropagation();
        return false;
      });

      if(useAjax) {
        $signinForm.submit(function(e) {
          login();
          return false;
        });

        $signinBtn.click(function(e) {
          login();
          return false;
        });
      }


      $parent.find('.show-signup-dialog').click(function(e) {
        $self.triggerHandler(EVENTS.SHOW_SIGNUP);
        return false;
      })
    }

    function initialize(_$parent, _useAjax){
      $parent = _$parent;
      useAjax = _useAjax;

      $signinBtn = $parent.find('.signin-submit')
      $signinForm = $parent.find('.signin-form')
      $signinCancelBtn = $parent.find('.signin-cancel')
      $email = $parent.find('input[name="session[email]"]');
      $password = $parent.find('input[name="session[password]"]');
      $rememberMe = $parent.find('input[name="user[remember_me]"]');

      if($signinForm.length == 0) throw "no signin form found";
      events();
    }
    
    this.initialize = initialize;
    this.reset = reset;
    
    return this;
  }
})(window, jQuery);