(function(context,$) {

    "use strict";

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

    context.JK.SigninDialog = function(app) {
        var EVENTS = context.JK.EVENTS;
        var logger = context.JK.logger;
        var rest = context.JK.Rest();
        var dialogId = '#signin-dialog';
        var $dialog = null;
        var signinHelper = null;
        var redirectTo = null;


        function beforeShow(args) {
          logger.debug("showing login form")
          if(args.redirect_to) {
            redirectTo = "/client#/redeemComplete"
          }
          else {
            redirectTo = null;
          }
          if(redirectTo) {
            logger.debug("setting redirect to in login dialog")
          }
          signinHelper.reset(redirectTo);
        }

        function afterShow() {
          $dialog.find('input[name="session[email]"]').focus();
        }

        function afterHide() {
          logger.debug("hiding login form")
          redirectTo = null;
        }

        function initialize(){

            var dialogBindings = {
                'beforeShow' : beforeShow,
                'afterShow' : afterShow,
                'afterHide': afterHide
            };

            app.bindDialog('signin-dialog', dialogBindings);

          $dialog = $(dialogId);

          signinHelper = new context.JK.SigninHelper(app);
          $(signinHelper).on(EVENTS.SHOW_SIGNUP, function() {
            app.layout.closeDialog('signin-dialog')
            app.layout.showDialog('signup-dialog')
          })
          signinHelper.initialize($dialog, true);
        }

        this.initialize = initialize;
    }
})(window, jQuery);