var PayPeriodsFormView = Backbone.View.extend({
    dates: [],
    clockOut: '',
    clockIn: '',
    id: '',
    name: '',
    timeId: '',
    editedCard: '',
    alreadyRendered: false,

    prefillState: false,
    renderedCalander: false,
    renderedErrors: false,

    events: { 
        'click .card-panel-entity': 'highlightCard',
        'click #send-times-to-accounting' : 'sendTimesToAccounting',
        'click #add-break-times' : 'addClockIn',
        'click .choose-item-trigger' : 'openPayTimeModal',
        'click .close-employee-time-modal': 'closeEmployeeTimeModal',
        'change #clockIn' : 'changeTotal',
        'change #clockOut' : 'changeTotal',
        'click #add-clock-in' : 'addClockIn',
        'click .save-pay-period-button ' : 'savePayPeriod',
        'click .save-new-pay-period-button' : 'addNewPayPeriod',
        'click .close-new-employee-time-modal' : 'closeNewEmployeeTimeModal',
        'click .delete-pay-period-button' : 'removePayPeriodForm',
        'click #delete-pay-period-confirm' : 'removePayPeriod',
        'change #newClockIn': 'changeTotal',
        'change #newClockOut': 'changeTotal',
        'click #cancel-delete-pay-period-confirm' : 'closeDeleteConfirmModal',
        'keydown .timeMask' : 'onTimeInput'

    },

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.payPeriodsFormTemplate = options.template; 
        this.payPeriods = options.payPeriods;
        this.chosenDate = options.chosenDate;
        this.collection = options.collection;
        this.employees = options.employees;
        this.parentModal = options.parentModal;
        this.payTypes = options.payTypes;
        this.breakTypes = options.breakTypes;
        this.badDates = options.badDates;
        this.goodDates = options.goodDates;
        this.alreadyRendered = options.alreadyRendered;
        this.payPeriodInfo = options.payPeriodInfo;
        this.clickedEvent = options.clickedEvent;
        this.getPayPeriods = options.getPayPeriods;
        this.renderPayPeriods = options.renderPayPeriods;
        this.addEvents = options.addEvents;
        this.renderTimes();
        // this.listenTo(this.collection, 'update', this.render);
    },

    render: function () {
        var that = this;
        this.dates.sort( (date1, date2) => {
            return date1.employeeName.localeCompare(date2.employeeName);
        });
        var approvedDates = this.dates.filter(date => {
             return date.in != "" && date.out != "" && !isNaN(date.total)
        });
        var errorDates = this.dates.filter(date => {
            return date.in == "" || date.out == "" || isNaN(date.total)
        });
        this.$el.html(this.template({
            chosenDate: toDateString(this.chosenDate),
            errorDates: errorDates,
            approvedDates: approvedDates,
            employees: this.employees,
            payTypes:  this.payTypes,
            breakTypes:  this.breakTypes
        }));

        $(document).ready(function() {
            $('.tooltipped').tooltip();
            $('select').formSelect();
            $('.fixed-action-btn').floatingActionButton();
            // var twelveHour = true;
            // if(App.serverInfo.country == 'IL' || App.serverInfo.country == 'UK')
            //     twelveHour = false;

            var pickerElement = document.getElementById('clockInBtn');
            M.Timepicker.init(pickerElement, {
                ...App.timepickerOptions,
                onCloseEnd: function () {
                    document.getElementById('clockIn').value = document.getElementById('clockInBtn').value;
                }
            });

            pickerElement = document.getElementById('clockOutBtn');
            M.Timepicker.init(pickerElement, {
                ...App.timepickerOptions,
                onCloseEnd: function () {
                    document.getElementById('clockOut').value = document.getElementById('clockOutBtn').value;
                }
            });
                
            pickerElement = document.getElementById('newClockInBtn');
            M.Timepicker.init(pickerElement, {
                ...App.timepickerOptions,
                onCloseEnd: function () {
                    document.getElementById('newClockIn').value = document.getElementById('newClockInBtn').value;
                }
            });

            pickerElement = document.getElementById('newClockOutBtn');
            M.Timepicker.init(pickerElement, {
                ...App.timepickerOptions,
                onCloseEnd: function () {
                    document.getElementById('newClockOut').value = document.getElementById('newClockOutBtn').value;
                }
            });

            $('.timeMask').attr({'maxlength':'8','placeholder':'--:-- --'});
            if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
                $('.timeMask').attr('inputmode', 'none');
            }
        });
        this.formModal = this.$el.find('#pay-periods-form-modal').modal();
        return this;
    },

    onTimeInput: function (e) {
        const input = e.currentTarget;
        const len = input.value.length;
        const keyCode = e.keyCode;

        if(len > 8)
            return false;

        const key = e.key.toUpperCase();
        const isBackspace = keyCode == 8;
        const isTab = keyCode == 9;
        
        if( !isTab && !isBackspace && keyCode != 32 && keyCode != 0 && key != 'P' && key != 'A' || (len < 5 && (key == 'P' || key == 'A'))){
            const isNumber = isFinite(e.key);
            if(!isNumber && keyCode > 64 && keyCode < 91) {
                return false;
            }
        }

        if (!isBackspace && len == 2)
            input.value += ":";


        if((len == 5) ) {
            if(key == 'P')
                input.value += " PM";
            else if(key == 'A')
                input.value += " AM";
            else if(isBackspace || isTab)
                return true;
            else
                return false;

        } else if((len == 6) ) {
            if(key == 'P')
                input.value += "PM";
            else if(key == 'A')
                input.value += "AM";
            else if(isBackspace || isTab)
                return true;
            else
                return false;
        }
    },

    nextInput: function(e) {
        var currentTarget = e.currentTarget.id;
        if (currentTarget == "newClockIn") {
            this.$el.find("#newClockOut").trigger("click");
        }
        else if (currentTarget == "clockIn") {
            this.$el.find("#clockOut").trigger("click");
        }
    },

    unFocus: function (e) {
        e.preventDefault();
        $('#newClockOut').prop("readonly", true);
        $('#clockOut').prop("readonly", true);
    },

    renderTimes: function () {
        this.dates = [];
        var chosenDateFormat = new Date(this.chosenDate);
        // var month = chosenDateFormat.getUTCMonth() + 1; //months from 1-12
        // var day = chosenDateFormat.getUTCDate();
        // var year = chosenDateFormat.getUTCFullYear();
        // if (App.serverInfo.isRightToLeft && App.serverInfo.isMobileServer && !this.clickedEvent && !this.alreadyRendered) {
        //     if (day - 1 != 0)  {
        //         day = day - 1;
        //     }
        //     else {
        //         var testDate = new Date(year, month - 1, 0);
        //         month = testDate.getUTCMonth() + 1; //months from 1-12
        //         day = testDate.getUTCDate();
        //         year = testDate.getUTCFullYear();
        //         day++;
        //     }
        //     this.chosenDate = year + "-" + month + "-" + day;

        // }
        // var dateSelected = year + "/" + month + "/" + day;
        dateSelected = moment(this.chosenDate).format("YYYY/M/DD");
        for (var i = 0; i < this.collection.length; i++) {
            var inDate = moment(this.collection.models[i].attributes.in).format("YYYY/M/DD");
            var outDate = moment(this.collection.models[i].attributes.out).format("YYYY/M/DD");

            if (inDate == dateSelected || (this.collection.models[i].attributes.in == "" && outDate == dateSelected)) {
                this.dates.push(this.collection.models[i].attributes)
            }
        }
    },

    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);
        }
    },

    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');
        }
    },

    sendTimesToAccounting: function () {
        var that = this;
        var sessionToken = this.getCookie();
        
        if (App.serverInfo.hasAccounting) {
            $.ajax({
                url: '/data/send-times-payroll',
                data: {
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',
    
                success: function (data) {
                    M.toast({ html: '{Literal}Times sent 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 sending times to accounting{/Literal}' });
                    }
                }
            });    
        }
        else {
            M.toast({ html: '{Literal}Your AccuServer does not have accounting integration{/Literal}' }); 
        }
    },

    validateTimeInput: function(element) {
        var inputEl = document.getElementById(element);
        var hour = inputEl.value.substring(0,2);
        var min = inputEl.value.substring(3,5);
        if(!isFinite(hour) || !isFinite(min)) {
            inputEl.classList.add('invalid');
            return false;
        }
        hour = Number.parseInt(hour);
        if( hour < 0  || hour > 23) {
            inputEl.classList.add('invalid');
            return false;
        }

        min = Number.parseInt(min);
        if( min < 0  || min > 59) {
            inputEl.classList.add('invalid');
            return false;
        }

        return true;
    },

    openPayTimeModal: function (e) {
        this.editedCard = $(e.currentTarget.parentElement.parentElement);
        var element = $(e.currentTarget.parentElement.parentElement);
        this.clockOut = $(element).attr('clock-out-id');
        this.clockIn = $(element).attr('clock-in-id');
        this.id = $(element).attr('data-id');
        this.name = $(element).attr('employee-name-id');
        this.timeId = $(element).attr('time-id');
        this.payLevel = $(element).attr('pay-level-id');
        this.breakType = $(element).attr('break-type-id');


        var name = document.getElementById('name');
        name.value = this.name;

        var totalHours = document.getElementById('total');
        totalHours.value = "";

        var clockInHours = document.getElementById('clockIn');
        clockInHours.value = "";

        var clockOutHours = document.getElementById('clockOut');
        clockOutHours.value = "";

        if (this.clockIn == "") {
            var clockInLabel = document.getElementById("clockInLabel");
            clockInLabel.style.color = "red";
        }
        else if (this.clockOut == "") {
            var clockOutLabel = document.getElementById("clockOutLabel");
            clockOutLabel.style.color = "red";
        }

        for (var i = 0; i < this.dates.length; i++) {
            if (this.dates[i].in == this.clockIn && this.dates[i].out == this.clockOut && this.dates[i].employeeId == this.id && this.dates[i].employeeName == this.name) {
                if (this.dates[i].in == "" || this.dates[i].out == "" ) {
                    totalHours.value = "---"
                }
                else {
                    totalHours.value = milisecondsToTimeString(this.dates[i].total);
                }

                if (this.dates[i].in != "") {
                    // var dateIn = new Date(this.dates[i].in);
                    // var h = dateIn.getHours();
                    // var m = dateIn.getMinutes();
                    // m = (10 > m) ? "0" + m : m;
                    // test1 = moment().hours(h).minutes(m);
                    // clockInHours.value = test1.format("hh:mm A");
                    clockInHours.value = toTimeString(this.dates[i].in);
                }
                
                if (this.dates[i].out != "") {
                    // var dateOut = new Date(this.dates[i].out);
                    // var h = dateOut.getHours();
                    // var m = dateOut.getMinutes();
                    // m = (10 > m) ? "0" + m : m;
                    // test2 = moment().hours(h).minutes(m);
                    // clockOutHours.value = test2.format("hh:mm A");
                    clockOutHours.value = toTimeString(this.dates[i].out);
                }
            }
        }

        // generate pay type dropdown
        var option = "";
        $("#payType-dropdown").html("");
        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

        option = $('<option>');
        $(option).val("-1");
        if(this.payLevel == -1)
            $(option).attr('selected', 'selected');

        $(option).html("{Literal}Select Pay Level{/Literal}");
        $("#payType-dropdown").append(option);

        for (var i = 0; i < Object.size(this.payTypes); i++) 
        {
            if(this.payTypes[i] === '')
                continue;
            
            option = $('<option>');
            $(option).val(i);
            $(option).html(this.payTypes[i]);
            if ( this.payLevel == i + 1 ) 
            {
                $(option).attr('selected', 'selected');
            }
            
            $("#payType-dropdown").append(option);
        }
        

        $("#payType-dropdown").formSelect();

        // generate break types dropdown
        $("#breakType-dropdown-edit").html("");
        if(this.breakType != ""){
            option = $('<option>');
            $(option).val("");
            $(option).html("{Literal}Select Break Type{/Literal}");
            $("#breakType-dropdown-edit").append(option);

            for (var i = 0; i < this.breakTypes.length; i++) 
            {   
                option = $('<option>');
                $(option).val(this.breakTypes[i].id);
                $(option).html(this.breakTypes[i].type);
                if ( this.breakType == this.breakTypes[i].id )
                {
                    $(option).attr('selected', 'selected');
                }
                
                $("#breakType-dropdown-edit").append(option);
            }
            
            $("#breakType-dropdown-edit-container").show();
            $("#payType-dropdown-edit-container").hide();
            $("#breakType-dropdown-edit").formSelect();
        } else {
            $("#breakType-dropdown-edit-container").hide();
            $("#payType-dropdown-edit-container").show();
        }

        payPeriodForm = this.$el.find('#employee-times-modal').modal();
        payPeriodForm.modal('open');
    },

    closeEmployeeTimeModal: function () {
        payPeriodForm = this.$el.find('#employee-times-modal').modal();
        payPeriodForm.modal('close');
    },

    closeNewEmployeeTimeModal: function () {
        payPeriodForm = this.$el.find('#new-employee-times-modal').modal();
        payPeriodForm.modal('close');
    },

    savePayPeriod: function () {
        var that = this;
        
        var sessionToken = this.getCookie();
        var clockIn = this.$el.find("#clockIn").val();
        var clockOut = this.$el.find("#clockOut").val();
        var total = this.$el.find("#clockOut").val();
        var totalHours = this.$el.find("#total").val();
        var payLevel = this.$el.find('#payType-dropdown').val();
        var breakType = this.$el.find('#breakType-dropdown-edit').val();

        if (clockIn != "") {
            if(!that.validateTimeInput('clockIn' || !that.validateTimeInput('clockOut')))
                return false;
            var clockInTime = new Date("January 1, 2000 " + clockIn);
            var clockOutTime = new Date("January 1, 2000 " + clockOut);

            for (var i = 0; i < this.dates.length; i++) {
                if (this.dates[i].in == this.clockIn && this.dates[i].out == this.clockOut && this.dates[i].employeeId == this.id && this.dates[i].employeeName == this.name) {
                    var dateIn = new Date(clockInTime);
                    var hoursIn = dateIn.getHours();
                    var minutesIn = dateIn.getMinutes();
                    if(Number.isNaN(hoursIn) || Number.isNaN(minutesIn)) {
                        this.$el.find("#clockIn").addClass('invalid');
                        return;
                    }
                    minutesIn = (10 > minutesIn) ? "0" + minutesIn : minutesIn;
                    var ampm = hoursIn >= 12 ? 'pm' : 'am';
                    test1 = moment().hours(hoursIn).minutes(minutesIn);
                    clockInFormated = test1.format("HH:mm");
                    clockInFormatedAmPm = test1.format("hh:mm A");

                    var dateOut = new Date(clockOutTime);
                    var hoursOut = dateOut.getHours();
                    var minutesOut = dateOut.getMinutes();
                    if(Number.isNaN(hoursIn) || Number.isNaN(minutesIn)) {
                        this.$el.find("#clockOut").addClass('invalid');
                        return;
                    }
                    minutesOut = (10 > minutesOut) ? "0" + minutesOut : minutesOut;
                    var ampm = hoursOut >= 12 ? 'pm' : 'am';
                    test2 = moment().hours(hoursOut).minutes(minutesOut);
                    clockOutFormated = test2.format("HH:mm");
                    clockOutFormatedAmPm = test2.format("hh:mm A");

                    var previousIn = this.dates[i].in;
                    var previousOut = this.dates[i].out;

                    this.dates[i].in = this.chosenDate + " " + clockInFormated + ":00.0";
                    if(clockOut != '') {
                    if(hoursOut < hoursIn) {
                        var newDateOut =  moment(this.chosenDate).add('days',1).format("YYYY-MM-DD");
                        this.dates[i].out = newDateOut + " " + clockOutFormated + ":00.0";
                    }
                    else
                        this.dates[i].out = this.chosenDate + " " + clockOutFormated + ":00.0";
                    }
                    this.dates[i].timeId = this.timeId;
                    this.dates[i].total = new Date(this.dates[i].out).getTime() - new Date(this.dates[i].in).getTime();
                    that.dates[i].payLevel = Number.parseInt(payLevel) + 1;

                    // previousIn = previousIn == "" ? this.dates[i].in : previousIn;
                    // previousOut = previousOut == "" ? this.dates[i].out : previousOut;
                    
                    previousIn = this.chosenDate + " 00:00:00.0";
                    previousOut = moment(this.chosenDate).add('days',10).format("YYYY-MM-DD") + " 23:59:59.9";
                    

                    $.ajax({
                        url: '/data/edit-time',
                        data: {
                            token: sessionToken,
                            employeeId: that.id,
                            timeId: this.timeId,
                            in: this.dates[i].in,
                            out: this.dates[i].out,
                            payLevel: payLevel,
                            breakType: breakType,
                            previousIn: previousIn,
                            previousOut: previousOut
                        },
                        dataType: 'json',
                        type: 'POST',
                        success: function (data) {
                            M.toast({
                                html: '{Literal}Time Saved Successfully{/Literal}' 
                            });
                            var thisEditedDate = that.dates[i];
                            for (var t = 0; t < that.goodDates.length; t++) {
                                if (that.dates[i].employeeId == that.goodDates[t].employeeId && that.dates[i].employeeName ==  that.goodDates[t].employeeName && that.dates[i].timeId == that.goodDates[t].timeId) {
                                    that.goodDates[t] = that.dates[i];
                                    break;
                                }
                            }

                            var newBadDates = [];

                            for (var t = 0; t < that.badDates.length; t++) {
                                var badDate = new Date(that.badDates[t]);
                                var h = badDate.getHours();
                                var m = badDate.getMinutes();
                                m = (10 > m) ? "0" + m : m;
                                badDate = moment().hours(h).minutes(m);
                                badDate = badDate.format("hh:mm A")

                                if (badDate == (clockIn) || badDate == (clockOut)) {
                                    that.badDates.splice(t, 0); 
                                    that.goodDates.push(thisEditedDate);
                                }
                                else {
                                    newBadDates.push(that.badDates[t]);
                                }
                            }
                            
                            that.badDates = newBadDates;
                            that.getPayPeriods();
                            that.alreadyRendered = true;
                            that.render();
                            // payPeriodForm.modal('close'); 
                        },
                        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}'
                                });
                            }
                        }
                    });
                    break;
                }
            }
        }
        else {
            M.toast({ html: '{Literal}Both Clock In and Clock Out must be defined{/Literal}' });
        }
    },

    changeTotal: function (e) {
        var currentTarget = e.currentTarget.id;
        var clockIn = this.$el.find("#clockIn").val();
        var clockOut = this.$el.find("#clockOut").val();
        
        // var total = $("#total").val();
        if (clockIn === '' || clockOut === '')
            $("#total").val('');
        else {
            var clockInDate = moment("1970-01-01 " + clockIn, "YYYY-MM-DD hh:mm a").valueOf();
            var clockOutDate = moment("1970-01-01 " + clockOut, "YYYY-MM-DD hh:mm a").valueOf();
            $("#total").val(milisecondsToTimeString(clockOutDate - clockInDate));
        }   

        if (currentTarget == "newClockIn") {
            this.$el.find("#newClockOut").trigger("click");
            var field = document.createElement('input');
            field.setAttribute('type', 'text');
            document.body.appendChild(field);

            setTimeout(function() {
                field.focus();
                setTimeout(function() {
                    field.setAttribute('style', 'display:none;');
                }, 50);
            }, 50);
            // M.toast({ html: '{Literal}Please Choose Clock Out Time{/Literal}' });
        }
        else if (currentTarget == "clockIn") {
            this.$el.find("#clockOut").trigger("click");
            var field = document.createElement('input');
            field.setAttribute('type', 'text');
            document.body.appendChild(field);

            setTimeout(function() {
                field.focus();
                setTimeout(function() {
                    field.setAttribute('style', 'display:none;');
                }, 50);
            }, 50);
            // M.toast({ html: '{Literal}Please Choose Clock Out Time{/Literal}' });
        }

        e.preventDefault();
        
    },

    addClockIn: function (e) {
        // var newBreak = document.getElementById('newBreak');
        // newBreak.value = "";

        // var newLunch = document.getElementById('newLunch');
        // newLunch.value = "";

        if(e.currentTarget.id == "add-break-times"){
            $("#breakType-dropdown-container").show();
            $("#payLevel-dropdown-container").hide();
        }
        else {
            $("#payLevel-dropdown-container").show();
            $("#breakType-dropdown-container").hide();
        }

        var newClockIn = document.getElementById('newClockIn');
        newClockIn.value = "";

        var newClockOut = document.getElementById('newClockOut');
        newClockOut.value = "";

        var newPayPeriodModal = this.$el.find('#new-employee-times-modal').modal();
        newPayPeriodModal.modal('open');
    },

    addNewPayPeriod: function () {
        var that = this;
        var sessionToken = this.getCookie();
        var clockIn = this.$el.find("#newClockIn").val();
        var clockOut = this.$el.find("#newClockOut").val();
        // var newBreak = this.$el.find("#newBreak").val();
        // var lunch = this.$el.find("#newLunch").val();
        var employeeName = this.$el.find('#employee-dropdown option:selected:not(option[value=employee0])').text();
        var payLevel = this.$el.find('#payLevel-dropdown').val();
        var breakType = this.$el.find('#breakType-dropdown').val();
        var employeeId = this.$el.find('#employee-dropdown').val();
        var total = "";

        if(document.getElementById('breakType-dropdown-container').style.display != 'none' && breakType == '') {
            M.toast({ html: '{Literal}An break type must be chosen{/Literal}' });
            return
        }

        if (clockIn != "") {
            if(!that.validateTimeInput('newClockIn'))
                return;

            var clockInTime = new Date("January 1, 2000 " + clockIn);

            var clockOutTime = "";
            if(clockOut != "")
                clockOutTime = new Date("January 1, 2000 " + clockOut);

            if (employeeName == "") {
                M.toast({ html: '{Literal}An employee must be chosen{/Literal}' });
            }
            else {

                var dateIn = new Date(clockInTime);
                var hoursIn = dateIn.getHours();
                var minutesIn = dateIn.getMinutes();
                if(Number.isNaN(hoursIn) || Number.isNaN(minutesIn)) {
                    this.$el.find("#newClockIn").addClass('invalid');
                    return;
                }
                minutesIn = (10 > minutesIn) ? "0" + minutesIn : minutesIn;
                var ampm = hoursIn >= 12 ? 'pm' : 'am';
                test1 = moment().hours(hoursIn).minutes(minutesIn);
                clockInFormated = test1.format("HH:mm");
                clockInFormatedAmPm = test1.format("hh:mm A");
                var inTime = this.chosenDate + " " + clockInFormated + ":00.0";


                if(clockOutTime != ""){
                    if(!that.validateTimeInput('newClockIn'))
                        return;
                    var dateOut = new Date(clockOutTime);
                    var hoursOut = dateOut.getHours();
                    var minutesOut = dateOut.getMinutes();
                    if(Number.isNaN(hoursIn) || Number.isNaN(minutesIn)) {
                        this.$el.find("#newClockOut").addClass('invalid');
                        return;
                    }
                    minutesOut = (10 > minutesOut) ? "0" + minutesOut : minutesOut;
                    var ampm = hoursOut >= 12 ? 'pm' : 'am';
                    test2 = moment().hours(hoursOut).minutes(minutesOut);
                    clockOutFormated = test2.format("HH:mm");
                    clockOutFormatedAmPm = test2.format("hh:mm A");

                    if(hoursOut < hoursIn) {
                        var newDateOut =  moment(this.chosenDate).add('days',1).format("YYYY-MM-DD");
                        var out = newDateOut + " " + clockOutFormated + ":00.0";
                    }
                    else
                        var out = this.chosenDate + " " + clockOutFormated + ":00.0";

                    var total = new Date(out).getTime() - new Date(inTime).getTime();
                } else {
                    var total = '';
                    var out = '';
                }

                
                
                var updatedModel = {
                    id: employeeId,
                    payLevel: payLevel,
                    breakType: breakType,
                    employeeId: employeeId,
                    employeeName: employeeName,
                    out: out,
                    total: total,
                    in: inTime
                };

                $.ajax({
                    url: '/data/add-times',
                    data: {
                        token: sessionToken,
                        id: employeeId,
                        in: inTime,
                        out: out,
                        // total: total,
                        payLevel: payLevel,
                        breakType: breakType
                    },
                    dataType: 'json',
                    type: 'POST',
                    success: function (data) {
                        M.toast({
                            html: '{Literal}Time Saved Successfully{/Literal}' 
                        });
                        that.dates.push(updatedModel);

                        that.getPayPeriods();
                        that.render();
                        
                        // var newPayPeriodModal = that.$el.find('#new-employee-times-modal').modal();
                        // newPayPeriodModal.modal('close');
                        // that.closeNewEmployeeTimeModal();
                        // that.$el.find('#pay-periods-form-modal').parent().parent().modal('close');
                        var foundTime = false;
                        for (var t = 0; t < that.goodDates.length; t++) {
                            if (updatedModel.employeeId == that.goodDates[t].id && updatedModel.employeeName ==  that.goodDates[t].name && updatedModel.timeId == that.goodDates[t].timeId) {
                                foundTime = true;
                            }
                        }

                        for (var t = 0; t < that.badDates.length; t++) {
                            if (updatedModel.in == that.badDates[t] || updatedModel.out ==  that.badDates[t]) {
                                that.badDates.splice(t, 1);
                            }
                        }

                        if (!foundTime) {
                            that.goodDates.push(updatedModel);
                        }

                    },
                    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}'
                            });
                        }
                    }
                });
            }
        }
        else {
            M.toast({ html: '{Literal}At least Clock In be defined{/Literal}' });
        }
    },

    removePayPeriodForm: function () {
        $('#delete-pay-period-modal').modal().modal('open');
    },

    removePayPeriod: function () {
        var that = this;
        var sessionToken = this.getCookie();
        var clockIn = this.$el.find("#clockIn").val();
        var clockOut = this.$el.find("#clockOut").val();
        // var fromDate = new Date(this.chosenDate).setHours(0,0,0,0);
        // var thruDate = new Date(this.chosenDate).setHours(23,59,59,0);
        var fromDate = $("#calendar").fullCalendar('getView').start._i;
        var thruDate = $("#calendar").fullCalendar('getView').end._i;
        $.ajax({
            url: '/data/remove-time',
            data: {
                token: sessionToken,
                employeeId: this.id,
                timeId: this.timeId,
                fromDate: fromDate,
                thruDate: thruDate,
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                M.toast({
                    html: '{Literal}Time Deleted Successfully{/Literal}' 
                });
                
                that.editedCard.hide();
                that.editedCard.css('display', 'none');
                that.editedCard.remove();

                for (var i = 0; i < that.dates.length; i++) {
                    if (that.dates[i].employeeId == that.id && that.dates[i].timeId == that.timeId) {
                        that.dates.splice(i, 1); 
                    }
                }

                for (var i = 0; i < that.goodDates.length; i++) {
                    if (that.goodDates[i].employeeId == that.id && that.goodDates[i].timeId == that.timeId) {
                        that.goodDates.splice(i, 1); 
                    }
                }
                
                newBadDates = [];

                for (var t = 0; t < that.badDates.length; t++) {
                    var badDate = new Date(that.badDates[t]);
                    var h = badDate.getHours();
                    var m = badDate.getMinutes();
                    m = (10 > m) ? "0" + m : m;
                    badDate = moment().hours(h).minutes(m);
                    badDate = badDate.format("hh:mm A")

                    if (badDate == (clockIn) || badDate == (clockOut)) {
                        that.badDates.splice(t, 0); 
                        that.goodDates.push(thisEditedDate);
                    }
                    else {
                        newBadDates.push(that.badDates[t]);
                    }
                }
                
                that.badDates = newBadDates;
                that.alreadyRendered = true;
                var response = that.getPayPeriods();
                response.then( () => {
                    that.render();
                })
                
                // payPeriodForm.modal('close'); 
            },
            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}'
                    });
                }
            }
        });
    },
    
  
    closeDeleteConfirmModal: function() {
        this.$el.find('#delete-pay-period-modal').modal('close');
    }
});