
// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['fs/presenter/users/UsersPresenter',
        'fs/view/users/UsersViewUtil',
        'hp/view/FormStateView',
        'hp/core/Localizer',
        'hp/model/Session',
        'hp/core/Notifications',
        'jquery',
        'hp/lib/jquery.hpToggle',
        'lib/jquery.validate' ],
function(presenter, UsersViewUtil, FormStateView, Localizer, session, notifications) { "use strict";

    var UsersAddView = (function() {

        /**
         * Constructor
         */
        function UsersAddView() {
            var FORM = '#fs-user-add-form',
                ADD = '#fs-user-add',
                ADDAGAIN = "#fs-user-add-again",
                NAME = '#fs-user-loginname',
                FULLNAME = '#fs-user-fullname',
                INITIAL_PASSWD = '#fs-user-initialpasswd',
                INITIAL_PASSWD_HELP = '#fs-user-initialpasswd-help',
                CONFIRM_PASSWD = '#fs-user-confirmpasswd',
                EMAIL = '#fs-user-email',
                OFFICE_PHONE = '#fs-user-officephone',
                MOBILE_PHONE = '#fs-user-mobilephone',
                ROLE_VALIDATOR = '#fs-user-role-validator',
                ROLES_LIST = '#fs-user-roles-list',
                ROLES = ROLES_LIST + ' input[type="checkbox"]',
                ROLE_SWITCH = '#fs-user-role-switch',
                CANCEL = '#fs-user-add-cancel',
                ROLE_LIST ='#fs-user-roles',
                ROLE_SELECT_NAME = 'fsuserrolename',
                ROLE_SWITCH_RADIO = 'input[name=fsuserrolename]:checked',
                ROLE_SPECIALIZED_CHECKBOXES = "input[type='checkbox'][id^='fs-user-role']",
                SPECIALIZED_VALUE = 'specialized',
                FULL_VALUE = 'full',
                READONLY_VALUE = 'readonly',
                SPECIALIZED_BUTTONSET ='#fs-user-role-name-specialized',
                FULLNAME_OPTIONAL = "#fs-user-fullname-optional",
                EMAIL_OPTIONAL = "#fs-user-email-optional",
                OFFICEPHONE_OPTIONAL = "#fs-user-officephone-optional",
                MOBILEPHONE_OPTIONAL = "#fs-user-mobilephone-optional",
                INFRASTRUCTURE_ADMINISTRATOR = 'Infrastructure administrator',
                READ_ONLY = 'Read only';

            var validator;
            // prevent double click
            var isSubmitted;
            var formStateView = new FormStateView();
            var firstRoleTemplate = null,
                roleTemplate = null;
            var isSpecialized;
            var currentUserName;
            var currentUserFullName;
            var addAgain = false;
            var allRadio = false;
            var oneRole= false;
            var taskName;
            var isValidLogin = true;//assume is true i.e loginname is valid
            var numberOfClicks = 0;

            /**
            * @private To check the checkbox or uncheck the checkbox of a role
            * under 'Specialized' radio button if only 1 specialized role is
            * present in list.
            */
            function autoCheckSpecializedRole(boolValue){
                var theRoles = $(ROLES);
                if (theRoles.length === 1){
                    theRoles.prop('checked',boolValue).trigger('change');
                }
            }

            /**
            * @private
            */
            function onSpecializedUserClick() {
                isSpecialized = true;
                $(ROLE_VALIDATOR).val("");
                $(SPECIALIZED_BUTTONSET).attr("checked", true);
                $(ROLES_LIST).show();
                autoCheckSpecializedRole(true);
            }

            /**
            * @private
            */
            function onFullOrReadonlyUserClick() {
                isSpecialized = false;
                $(ROLE_VALIDATOR).val("set");
                autoCheckSpecializedRole(false);
                $(ROLES_LIST).hide();
            }

            /**
            * @private
            */
            function displayRoles() {
                if ($(ROLE_SWITCH_RADIO).val() === SPECIALIZED_VALUE){
                    onSpecializedUserClick();
                }
                else{
                    onFullOrReadonlyUserClick();
                }
            }

            /**
             * @private
             */
            function resetCancel() {
                $(NAME).val("");
                $(FULLNAME).val("");
                $(INITIAL_PASSWD).val("");
                $(CONFIRM_PASSWD).val("");
                $(EMAIL).val("");
                $(OFFICE_PHONE).val("");
                $(MOBILE_PHONE).val("");
                $(ROLE_SWITCH).attr('checked', true).trigger('change');
                $(ROLES).prop("checked", false);
                $(ROLE_VALIDATOR).val("");
                validator.resetForm();
                formStateView.reset();
                if (addAgain){
                    onSpecializedUserClick();
                    $(NAME).focus();
                }
                isValidLogin = true;
                numberOfClicks = 0;
                isSubmitted = false;
            }


            /**
             * @private
             */
            function onRolesAddedSuccess(user) {
                var alertMsg = Localizer.getString('fs.users.add.add');
                var userAddedSuccess = {
                    summary : alertMsg,
                    uri : taskName,
                    sourceName : currentUserName,
                    sourceUri : "/rest/users/"+ currentUserName,
                    progress : 100,
                    changing : false,
                    status : "ok",
                    details : Localizer.getString('fs.users.add.addSuccess', [currentUserName])
                };
                notifications.add(userAddedSuccess, true);
                resetCancel();
                formStateView.setMessage({summary:alertMsg, status:'ok', changing : false});
                if (!addAgain) {
                    $(CANCEL).trigger('click');
                }
            }

            /**
             * @private
             */
            function onRolesAddedError(errorMessage) {
                var addMsg = Localizer.getString('fs.users.add.roleerror',[$(NAME).val()]);
                var errorMsg = Localizer.formatRestError(addMsg,
                        errorMessage);
                formStateView.setMessage({summary: addMsg, status: 'error',
                    details: errorMsg});
                presenter.deleteUser(currentUserName);
                var userAddedError = {
                    summary : Localizer.getString('fs.users.add.add'),
                    sourceName : currentUserName,
                    uri : taskName,
                    changing : false,
                    status : "error",
                    details : errorMsg
                };
                notifications.add(userAddedError, true);
                isSubmitted = false;
            }

            /**
             * @private
             */
            function onUserAddedSuccess(user) {
                var username, fullname, alertMsg;
                var roles = [];
                username = user.userName;
                fullname = user.fullName;
                var addMsg = Localizer.getString('fs.users.add.add');
                alertMsg = Localizer.getString('fs.users.add.addingMsg', [ username ]);
                var userAddProgress = {
                    summary : addMsg,
                    uri : taskName,
                    sourceName : username,
                    sourceUri : "/rest/users/"+ username,
                    progress : 50,
                    changing : true,
                    status : "info",
                    details : alertMsg
                };
                notifications.add(userAddProgress, false);
                formStateView.setMessage({summary:alertMsg, status:'info', changing:true});
                //if only one role also we show radio button, no harm
                if (allRadio || oneRole){
                   roles.push($(ROLE_SWITCH_RADIO).val());
                }
                else if(isSpecialized)
                {
                    $(ROLES).each(function(index, role) {
                        if ($(role).is(':checked')) {
                            roles.push($(role).val());
                        }
                    });
                }
                else if($(ROLE_SWITCH_RADIO).val() === FULL_VALUE){
                    roles.push(INFRASTRUCTURE_ADMINISTRATOR);
                }else if ($(ROLE_SWITCH_RADIO).val() === READONLY_VALUE){
                    roles.push(READ_ONLY);
                }
                currentUserName =username;
                currentUserFullName = fullname;
                presenter.assignUserToRoles(username, roles);
            }

            /**
             * @private
             */
            function onUserAddedError(errorMessage) {
                var addMsg = Localizer.getString('fs.users.add.error',[$(NAME).val()]);
                var errorMsg = Localizer.formatRestError(addMsg,
                        errorMessage);
                formStateView.setMessage({summary: addMsg, status: 'error',
                    errorMessage: errorMsg});
                var userAddedError = {
                    summary : Localizer.getString('fs.users.add.add'),
                    sourceName : $(NAME).val(),
                    uri : taskName,
                    changing : false,
                    status : "error",
                    details : errorMsg
                };
                notifications.add(userAddedError, true);
                isSubmitted = false;
            }

            /**
             * @public
             */
            function onAddUserClick(addType) {
              if (addType === 'ADDAGAIN'){
                    addAgain = true;
                }else if (addType === 'ADD'){
                    addAgain = false;
                }

                if ($(FORM).valid() && isSubmitted == false) {
                    numberOfClicks = numberOfClicks + 1;
                    isSubmitted = true;
                    var notifMsg = Localizer.getString('fs.users.add.addingMsg',[$(NAME).val()]);
                    formStateView.setMessage(notifMsg, 'info', true);
                    if(numberOfClicks == 1){
                        taskName = session.getUser() + '-addUserTask-' + (new Date()).getTime();
                    }
                    var userAddBegin = {
                        summary : Localizer.getString('fs.users.add.add'),
                        uri : taskName,
                        sourceName : $(NAME).val(),
                        sourceUri : "/rest/users/"+ $(NAME).val(),
                        progress : 0,
                        changing : true,
                        status : "info",
                        details : notifMsg
                    };
                    notifications.add(userAddBegin, false);
                    presenter.addUser($(NAME).val(), $(FULLNAME).val(),
                            $(INITIAL_PASSWD).val(), $(CONFIRM_PASSWD)
                            .val(), $(EMAIL).val(), $(
                                    OFFICE_PHONE).val(),
                                    $(MOBILE_PHONE).val());
                }

                return false;
            }

          //to construct the role section in the page
            function updateRoles(){

                var roles = presenter.getRoles(),
                    rolesList = $(ROLES_LIST);

                $(rolesList).empty();

                if (roles.length == 1){
                  $(ROLE_VALIDATOR).val("set");
                  oneRole = true;
                }
                if (allRadio || oneRole){
                    isSpecialized = true;
                    $(ROLE_SWITCH).empty();
                }
                var counter = 0;//counter as in else case case we need to know the right order

                $.each(roles, function(index, role) {//iterating through all available roles
                    var roleValue =  role.roleName ? role.roleName.replace(/_/, ' ') : 'noname';
                    var roleDisplay = UsersViewUtil.getLocalizedRoleDisplay(roleValue);

                    if(allRadio || oneRole){
                        var radio = $("<input type='radio'>");
                        var id = roleValue.replace(' ','-');//id is the roles as in DB, space replaced by hyphen
                        radio.attr("name", ROLE_SELECT_NAME)
                             .attr("id", id)
                             .attr("value", roleValue);
                        var label = $('<label/>');
                        label.attr("for", id);
                        label.html(roleDisplay);

                        $(ROLE_SWITCH).append(radio);
                        $(ROLE_SWITCH).append(label);
                        if (counter == 0){//roles validation error
                            var valid = $("<input type='hidden'>");
                              valid.attr("name", "role_validator")
                                   .attr("id", "fs-user-role-validator")
                                   .addClass("hp-error");
                              $(ROLE_SWITCH).append(valid);
                         }
                        if (index !== roles.length - 1){
                           $(ROLE_SWITCH).append($('<br/>'));
                        }
                        counter = counter + 1;
                    }else {
                        //because full and read only are in the toggle
                        if (role.roleName !== 'No_Privileges' &&
                            role.roleName !== INFRASTRUCTURE_ADMINISTRATOR &&
                            role.roleName !== READ_ONLY) {

                            var item = (counter === 0) ? firstRoleTemplate.clone() : roleTemplate.clone();
                            var idChkbox = 'fs-user-role-' + counter;
                            var labelChkbox = roleDisplay;
                            item.attr('id', '');
                            item.show();
                            $('input[type="checkbox"]', item).attr('id', idChkbox)
                                .val(role.roleName)
                                .attr('name', 'fsuserrolecheckbox');
                            $('label:eq(1)', item).text(labelChkbox)
                                .attr('for', idChkbox);
                            rolesList.append(item);
                            counter = counter + 1;
                        }
                    }
                });
                if (allRadio || oneRole){
                    $(ROLE_LIST).empty(); //dont show the list of checkboxes
                }else{
                    $(ROLE_SPECIALIZED_CHECKBOXES).on('change',function(){
                        if(checkRoles()){
                            $(ROLE_VALIDATOR).val("set");
                            $(ROLE_VALIDATOR).next().hide();//the auto generated error label
                        }else{
                            $(ROLE_VALIDATOR).val("");
                        }
                    });
                    autoCheckSpecializedRole(true);
                }
                formStateView.reset();
            }

            function onAddUserCancelClick(){
                formStateView.reset();
            }

            function getProductConfigSuccess(productConfigs){
                UsersViewUtil.setProductConfigs(productConfigs);
                UsersViewUtil.checkRequired(FULLNAME_OPTIONAL,EMAIL_OPTIONAL,MOBILEPHONE_OPTIONAL,OFFICEPHONE_OPTIONAL);
                if (UsersViewUtil.getPropertyValue(
                    UsersViewUtil.configs[UsersViewUtil.ROLES_TEMPLATE]) === "exclusive"){
                    allRadio = true;
                }
                updateRoles();
                var passwordArgs = [];
                passwordArgs[0] = function(){return UsersViewUtil.getPropertyValue(
                        UsersViewUtil.configs[UsersViewUtil.PASSWORD_MINLENGTH],
                        UsersViewUtil.MIN_PASSWORD_LENGTH);};
                $(INITIAL_PASSWD_HELP).text(Localizer.getString(
                    "fs.users.validations.passwordHintDynamic", passwordArgs));
            }

            function getProductConfigError(errorInfo){
                UsersViewUtil.setProductConfigs({});
            }

            function registerEvents(){
                presenter.on('rolesChanged', updateRoles);
                presenter.on('userAddedSuccess', onUserAddedSuccess);
                presenter.on('userAddedError', onUserAddedError);
                presenter.on('assignUserToRolesSuccess', onRolesAddedSuccess);
                presenter.on('assignUserToRolesError', onRolesAddedError);
                presenter.on('getProductConfigSuccess', getProductConfigSuccess);
                presenter.on('getProductConfigError', getProductConfigError);
            }

            function removeEvents(){
                presenter.off('rolesChanged', updateRoles);
                presenter.off('userAddedSuccess', onUserAddedSuccess);
                presenter.off('userAddedError', onUserAddedError);
                presenter.off('assignUserToRolesSuccess', onRolesAddedSuccess);
                presenter.off('assignUserToRolesError', onRolesAddedError);
                presenter.off('getProductConfigSuccess', getProductConfigSuccess);
                presenter.off('getProductConfigError', getProductConfigError);
            }

            /**
             * @private
             */
            function checkRoles() {
                $(ROLE_VALIDATOR).val("");
                var result = false;
                if(isSpecialized)
                {
                    $(ROLES).each(function(index, role) {
                        if ($(role).is(':checked')) {
                          $(ROLE_VALIDATOR).val("set");
                            result = true;
                        }
                    });
                }
                else
                {
                  $(ROLE_VALIDATOR).val("set");
                    result = true;
                }

                return result;
            }

            /**
             * @private
             */
           function checkLoginNameExists(loginName){
                presenter.checkLoginNameExists(loginName,{
                    success : function (doesExist){
                        isValidLogin = !doesExist; //if exists, it is not a valid login
                    },
                    error : function (errorInfo){
                        isValidLogin = true; //if any error, just say its a valid login - will be caught at backend anyway
                    }
                } );

              return isValidLogin;
            }

            /**
             * @private
             */
           function initForm() {

                isSubmitted = false;
                var validRoleValidation = Localizer.getString('fs.users.validations.roleValidation');
                var validMatchPasswd = Localizer.getString('fs.users.add.matchpasswd');
                var validUserNameAlphanum = Localizer.getString('fs.users.validations.usernameValidation');
                var validUserNameFirstletter = Localizer.getString('fs.users.validations.usernameValidation2');
                var validPhoneNum = Localizer.getString('fs.users.validations.phonenumValidation');
                var validFullname = Localizer.getString('fs.users.validations.fullnameValidation');
                var validPassword = Localizer.getString('fs.users.validations.passwordValidation');
                var validLoginNameValidation = Localizer.getString('fs.users.validations.validLoginNameValidation');
                $.validator.addMethod("userRoleValidation", function
                        (value, element, param) {
                    return checkRoles();
                }, validRoleValidation);

                $.validator.addMethod("cicAddUserLoginNameValidation", function
                        (value, element, param) {
                    return checkLoginNameExists(value);
                }, validLoginNameValidation);

                validator = $(FORM).validate({
                    rules : {
                        loginname : {
                            required : true,
                            maxlength :  function(){return UsersViewUtil.getPropertyValue(
                                UsersViewUtil.configs[UsersViewUtil.USERNAME_MAXLENGTH],UsersViewUtil.MAX_NAME_LENGTH);} ,
                            minlength :  function(){return UsersViewUtil.getPropertyValue(
                                UsersViewUtil.configs[UsersViewUtil.USERNAME_MINLENGTH],UsersViewUtil.MIN_NAME_LENGTH);},
                            cicUsersAddAlphaNumCheck : NAME,
                            cicUsersAddStartsWithLetterCheck : NAME,
                            cicAddUserLoginNameValidation : NAME
                        },
                        fullname : {
                            required :  function(){return UsersViewUtil.getPropertyValue(
                                UsersViewUtil.configs[UsersViewUtil.FULLNAME_REQUIRED],false);} ,
                            cicUsersAddFullNameCheck : FULLNAME,
                            minlength :  function(){return UsersViewUtil.getPropertyValue(
                                UsersViewUtil.configs[UsersViewUtil.FULLNAME_MINLENGTH], UsersViewUtil.MIN_NAME_LENGTH);},
                            maxlength : function(){return UsersViewUtil.getPropertyValue(
                                UsersViewUtil.configs[UsersViewUtil.FULLNAME_MAXLENGTH],UsersViewUtil.MAX_NAME_LENGTH);}
                        },
                        email : {
                            required :  function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.EMAIL_REQUIRED],false);} ,
                            email : EMAIL,
                            maxlength :  function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.EMAIL_MAXLENGTH],UsersViewUtil.MAX_EMAIL_LENGTH);}
                        },
                        initialpasswd : {
                            required : true,
                            cicUsersAddCheckPasswdString : INITIAL_PASSWD,
                            minlength : function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.PASSWORD_MINLENGTH],UsersViewUtil.MIN_PASSWORD_LENGTH);},
                            maxlength :  function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.PASSWORD_MAXLENGTH],UsersViewUtil.MAX_PASSWORD_LENGTH);}
                        },
                        confirmpasswd : {
                            cicUsersAddMatchPasswd : INITIAL_PASSWD
                        },
                        officephone : {
                            required : function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.OFFICE_REQUIRED],false);} ,
                            cicUsersAddOfficePhoneNumCheck : OFFICE_PHONE,
                            maxlength :  function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.OFFICE_MAXLENGTH],UsersViewUtil.MAX_NUMBER_LENGTH);} ,
                            minlength :  function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.OFFICE_MINLENGTH],UsersViewUtil.MIN_NUMBER_LENGTH);}
                        },
                        mobilephone : {
                            required : function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.MOBILE_REQUIRED],false);} ,
                            cicUsersAddMobilePhoneNumCheck : MOBILE_PHONE,
                            maxlength :  function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.MOBILE_MAXLENGTH],UsersViewUtil.MAX_NUMBER_LENGTH);} ,
                            minlength :  function(){return UsersViewUtil.getPropertyValue(
                                    UsersViewUtil.configs[UsersViewUtil.MOBILE_MINLENGTH],UsersViewUtil.MIN_NUMBER_LENGTH);}
                        },
                        role_validator : {required : true}
                    },
                    messages : {
                      role_validator : {//only when all are radio buttons
                            required : validRoleValidation
                        }
                    },
                    errorPlacement : function(error, element){//only when all are radio buttons
                        if ((allRadio || oneRole) && element.attr('type') === 'radio') {
                            //insert the error message after first radio button's label
                            var ff='input[type="radio"][id="' + element.attr('id') + '"]:first';
                            error.insertAfter(element.siblings('label[for="' + $(ff).attr("id") +'" ]'));
                        }else{
                            error.insertAfter(element);
                        }
                    }
                });

            //alphanumeric and - . _
            jQuery.validator.addMethod("cicUsersAddAlphaNumCheck", function(value,
                element, param) {
              var regex =  UsersViewUtil.getPropertyValue(UsersViewUtil.configs[UsersViewUtil.USERNAME_VALID],"^[0-9-_a-zA-Z]+$");
              return (new RegExp(regex).test(value));
                },
                function (){ return UsersViewUtil.getPropertyValue(
                    UsersViewUtil.configs[UsersViewUtil.USERNAME_ERRORMSG], validUserNameAlphanum);
                }
            );

            //No special characters allowed <>;,"'&\/|+.:=
            jQuery.validator.addMethod("cicUsersAddCheckPasswdString", function(
                value, element, param) {
                var regex =  UsersViewUtil.getPropertyValue(UsersViewUtil.configs[UsersViewUtil.PASSWORD_VALID],"^[^<>;,\"'&\\\\/|+:= ]+$") ;
                return (new RegExp(regex).test(value));
                },
                function (){ return UsersViewUtil.getPropertyValue(
                        UsersViewUtil.configs[UsersViewUtil.PASSWORD_ERRORMSG], validPassword);
                }
            );

            //should start with a letter only
            jQuery.validator.addMethod("cicUsersAddStartsWithLetterCheck", function(
                value, element, param) {
                return (/^[a-zA-Z]+.*$/.test(value));
                },
            validUserNameFirstletter);

            // check for  special characters
            jQuery.validator.addMethod("cicUsersAddMobilePhoneNumCheck", function(value,
                element, param) {
                var regex =  UsersViewUtil.getPropertyValue(UsersViewUtil.configs[UsersViewUtil.MOBILE_VALID],"^[^\"'&=<>]+$") ;
                var isValidPh = new RegExp(regex).test(value);
                return (value.length == 0 || isValidPh);
                },
                function (){ return UsersViewUtil.getPropertyValue(
                        UsersViewUtil.configs[UsersViewUtil.MOBILE_ERRORMSG], validPhoneNum);
                }
            );

            // check for  special characters
            jQuery.validator.addMethod("cicUsersAddOfficePhoneNumCheck", function(value,
                element, param) {
                var regex =  UsersViewUtil.getPropertyValue(UsersViewUtil.configs[UsersViewUtil.OFFICE_VALID],"^[^\"'&=<>]+$") ;
                var isValidPh = new RegExp(regex).test(value);
                return (value.length == 0 || isValidPh);
                },
                function (){ return UsersViewUtil.getPropertyValue(
                        UsersViewUtil.configs[UsersViewUtil.OFFICE_ERRORMSG], validPhoneNum);
                }
            );

            // check for fullname contain letters ' . - and space
            jQuery.validator.addMethod("cicUsersAddFullNameCheck",function(value,
                element, param) {
                var regex =  UsersViewUtil.getPropertyValue(UsersViewUtil.configs[UsersViewUtil.FULLNAME_VALID],"^[a-zA-Z0-9 ._'\-]+$");
                var isValidFullname = new RegExp(regex).test(value);
                return (isValidFullname || value.length == 0);
                },
                function (){ return UsersViewUtil.getPropertyValue(UsersViewUtil.configs[UsersViewUtil.FULLNAME_ERRORMSG],validFullname);});

            //match password
            jQuery.validator.addMethod("cicUsersAddMatchPasswd", function(
                value, element, param) {
                // bind to the blur event of the target in order to
                // revalidate whenever the target field is updated
                var target = $(param).unbind(".validate-equalTo")
                  .bind("blur.validate-equalTo", function() {
                    $(element).valid();
                  });
                return value == target.val();
                },
            validMatchPasswd);

        }

        function onChangeOfRole(){
            displayRoles();
            if(checkRoles()){
                $(ROLE_VALIDATOR).next().hide();//the auto generated error label
            }
        }



          /**
             * @public
             */
            this.init = function() {
                // Remove the template for a role from the DOM (used for cloning later)
                firstRoleTemplate = $('#fs-user-first-role-template').detach();
                roleTemplate = $('#fs-user-role-template').detach();

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


                $(ADDAGAIN).on('click', function(ev) {
                    onAddUserClick('ADDAGAIN');
                    ev.preventDefault();
                });
                $(ADD).on('click', function(ev) {
                    onAddUserClick('ADD', ev);
                    ev.preventDefault();
                });

                $(ROLE_SWITCH).buttonset();
                onSpecializedUserClick();

                $(ROLE_SWITCH).change(function(e){
                  onChangeOfRole();
                });

                $(CANCEL).on('click', function(ev){
                  onAddUserCancelClick();

                });

                registerEvents();
                presenter.getProductConfig();
            };

            /**
             * @public
             */
            this.resume = function() {
                resetCancel();
                onSpecializedUserClick();
                registerEvents();
                presenter.getProductConfig();

            };

            this.pause = function () {
                formStateView.reset();
                removeEvents();
            };
        }


        return new UsersAddView();
    }());

    return UsersAddView;
});
