//(C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(
        [ 'hp/core/Router',
          'fs/presenter/settings/AuthNPresenter',
          'hp/view/FormStateView',
          'hp/core/Notifications',
          'text!fsPages/settings/authentication/edit_directory.html',
          'text!fsPages/settings/authentication/directoryupdate_confirm.html',
          'hp/view/DialogView',
          'hp/model/Session',
          'hp/core/Localizer',
          'fs/view/users/UsersViewUtil',
          'fs/model/settings/ProductConfig',
          'jquery',
          'lib/jquery.selectBox',
          'lib/jquery.validate',
          'lib/jquery.dataTables' ],
          function(router, presenter, FormStateView, notifications,edithtml,updateDirHtml, DialogView, session,
                  Localizer,UsersViewUtil, ProductConfig) {
            "use strict";
           var AuthnEditDirectoryView = (function() {
                var EDIT_DIRECTORY_DIALOG ='#fs-authn-edit-directory-dialog',
                    EDIT_DIRSERVER_DIALOG ='#fs-authn-edit-dirserver-dlg',
                    EDIT_FORM = '#fs-settings-authn-directory-edit-form',
                    DIR_NAME_TEXT = '#fs-settings-authn-dir-name-text',
                    TYPE_SELECT = "#fs-settings-authn-dir-type-select",
                    UID_TEXT = '.fs-settings-authn-search-context-uid-text',
                    ORG_TEXT = '.fs-settings-authn-search-context-org-text',
                    TOP_TEXT = '.fs-settings-authn-search-context-top-text',
                    USER_NAME_TEXT = '#fs-settings-authn-user-name-text',
                    PASSWORD_TEXT = '#fs-settings-authn-password-text',
                    HOST_NAME_ERROR = '#fs-settings-authn-dir-server-text-error',
                    ADD_DIR_SERVER_FORM = '#fs-authn-edit-dir-server-form',
                    HOST_NAME = '#fs-settings-authn-host-name-text',
                    SSL_PORT = '#fs-settings-authn-port-text',
                    KEY = '#fs-settings-authn-certificate',
                    EDIT_DIR_SERVERS_TABLE= '#fs-edit-dir-servers-table',
                    ADD_DIRSERVER_HEADER = "#add_dir_server_header",
                    ADD_DIRSERVER_FOOTER = "#add-dir-server-footer",
                    EDIT_DIRSERVER_HEADER = "#edit_dir_server_header",
                    EDIT_DIRSERVER_FOOTER = "#edit-dir-server-footer",
                    CREDENTIALS_TEXT_MSG = '#fs-settings-authn-credentials-text',
                    DUPLICATEHOST_ERROR = '#fs-settings-authn-hostname-duplicate-error',
                    HELP_TEXT = '#fs-settings-authn-search-context-help',
                    APPLY_SEARCH_CONTEXT_WARNING ='#fs-settings-search-context-warning',
                    APPLY_SEARCH_CONTEXT_WARNING_MSG ='#fs-settings-search-context-warning-msg';
                /**
                 * @class View script for the Edit Directory page.
                 */
                function AuthnEditDirectoryView() {
                    var dialog = null,
                    editDirDialog = null,
                    editDirectoryTemplate = null,
                    addDirServerDlgTemplate = null,
                    dirFormStateView = new FormStateView(),
                    serverFormStateView = new FormStateView(),
                    directoryValidator = null,
                    serverValidator = null,
                    editEntries = [],
                    editServersTable = null,
                    rowlength = 0,
                    editServersList = [],
                    serverDto = null,
                    dirEditHtml = $(edithtml),
                    initialized = false,
                    errorInUID = false,
                    dirErrorCount = 0,
                    serverErrorCount = 0,
                    addAgainDirectory = false,
                    loginDomain = "",
                    editRow = null,
                    validateDirServerIP = true,
                    productConfigMembersData = null,
                    directoryData = null,
                    defaultDirectoryName = null,
                    updateDirDialog = null;

                    /**
                     * Delete the directory sever
                     */
                    function onDeleteDirServer(event) {
                      if( !event.isPropagationStopped()){
                        var row = $(this).parents('tr')[0];
                        var entry = editServersTable.fnGetData(row);
                        if(!entry) {
                            return;
                        }
                        editEntries = $.grep(editEntries, function (entry2) {
                            return entry2.id !== entry.id;
                        });

                        editServersList = $.grep(editServersList, function (sentry2) {
                            return sentry2.directoryServerIpAddress !== entry.name;
                        });
                        var alertMsg = Localizer.getString(
                                'fs.settings.authn.addDirectory.remove_server_success', [entry.name]);
                        dirFormStateView.setMessage({
                            summary : alertMsg,
                            status : 'ok',
                            alertMsg : alertMsg
                        });

                        editServersTable.fnDeleteRow(row);
                        editServersTable.fnDraw();
                        rowlength = rowlength-1;
                        if(editServersList.length === 0) {
                            rowlength = 0;
                            $(EDIT_DIR_SERVERS_TABLE).hide();
                        }
                        event.stopPropagation();
                        event.preventDefault();
                        }
                      }
                    /**
                     * Reset the directory server params
                     */
                    function resetServerParams() {
                        $(HOST_NAME).val("");
                        $(SSL_PORT).val("");
                        $(KEY).val("");
                        $(HOST_NAME_ERROR).removeClass('hp-error');
                        $(HOST_NAME_ERROR).parent().removeClass('hp-has-error');
                        $(HOST_NAME_ERROR).text('');
                        $(HOST_NAME_ERROR).hide();
                        serverValidator.resetForm();
                        serverFormStateView.reset();
                        serverErrorCount = 0;
                    }

                    /**
                     * add directory server success
                     */
                    function onAddServerSuccess() {
                     // get host name from the text field
                        var serverHost = $(HOST_NAME).val();
                        var port = $(SSL_PORT).val();
                        var certificate = $(KEY).val();
                        var rowId = rowlength+1;
                        var row = [{id:rowId, name:serverHost, status:Localizer.getString('fs.settings.authn.addServer.certificate_state_yes'),
                                  port:port,certificate:certificate}];
                        editServersTable.fnAddData(row);
                        editServersTable.fnAdjustColumnSizing();
                        editServersTable.fnDraw();
                        $(EDIT_DIR_SERVERS_TABLE).css("display", "block");
                        $(EDIT_DIR_SERVERS_TABLE).show();
                        editServersList.push(serverDto);
                        //Change : Directory servers to 'server name'
                        var alertMsg = Localizer.getString('fs.settings.authn.addServer.success', [serverHost]);
                        notifications.add({ summary : alertMsg, status : 'ok' }, true);
                        serverFormStateView.setMessage({
                            summary : alertMsg,
                            status : 'ok',
                            alertMsg : alertMsg
                        });
                       // reset the params
                        resetServerParams();
                        if(!addAgainDirectory){
                           dialog.cancel();
                        }

                    }

                    /**
                     * add directory server success
                     */
                    function onEditServerSuccess() {
                     // get host name from the text field
                     var serverHost = $(HOST_NAME).val();
                     var port = $(SSL_PORT).val();
                     var certificate = $(KEY).val();
                     var association = editServersTable.fnGetData(editRow);
                     $.each(editServersList, function(index, servers) {
                           if(this.directoryServerIpAddress === association.name){
                                editServersList.splice(index,1,serverDto);
                          }
                      });
                     editServersTable.fnUpdate(serverHost, editRow, 0, false );
                     editServersTable.fnUpdate(port, editRow, 2, false );
                     editServersTable.fnUpdate(certificate, editRow, 3, false );
                     editServersTable.fnDraw();
                     // reset the params
                     resetServerParams();
                     if(!addAgainDirectory){
                           dialog.cancel();
                        }

                    }
                    /**
                     * @private Add a server side error to the list of errors that the validator will display
                     * @param {object} validatorErrors The list of errors that the validator will display
                     * @param {object} errorFromServer The error from a REST response body to add to the list
                     */
                    function addValidatorError(validatorErrors, errorFromServer) {
                        var errorMessage = errorFromServer.message;
                        var sourceId = errorFromServer.errorSource;
                        var validatorErrorsMap = {
                            "dirname" : "name",
                            "type" : "authProtocol",
                            "uid" : "userNameField",
                            "org" : "org",
                            "top" : "top",
                            "servers" : "directoryServers",
                            "port" : "portNumber"
                        };

                        $.map(validatorErrorsMap, function(value, key) {

                            if(sourceId === value) {
                                validatorErrors[key] = errorMessage;
                                if(value.match("portNumber")) {
                                    serverErrorCount++;
                                }
                                else {
                                    dirErrorCount++;
                                }
                            }
                        });

                        if(sourceId.indexOf("server:") === 0) {
                            validatorErrors.username = errorMessage;
                            dirErrorCount++;
                        }
                        else if(sourceId.indexOf("certificate") === 0) { // cerificate expired && cerificate
                            validatorErrors.publickey = errorMessage;
                            serverErrorCount++;
                        }
                        else if(sourceId.indexOf("ipAddress") === 0) { // ipAddress && ipAddress:portNumber
                            validatorErrors.hostname = errorMessage;
                            serverErrorCount++;
                        }
                        else if(sourceId.indexOf("org") === 0) { // org contains more than 4 entries
                            validatorErrors.org = errorMessage;
                            serverErrorCount++;
                        }
                    }
                    /**
                     * validate directory server params
                     */
                    function addDirServer(button){
                       var close = $(button).hasClass('hp-primary'); // false means leave dialog open
                       if ($(ADD_DIR_SERVER_FORM).valid()) {
                         serverDto = {
                               "type" : "LoginDomainDirectoryServerInfoDto",
                               "directoryServerSSLPortNumber" : $(SSL_PORT).val(),
                               "directoryServerIpAddress" : $(HOST_NAME).val(),
                               "directoryServerCertificateStatus" : "",
                               "serverStatus" : "",
                               "directoryServerCertificateBase64Data" : $(KEY).val()
                           };
                              onAddServerSuccess();
                               if(close) {
                                dialog.cancel();
                               }
                        }
                          return false;
                    }
                    /**
                     * duplicate directory server check while editing the server
                     */
                    function isDuplicateServer(){
                        var result = true;
                        var hostname = $(HOST_NAME).val();
                        var editData = editServersTable.fnGetData(editRow);
                        if(editData.name !== hostname){
                        $.each(editServersList, function(index, servers) {
                            if(hostname === servers.directoryServerIpAddress){
                                  result  = false;
                                  return false ;
                              }
                          });
                        }
                        return result;
                    }
                    /**
                     * validate directory server params
                     */
                    function editDirServer(button){
                       var close = $(button).hasClass('hp-primary'); // false means leave dialog open
                        if ($(ADD_DIR_SERVER_FORM).valid() && isDuplicateServer()) {
                         serverDto = {
                               "type" : "LoginDomainDirectoryServerInfoDto",
                               "directoryServerSSLPortNumber" : $(SSL_PORT).val(),
                               "directoryServerIpAddress" : $(HOST_NAME).val(),
                               "directoryServerCertificateStatus" : "",
                               "serverStatus" : "",
                               "directoryServerCertificateBase64Data" : $(KEY).val()
                               };
                                   onEditServerSuccess();
                                   if(close) {
                                       dialog.cancel();
                                   }

                       }else if(!isDuplicateServer()){
                           $(DUPLICATEHOST_ERROR).text(Localizer.getString('fs.settings.authn.addServer.duplicate_host'));
                           $(DUPLICATEHOST_ERROR).addClass('hp-error');
                           $(DUPLICATEHOST_ERROR).parent().addClass('hp-has-error');
                           $(DUPLICATEHOST_ERROR).show();
                         }
                       return false;

                    }
                    /**
                     * show directory server dialog
                     */
                    function onAddDirServer() {
                       dialog = new DialogView({
                            contents : addDirServerDlgTemplate,
                            ok: function(button) {

                             },
                            cancel: function() {
                                  if ($(EDIT_DIRSERVER_DIALOG).is(':data(dialog)')) {
                                   $(EDIT_DIRSERVER_DIALOG).dialog("close");
                               }

                                }
                        });
                        dialog = dialog;
                        $(HOST_NAME).focus();
                        $(KEY).attr("placeholder", Localizer.getString('fs.settings.authn.addDirectory.certificate_placeholder'));
                    }
                    /**
                     * @private
                     */
                    function onEditDirServer(event) {
                     validateDirServerIP = false;
                     if( !event.isPropagationStopped()){
                        var row = $(this).parents('tr')[0];
                        var association = editServersTable.fnGetData(row);
                        editRow = row ;
                        resetServerParams();
                        $(HOST_NAME, addDirServerDlgTemplate).val(association.name);
                        $(SSL_PORT, addDirServerDlgTemplate).val(association.port);
                        $(KEY, addDirServerDlgTemplate).val(association.certificate);
                        $(ADD_DIRSERVER_HEADER, addDirServerDlgTemplate).hide();
                        $(ADD_DIRSERVER_FOOTER, addDirServerDlgTemplate).hide();
                        $(EDIT_DIRSERVER_HEADER, addDirServerDlgTemplate).show();
                        $(EDIT_DIRSERVER_FOOTER, addDirServerDlgTemplate).show();
                        serverValidator.resetForm();
                        onAddDirServer();
                    }
                      event.stopPropagation();
                          event.preventDefault();
                      }
                     /**
                     * create the directory server table
                     */
                    function loadDirServers() {
                          editEntries =[];
                          for (var i = 0; i<editServersList.length; i+=1) {
                          $(EDIT_DIR_SERVERS_TABLE).show();
                              editEntries.push({
                                    id: i,
                                    name: editServersList[i].directoryServerIpAddress,
                                    status: editServersList[i].directoryServerCertificateStatus,
                                    port: editServersList[i].directoryServerSSLPortNumber,
                                    certificate: editServersList[i].directoryServerCertificateBase64Data

                                });
                            }
                        if(editServersList !== null){

                         editServersTable = $(EDIT_DIR_SERVERS_TABLE).dataTable({
                            bPaginate : false,
                            bFilter : false,
                            bInfo : false,
                            sScrollXInner : "100%",
                            bScrollCollapse : true,
                            bDestroy : true,
                            bAutoWidth: false,
                            aaData : editEntries,
                            aoColumns : [
                             {
                                sTitle : Localizer.getString('fs.settings.authn.addServer.table_column_server'),
                                mDataProp : 'name',
                                sWidth : 20
                            }, {
                                sTitle : Localizer.getString('fs.settings.authn.addServer.table_column_certificate'),
                                mDataProp : 'status',
                                sWidth : 20
                            },
                            {
                               sTitle : 'port',
                                mDataProp : 'port',
                                sWidth : 5,
                                bVisible : false
                            },
                            {  sTitle : 'certificate',
                               mDataProp : 'certificate',
                               sWidth : 5,
                               bVisible : false
                                },
                            {
                                fnRender : function(oObj) {
                                    return '<div class="hp-edit"></div>';
                                },
                                sDefaultContent : '',
                                sClass : 'hp-icon',
                                sWidth : 5,
                                bSortable : false
                            }, {
                                fnRender : function(oObj) {
                                    return '<div class="hp-close"></div>';
                                },
                                sDefaultContent : '',
                                sClass : 'hp-icon',
                                sWidth : 5,
                                bSortable : false
                            }
                          ]
                        });
                        $(EDIT_DIR_SERVERS_TABLE).on('click', '.hp-close', onDeleteDirServer);
                        $(EDIT_DIR_SERVERS_TABLE).on('click', '.hp-edit', onEditDirServer);

                     }
                    }
                    /**
                     * @private
                     */
                 function formatNotificationDetails(serverError) {
                    var resolutionList = serverError.recommendedActions;
                    var resolutionMessage = "";
                      $.each(resolutionList, function(index, resolution) {
                          serverError.recommendedActions.join('<br>');
                             resolutionMessage = serverError.recommendedActions.join('<br>');
                            });
                        var failureNotificationDetails = {
                         summary : serverError.message
                                    + " "
                                    + (resolutionMessage),
                               details : serverError.details,
                               status : "error"
                        };
                        return failureNotificationDetails;
                    }
                    /**
                     * @private
                     */
                    function onAddDirError(errorInfo) {
                       var details = '';
                       var resolutions = '';
                       var failureNotificationDetails = '';
                       var serverErrorList = errorInfo.nestedErrors;
                       if(serverErrorList.length !== 0){
                       $.each(serverErrorList, function(index, serverError) {
                             details = details + serverError.details;
                             var resolutionList = serverError.recommendedActions;
                              failureNotificationDetails = formatNotificationDetails(serverError);
                              $.each(resolutionList, function(index, resolution) {
                                      resolutions += serverError.recommendedActions.join('<br>');
                              });
                        });
                       }else {
                           details = errorInfo.details ;
                           resolutions = errorInfo.resolution;
                       }
                       dirFormStateView.setMessage({
                            summary : details,
                            status : 'error',
                            details : resolutions
                        });

                    }
                   function checkIfAtleastOneDirServer() {
                        // check if user has provided at least one directory server
                        // for the login domain
                        if(editServersList.length === 0) {
                            $(HOST_NAME_ERROR).text(Localizer.getString('fs.settings.authn.edit.directory_server_required_error'));
                            $(HOST_NAME_ERROR).addClass('hp-error');
                            $(HOST_NAME_ERROR).parent().addClass('hp-has-error');
                            $(HOST_NAME_ERROR).show();

                            return false;
                        }

                        return true;
                    }
                    /**
                     * @private
                     */
                    function redirect() {
                        directoryValidator.resetForm();
                        dirFormStateView.reset();
                        router.go('/settings/show/overview', 'settings overview');
                    }

                    /**
                     * @private
                     */
                    function onEditDirSuccess() {
                        var alertMsg = Localizer.getString(
                                'fs.settings.authn.addDirectory.add_success', [$(DIR_NAME_TEXT).val()]);
                        dirFormStateView.setMessage({
                            summary : alertMsg,
                            status : 'ok',
                            alertMsg : alertMsg
                        });

                        var dirAddedSuccess = {
                            summary : Localizer.getString('fs.settings.authn.addDirectory.success_notification'),
                            status : "ok"
                        };
                        notifications.add(dirAddedSuccess, true, true, true);
                        redirect();

                    }
                    /**
                     * Verify the search context is modified
                     */
                    function isSearchContextChanged() {
                        if(directoryData.userNameField !== $(UID_TEXT).val()){
                            return true;
                        } else if (directoryData.org !== $(ORG_TEXT).val()) {
                            return true;
                        } else if (directoryData.top !== $(TOP_TEXT).val()) {
                            return true;
                        }
                        return false;
                    }
                    /**
                     * call the put API to update a directory
                     * on success
                     */
                    function onEditDirectory(button,uri) {
                        var close = $(button).hasClass('hp-primary'); // false means leave dialog open
                        if ($(EDIT_FORM).valid() && checkIfAtleastOneDirServer()) {
                            var dirConfig = {
                                    "name" : $(DIR_NAME_TEXT).val(),
                                    "userName" : $(USER_NAME_TEXT).val(),
                                    "password" : $(PASSWORD_TEXT).val(),
                                    "authProtocol" : $(TYPE_SELECT + " :selected").val(),
                                    "org" : $(ORG_TEXT).val(),
                                    "top" : $(TOP_TEXT).val(),
                                    "userNameField" : $(UID_TEXT).val(),
                                    "directoryServers" : editServersList
                            };
                            if(productConfigMembersData['settings.security.ldap.settings.edit.confirmation'] === "true" &&
                                    defaultDirectoryName === directoryData.name && isSearchContextChanged()){
                                var contentsDir = $(updateDirHtml);
                                $("#fs-dir-update-confirm-title", contentsDir).text(Localizer.getString('fs.settings.authn.edit.search_ctx_update_title'));
                                $("#fs-dir-update-confirm-msg", contentsDir).text(Localizer.getString('fs.settings.authn.edit.search_ctx_update_common_msg'));
                                $("#fs-dir-update-confirm-msg1", contentsDir).text(Localizer.getString('fs.settings.authn.edit.search_ctx_update_confirm_msg'));
                                updateDirDialog = new DialogView({contents: contentsDir,
                                    ok: function () {
                                        presenter.updateDirectory(uri,dirConfig, {
                                            success : function() {
                                                onEditDirSuccess();
                                                if(close) {
                                                    editDirDialog.cancel();
                                                }
                                            },
                                            error : onAddDirError
                                        });},
                                        cancel: function () {
                                        }
                                });
                            }else {

                                presenter.updateDirectory(uri,dirConfig, {
                                    success : function() {
                                        onEditDirSuccess();
                                        if(close) {
                                            editDirDialog.cancel();
                                        }
                                    },
                                    error : onAddDirError
                                });
                            }
                        }
                        else if(checkIfAtleastOneDirServer()){
                            var error = {
                                    "errorMessage" : Localizer.getString('fs.settings.authn.edit.save_failure'),
                                    "resolution" : Localizer.getString('fs.settings.authn.edit.failure_resolution')
                            };
                            dirFormStateView.setMessage({
                                summary : error.errorMessage,
                                status : 'error'
                            });
                        }
                    }
                    /**
                     * Loads the product-config data
                     */
                    function loadProductConfigData(){
                        ProductConfig.getproductConfigMembers({
                            success : function(productConfigMembers) {
                                productConfigMembersData = productConfigMembers;
                            }
                        });
                    }
                    /**
                     * @private
                     */
                    function validateServerForm() {
                        /*
                         * Regex for Hostname
                         * (?=^.{1,254}$) matches domain names (that can begin with any char) that are long
                         * between 1 and 254 char, it could be also 5,254 if we assume co.uk is the minimum length.
                         * (^ starting match
                         * (?: define a matching group
                         * (?!\d+\.) the domain name should not be composed by numbers, so 1234.co.uk or abc.123.uk
                         * aren't accepted while 1a.ko.uk yes.
                         * [a-zA-Z0-9_\-] the domain names should be composed by words with only a-zA-Z0-9_-
                         * {1,63} the lenght of any domain level is maximum 63 char, (it could be 2,63)
                         * + and
                         * (?:[a-zA-Z]{2,})$) the final part of the domain name should not be followed by any other
                         * word and must be composed of a word minumum of 2 char a-zA-Z
                         *
                         * Also checks for dotted notation for a valid IP address check - xxx.xxx.xxx.xxx where
                         * xxx can be anything between 0 and 255
                         */
                        $.validator.addMethod("fsDirServerHostCheck", function(value, element, param) {
                            return (/^(([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.){3}([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/
                                                    .test(value) ||
                                    /(?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$)/.test(value));
                        }, Localizer.getString('fs.settings.authn.addServer.invalid_host'));

                        $.validator.addMethod("notDuplicateDirSever", function(value, element) {
                            var duplicate = false;
                            if(validateDirServerIP){
                            for(var i = 0; i < editServersList.length; i++) {
                                if(value.match(editServersList[i].directoryServerIpAddress))
                                {
                                    duplicate = true;
                                }
                            }
                            }
                            return (!duplicate);
                        }, Localizer.getString('fs.settings.authn.addServer.duplicate_host'));

                        $.validator.addMethod("fsDirServerPortNumericCheck",function(value, element) {
                            return (/^[\d]+$/.test(value));
                        }, Localizer.getString('fs.settings.authn.addServer.invalid_port'));

                        $.validator.addMethod("fsDirServerPortInRangeCheck",function(value, element) {
                            return (value >= 0 && value <= 65535);
                        }, Localizer.getString('fs.settings.authn.addServer.invalid_port_range'));

                        $.validator.addMethod("fsDirServerCertCheck",function(value, element) {
                             return (value.match("^-----BEGIN") &&
                                    value.match("END CERTIFICATE-----$"));
                        }, Localizer.getString('fs.settings.authn.addServer.invalid_certificate'));

                       serverValidator = $(ADD_DIR_SERVER_FORM).validate({
                            rules : {
                                hostname : {
                                    required : true,
                                    fsDirServerHostCheck : HOST_NAME,
                                    notDuplicateDirSever : HOST_NAME
                               },
                               port : {
                                   required : true,
                                   fsDirServerPortNumericCheck : SSL_PORT,
                                   fsDirServerPortInRangeCheck : SSL_PORT
                               },
                               publickey : {
                                   required : true,
                                   fsDirServerCertCheck : KEY
                               }
                           }
                       });

                    }

                    /**
                     * @private
                     */
                    function validateDirectoryForm() {
                        $.validator.addMethod("fsDirNamingAttributeCheck", function(
                                value, element, param) {
                            errorInUID = true;
                            $('#fs-settings-authn-example-text').show();
                            return (value.toLowerCase().match("cn") || value.toLowerCase().match("uid"));
                        }, Localizer.getString('fs.settings.authn.addDirectory.invalid_naming_attribute'));
                        if(productConfigMembersData['settings.security.ldap.multirdn.disable'] === "true") {
                            $.validator.addMethod(
                                    "fsEditDirDisableMultiRdn", function(
                                            value, element, param) {
                                        errorInUID = true;
                                        var match = value.match(/\+/g);
                                        var count = match ? match.length : 0;
                                        return (count < 1);
                                    }, Localizer.getString('fs.settings.authn.addDirectory.disable_multirdn'));
                             }else {
                                 var noOfRDNsSupported = 10;
                                 if(productConfigMembersData['settings.security.ldap.no.of.rdns.supported'] !== undefined &&
                                     !isNaN(productConfigMembersData['settings.security.ldap.no.of.rdns.supported']) &&
                                     productConfigMembersData['settings.security.ldap.no.of.rdns.supported'] != 0){
                                         noOfRDNsSupported = productConfigMembersData['settings.security.ldap.no.of.rdns.supported'];  
                                 }
                               $.validator.addMethod(
                                         "fsMaxSearchContextCheck", function(
                                                 value, element, param) {
                                             errorInUID = true;
                                             var match = value.match(/\+/g);
                                             var count = match ? match.length : 0;
                                             return (count < noOfRDNsSupported);
                                         }, Localizer.getString('fs.settings.authn.addDirectory.max_search_context',[noOfRDNsSupported]));
                             }
                            directoryValidator = $(EDIT_FORM).validate({
                            rules : {
                              username : {
                                  required : true
                               },
                              password : {
                                  required : true
                               }
                            },
                            ignore : ":hidden"
                        });

                        //create a validtor group for search-context controls so error message appears in one place
                        directoryValidator.groups["uid"] = 'search-context';
                        directoryValidator.groups["org"] = 'search-context';
                        directoryValidator.groups["top"] = 'search-context';

                        $(UID_TEXT).rules("add", {
                                            required : true,
                                            fsDirNamingAttributeCheck : UID_TEXT,
                                            messages : {
                                                required : Localizer.getString('fs.settings.authn.edit.baseDN_required_error')
                                            }
                                       });
                        if(productConfigMembersData['settings.security.ldap.multirdn.disable'] === "true"){
                            $(ORG_TEXT).rules("add", {
                                required : true,
                                fsEditDirDisableMultiRdn : ORG_TEXT,
                                messages : {
                                    required : Localizer
                                            .getString('fs.settings.authn.edit.baseDN_required_error')
                                }
                            });
                        }else{
                            $(ORG_TEXT).rules("add", {
                                required : true,
                                fsMaxSearchContextCheck : ORG_TEXT,
                                messages : {
                                    required : Localizer
                                            .getString('fs.settings.authn.edit.baseDN_required_error')
                                }
                            });
                        }
                        $(TOP_TEXT).rules("add",{
                                            required : true,
                                            messages : {
                                                required : Localizer.getString('fs.settings.authn.edit.baseDN_required_error')
                                            }
                                        });
                    }
                    /*
                     * load directory data from serer
                     */
                    function loadDirectoryData(config){
                        editServersList = config.directoryServers;
                        rowlength = editServersList.length;
                        $(DIR_NAME_TEXT,dirEditHtml).val(config.name);
                        $(TYPE_SELECT).val(config.authProtocol);
                        $(TYPE_SELECT).selectBox('control').show();
                        $(TYPE_SELECT).selectBox('reset');
                        $(UID_TEXT,dirEditHtml).val(config.userNameField);
                        $(ORG_TEXT,dirEditHtml).val(config.org);
                        $(TOP_TEXT,dirEditHtml).val(config.top);
                        $(USER_NAME_TEXT,dirEditHtml).val("");
                        $(PASSWORD_TEXT,dirEditHtml).val("");
                        loginDomain = config.loginDomain;
                        loadDirServers();
                     }
                    function localizeHelpText(){
                        $(HELP_TEXT).text("("+Localizer.getString('fs.settings.authn.addDirectory.help_example')+":"+
                        Localizer.getString('fs.settings.authn.addDirectory.help_field1')+": CN / UID "+
                        Localizer.getString('fs.settings.authn.addDirectory.help_field2')+": OU=example.com, OU=Users "+
                        Localizer.getString('fs.settings.authn.addDirectory.help_field3')+": DC=examplecorp, DC=net)");
                        }
                    function isCredentialsTextMsgShow(){
                        
                        if(UsersViewUtil.configs[UsersViewUtil.LDAP_CREDENTIAL_SAVE] !== null &&
                        UsersViewUtil.configs[UsersViewUtil.LDAP_CREDENTIAL_SAVE] !== undefined  &&
                        UsersViewUtil.configs[UsersViewUtil.LDAP_CREDENTIAL_SAVE] === "true" ){
                              $(CREDENTIALS_TEXT_MSG).hide();
                         }else{
                            $(CREDENTIALS_TEXT_MSG).show();
                         }
                            }

                    function init(config, defaultDirectory) {
                    if (!initialized) {
                       initialized = true;
                       validateDirectoryForm();
                       validateServerForm();
                       directoryValidator.resetForm();
                       $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).hide();
                       editDirectoryTemplate = $(EDIT_DIRECTORY_DIALOG);
                       dirFormStateView.init({
                           form : EDIT_FORM,
                           autoTrack : true
                       });
                       presenter.loadSettingsEdit();
                       localizeHelpText();
                       addDirServerDlgTemplate = $(EDIT_DIRSERVER_DIALOG).detach().show();
                       Localizer.localizeDom(addDirServerDlgTemplate);
                       serverFormStateView.init({form: $('form', addDirServerDlgTemplate), autoTrack: true});
                       $(editDirectoryTemplate).on('click', '#fs-settings-authn-add-dir-servers', function (ev) {
                           resetServerParams();
                           validateDirServerIP = true;
                           $(ADD_DIRSERVER_HEADER, addDirServerDlgTemplate).show();
                           $(ADD_DIRSERVER_FOOTER, addDirServerDlgTemplate).show();
                           $(EDIT_DIRSERVER_HEADER, addDirServerDlgTemplate).hide();
                           $(EDIT_DIRSERVER_FOOTER, addDirServerDlgTemplate).hide();
                           $(HOST_NAME, addDirServerDlgTemplate).val("");
                           $(SSL_PORT, addDirServerDlgTemplate).val("");
                           $(KEY, addDirServerDlgTemplate).val("");
                            onAddDirServer();
                            ev.preventDefault();
                         });
                        $(addDirServerDlgTemplate).on('click', '#fs-cancel-add-dir-server', function (event) {
                            dialog.cancel();
                            event.preventDefault();
                        });
                        $(addDirServerDlgTemplate).on('click', '#fs-cancel-edit-dir-server', function (event) {
                            dialog.cancel();
                            event.preventDefault();
                        });
                        $(addDirServerDlgTemplate).on('click', '#edit-dir-server-ok', function (event,button) {
                            editDirServer(button);
                            event.preventDefault();
                        });
                        $(addDirServerDlgTemplate).on('click', '#add-dir-server-ok', function (event,button) {
                             addAgainDirectory = false;
                             addDirServer(button);
                             event.preventDefault();
                        });
                        $(addDirServerDlgTemplate).on('click', '#addagain-dir-server-ok', function (event,button) {
                             addAgainDirectory = true;
                             addDirServer(button);
                             event.preventDefault();
                         });
                        var protocols = presenter.getActiveProtocols();
                        $.each(protocols, function(index, protocol) {
                           $(TYPE_SELECT).append($('<option>', {
                               value : protocol.Id
                           }).text(protocol.name));
                       });
                       $(TYPE_SELECT).selectBox({
                       autoWidth : false
                            });
                            $(TYPE_SELECT).selectBox('control').hide();
                        }
                        isCredentialsTextMsgShow();
                        // manually update formStateView on Search context controls
                        // because 3 textboxes are connected to 1 label
                        $(APPLY_SEARCH_CONTEXT_WARNING_MSG, editDirectoryTemplate).text(Localizer.getString('fs.settings.authn.edit.search_ctx_update_common_msg')+
                                Localizer.getString('fs.settings.authn.edit.search_ctx_update_warning_msg'));
                        $(UID_TEXT).change(function() {
                            $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).hide();
                            if(productConfigMembersData['settings.security.ldap.settings.edit.warning'] === "true" && (defaultDirectory.name === config.name) && ($(this).val() !== config.userNameField)) {
                                $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).show();
                            }
                            dirFormStateView.update(
                                    "fs-settings-authn-search-context-uid-text",
                                    Localizer.getString('fs.settings.authn.addDirectory.search_context_uid'), $(this).val(),
                            "");
                        });
                        $(ORG_TEXT).change(function() {
                            $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).hide();
                            if(productConfigMembersData['settings.security.ldap.settings.edit.warning'] === "true"&&(defaultDirectory.name === config.name) && ($(this).val() !== config.org)) {
                                $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).show();
                            }
                            dirFormStateView.update(
                                    "fs-settings-authn-search-context-org-text",
                                    Localizer.getString('fs.settings.authn.addDirectory.search_context_org'), $(this).val(),
                            "");
                        });
                        $(TOP_TEXT).change(function() {
                            $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).hide();
                            if(productConfigMembersData['settings.security.ldap.settings.edit.warning'] === "true" &&(defaultDirectory.name === config.name) && ($(this).val() !== config.top)) {
                                $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).show();
                            }
                            dirFormStateView.update(
                                    "fs-settings-authn-search-context-top-text",
                                    Localizer.getString('fs.settings.authn.addDirectory.search_context_top'), $(this).val(),
                            "");
                        });
                    }

                    this.pause = function() {
                        // In case we navigate away before the apply completes
                        directoryValidator.resetForm();
                        serverValidator.resetForm();
                        dirFormStateView.reset();
                        serverFormStateView.reset();
                    };

                    this.resume = function() {

                        directoryValidator.resetForm();
                        serverValidator.resetForm();
                        dirFormStateView.reset();
                        serverFormStateView.reset();
                        isCredentialsTextMsgShow();
                        $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).hide();
                    };
                    //to clear the validators
                    function functionCheck(){
                      if (initialized){
                          directoryValidator.resetForm();
                          serverValidator.resetForm();
                          dirFormStateView.reset();
                          serverFormStateView.reset();
                        }
                    }
                    //initialise the edit directory dialog
                    this.initialize = function(event,config,defaultDirectory){
                        functionCheck();
                        $(APPLY_SEARCH_CONTEXT_WARNING, editDirectoryTemplate).hide();
                        editDirDialog = new DialogView({
                            contents:dirEditHtml,
                            ok: function (button) {
                                 onEditDirectory(button,config.uri);
                                 return false;
                       },
                           cancel: function () {
                           redirect();
                        }
                        });
                        loadProductConfigData();
                        directoryData = config;
                        defaultDirectoryName = defaultDirectory.name;
                        init(config, defaultDirectory);
                        loadDirectoryData(config);
                        event.stopPropagation();
                        event.preventDefault();
                        return false;
                    };
                }

                return new AuthnEditDirectoryView();
            }());

            return AuthnEditDirectoryView;
        });
