var EmployeesView = Backbone.View.extend({
    fullCollection: {},
    userGroups: {},
    tills: {},
    formModal: null,
    hasAccess: false,
    payTypes: {},
    userGroups: {},
    posUsers: {},
    employeePosUserArray: [],
    posUserArray: [],
    employeeArray: [],
    masterArray: [],
    totalNumericValues: 0,    
    savedEmployee: {},
    savedEmployeeAndPosUser: false,
    payTypeSelectInstance: {},
    isCreateMode: false,
    editingNowEmployee: {},

    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .edit-employee-trigger': 'editEmployee',
        'click #add-employee-button': 'addEmployee',
        'click .save-button': 'saveEmployee',
        'click .delete-button': 'deletionModal',
        'click #delete-employee-confirm': 'removeEmployee',
        'keyup #password' : 'passwordStrengthCheck',
        'click .search-employees-button' : 'searchEmployee',
        'keyup #employeeSearch' : 'searchEmployee',
    },

    breadcrumb: {},

    styles: [
        'ap-blue',
        'ap-teal-light',
        'ap-light-purple'
    ],

    employeeStyleMapping: {},
    userGroupStyleMapping: {},

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.employeesFormTemplate = options.employeesFormTemplate;
        this.breadcrumb = options.breadcrumb;
        this.collection = options.collection;
        this.listenTo(this.collection, 'reset', this.render);
        this.listenTo(this.collection, 'remove', this.render);
        this.listenTo(this.collection, 'add', this.render);
        this.getPayTypes();
    },

    render: function () {
        this.$el.html(this.template({
            employees: this.collection.toJSON(),
        }));
        App.breadCrumbToolTip = "Create, manage, and edit your employees"; 

        App.setBreadcrumbs(this.breadcrumb);
        $(document).on('keydown', 'input, select', function(e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
              ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select,button,select').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    form.submit();
                }
                return false;
            }
        });
        //$('select').formSelect();
        $('.tooltipped').tooltip();
        this.formModal = this.$el.find('#employees-form-modal').modal();
        this.masterArray = []
        return this;
    },

    editEmployee: function (e) {
        if (this.hasAccess) {
            this.isCreateMode = false;
            this.formModal = this.$el.find('#employees-form-modal').modal();
            var element = $(e.currentTarget);
            var userId = $(element).attr('data-id');
            var user = this.collection.get(userId);
            if (user == undefined) {
                user = this.savedEmployee;
            }
            this.editingNowEmployee = user;
            this.employeesFormView = new EmployeesFormView({
                template: this.employeesFormTemplate,
                model: user,
                payTypes: this.payTypes,
                tills: this.tills,
                userGroups: this.userGroups,
                isCreateMode: this.isCreateMode
            });
            this.$el.find('#employees-form-modal').html(this.employeesFormView.render().el);
            this.payTypeSelectInstance = M.FormSelect.init(this.$el.find('select'));
            this.formModal.modal('open');
        }
        else {
            M.toast({ html: '{Literal}You do not have access to edit employees{/Literal}' });
        }
    },

    addEmployee: function () {
        this.isCreateMode = true;
        var employee = new Employee();
        this.employeesFormView = new EmployeesFormView({
            template: this.employeesFormTemplate,
            model: employee,
            payTypes: this.payTypes,
            tills: this.tills,
            userGroups: this.userGroups,
            isCreateMode: this.isCreateMode
        });
        this.formModal = this.$el.find('#employees-form-modal').modal();
        this.$el.find('#employees-form-modal').html(this.employeesFormView.render().el);
        this.payTypeSelectInstance = M.FormSelect.init(this.$el.find('select'));
        this.$el.find("select[required]").css({
            display: "block", 
            position: 'absolute',
            visibility: 'hidden'
        });  
        this.formModal.modal('open');
    },

    highlightCard: function (e) {
        this.$el.find('.edit').hide();
        this.$el.find('.card-panel-entity').removeClass('active');
        var element = $(e.currentTarget);
        var selected = $(element).attr('data-selected') === '1';
        
        if (selected) {
            $(element).removeAttr('data-selected');
            $(element).removeClass('active');
            $(element).find('.edit').hide();
        } else {
            $(element).removeAttr('data-selected');
            $(element).attr('data-selected', '1');
            $(element).find('.edit').show();
            $(element).addClass('active');
        }
    },

    getPayTypes: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-pay-types',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                for ( var key in data.results ) {
                    // if (data.results[key] != "") {
                        that.payTypes[key] = data.results[key];
                    // }
                }
                that.getUserGroups();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem fetching item types from the server{/Literal}' });
                }
            }
        });
    },

    getUserGroups: function () {
        var parentView = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-user-groups',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                parentView.userGroups = transformObjectArrayToKeyValueObject(data.results, 'id', 'name');
                parentView.generateUserGroupStyleMapping(data.results);
                parentView.getTills();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({
                        html: '{Literal}There was a problem fetching data from the server{/Literal}'
                    });
                }
            }
        });
    },

    generateUserGroupStyleMapping: function (data) {
        var userGroups = [];
        var totalStyles = this.styles.length;
        var currentStyle = 0;
        for (var i = 0; i < data.length; i++) {
            if (userGroups.indexOf(data[i].id) < 0) {
                userGroups.push(data[i].id);
                this.userGroupStyleMapping[data[i].id] = this.styles[currentStyle];
                if (currentStyle < totalStyles - 1) {
                    currentStyle++;
                } else {
                    currentStyle = 0;
                }
            }
        }
    },

    getTills: function (parentView) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-tills-list',
            data: {
                token: sessionToken,
                includeInactive: false
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.tills = data.results;
                var onlineOrdersTillNames = data.onlineOrdersTillNames;
                that.tills.forEach( till => {
                    till.isOnlineOrdering = onlineOrdersTillNames.includes(till.name);
                })
                that.getPOSUsers();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({
                        html: '{Literal}There was a problem fetching data from the server{/Literal}'
                    });
                }
            }
        });
    },

    getPOSUsers: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-pos-users',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                for (var i = 0; i < data.results.length; i++) {
                    var autoTillId = data.results[i].till;                     
                    if (typeof that.tills !== 'undefined') {
                        var tills = that.tills.filter(
                            function (element) {
                                return element.id === tills;
                            }
                        );
                        if (tills.length > 0) {
                            data.results[i].tillName = tills[0].name;
                        } else {
                            data.results[i].tillName = 'N/A';    
                        }
                    } else {
                        data.results[i].tillName = 'N/A';
                    }
                }
                that.posUsers = data.results;
                that.posUsers.sort(function (a, b) {
                    return a.id.toLowerCase() < b.id.toLowerCase() ? -1 : (a.id.toLowerCase() > b.id.toLowerCase() ? 1 : 0);
                });
                that.getEmployees();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({
                        html: '{Literal}There was a problem fetching POS Users from the server{/Literal}'
                    });
                }
            }
        });
    },

    getCookie: function() {
        var nameEQ = "sessionCookie" + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
    },

    getEmployees: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-employees',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                // that.renderEmployees(data.results);
                that.employeeList = data.results;
                that.employeeList.sort(function (a, b) {
                    return a.id.toLowerCase() < b.id.toLowerCase() ? -1 : (a.id.toLowerCase() > b.id.toLowerCase() ? 1 : 0);
                });
                that.renderEmployees();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.renderEmployees();
                }
            }
        });
    },

    searchEmployee: function(e) {
        if(e.currentTarget.id == 'employeeSearch' && e.keyCode != 13)
            return;
        var that = this;
        var text = document.getElementById('employeeSearch').value.toLowerCase();
        var showInactiveOnly = document.querySelector('#showInactiveOnly input').checked;
        var models = this.fullCollection.filter(function(model){
           return (model.attributes.name.toLowerCase().includes(text) || model.attributes.posUserId.toLowerCase().includes(text))
                && ( (showInactiveOnly && model.attributes.isActive === false) || !showInactiveOnly) 
        });
        // this.fullCollection = collection;
        this.collection.reset(models);
    },

    renderEmployees: function () {
        var that = this;

        for (var i = 0; i < that.posUsers.length; i++) {
            var posUserEmployeeModel = {
                // idAttribute: data[i].name,
                accountingId: "",
                isPosUser: that.posUsers[i].userType == "POS",
                isEmployee: false,
                currentHours: 0,
                employeeClass: "",
                id: Math.floor(Math.random() * 1000) + 1  ,
                isClockedIn: false,
                manager: false,
                name: that.posUsers[i].userName,
                overtimeOver8: true,
                payLevel1: "",
                payLevel2: "",
                payLevel3: "",
                payLevel4: "",
                payLevel5: "",
                payLevel6: "",
                payLevel7: "",
                payLevel8: "",
                payLevel9: "",
                payLevel10: "",
                payLevel11: "",
                payLevel12: "",
                payLevel13: "",
                payLevel14: "",
                payLevel15: "",
                payLevel16: "",
                payLevel17: "",
                payLevel18: "",
                payLevel19: "",
                payLevel20: "",
                // payLevelNumber: 0,
                group: that.posUsers[i].group, 
                posUserId: that.posUsers[i].id,
                isDriver: that.posUsers[i].isDriver,
                isServer: that.posUsers[i].isServer,
                logOutTime: that.posUsers[i].logOutTime,
                openOrderCount: that.posUsers[i].openOrderCount,
                passcode: that.posUsers[i].passcode,
                serverId: that.posUsers[i].serverId,
                till: that.posUsers[i].till,
                tillName: that.posUsers[i].tillName,
                userType: that.posUsers[i].userType,
                isActive: true
            }

            if (that.posUsers[i].isServer && that.posUsers[i].passcode == "" || that.posUsers[i].isDriver && that.posUsers[i].passcode == "") {
                posUserEmployeeModel.isPosUser = false;
            }

            that.masterArray.push(posUserEmployeeModel);
        }

        for (var i = 0; i < that.employeeList.length; i++) {

            var foundPosUser = that.masterArray.find(u => u.passcode == that.employeeList[i].id);

            if (!foundPosUser) {
                var minutes = parseInt((that.employeeList[i].currentHours/(1000*60))%60)
                , hours = parseInt((that.employeeList[i].currentHours/(1000*60*60))%24);
                hours = (hours < 10) ? "0" + hours : hours;
                minutes = (minutes < 10) ? "0" + minutes : minutes;
                that.employeeList[i].currentHours = hours + ":" + minutes;
                
                var posUserEmployeeModel = {
                    idAttribute: that.employeeList[i].name,
                    isPosUser: false,
                    isEmployee: true,
                    accountingId: that.employeeList[i].accountingId,
                    currentHours: that.employeeList[i].currentHours,
                    employeeClass: that.employeeList[i].employeeClass,
                    isClockedIn: that.employeeList[i].isClockedIn,
                    id: that.employeeList[i].id,
                    manager: that.employeeList[i].manager,
                    name: that.employeeList[i].name,
                    overtimeOver8: that.employeeList[i].overtimeOver8,
                    payLevel1: that.employeeList[i].payLevel1,
                    payLevel2: that.employeeList[i].payLevel2,
                    payLevel3: that.employeeList[i].payLevel3,
                    payLevel4: that.employeeList[i].payLevel4,
                    payLevel5: that.employeeList[i].payLevel5,
                    payLevel6: that.employeeList[i].payLevel6,
                    payLevel7: that.employeeList[i].payLevel7,
                    payLevel8: that.employeeList[i].payLevel8,
                    payLevel9: that.employeeList[i].payLevel9,
                    payLevel10: that.employeeList[i].payLevel10,
                    payLevel11: that.employeeList[i].payLevel11,
                    payLevel12: that.employeeList[i].payLevel12,
                    payLevel13: that.employeeList[i].payLevel13,
                    payLevel14: that.employeeList[i].payLevel14,
                    payLevel15: that.employeeList[i].payLevel15,
                    payLevel16: that.employeeList[i].payLevel16,
                    payLevel17: that.employeeList[i].payLevel17,
                    payLevel18: that.employeeList[i].payLevel18,
                    payLevel19: that.employeeList[i].payLevel19,
                    payLevel20: that.employeeList[i].payLevel20,
                    // payLevelNumber: that.employeeList[i].payLevelNumber,
                    group: "", 
                    posUserId: "",
                    isDriver: false,
                    isServer: false,
                    logOutTime: 0,
                    openOrderCount: '',
                    passcode: '',
                    serverId: '',
                    till: '',
                    tillName: '',
                    userType: 'POS',
                    isActive: that.employeeList[i].isActive
                }

                that.masterArray.push(posUserEmployeeModel);

            } else {
                foundPosUser.idAttribute = that.employeeList[i].name;
                foundPosUser.isEmployee = true;
                foundPosUser.accountingId = that.employeeList[i].accountingId;
                foundPosUser.currentHours = that.employeeList[i].currentHours;
                foundPosUser.employeeClass = that.employeeList[i].employeeClass;
                foundPosUser.isClockedIn = that.employeeList[i].isClockedIn;
                foundPosUser.id = that.employeeList[i].id;
                foundPosUser.manager = that.employeeList[i].manager;
                foundPosUser.name = that.employeeList[i].name;
                foundPosUser.overtimeOver8 = that.employeeList[i].overtimeOver8;
                foundPosUser.payLevel1 = that.employeeList[i].payLevel1;
                foundPosUser.payLevel2 = that.employeeList[i].payLevel2;
                foundPosUser.payLevel3 = that.employeeList[i].payLevel3;
                foundPosUser.payLevel4 = that.employeeList[i].payLevel4;
                foundPosUser.payLevel5 = that.employeeList[i].payLevel5;
                foundPosUser.payLevel6 = that.employeeList[i].payLevel6;
                foundPosUser.payLevel7 = that.employeeList[i].payLevel7;
                foundPosUser.payLevel8 = that.employeeList[i].payLevel8;
                foundPosUser.payLevel9 = that.employeeList[i].payLevel9;
                foundPosUser.payLevel10 = that.employeeList[i].payLevel10;
                foundPosUser.payLevel11 = that.employeeList[i].payLevel11;
                foundPosUser.payLevel12 = that.employeeList[i].payLevel12;
                foundPosUser.payLevel13 = that.employeeList[i].payLevel13;
                foundPosUser.payLevel14 = that.employeeList[i].payLevel14;
                foundPosUser.payLevel15 = that.employeeList[i].payLevel15;
                foundPosUser.payLevel16 = that.employeeList[i].payLevel16;
                foundPosUser.payLevel17 = that.employeeList[i].payLevel17;
                foundPosUser.payLevel18 = that.employeeList[i].payLevel18;
                foundPosUser.payLevel19 = that.employeeList[i].payLevel19;
                foundPosUser.payLevel20 = that.employeeList[i].payLevel20;
                foundPosUser.isActive = that.employeeList[i].isActive;
                
            }
        }

        that.generateEmployeeStyleMapping(that.masterArray)

        var collection = new EmployeeCollection();
        for (var i = 0; i < that.masterArray.length; i++) {
            var currentEmployee = that.masterArray[i];
            collection.add(new Employee(currentEmployee));
        }

        that.fullCollection = collection;
        var activeModels = collection.filter(function(model){
            return model.attributes.isActive
         });
         
        that.collection.reset(activeModels);
        this.checkAccess();
    
    },

    checkAccess: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/check-access',
            data: {
                accessName: (App.IDS_USERS),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.hasAccess = true;
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.responseJSON.hasAccess == false) {
                    that.hasAccess = false;
                }
            }
        });
    },


    generateEmployeeStyleMapping: function (data) {
        var userGroups = [];
        var totalStyles = this.styles.length;
        var currentStyle = 0;
        for (var i = 0; i < data.length; i++) {
            if (userGroups.indexOf(data[i].id) < 0) {
                userGroups.push(data[i].id);
                this.employeeStyleMapping[data[i].id] = this.styles[currentStyle];
                if (currentStyle < totalStyles - 1) {
                    currentStyle++;
                } else {
                    currentStyle = 0;
                }
            }
        }
    },

    deletionModal: function (e) {
        var that = this;
        var element = $(e.currentTarget);
        var posUserId = $(element).attr('data-id');
        $("#data-employee-id").val(posUserId);
        $('#delete-employee-modal').modal().modal('open');
    },

    removeEmployee: async function() {
        var mgmtUserSwitch = this.$el.find('#management:checked').length > 0;
        var posUserSwitch = this.$el.find('#posUserSwitch:checked').length > 0;
        var accuShiftSwitch = this.$el.find('#accuShiftSwitch:checked').length > 0;
        var serverSwitch = this.$el.find('#server:checked').length > 0;
        var driverSwitch = this.$el.find('#driver:checked').length > 0;
        if (posUserSwitch && accuShiftSwitch) {
            this.removeEmployeeAndPosUser = true;
        }

        if (posUserSwitch || serverSwitch || driverSwitch || mgmtUserSwitch) {
            await this.deletePOSUser();
        }
        if (accuShiftSwitch) {
            await this.deleteEmployee();
        }
        this.formModal.modal('close');
        this.removeEmployeeAndPosUser = false;
        this.getPOSUsers();
    },

    deletePOSUser: async function() {
        var employeeId = this.employeesFormView.model.attributes.id;
        var posUserId = this.employeesFormView.model.attributes.posUserId;
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/delete-pos-user',
            type: 'POST',
            data: {
                // employeeId: posUserId,
                posUserId: posUserId,
                token: sessionToken,
                accessName: (App.IDS_USERS)
            },
            method: 'POST',
            success: function (data) {
                var success = false;
                if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                    success = data.results.success;
                }
                if (success !== null) {
                    that.collection.remove(posUserId);
                }

                M.toast({ html: '{Literal}Employee deleted successfully{/Literal}' });
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    if(e.responseJSON.message)
                        M.toast({ html: e.responseJSON.message });
                    else
                        M.toast({ html: '{Literal}There was a problem deleting this Employee please try again later{/Literal}.' });
                }
            }
        });
        this.render();
    },

    deleteEmployee: async function(e) {
        var employeeId = this.employeesFormView.model.attributes.id;
        var posUserId = this.employeesFormView.model.attributes.posUserId;
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/delete-employee',
            type: 'POST',
            data: {
                employeeId: employeeId,
                // posUserId: posUserId,
                token: sessionToken,
                accessName: (App.IDS_USERS)
            },
            method: 'POST',
            success: function (data) {
                var success = false;
                if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                    success = data.results.success;
                }
                if (success !== null) {
                    that.collection.remove(posUserId);
                }

                M.toast({ html: '{Literal}Employee deleted successfully{/Literal}' });
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem deleting this Employee please try again later{/Literal}.' });
                }
            }
        });
    },

    passwordStrengthCheck: function () {
        var mgmtUserSwitch = this.$el.find('#management:checked').length > 0;
        if(!mgmtUserSwitch)
            return true;
            
        var iChars = "`~!@#$%^&*()_+=[]{}:,<>./*\\\'\"";
        var passwordEl = document.getElementById("password");
        var password = passwordEl.value;
        var helperTextEl = document.querySelector("#password ~ .helper-text");
        var helperText = '';

        if(password.length < 8)
            helperText = '{Literal}Password must be at least 8 characters long{/Literal}';
        else if(!password.match(/^(?=.*[A-Z])/))
            helperText = '{Literal}Password must include one uppercase letter{/Literal}';
        else if(!password.match(/^(?=.*[a-z])/))
            helperText = '{Literal}Password must include one lowercase letter{/Literal}';
        else if(!password.match(/^(?=.*\d)/))
            helperText = '{Literal}Password must include one number{/Literal}';
        else if(!password.match(/[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/))
            helperText = '{Literal}Password must include one special character{/Literal}';

        helperTextEl.innerText = helperText;
        passwordEl.classList = '';
        var valid = helperText == '';
        if(valid)
            passwordEl.classList.add('valid');
        else
            passwordEl.classList.add('invalid');

        return valid;
    },

    validateForm: function () {
        var valid = true;
        var validateName = this.$el.find("#name").val();
        var validatePosUser = this.$el.find("#posUserId").val();
        var posUserSwitch = this.$el.find('#posUserSwitch:checked').length > 0;
        var accuShiftSwitch = this.$el.find('#accuShiftSwitch:checked').length > 0;
        var driver = this.$el.find('#driver:checked').length > 0;
        var server = this.$el.find('#server:checked').length > 0;
        var mgmtUserSwitch = this.$el.find('#management:checked').length > 0;

        var isPosUser = posUserSwitch || driver || server || mgmtUserSwitch;
        var isNameChanged = false;
        var isPosUserChanged  = false;
        if(!this.isCreateMode) {
            isNameChanged = this.editingNowEmployee?.attributes?.name != validateName;
            isPosUserChanged = this.editingNowEmployee?.attributes?.posUserId != validatePosUser;
        }
        if (validateName.trim().length < 1 ) {
            this.$el.find("#name").addClass("invalid");
            valid = false;
        }
        else {
            var iChars = "`~!@#$%^&*()_+=[]{}:;,<>/?*\\\'\"";
            for (var i = 0; i < validateName.length; i++) {
                if (iChars.indexOf(validateName.charAt(i)) != -1) {
                    this.$el.find("#name").addClass("invalid");
                    valid = false;
                    break;
                }
            }
        }
        
        if(isPosUser) {
            if (validatePosUser.trim().length < 1 ) {
                this.$el.find("#posUserId").addClass("invalid");
                valid = false;
            }
            else {
                var iChars = "`~!@#$%^&*()_+=[]{}:;,<>/?*\\\'\"";
                for (var i = 0; i < validatePosUser.length; i++) {
                    if (iChars.indexOf(validatePosUser.charAt(i)) != -1) {
                        this.$el.find("#posUserId").addClass("invalid");
                        valid = false;
                        break;
                    }
                }

                var foundEmployees = this.collection.models.filter( model => model.attributes.posUserId == validatePosUser);
    
                if(foundEmployees.length > 0 && isPosUserChanged || foundEmployees.length > 0 && this.isCreateMode)
                {
                    valid = false;
                    M.toast({ html: '{Literal}Two users cannot have the same user name{/Literal}' });
                    this.$el.find("#posUserId").addClass("invalid");
                }
            }  
        }

        if(!(posUserSwitch || accuShiftSwitch || driver || server || mgmtUserSwitch)) {
            M.toast({ html: '{Literal}User type not selected{/Literal}' });
            valid = false;
        }

        if (isPosUser) {
            var userGroup = this.$el.find('#user-group-form-dropdown').val();
            if (userGroup == '') {
                valid = false;
                M.toast({ html: '{Literal}User group not selected{/Literal}' });
            }
        }

        var validatePassword = this.$el.find("#password").val();

        if (!mgmtUserSwitch && validatePassword.length < 4 && validatePassword != '') {
                M.toast({ html: '{Literal}Passwords must contain at least 4 numeric values{/Literal}' });
                valid = false;
            
        }
        
        if (!mgmtUserSwitch && validatePassword.length >= 4 ) {
            const validPassword = validatePassword.match(/^\d+$/) != null;
            if(!validPassword) {   
                M.toast({ html: '{Literal}Password must be numeric only{/Literal}' });
                valid = false;
            }
        }

        if(validatePassword === "" && this.isCreateMode) {
            valid = false;
            this.$el.find("#password").addClass("invalid");
        }


        var iChars = "`~!@#$%^&*()_+=[]{}:,<>./*\\\'\"";

        var passwordKeys = [];

        if (validatePassword != '') {
            var foundEmployees = this.collection.models.filter( model => model.attributes.passcode == validatePassword);
            if(foundEmployees.length > 0 )
            {
                valid = false;
                M.toast({ html: '{Literal}Two users cannot have the same password{/Literal}' });
                // this.$el.find("#password").addClass("invalid");
            }
        }

        // if (mgmtUserSwitch && validatePassword != '') {
        //     var foundEmployees = this.collection.models.filter( model => model.attributes.passcode == validatePassword);
        //     if(foundEmployees.length > 0 && isPosUserChanged || foundEmployees.length > 0 && this.isCreateMode )
        //     {
        //         valid = false;
        //         M.toast({ html: '{Literal}Two users cannot have the same password{/Literal}' });
        //         this.$el.find("#password").addClass("invalid");
        //     }
        // }

        if(mgmtUserSwitch && validateName != ''){
            var foundEmployees = this.collection.models.filter( model => model.attributes.name == validateName);
            if(foundEmployees.length > 0 && isNameChanged || foundEmployees.length > 0 && this.isCreateMode )
            {
                valid = false;
                M.toast({ html: '{Literal}Two users cannot have the same name{/Literal}' });
                this.$el.find("#name").addClass("invalid");
            }
        }

        if(mgmtUserSwitch && validatePassword != '' && !this.passwordStrengthCheck()) {
            M.toast({ html: '{Literal}Invalid management password{/Literal}' });
            valid = false;
        }

        return valid;
    },

    getFormValues: function () {
        var name = this.$el.find('#name').val();
        var posUserId = this.$el.find('#posUserId').val();

        var server = this.$el.find('#server:checked').length > 0;
        var driver = this.$el.find('#driver:checked').length > 0;
        var mgmtUser = this.$el.find('#management:checked').length > 0;
        var userType = mgmtUser ? 'MGMT' : 'POS';
        var passcode = this.$el.find('#password').val();

        if (passcode.startsWith(";") && passcode.endsWith("?")) {
            passcode = passcode.substring(1, passcode.length -1);
        }

        if (passcode == "") {
            if (this.employeesFormView.model.attributes.passcode != "") {
                passcode = this.employeesFormView.model.attributes.passcode;
            }
            else {
                passcode = this.employeesFormView.model.attributes.id;
            }
            this.totalNumericValues = 4;
        }
        else if (passcode != "") {
            this.totalNumericValues = 0;  
            if (!server && !driver) {
                for(var i = 0; i < passcode.length; i++) {
                    if (!isNaN(passcode.indexOf(i))) {
                        this.totalNumericValues++;
                    }
                }
            }
            else {
                this.totalNumericValues = 4;
            }   
        }
       
        var till = this.$el.find('#auto-till-form-dropdown').val();

        var logOutTime = this.$el.find('#idle-timeout-form-dropdown').val();

        var payLevelNumber = this.$el.find("pay-level-dropdown").val();

        var userGroup = this.$el.find('#user-group-form-dropdown option:selected').val();

        if (App.serverInfo.isFoodService) {
            var server = this.$el.find('#server:checked').length > 0;
            var driver = this.$el.find('#driver:checked').length > 0;
            var salesRep = this.$el.find('#server:checked').length > 0;
        }
        else {
            var server = this.$el.find('#server:checked').length > 0;
            var driver = false;
            var salesRep = this.$el.find('#server:checked').length > 0;
        }

        var selectedPayLevels = this.payTypeSelectInstance[3].getSelectedValues();
        var paylevels = {};
        for (i = 1; i <= 20; i++) {
            var isSelected = selectedPayLevels.includes(i.toString());
            paylevels["payLevel" + i] = isSelected ? i : '';
        }
       
        var manager = this.$el.find('#manager:checked').length > 0;
        var overtimeOver8 = this.$el.find('#overtimeOver8:checked').length > 0;

        var newPassword = "";
        if (this.$el.find('#password').val() != "") {
            newPassword = this.$el.find('#password').val();
        }

        var isActive = document.getElementById('isActive').checked;

        var accuShiftSwitch = this.$el.find('#accuShiftSwitch:checked').length > 0;

       
            var updatedModel = {
                accountingId: this.employeesFormView.model.attributes.accountingId,
                currentHours: this.employeesFormView.model.attributes.currentHours,
                employeeClass: this.employeesFormView.model.attributes.employeeClass,
                isClockedIn: this.employeesFormView.model.attributes.isClockedIn,
                payLevelNumber: payLevelNumber,
                id: this.employeesFormView.model.attributes.id,
                oldId: this.employeesFormView.model.attributes.id,
                manager: manager,
                name: name,
                userName: name,
                overtimeOver8: overtimeOver8,
                payLevel1:paylevels.payLevel1,
                payLevel2: paylevels.payLevel2,
                payLevel3: paylevels.payLevel3,
                payLevel4: paylevels.payLevel4,
                payLevel5: paylevels.payLevel5,
                payLevel6: paylevels.payLevel6,
                payLevel7: paylevels.payLevel7,
                payLevel8: paylevels.payLevel8,
                payLevel9: paylevels.payLevel9,
                payLevel10: paylevels.payLevel10,
                payLevel11: paylevels.payLevel11,
                payLevel12: paylevels.payLevel12,
                payLevel13: paylevels.payLevel13,
                payLevel14: paylevels.payLevel14,
                payLevel15: paylevels.payLevel15,
                payLevel16: paylevels.payLevel16,
                payLevel17: paylevels.payLevel17,
                payLevel18: paylevels.payLevel18,
                payLevel19: paylevels.payLevel19,
                payLevel20: paylevels.payLevel20,
                group: userGroup, 
                accuShiftSwitch: accuShiftSwitch,
                posUserId: posUserId,
                isDriver: driver,
                isServer: server,
                userType: userType,
                logOutTime: logOutTime,
                openOrderCount: this.employeesFormView.model.attributes.openOrderCount,
                passcode: passcode,
                serverId: this.employeesFormView.model.attributes.serverId,
                till: till,
                tillName: this.employeesFormView.model.attributes.tillName,
                newPassword: newPassword,
                isActive: isActive
            }
        
            if (!App.serverInfo.isFoodService) {
                updatedModel.isDriver = false;
                updatedModel.isDriver = salesRep;
            }

        this.employeesFormView.model.set(updatedModel);

        this.collection.set(this.employeesFormView.model);
        return updatedModel;
    },

    saveEmployee: async function (){
        var validation = this.validateForm();
        var posUserSwitch = this.$el.find('#posUserSwitch:checked').length > 0;
        var accuShiftSwitch = this.$el.find('#accuShiftSwitch:checked').length > 0;
        var serverSwitch = this.$el.find('#server:checked').length > 0;
        var driverSwitch = this.$el.find('#driver:checked').length > 0;
        var managementSwitch = this.$el.find('#management:checked').length > 0;
        if(validation) {
            this.getFormValues();
            if (posUserSwitch && accuShiftSwitch) {
                this.savedEmployeeAndPosUser = true;
            }

            if (posUserSwitch || serverSwitch || driverSwitch || managementSwitch) {
                await this.savePOSUser();
            }
            if (accuShiftSwitch) {
                await this.sendEmployee();
            }
            this.formModal.modal('close');
            this.savedEmployeeAndPosUser = false;
            // this.getPOSUsers();
            location.reload();

        }
    },

    savePOSUser: async function () {
        var that = this;
        var originalPosUserId = that.employeesFormView.model._previousAttributes.posUserId;
        
        if (this.totalNumericValues < 4) {
            M.toast({ html: '{Literal}Passwords must contain 4 numeric values{/Literal}' });
        }
        else {
            var sessionToken = this.getCookie();
            
            return $.ajax({
                url: '/data/save-pos-user',
                data: {
                    user: JSON.stringify(that.employeesFormView.model.toJSON()),
                    token: sessionToken,
                    accessName: (App.IDS_USERS),
                    originalPosUserId: originalPosUserId === undefined ? "" : originalPosUserId
                },
                dataType: 'json',
                type: 'POST',

                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
                    M.toast({ html: '{Literal}Employee updated successfully!{/Literal}' });
                },

                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}There was a problem updating this Employee please try again later{/Literal}.' });
                    }
                },
                complete: function () {
                    this.isCreateMode = false;
                }
            });
        }
    },

    sendEmployee: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        var updateCollection = that.collection;
        // if(this.savedEmployeeAndPosUser) {
            that.employeesFormView.model.attributes.id = that.employeesFormView.model.attributes.passcode;
        // }
        // else if (that.employeesFormView.model.attributes.id == "") {
        //     that.employeesFormView.model.attributes.id = that.employeesFormView.model.attributes.newPassword;
        // }
        return $.ajax({
            url: '/data/save-employee',
            data: {
                employee: JSON.stringify(that.employeesFormView.model.toJSON()),
                token: sessionToken,
                newPassword: that.employeesFormView.model.attributes.newPassword
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that = (that.employeesFormView.model);
                // updateCollection.add(that);

                if (!that.savedEmployeeAndPosUser) {
                    M.toast({ html: 'Employee updated successfully!' });
                }
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem updating this Employee please try again later{/Literal}.' });
                }
            }
        });
    }
});