/**
 * User: jeremy
 * Date: Jan 21, 2011
 * Time: 1:36:10 PM
 */
function LoginController() {
    var self = this;
    this.error = null;
    this.loginForm = null;
    this.forgotForm = null;
    this.stack = null;
    this.loginBox = null;
    this.closeLogin = null;
    this.signInButton = null;
    this.forgotPasswordButton = null;
    jQuery(document).ready(function() {
        self.onLoad();
    });
}
LoginController.prototype = new BaseController();
LoginController.prototype.onLoad = function() {
    var self = this;
    var keyPressListener = function (e) {
        self.onKeyPress(e);
    };
    this.error = jQuery("#loginErrors");
    this.loginForm = jQuery("#loginForm");
    this.forgotForm = jQuery("#forgotPasswordForm");
    this.loginBox = jQuery('#loginBox');
    this.stack = new ViewStack("#loginFormWrapper");
    this.closeLogin = jQuery("#closeLoginBox")
    this.stack.showIndex(0);
    this.addListener('loginFailedEvent', function (e, r) {
        self.onLoginFailed(r);
    })

    this.closeLogin.click(function () {
        self.loginForm[0].reset();
        self.forgotForm[0].reset();
        self.loginBox.fadeOut('slow');
        self.removeListener('keypress', keyPressListener);
    })
    this.signInButton = jQuery("#signinButton");

    this.signInButton.click(function () {
        self.error.hide();
        self.stack.showIndex(0);
        self.loginBox.fadeIn('slow');
        self.loginForm.find('.userName').focus();
        self.addListener('keypress', keyPressListener);
    })
    this.forgotPasswordButton = jQuery("#forgotPasswordLink");
    this.forgotPasswordButton.click(function() {
        self.stack.showIndex(1);
    })

    this.loginForm.submit(function() {
        var service = new Services();
        self.error.hide();
        service.login(self.loginForm.serialize());
        return false;
    })
    this.addListener('passwordFound', function() {
        self.onPasswordFound();
    })
    this.addListener('findPasswordError', function() {
        self.onGetPasswordError();
    })
    this.forgotForm.submit(function() {
        self.error.hide();
        var service = new Services();
        service.forgotPassword(self.forgotForm.serialize());
        return false;
    })
}

LoginController.prototype.showForgotPassword = function() {
    this.loginBox.fadeIn('slow');
    this.forgotPasswordButton.click();
}

LoginController.prototype.onGetPasswordError = function () {
    this.error.show();
    this.error.children('#loginErrorMessage').html("Account not found.");
}

LoginController.prototype.onPasswordFound = function () {
    this.closeLogin.click();
}

LoginController.prototype.onKeyPress = function (event) {
    if (event.keyCode == 27) {
        this.closeLogin.click();
    }
}

LoginController.prototype.onLoginFailed = function (result) {
    this.error.show();
    this.error.children('#loginErrorMessage').html(result.errors[0]);
}
var loginController = new LoginController();
