// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(
        [ 'fs/view/settings/authentication/AuthenticationSettingsBaseView',
          'fs/presenter/settings/AuthNPresenter',
                'hp/view/FormStateView',
                'hp/core/Notifications',
                'hp/model/Session',
                'hp/core/Localizer',
                'jquery',
                'lib/jquery.selectBox',
                'lib/jquery.validate'],
        function(baseView, presenter, FormStateView, notifications, session, localizer) {
            "use strict";

            var AuthenticationEditView = (function() {

                var OK = '#fs-settings-edit-ok',
                CANCEL = '#fs-settings-edit-cancel',
                ADD_SERVICE = "#fs-settings-edit-add-authn-service",
                DISABLED = 'disabled',
                SPINNER = '#fs-settings-edit-spinner',
                NOTIFY_BOX = '#fs-settings-details-notify',
                DISMISS = "#fs-settings-edit-notify-dismiss_link",
                DEFAULT_PROVIDER_SELECT = '#fs-settings-authn-edit-default-provider',
                FORM = "#fs-settings-authentication-edit-form",
                LOCAL_LOGIN_CHECK = "#fs-settings-authn-edit-allow-local";

                var TEMPLATE = "#fs-authn-service-template",
                LIST = '#fs-services',
                SERVICE_NAME_TXT = ".fs-settings-authn-service-name-text",
                PROTOCOL_SELECT = ".fs-settings-authn-service-protocol-select",
                BASEDN_USERNAME_TXT = ".fs-settings-authn-service-baseDN-username-text",
                BASEDN_ORG_TXT = ".fs-settings-authn-service-baseDN-org-text",
                BASEDN_TOP_TXT = ".fs-settings-authn-service-baseDN-top-text",
                DIRECTORY_SERVERS_HOST_NAME_TXT = ".fs-settings-authn-service-dir-server-text",
                SERVICE_REMOVE_BUTTON = "#fs-settings-authn-service-remove",
                ADD_SERVER_BUTTON = "#fs-settings-authn-service-add-servers",
                SERVER_LIST = ".fs-settings-authn-service-directory-servers",
                DIR_SERVER_TEMPLATE = ".directory-servers-template",
                SERVER_STATUS = "#server-status",
                SERVER_NAME = "#server-name",
                SERVER_REMOVE = "#server-remove",
                HOST_NAME_ERROR = "#fs-settings-authn-service-dir-server-text-error",
                BASEDN_ERROR = "#fs-settings-authn-baseDN-text-error",
                DEFAULT_DIRECTORY_ERROR = "#fs-settings-authn-edit-default-provider-error",
                DEFAULT_DIRECTORY_DELETE_ERROR = "#fs-settings-authn-default-directory-delete-error",
                DIRECTORY_SERVER_DUPLICATE_ERROR = "#fs-settings-authn-directory-duplicate-error";

                /**
                 * @class View script for the Authentication Settings panel of
                 *        the Edit Settings page.
                 */
                function AuthenticationEditView() {

                    var providerConfigs = [];
                    var deletedProviderConfigs = [];
                    var defaultProvider = null;
                    var allowLocalLoginDto = null;
                    var cancelAfterApply = false;
                    var formStateView = new FormStateView();
                    var serverTemplate;
                    var validator;

                    function createNewAuthServer() {
                        var config = {
                            "name" : "",
                            "loginDomain" : "",
                            "authProtocol" : "",
                            "org" : "",
                            "userNameField" : "",
                            "top" : "",
                            "servers" : []
                        };
                        presenter.addProviderConfig(config);
                        return config;
                    }

                    function onRemoveServerClicked(service, row) {
                        var serverToRemove = $(row).closest('tr').find(SERVER_NAME).text();
                        var id = $(service).attr("id");
                        var config = presenter.getProviderConfigByIndex(id);
                        presenter.removeServerFromProvider(config, serverToRemove);
                        $(row).closest('tr').remove();
                    }

                    function addToDirectoryServers(server, service, status) {
                        var list = $(".hp-form-input", service);
                        var item = serverTemplate.clone();

                        if (status) {
                            $(SERVER_STATUS, item).find('div').addClass('hp-status-ok');
                        } else {
                            $(SERVER_STATUS, item).find('div').addClass('hp-status-error');
                        }

                        $(SERVER_NAME, item).append(server);
                        $(SERVER_REMOVE, item).bind("click", function(ev) {
                            onRemoveServerClicked(service, item);
                        });

                        $('table tbody', list).append(item);
                        $('table',list).show();
                        list.show();
                    }

                    function validateIfDefaultDirectory(loginDomain) {
                        if ($(DEFAULT_PROVIDER_SELECT).val() === loginDomain) {
                            return true;
                        } else {
                            return false;
                        }
                    }

                    function onRemoveServiceClicked(ev, caller) {
                        var id = $(caller).attr("id");
                        var config = presenter.getProviderConfigByIndex(id);
                        if (config !== null) {
                            if (!validateIfDefaultDirectory(config.loginDomain)) {
                                presenter.removeProviderConfig(config, id);
                                $(DEFAULT_DIRECTORY_DELETE_ERROR, caller)
                                        .hide();
                                caller.hide();
                            } else {
                                $(DEFAULT_DIRECTORY_DELETE_ERROR, caller)
                                    .text(localizer.getString('fs.settings.authn.edit.default_dir_delete_error'));
                                $(DEFAULT_DIRECTORY_DELETE_ERROR, caller).addClass('hp-error');
                                $(DEFAULT_DIRECTORY_DELETE_ERROR, caller).show();
                            }
                        }
                    }

                    function onAddServerClicked(ev, service) {
                        // find the service item id
                        var id = $(service).attr("id");

                        // get host name from the text field
                        var server = $(DIRECTORY_SERVERS_HOST_NAME_TXT, service).val();
                        if ($.trim(server) === '') {
                            $(HOST_NAME_ERROR, service)
                                .text(localizer.getString('fs.settings.authn.edit.host_name_error'));
                            $(DIRECTORY_SERVERS_HOST_NAME_TXT, service).addClass('error');
                            $(HOST_NAME_ERROR, service).addClass('hp-error');
                            $(HOST_NAME_ERROR, service).show();
                            $(DIRECTORY_SERVERS_HOST_NAME_TXT, service).focus();
                            return;
                        } else {
                            $(DIRECTORY_SERVERS_HOST_NAME_TXT, service).removeClass('error');
                            $(HOST_NAME_ERROR, service).text('');
                            $(HOST_NAME_ERROR, service).hide();
                        }

                        var servers = presenter.getProviderConfigByIndex(id).servers;
                        servers.push(server);

                        addToDirectoryServers(server, service, false); // false status == not verified
                        // clear the text in the host name field
                        $(DIRECTORY_SERVERS_HOST_NAME_TXT, service).val("");
                    }

                    function buildServiceForm(authServiceConfig) {

                        var serviceNameText = "";
                        var protocolText = "";
                        var loginDomain = "";
                        var topText = "";
                        var userNameFieldText = "";
                        var orgText = "";
                        var servers = [];
                        var uri = "";
                        var service;
                        var templateId = "";

                        if (authServiceConfig) {

                            serviceNameText = authServiceConfig.name;
                            loginDomain = authServiceConfig.loginDomain;
                            protocolText = authServiceConfig.authProtocol;
                            topText = authServiceConfig.top;
                            userNameFieldText = authServiceConfig.userNameField;
                            orgText = authServiceConfig.org;
                            servers = authServiceConfig.directoryServers;
                            uri = authServiceConfig.uri;

                            // store the index of the config as the template ID
                            templateId = presenter.getIndexByConfigId(authServiceConfig.loginDomain);
                        }

                        //clone the template, add values to the controls and then add the cloned template to the page
                        service = $(TEMPLATE).clone();

                        if (templateId === "") {
                            var config = createNewAuthServer();
                            loginDomain = config.loginDomain;
                            templateId = (presenter.getProviderConfigs().length - 1);
                        }
                        service.attr("id", templateId);
                        $(service).data("loginDomain", loginDomain);
                        $(service).data("uri", uri);

                        var protocols = presenter.getActiveProtocols();
                        $.each(protocols, function(index, protocol) {
                            $(PROTOCOL_SELECT, service).append($('<option>', {
                                value : protocol.Id
                            }).text(protocol.name));
                        });

                        //apply select box styling
                        $(PROTOCOL_SELECT, service).selectBox({autoWidth: false});

                        //add id and name attribute to all controls to make formStateView and jquery validator work correctly
                        $(SERVICE_NAME_TXT, service).attr("id","fs-authentication-service-name-" + templateId);
                        $(SERVICE_NAME_TXT, service).attr("name","serviceName-" + templateId);
                        $(SERVICE_NAME_TXT, service).addClass("required");

                        $(PROTOCOL_SELECT, service).attr("id","fs-authentication-protocol-" + templateId);

                        $(BASEDN_USERNAME_TXT, service).attr("id","fs-authentication-basednUser-" + templateId);
                        $(BASEDN_USERNAME_TXT, service).attr("name","basednUser-" + templateId);

                        $(BASEDN_ORG_TXT, service).attr("id","fs-authentication-basednOrg-" + templateId);
                        $(BASEDN_ORG_TXT, service).attr("name","basednOrg-" + templateId);

                        $(BASEDN_TOP_TXT, service).attr("id","fs-authentication-basednTop-" + templateId);
                        $(BASEDN_TOP_TXT, service).attr("name","basednTop-" + templateId);

                        $(BASEDN_ERROR,service).attr("id","fs-settings-authn-baseDN-text-error-" + templateId );

                        $(".fs-service-name-label", service).attr("for","fs-authentication-service-name-" + templateId);
                        $(".fs-protocol-label", service).attr("for","fs-authentication-protocol-" + templateId);

                        //set values on each control
                        $(PROTOCOL_SELECT, service).val(protocolText);
                        $(SERVICE_NAME_TXT, service).val(serviceNameText);
                        $(BASEDN_USERNAME_TXT, service).val(userNameFieldText);
                        $(BASEDN_ORG_TXT, service).val(orgText);
                        $(BASEDN_TOP_TXT, service).val(topText);

                        serverTemplate = $(DIR_SERVER_TEMPLATE, service).removeClass(DIR_SERVER_TEMPLATE).remove().show();

                        // manually update formStateView on BaseDN controls
                        // because 3 textboxes are connected to 1 label
                        $(BASEDN_USERNAME_TXT, service).change(
                                function() {
                                    formStateView.update(
                                            "fs-authentication-basednUser-" + templateId,
                                            "Base DN(User ID)", $(this).val(),
                                            "");
                                });
                        $(BASEDN_ORG_TXT, service).change(
                                function() {
                                    formStateView.update(
                                            "fs-authentication-basednOrg-" + templateId,
                                            "Base DN(Org)", $(this).val(), "");
                                });
                        $(BASEDN_TOP_TXT, service).change(
                                function() {
                                    formStateView.update(
                                            "fs-authentication-basednTop-" + templateId,
                                            "Base DN(Top)", $(this).val(), "");
                                });

                        //create a validtor group for base DN controls so error message appears in one place
                        validator.groups["basednUser-" + templateId] = 'baseDN-' + templateId;
                        validator.groups["basednOrg-" + templateId] = 'baseDN-' + templateId;
                        validator.groups["basednTop-" + templateId] = 'baseDN-' + templateId;

                        if (session.getAuthService() === serviceNameText) {
                            $(SERVICE_REMOVE_BUTTON, service).hide();
                        } else if ($(DEFAULT_PROVIDER_SELECT).val() === loginDomain) {
                            $(SERVICE_REMOVE_BUTTON, service).hide();
                        } else {
                            $(SERVICE_REMOVE_BUTTON, service).show();
                        }

                        if (servers.length > 0) {
                            $.each(servers, function(index, server) {
                                addToDirectoryServers(server.directoryServerIpAddress, service);
                            });
                        }

                        $(SERVER_LIST).show();

                        service.show();
                        $(LIST).append(service);

                        $(PROTOCOL_SELECT, service).selectBox('reset');

                        //add validator rules after the controls are added to the screen.
                        //Otherwise you will get 'element is undefined' error
                        $("#fs-authentication-basednUser-" + templateId).rules("add", {
                                            required : true,
                                            messages : {
                                                required : localizer.getString('fs.settings.authn.edit.baseDN_required_error')
                                            }
                                        });

                        $("#fs-authentication-basednOrg-" + templateId).rules("add", {
                                            required : true,
                                            messages : {
                                                required : localizer
                                                        .getString('fs.settings.authn.edit.baseDN_required_error')
                                            }
                                        });

                        $("#fs-authentication-basednTop-" + templateId).rules("add",{
                                            required : true,
                                            messages : {
                                                required : localizer.getString('fs.settings.authn.edit.baseDN_required_error')
                                            }
                                        });

                        $("#fs-authentication-service-name-" + templateId).rules("add",{
                            isDuplicateDirectoryServiceName : DIRECTORY_SERVER_DUPLICATE_ERROR
                        });


                        $(ADD_SERVER_BUTTON, service).bind('click', function(ev) {
                            onAddServerClicked(ev, service);
                            ev.preventDefault(ev);
                        });

                        $(SERVICE_REMOVE_BUTTON, service).bind('click', function(ev) {
                            onRemoveServiceClicked(ev, service);
                            ev.preventDefault(ev);
                        });

                        return service;
                    }

                    function setDefaultProviderDisplayValue() {
                        if (defaultProvider !== null) {
                            $(DEFAULT_PROVIDER_SELECT).val(defaultProvider.loginDomain);
                            $("#fs-settings-authn-edit-default-provider-not-set").hide();
                            try {
                                $(DEFAULT_PROVIDER_SELECT).selectBox('control').show();
                            } catch (error) {
                                // nothing
                            }
                        }
                        $(DEFAULT_PROVIDER_SELECT).selectBox('reset');
                    }

                    function getGlobalSettingsSuccess() {
                        allowLocalLoginDto = presenter.getAllowLocalLogin();

                        if (allowLocalLoginDto !== null) {

                            $(LOCAL_LOGIN_CHECK).show();
                            $("#fs-settings-authn-label-allow-local-explain").show();
                            $(LOCAL_LOGIN_CHECK).prop("checked", allowLocalLoginDto.allowLocalLogin);
                            if (session.getAuthService() === 'LOCAL') {
                                $(LOCAL_LOGIN_CHECK).attr("disabled", true);
                            }
                            if (allowLocalLoginDto.allowLocalLogin) {
                                if (session.getAuthService() !== "LOCAL") {
                                    $("#fs-settings-authn-label-allow-local-explain").hide();
                                }
                                $(DEFAULT_PROVIDER_SELECT).append($("<option>", {value : "0"})
                                        .text(localizer.getString('login.LocalUser')));
                                $("#fs-settings-authn-edit-default-provider-not-set").hide();
                                try {
                                    $(DEFAULT_PROVIDER_SELECT).selectBox('control').show();
                                } catch (error) {
                                    // nothing
                                }
                            }
                        }

                        var providerInfos = presenter.getProviderInfos();
                        defaultProvider = presenter.getDefaultProvider();
                        if (providerInfos !== null && providerInfos.length > 0) {
                            $.each(providerInfos, function(index, providerInfo) {
                                $(DEFAULT_PROVIDER_SELECT).append($("<option>", {
                                    value : providerInfo.loginDomain
                                }).text(providerInfo.name));
                            });
                        }
                        setDefaultProviderDisplayValue();
                    }

                    function displayProviderCongigurations(){
                        var authConfigs = presenter.getProviderConfigs();
                        $.each(authConfigs, function(index, config) {
                            buildServiceForm(config);
                        });
                    }

                    function enableButtons() {
                        $(OK).removeAttr(DISABLED);
                        cancelAfterApply = false;
                    }

                    function disableButtons() {
                        $(OK).attr(DISABLED, DISABLED);
                    }

                    function onError(error) {
                        formStateView.setMessage({
                            summary : error.failureMessage,
                            status : "error",
                            errorMessage : error.errorInfo
                        });
                        $(SPINNER).hide();
                        enableButtons();
                    }

                    function validateForm() {
                        var errorCount = 0;

                        $(DEFAULT_DIRECTORY_ERROR).text('');
                        $(DEFAULT_DIRECTORY_ERROR).hide();

                        // filter out the hidden/removed template
                        $(".hp-form-item")
                            .not($(TEMPLATE))
                            .map( function(index) {
                                var service = $(this);
                                if ($(service).is(":visible")) {
                                    // check if user has provided at least one directory server
                                    // for the login domain
                                    if ($('table tbody tr', service).length < 1) {
                                        $(HOST_NAME_ERROR, service)
                                        .text(localizer.getString('fs.settings.authn.edit.directory_server_required_error'));
                                        $(DIRECTORY_SERVERS_HOST_NAME_TXT,service).addClass('hp-error');
                                        $(HOST_NAME_ERROR, service).addClass('hp-error');
                                        $(HOST_NAME_ERROR, service).parent().addClass('hp-has-error');
                                        $(HOST_NAME_ERROR, service).show();

                                        errorCount++;
                                    }
                                }
                            }).get();

                        //check to see if user has not allowed local login and still has LOCAL selected
                        //as default provider
                        if (!$(LOCAL_LOGIN_CHECK).prop("checked") && $(DEFAULT_PROVIDER_SELECT).val() === '0') {
                            errorCount++;
                            $(DEFAULT_DIRECTORY_ERROR).text(localizer.getString('fs.settings.authn.edit.default_dir_error'));
                            $(DEFAULT_DIRECTORY_ERROR).addClass('hp-error');
                            $(DEFAULT_DIRECTORY_ERROR).show();
                        }

                        //check if user has already deleted a provider and then BEFORE saving choose the
                        //deleted provider to be the default provider
                        if (presenter.IsProviderSetForDelete($(DEFAULT_PROVIDER_SELECT).val())){
                            errorCount++;
                            $(DEFAULT_DIRECTORY_ERROR)
                                .text(localizer.getString('fs.settings.authn.edit.default_dir_delete_error2'));
                            $(DEFAULT_DIRECTORY_ERROR).addClass('hp-error');
                            $(DEFAULT_DIRECTORY_ERROR).show();

                            //show the hidden provider - which was initally set to delete
                            var defaultProvider = $(DEFAULT_PROVIDER_SELECT).val();
                            $(".hp-form-item").map(function(index) {
                                var service = $(this);
                                if ($(service).is(":hidden")) {
                                    if($(service).data('loginDomain') === defaultProvider){
                                        $(service).show();
                                        presenter.undoDeleteProvider(defaultProvider,$(service).attr("id") );
                                    }
                                }
                            }).get();
                        }

                        if (errorCount > 0) {
                            return false;
                        } else {
                            return true;
                        }
                    }

                    function getAllDirectoriesConfigured() {

                        // filter out the hidden/removed and template
                        $(".hp-form-item").not($(TEMPLATE)).map(function(index) {
                            var service = $(this);
                            var id = $(service).attr("Id");
                            if ($(service).is(":visible")) {
                                var providerConfig = presenter.getProviderConfigByIndex(id);
                                if (providerConfig !== null) {
                                    providerConfig.name = $(SERVICE_NAME_TXT, service).val();
                                    providerConfig.authProtocol = $(PROTOCOL_SELECT + " :selected",service).val();
                                    providerConfig.org = $(BASEDN_ORG_TXT, service).val();
                                    providerConfig.userNameField = $(BASEDN_USERNAME_TXT, service).val();
                                    providerConfig.top = $(BASEDN_TOP_TXT, service).val();
                                }
                            }
                            else
                            {
                                //deleted directories are set to invisible, place them on the providerConfig array as null
                                //in order to maintain the the order of item on the screen to match the order of items
                                //on the array.
                                if(id !== null && id >= 0){
                                    var providers = presenter.getProviderConfigs();
                                    if(providers[id] !== null){
                                        providers.splice(id,0,null);
                                    }
                                }
                            }
                        }).get();
                    }

                    function onApplySuccess() {
                        var alertMsg = localizer.getString('fs.settings.authn.edit.success');
                        var notif = {
                                summary : alertMsg,
                                status : 'ok'
                            };
                            notifications.add(notif, true);

                        if (cancelAfterApply) {
                            $(CANCEL).trigger('click');
                        }
                        enableButtons();
                    }

                    function onApplyError(error) {
                        formStateView.setMessage({
                            summary : error.failureMessage,
                            status : "error",
                            errorMessage : error.errorInfo
                        });
                        enableButtons();
                    }

                    function apply(cancelOnSuccess) {
                        disableButtons();
                        cancelAfterApply = cancelOnSuccess;
                        if ($(FORM).valid() & validateForm()) {
                            getAllDirectoriesConfigured();
                            presenter.setAllowLocalLogin($(LOCAL_LOGIN_CHECK).prop("checked"));
                            presenter.setDefaultProviderById($(DEFAULT_PROVIDER_SELECT).val());
                            presenter.saveSettings({
                                success : onApplySuccess,
                                error : onApplyError
                            });
                        } else {
                            var error = {
                                "failureMessage" : localizer.getString('fs.settings.authn.edit.save_failure'),
                                "errorInfo" : {
                                    "errorMessage" : "",
                                    "resolution" : localizer.getString('fs.settings.authn.edit.failure_resolution')
                                }
                            };
                            onApplyError(error);
                        }
                    }

                    function toggleLocalLoginCheckbox() {
                        var exists = false;

                        if ($(LOCAL_LOGIN_CHECK).is(':checked')) {
                            if ($(DEFAULT_PROVIDER_SELECT + ' option[value="0"]').text() ===
                                localizer.getString('login.LocalUser')) {
                                exists = true;
                            }
                            if (!exists) {
                                $(DEFAULT_PROVIDER_SELECT).append(
                                        $("<option>", {value : "0"}).text(localizer.getString('login.LocalUser')));
                                $(DEFAULT_PROVIDER_SELECT).selectBox('reset');
                            }
                        }
                    }

                    function addAuthService() {
                        var service = buildServiceForm();
                        $(SERVICE_NAME_TXT,service).focus();
                    }

                    function loadData() {
                        providerConfigs = [];
                        deletedProviderConfigs = [];
                        validator.resetForm();
                        presenter.loadSettingsEdit();
                    }

                    function subscribeToEvents(){
                        presenter.on("getGlobalSettingsComplete", getGlobalSettingsSuccess);
                        presenter.on("getGlobalSettingsError", onError);
                        presenter.on("setAuthenticationSettingsError", onError);
                        presenter.on("onGetAllProvidersComplete", displayProviderCongigurations);
                    }

                    function unSubscribeToEvents(){
                        presenter.off("getGlobalSettingsComplete", getGlobalSettingsSuccess);
                        presenter.off("getGlobalSettingsError", onError);
                        presenter.off("setAuthenticationSettingsError", onError);
                        presenter.off("onGetAllProvidersComplete", displayProviderCongigurations);
                    }

                    this.init = function() {

                       formStateView.init({
                            form : FORM,
                            autoTrack : true
                        });

                        validator = $(FORM).validate({
                                            ignore : ":hidden",
                                            errorPlacement : function(error,element) {
                                                if (element.hasClass("fs-settings-authn-service-baseDN-username-text") ||
                                                         element.hasClass("fs-settings-authn-service-baseDN-org-text") ||
                                                         element.hasClass("fs-settings-authn-service-baseDN-top-text")) {
                                                    $('div', element.parent()).not(".hp-help").append(error).show();
                                                } else {
                                                    error.insertAfter(element);
                                                }
                                            }
                                        });

                        $.validator.addMethod("isDuplicateDirectoryServiceName",function(value, element) {
                                 var arr = [];
                                 $(".fs-settings-authn-service-name-text").map(function(){

                                     if($(this).is(":visible") &&
                                        $(this).val() === value){
                                         arr.push(value);
                                     }
                                    });
                                return arr.length <= 1;
                            }, localizer.getString('fs.settings.authn.edit.directory_server_duplicate_error'));

                        // Handlers for the buttons.
                        $(OK).click(function(ev) {
                            $(SPINNER).show();
                            apply(true);
                            ev.preventDefault();
                        });

                        $(CANCEL).click(function(ev) {
                            validator.resetForm();
                            formStateView.reset();
                            //presenter.loadSettingsOverview();
                        });

                        $(DISMISS).click(function(ev) {
                            $(NOTIFY_BOX).slideUp('fast');
                            ev.preventDefault();
                        });

                        $(ADD_SERVICE).click(function(ev) {
                            addAuthService();
                            ev.preventDefault();
                        });

                        // Don't show the spinner.
                        $(SPINNER).hide();

                        $(NOTIFY_BOX).hide();

                        $("#fs-settings-authn-edit-allow-local-not-set").show();
                        $(LOCAL_LOGIN_CHECK).hide();
                        $("#fs-settings-authn-label-allow-local").hide();
                        $("#fs-settings-authn-edit-default-provider-not-set").show();
                        $(DEFAULT_PROVIDER_SELECT).selectBox({
                            autoWidth : false
                        });
                        $(DEFAULT_PROVIDER_SELECT).selectBox('control').hide();

                        subscribeToEvents();

                        loadData();

                        $(LOCAL_LOGIN_CHECK).bind('click', toggleLocalLoginCheckbox);
                    };

                    this.pause = function() {
                        // In case we navigate away before the apply completes
                        cancelAfterApply = false;
                        formStateView.reset();
                        validator.resetForm();
                        unSubscribeToEvents();
                    };

                    this.resume = function() {
                        $(LIST).empty();
                        $(DEFAULT_PROVIDER_SELECT).empty();
                        formStateView.reset();
                        validator.resetForm();
                        loadData();
                        subscribeToEvents();
                    };
                }

                return new AuthenticationEditView();
            }());

            return AuthenticationEditView;
        });

