jQuery(function(){
var LoginController = function(){
    this.onCompleteLoginRequest = function (mData){
        if(mData.success){
            self.$elLoginContainer.hide();
            if(typeof(mData.sRedirectUrl) != "undefined"){
                window.location.href = mData.sRedirectUrl;
            } else {
                window.location.reload();
            }
        } else {
            for(sKey in mData.errors){
                addErrorMessage(mData.errors[sKey]);
                highlightErrorFieldsForType(sKey);
            }
        }
    }

    function clearErrorMessages(){
        self.$elLoginContainer.find("p.error").remove();
        self.$elLoginContainer.find('input').removeClass('login-field-error');
        
    }

    function addErrorMessage(sMessage){
        self.$elLoginContainer.find("legend").after(
            '<p class="error">' + sMessage + '</p>'
        );
    }

    function highlightErrorFieldsForType(sErrorType){
        switch(sErrorType){
            case 'incorrect_credentials':
                highlightErrorFields(self.$elLoginContainer.find('input[type="text"]'));
                highlightErrorFields(self.$elLoginContainer.find('input[type="password"]'));
                break;
            case 'invalid_email':
                highlightErrorFields(self.$elLoginContainer.find('input[type="text"]'));
                break;
        }
    }

    function highlightErrorFields($elErrorFields){
        $elErrorFields.addClass('login-field-error');
    }

    function registerEventHandlers(){
        self.$elLoginContainer = $('#login-container');
        var $elForm = self.$elLoginContainer.find("form");
        $elForm.submit(function(){
            clearErrorMessages();
            $.post("/user/login", $elForm.serializeArray(), self.onCompleteLoginRequest, "json");
            return false;
        })

        var $elForgotPasswordLink = self.$elLoginContainer.find("a.login-password-forgot");
        $elForgotPasswordLink.click(function(){
            window.location.href = '/user/forgot?email=' + self.$elLoginContainer.find('input[type="text"]').attr('value');
            return false;
        });
    }

    var $elLoginContainer = null;
    var self = this;
    registerEventHandlers();
}
   new LoginController();
});
