(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.AccountIdentityScreen = function(app) {
        var logger = context.JK.logger;
        var rest = context.JK.Rest();
        var userId;
        var user = {};

        function beforeShow(data) {
            userId = data.id;
        }

        function afterShow(data) {
            resetForm();
            renderAccountIdentity();
        }

        function resetForm() {
            // remove all display errors
            $('#account-identity-content-scroller form .error-text').remove()
            $('#account-identity-content-scroller form .error').removeClass("error")
        }

        function populateAccountIdentity(userDetail) {
            var template = context.JK.fillTemplate($('#template-account-identity').html(), {
                email: userDetail.email
            });

            appendPasswordPrompt(template);
        }

        function appendPasswordPrompt(template) {
            $('#account-identity-content-scroller').html(template);

            // append overlay-small
            var overlay = context.JK.fillTemplate($('#template-overlay-small').html(), {
                id: 'email-update-password-dialog',
                title : 'your password is required'
            });

            overlay = $(overlay);

            var passwordForm = context.JK.fillTemplate($('#template-account-update-email-password-prompt-dialog').html(), {

            });

            $('.overlay-inner', overlay).append(passwordForm);

            $('#account-identity-content-scroller').append(overlay);
        }

        /****************** MAIN PORTION OF SCREEN *****************/
            // events for main screen
        function events() {
            $('#account-identity-content-scroller').on('click', '#account-edit-email-cancel', function(evt) { evt.stopPropagation(); navToAccount(); return false; } );
            $('#account-identity-content-scroller').on('click', '#account-edit-email-submit', function(evt) { evt.stopPropagation(); handleUpdateEmail(); return false; } );
            $('#account-identity-content-scroller').on('submit', '#account-edit-email-form', function(evt) { evt.stopPropagation(); handleUpdateEmail(); return false; } );
            $('#account-identity-content-scroller').on('click', '#account-edit-password-cancel', function(evt) { evt.stopPropagation(); navToAccount(); return false; } );
            $('#account-identity-content-scroller').on('click', '#account-edit-password-submit', function(evt) { evt.stopPropagation(); handleUpdatePassword(); return false; } );
            $('#account-identity-content-scroller').on('submit', '#account-edit-password-form', function(evt) { evt.stopPropagation(); handleUpdatePassword(); return false; } );
            $('#account-identity-content-scroller').on('click', '#email-update-password-dialog a[data-purpose=cancel]', function(evt) { evt.stopPropagation(); handleUpdateEmailPasswordPromptCancel(); return false; } );
            $('#account-identity-content-scroller').on('click', '#email-update-password-dialog a[data-purpose=submit]', function(evt) { evt.stopPropagation(); handleUpdateEmailPasswordPromptSubmit(); return false; } );
            $('#account-identity-content-scroller').on('submit', '#email-update-password-dialog form', function(evt) { evt.stopPropagation(); handleUpdateEmailPasswordPromptSubmit(); return false; } );
        }

        function renderAccountIdentity() {
            rest.getUserDetail()
                .done(populateAccountIdentity)
                .error(app.ajaxError);
        }

        function navToAccount() {
            resetForm();
            window.location = '/client#/account';
        }

        function handleUpdateEmail() {
            resetForm();

            $('#account-edit-email-submit').addClass('button-disabled');
            $('#account-edit-email-submit').bind('click', false);

            $('#email-update-password-dialog *').show();
            $('#email-update-password-dialog input[name=password]').focus();
        }

        function handleUpdateEmailPasswordPromptCancel() {
            $('#account-edit-email-submit').removeClass('button-disabled');
            $('#account-edit-email-submit').unbind('click', false);
            $('#email-update-password-dialog *').hide();
            $('#email-update-password-dialog input[name=password]').val('');
        }

        function handleUpdateEmailPasswordPromptSubmit() {
            $('#email-update-password-dialog *').hide();

            var email = $('#account_update_email').val();
            var password = $('#email-update-password-dialog input[name=password]').val();
            $('#email-update-password-dialog input[name=password]').val('');


            postUpdateEmail(email, password)
                .done(function(response) { postUpdateEmailSuccess(response, email) })
                .fail(postUpdateEmailFailure)
        }

        function handleUpdatePassword() {
            resetForm();

            $('#account-edit-password-submit').addClass('button-disabled');
            $('#account-edit-password-submit').bind('click', false);

            var currentPassword = $('#account-edit-password-form input[name=current_password]').val()
            var password = $('#account-edit-password-form input[name=password]').val()
            var passwordConfirmation = $('#account-edit-password-form input[name=password_confirmation]').val()

            postUpdatePassword(currentPassword, password, passwordConfirmation)
                .done(postUpdatePasswordSuccess)
                .fail(postUpdatePasswordFailure)
        }

        function postUpdateEmail(email, current_password) {

            var url = "/api/users/" + context.JK.currentUserId + "/update_email";
            return $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: url,
                data: JSON.stringify({ update_email: email, current_password : current_password}),
                processData: false
            });
        }

        function postUpdateEmailSuccess(response, email) {
            $('#account-edit-email-submit').removeClass('button-disabled');
            $('#account-edit-email-submit').unbind('click', false);
            app.notify(
                {   title: "Confirmation Email Sent",
                    text: "A confirmation email should arrive shortly at " + email + ". Please click the confirmation link in it to confirm your email change."
                },
                null, // notify method will add buttons
                true);
        }

        function postUpdateEmailFailure(xhr, textStatus, errorMessage) {
            $('#account-edit-email-submit').removeClass('button-disabled');
            $('#account-edit-email-submit').unbind('click', false);
            var errors = JSON.parse(xhr.responseText)

            if(xhr.status == 422) {
                $('#account_update_email').closest("div.field").addClass("error")
                var emailError = context.JK.get_first_error("update_email", errors);
                var passwordError = context.JK.get_first_error("current_password", errors);
                var combinedErrorMsg = ""
                if(emailError != null) {
                    combinedErrorMsg += "<li>email " + emailError + "</li>"
                }
                if(passwordError != null) {
                    combinedErrorMsg += "<li>password " + passwordError + "</li>"
                }

                if(combinedErrorMsg.length == 0) {
                    combinedErrorMsg = "unknown error"
                }

                $('#account_update_email').after("<ul class='error-text'>" + combinedErrorMsg + "</ul>")
            }
            else {
                app.ajaxError(xhr, textStatus, errorMessage)
            }
        }

        function postUpdatePassword(currentPassword, newPassword, newPasswordConfirm) {

            var url = "/api/users/" + context.JK.currentUserId + "/set_password";
            return $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: url,
                data: JSON.stringify({ old_password: currentPassword, new_password: newPassword, new_password_confirm: newPasswordConfirm }),
                processData: false
            });
        }

        function postUpdatePasswordSuccess(response) {
            $('#account-edit-password-submit').removeClass('button-disabled');
            $('#account-edit-password-submit').unbind('click', false);
            app.notify(
                {   title: "Password Changed",
                    text: "You have changed your password successfully."
                },
                null,
                true);
        }

        function postUpdatePasswordFailure(xhr, textStatus, errorMessage) {

            $('#account-edit-password-submit').removeClass('button-disabled');
            $('#account-edit-password-submit').unbind('click', false);
            var errors = JSON.parse(xhr.responseText)

            if(xhr.status == 422) {

                var current_password_errors = context.JK.format_errors("current_password", errors)
                var password_errors = context.JK.format_errors("password", errors)
                var password_confirmation_errors = context.JK.format_errors("password_confirmation", errors)

                if(current_password_errors != null) {
                    $('#account-edit-password-form input[name=current_password]').closest('div.field').addClass('error').end().after(current_password_errors);
                }

                if(password_errors != null) {
                    $('#account-edit-password-form input[name=password]').closest('div.field').addClass('error').end().after(password_errors);
                }

                if(password_confirmation_errors != null) {
                    $('#account-edit-password-form input[name=password_confirmation]').closest('div.field').addClass('error').end().after(password_confirmation_errors);
                }
            }
            else {
                app.ajaxError(xhr, textStatus, errorMessage)
            }
        }

        function initialize() {
            var screenBindings = {
                'beforeShow': beforeShow,
                'afterShow': afterShow
            };
            app.bindScreen('account/identity', screenBindings);
            events();
        }

        this.initialize = initialize;
        this.beforeShow = beforeShow;
        this.afterShow = afterShow;
        return this;
    };

})(window,jQuery);
