var PayPeriodsView = Backbone.View.extend({
    formModal: null,
    deletionModal: {},
    itemsAutocomplete: {},
    editedCollecton: {},
    sentItems: 0,
    badDates: [],
    goodDates: [],
    payPeriodInfo: {},
    employees: {},
    payTypes: {},
    breakTypes: {},
    alreadyRendered: false,
    chosenDate: "",
    accuShift: false,
    calendarMonth: null,
   
    prefillState: false,
    paymentTypeMapping: {},

    events: {
        'click #listFormat' : 'showListView',
        'click #calendarFormat' : 'showCalender',
        'click .tableRow': 'openPayPeriod',
        'click #advance-pay-period-button': 'showAdvancePayPeriod',
        'click #cancel-advance-pay-period': 'hideAdvancePayPeriod',
        'click #advance-pay-period-confirm' : 'advancePayPeriod',
        'click #edit-pay-period-button': 'showEditPayPeriodInfo',
        'click #cancel-pay-period-info': 'hideEditPayPeriodInfo',
        'click #save-pay-period-info-confirm': 'savePayPeriodInfo',
        'click #view-employee-hours-button' : 'renderEmployeeTimes2',
        'click  #delete-pay-period-confirm' : 'getPayPeriods',
        'click .timeClass' : 'handleTimeClick',
        'click button.fc-button' : 'getPayPeriods',
    },

    breadcrumb: {},

    styles: [
        'ap-blue',
        '#31619e'
    ],

    // inventoryStyleMapping: {},

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.payPeriodsFormTemplate = options.payPeriodsFormTemplate; 
        this.breadcrumb = options.breadcrumb;
        this.collection = options.collection;
        //this.listenTo(this.collection, 'reset', this.render);
        this.model = options.model;
        this.initPayPeriods();
    },

    addEvents: function () {
        var that = this;
        $("#calendar").fullCalendar('removeEvents');
        var periodEndDate;
        var periodStartDateMoment;
        periodStartDateMoment = $("#calendar").fullCalendar('getView').intervalStart.clone();
        periodEndDate = $("#calendar").fullCalendar('getView').intervalEnd.toDate();

        var periodStartDate = periodStartDateMoment.toDate();
       
        while(periodStartDateMoment.isSameOrBefore(periodEndDate)) {

            let newDate = periodStartDateMoment.toDate();
            newDate.setHours(0,0,0,0);
            periodStartDate.setHours(0,0,0,0);

            var total = 0;
            var thisCalDate = newDate.getTime();
            that.goodDates.forEach( goodDate => {
                var thisIn = new Date(goodDate.in);
                var thisOut = new Date(goodDate.out);
                thisIn = new Date(thisIn.setHours(0,0,0,0)).getTime();
                thisOut = new Date(thisOut.setHours(0,0,0,0)).getTime();
                if(thisIn === thisCalDate && !this.isUnpaidPaidBreak(goodDate) ) {
                    total += goodDate.total;
                }
            });
            
            if(total > 0) {
                var lable = ' {Literal}Total Hours{/Literal}: ';
                total = milisecondsToTimeString(total);            
                var event={ id:newDate , title: lable + total, start: newDate, color: '#31619e' };
                $('#calendar').fullCalendar('renderEvent', event, false);
            }
            
            that.badDates.forEach( badDate => {
                var thisBadDate = badDate.in === "" ? badDate.out : badDate.in;
                var thisBadDate = (new Date(thisBadDate)).setHours(0,0,0,0);
                if(thisBadDate === thisCalDate) {
                    var event = { id: newDate , title: '{Literal}Errors Found{/Literal}', start: newDate, color: '#f00' };
                    $('#calendar').fullCalendar('renderEvent', event, false);
                    return false;
                }
            });

            periodStartDateMoment.add(1,'days');

        }
    },

    isUnpaidPaidBreak: function(timeDetail) {
        var isUnpaidPaidBreak = false;
        if(timeDetail.breakType != ''){
            
            var foundBreak = this.breakTypes.find(b => b.id == timeDetail.breakType);
            if(foundBreak)
                isUnpaidPaidBreak = !foundBreak.isPaid;
        }

        console.log(isUnpaidPaidBreak)
        return isUnpaidPaidBreak;
    },

    render: function () {
        var that = this;
        $('.fc-day-grid-event').remove();
        App.breadCrumbToolTip = "Edit, add, and change employee hours";
        $(document).ready(function(){
            $('.fixed-action-btn').floatingActionButton();
            $('select').formSelect();
            $('.tooltipped').tooltip();
            var elems = document.querySelectorAll('.datepicker');
            var instances = M.Datepicker.init(elems, {
                autoClose: true,
                container: 'body',
                format: 'yyyy-mm-dd',
                // isRTL: App.rtl,
                i18n: App.i18n
            });
            $('.modal').modal();
            that.itemMapping = {};
            that.itemQtyMapping = {}  
        });
        

        this.$el.html(this.template({
            payPeriods: this.collection.toJSON(),
            payPeriodInfo: that.payPeriodInfo,
        }));

        $('.fixed-action-btn').floatingActionButton();
        $('select').formSelect();
        var elems = document.querySelectorAll('.datepicker');
        var instances = M.Datepicker.init(elems, {
            autoClose: true,
            container: 'body'    
        });
        $('.modal').modal();
        $('.tooltipped').tooltip();
        that.itemMapping = {};
        that.itemQtyMapping = {}  
            
        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) {
                that.$el.find(".save-button").trigger("click");
                return false;
            }
        });

        this.formModal = this.$el.find('#pay-periods-form-modal').modal();
        return this;
    },

    showListView: function () {
        $('#calendar').hide();
        $('#listFormat').hide();
        $('#calendarFormat').show();
        $('#listView').show();
    },

    showCalender: function () {
        $('#calendar').show();
        $('#listFormat').show();
        $('#calendarFormat').hide();
        $('#listView').hide();
    },

    openPayPeriod: function (e) {
        var element = $(e.currentTarget);
        var id = $(element).attr('data-id');
    },

    clickDate: function (date) {
        if (this.accuShift) {
            var that = this;
            that.chosenDate = date;
            this.payPeriodsFormView = new PayPeriodsFormView({
                template: that.payPeriodsFormTemplate,
                chosenDate: that.chosenDate,
                collection: that.collection,
                employees: that.employees,
                parentModal: that,
                payTypes: that.payTypes,
                breakTypes: that.breakTypes,
                payPeriodInfo: that.payPeriodInfo,
                alreadyRendered: that.alreadyRendered,
                goodDates: that.goodDates,
                badDates: that.badDates,
                renderCalendar: that.renderCalendar,
                getPayPeriods: that.getPayPeriods,
                renderPayPeriods: that.renderPayPeriods,
                addEvents: that.addEvents,
                // formModal: that.formModal
                
            });
    
            this.$el.find('#pay-periods-form-modal').html(that.payPeriodsFormView.render().el);
            that.formModal.modal('open');
            event.preventDefault();
        }
        else {
            M.toast({
                html: '{Literal}You do not have access to AccuShft{/Literal}'
            });
        }
    },

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

    showAdvancePayPeriod: function () {
        var payPeriodFormModal = this.$el.find('#advance-pay-period-modal').modal();
        $("#advance-from-pay-peroid").text(moment(this.payPeriodInfo.periodEnd).format('LL'));
        payPeriodFormModal.modal('open');
    },

    hideAdvancePayPeriod: function () {
        $('#advance-pay-period-modal').hide();
    },

    advancePayPeriod: function () {
        var that = this;
        var sessionToken = this.getCookie();
        if (this.accuShift) {
            $.ajax({
                url: '/data/advance-pay-period',
                data: {
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    M.toast({
                        html: '{Literal}Pay Period Advanced Successfully{/Literal}' 
                    });
                    location.reload();
                },
                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}You do not have access to AccuShft{/Literal}'
            });
        }
    },

    showEditPayPeriodInfo: function () {
        if (this.accuShift)
        {
            var periodEndDate = document.getElementById("periodEnd");
            var periodEnd = new Date(this.payPeriodInfo.periodEnd); 
            month = '' + (periodEnd.getMonth() + 1),
            day = '' + periodEnd.getDate(),
            year = periodEnd.getFullYear();
    
            if (month.length < 2) month = '0' + month;
            if (day.length < 2) day = '0' + day;
            periodEnd = [year, month, day].join('-');
    
            periodEndDate.value = periodEnd;
    
            var daysInPeriod = document.getElementById("periodDuration");
            daysInPeriod.value = this.payPeriodInfo.periodDuration;
    
            var weekStartDate = document.getElementById("weekStartDay");
            $("#weekStartDay").val(this.payPeriodInfo.weekStartDay);
    
            var weekEndDate = document.getElementById("weekEndDay"); 
            $("#weekEndDay").val(this.payPeriodInfo.weekEndDay);
    
            var hoursBeforeOT = document.getElementById("hoursBeforeOT");
            hoursBeforeOT.value = this.payPeriodInfo.hoursBeforeOT;
            
            $('select').formSelect();
            
            var editPayPeriodFormModal = this.$el.find('#edit-pay-period-modal').modal();
            editPayPeriodFormModal.modal('open');
        }
        else 
        {
            M.toast({
                html: '{Literal}You do not have access to AccuShift{/Literal}'
            }); 
        }
        
    },
    
    hideEditPayPeriodInfo: function () {
        $('#edit-pay-period-modal').hide();
    },

    savePayPeriodInfo: function () {
        var that = this;
        var sessionToken = this.getCookie();

        var hoursBeforeOT = this.$el.find('#hoursBeforeOT').val();
        var periodDuration = this.$el.find('#periodDuration').val();
        var weekEndDay = this.$el.find('#weekEndDay').val();
        var weekStartDay = this.$el.find('#weekStartDay').val();
        var periodEnd = this.$el.find('#periodEnd').val();
        var periodStart = this.$el.find('#periodEnd').val();

        var periodStart = new Date(periodEnd);
        periodStart.setDate(periodStart.getDate() - periodDuration);

        var d = new Date(periodEnd),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        periodEnd = [year, month, day].join('-');

        var d = new Date(periodStart),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        periodStart = [year, month, day].join('-');

        periodStart = periodStart + ' 00:00:01.0';
        periodEnd = periodEnd + ' 23:59:59.0';

        var updatedModel = {
            hoursBeforeOT: hoursBeforeOT,
            periodDuration: periodDuration,
            weekEndDay: weekEndDay,
            weekStartDay: weekStartDay,
            periodEnd: periodEnd,
            periodStart: periodStart
        };

        if (updatedModel != undefined) {
            this.payPeriodInfo = updatedModel;

            $.ajax({
                url: '/data/save-pay-period-info',
                data: {
                    token: sessionToken,
                    payPeriodInfo: JSON.stringify(updatedModel),
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    M.toast({
                        html: '{Literal}Pay Period Settings Save Successfully{/Literal}' 
                    });
                    // location.reload();
                },
                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}'
                        });
                    }
                }
            });
        }
    },

    initPayPeriods: async function () {
        try {
            await this.getEmployees();
            await this.getPayLevels();
            await this.getBreakTypes();
            await this.getPayPeriods();
            await this.checkAccess();
        }
        catch (e) {
            console.log(e);
        }
    },

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

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

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.responseJSON.hasAccess == false) {
                    that.accuShift = false;
                }
            }
        });
    },
    
    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);
        }
    },

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

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

    getEmployees: function () {
        var that = this;
        var sessionToken = this.getCookie();

        $.ajax({
            url: '/data/get-employees',
            data: {
                activeOnly: true,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.employees = (data.results);
            },
            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}'
                    });
                }
            }
        });
    },

    getPayPeriods: async function () {
        var that = this;
        var isCalendarInitilized = $('#calendar').children().length > 0;
        if(!isCalendarInitilized) {
            
            var today = new Date();            
            var startDate = moment(new Date(today.getFullYear(), today.getMonth(), 1)).format('YYYY-MM-DD HH:mm:ss');
            var endDate = moment(new Date(today.getFullYear(), today.getMonth()+1, 0)).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        }
        else {
            var startDate = $("#calendar").fullCalendar('getView').intervalStart.format('YYYY-MM-DD HH:mm:ss');
            var endDate = $("#calendar").fullCalendar('getView').intervalEnd.endOf('day').format('YYYY-MM-DD HH:mm:ss');
        }
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-pay-period',
            data: {
                token: sessionToken,
                startDate: startDate,
                endDate: endDate
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.payPeriodInfo = data.payPeriodInfo;
                // that.generatePayPeriodStyleMapping(data.payPeriods);
                that.renderPayPeriods(data);                
            },
            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}'
                    });
                }
            }
        });
    },

    getPayPeriodsAgain0: function (e) {
        var that = this;
      
        var startDate = $("#calendar").fullCalendar('getView').intervalStart.format("YYYY-MM-DD HH:mm:ss");
        var endDate = $("#calendar").fullCalendar('getView').intervalEnd.endOf('day').format("YYYY-MM-DD HH:mm:ss");
        var sessionToken = this.getCookie();
        if (e != undefined) {
            that.alreadyRendered = true;
        }
        return $.ajax({
            url: '/data/get-pay-period',
            data: {
                token: sessionToken,
                startDate: startDate,
                endDate: endDate
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.renderPayPeriodsAgain(data);
            },
            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}'
                    });
                }
            }
        });
    },

    renderPayPeriods: async function (data) {
        var that = this;
        var payPeriods = data.payPeriods;
        
        payPeriods.sort(function (a, b) {
            return a.employeeId.toLowerCase() < b.employeeId.toLowerCase() ? -1 : (a.employeeId.toLowerCase() > b.employeeId.toLowerCase() ? 1 : 0);
        });
        that.badDates = [];
        that.goodDates = [];

        var collection = new PayPeriodsCollection();
        for (var i = 0; i < payPeriods.length; i++) {
           
            var timeIn = new Date(payPeriods[i].in);
            var timeOut = new Date(payPeriods[i].out);
            
            if (isNaN(timeIn.getTime()) || payPeriods[i].in === "" || isNaN(payPeriods[i].total)) {
                that.badDates.push(payPeriods[i]);
            }
            else if (isNaN(timeOut.getTime()) || payPeriods[i].out === "") {
                that.badDates.push(payPeriods[i]);
            }
            else {
                that.goodDates.push(payPeriods[i]);
            }
           
            collection.add(new PayPeriods( payPeriods[i]));
        }

        that.collection.reset(collection.models);

        try {
            var isCalendarInitilized = $('#calendar').children().length > 0;
            if(!isCalendarInitilized)
                await this.renderCalendar();
                
            // await this.getPayPeriodsAgain();
            that.addEvents();

        }
        catch (e) {
            console.log(e);
        }
    },

    renderPayPeriodsAgain: async function (data) {
        var that = this;

        var payPeriods = data.payPeriods;
        payPeriods.sort(function (a, b) {
            return a.employeeId.toLowerCase() < b.employeeId.toLowerCase() ? -1 : (a.employeeId.toLowerCase() > b.employeeId.toLowerCase() ? 1 : 0);
        });
        that.badDates = [];
        that.goodDates = [];

        var collection = new PayPeriodsCollection();
        for (var i = 0; i < payPeriods.length; i++) {
            var timeIn = new Date(payPeriods[i].in);
            var timeOut = new Date(payPeriods[i].out);

            
            if (isNaN(timeIn.getTime()) || payPeriods[i].in === "" || isNaN(payPeriods[i].total)) {
                that.badDates.push(payPeriods[i]);
            }
            else if (isNaN(timeOut.getTime()) || payPeriods[i].out === "") {
                that.badDates.push(payPeriods[i]);
            }
            else {
                that.goodDates.push(payPeriods[i]);
            }
           
            collection.add(new PayPeriods( payPeriods[i]));
        }

        // var test = [];
        // var foundId = false;
        // for (var i = 0; i < this.collection.models.length; i++) {
        //     for (var j = 0; j < test.length; j++) {
        //         if (this.collection.models[i].attributes.employeeId == test[j]) {
        //             foundId = true;
        //         }
        //     }
        //     if (!foundId) {
        //         $('#payPeriodTable').append('<tr class="tableRow" data-id="' + this.collection.models[i].attributes.employeeId + '"><td class="employeeId">' + this.collection.models[i].attributes.employeeId + '</td><td class="accountingId">' + this.collection.models[i].attributes.accountingId + '</td> <td class="name">' + this.collection.models[i].attributes.employeeName + '</td> <td class="inOut">' + this.collection.models[i].attributes.in + ' / ' +  this.collection.models[i].attributes.out + '</td> <td class="payLevel">' + this.collection.models[i].attributes.payLevel + '</td> <td class="total">' + this.collection.models[i].attributes.total + '</td> </tr>');
        //         test.push(this.collection.models[i].attributes.employeeId);
        //     }
        //     foundId = false;
        // }

        that.collection.reset(collection.models);
        that.addEvents();
    },

    // generatePayPeriodStyleMapping: function (data) {
    //     var inventory = [];
    //     var totalStyles = this.styles.length;
    //     var currentStyle = 0;
    //     for (var i = 0; i < data.length; i++) {
    //         if (inventory.indexOf(data[i].employee) < 0) {
    //             inventory.push(data[i].employee);
    //             this.inventoryStyleMapping[data[i].employee] = this.styles[currentStyle];
    //             if (currentStyle < totalStyles - 1) {
    //                 currentStyle++;
    //             } else {
    //                 currentStyle = 0;
    //             }
    //         }
    //     }
    // },

    // rerenderCalandar: function () {
    //     that.renderedCalander = false;
    //     that.renderedErrors = false;
    // },

    renderCalendar: function () {
        var that = this;
        var today = new Date();
        var previousCell = null;
        $('.modal').modal();
        that.itemMapping = {};
        that.itemQtyMapping = {};
        var locale = App.rtl ? 'he' : 'en';
        var nextPrevButtonds = App.rtl ? 'next,prev, today' : 'prev,next, today';
        $('#calendar').one('calendar').fullCalendar({
            eventColor: "#ff0000",
            defaultDate: today,
            displayEventTime: false,
            eventStartEditable: false,
            editable: true,
            locale: locale,
            header: {
                left:  nextPrevButtonds,
                // left: 'prev,next',
                center: 'title',
                right: ''
            },
            dayRender: function (date, cell) {
               
                if ( that.payPeriodInfo.periodDuration > 0 ) {
                    var periodEndDate = new Date(that.payPeriodInfo.periodEnd);
                    var periodStartDate = moment(that.payPeriodInfo.periodEnd);
                    periodStartDate.add(-1 * (that.payPeriodInfo.periodDuration -1 ),'days');
                    periodStartDate = periodStartDate.toDate();


                    let newDate = date.toDate();
                    newDate.setHours(0,0,0,0);
                    periodEndDate.setHours(0,0,0,0);
                    periodStartDate.setHours(0,0,0,0);
                    
                    if ( newDate.getTime() >= periodStartDate.getTime() &&
                        newDate.getTime() <= periodEndDate.getTime() ) {
                        if (App.serverInfo.isRightToLeft) {
                            cell.css("background-color", "#97CAEB");
                        } 
                        else if (previousCell != null) {
                            previousCell.css("background-color", "#97CAEB");
                        }
                    }
                    previousCell = cell;
                }
            },
            eventClick: function (calEvent, jsEvent, view) {
                that.clickDate(calEvent.start.format('YYYY-MM-DD'));
            },
            dayClick: function(calEvent, jsEvent, view) {
                that.clickDate(calEvent.format("YYYY-MM-DD"));
            },
            viewRender: function() {
                that.renderedCalander = false;
                that.renderedErrors = false;
            },
           
        });

    },

    renderEmployeeTimes2: function () {
        var that = this;
        document.getElementById("employeeHoursForm").innerHTML = "";
        var html = "";

        that.employees.forEach( employee => {
            var employeeHasDates = false;
            var thisHtml = "<div id = '" + employee.id + "Div'> " + employee.name +"<hr size=2>";
            thisHtml += '<table class="table highlight" id="' + employee.id + 'Table"><thead><tr><th>{Literal}In{/Literal}</th><th>{Literal}Out{/Literal}</th><th>{Literal}Pay Level{/Literal}</th></thead><tbody>'
            
            that.badDates.forEach( date => {
                if(date.employeeId === employee.id){
                    employeeHasDates = true;
                    var timeIn = date.in === "" ? "---------------- --:--:--" : toDateTimeString(date.in);
                    var timeOut = date.out === "" ? "---------------- --:--:--" : toDateTimeString(date.out);
                    var payLevel = that.payTypes[date.payLevel - 1] === undefined ? "" : that.payTypes[date.payLevel - 1];
                    thisHtml +=  '<tr class="timeClass" style="color:red;" data-id="' + date.timeId + '"><td class="in">' +  timeIn + '</td> <td class="out">' +  timeOut + '</td><td class="payLevel">' + payLevel + '</td></tr>';
                }
            });
            
            that.goodDates.forEach( date => {
                if(date.employeeId === employee.id){
                    employeeHasDates = true;
                    var payLevel = that.payTypes[date.payLevel - 1] === undefined ? "" : that.payTypes[date.payLevel - 1];
                    thisHtml += '<tr class="timeClass" data-id="' + date.timeId + '"><td class="in">' + toDateTimeString(date.in) + '</td> <td class="out">' + toDateTimeString(date.out) + '</td><td class="payLevel">' + payLevel + '</td></tr>';
                }
            });

            thisHtml += "</tbody></table></div></br>";
            if(employeeHasDates)
                html += thisHtml;
        });

        $('#employeeHoursForm').append(html);
        var viewAllHoursFormModal = this.$el.find('#view-all-hours-modal').modal();
        viewAllHoursFormModal.modal('open');
    },

    handleTimeClick: function (e) {
        var element = $(e.currentTarget);
        var id = $(element).attr('data-id');

        var dates = [];
        for (var i = 0; i < this.collection.models.length; i++) {
            dates.push(this.collection.models[i].attributes);
        }

        var chosenDate = null;
        for (var i = 0; i < dates.length; i++) {
            if (dates[i].timeId == id) {
                chosenDate = dates[i];
            }
        }

        if (chosenDate != null) {
            var timeIn = new Date(chosenDate.in);
            var timeOut = new Date(chosenDate.out);

            if (!isNaN(timeIn.getTime())) {
                var test = moment(timeIn).format('YYYY-MM-DD');
            }
            else if (!isNaN(timeOut.getTime())) {
                var test = moment(timeOut).format('YYYY-MM-DD');
            }
        }

        var that = this;
        this.payPeriodsFormView = new PayPeriodsFormView({
            template: this.payPeriodsFormTemplate,
            chosenDate: test,
            collection: this.collection,
            employees: this.employees,
            payTypes: this.payTypes,
            parentModal: that,
            payPeriodInfo: that.payPeriodInfo,
            goodDates: that.goodDates,
            badDates: that.badDates,
            renderCalendar: that.renderCalendar,
            getPayPeriods: that.getPayPeriods,
            renderPayPeriods: that.renderPayPeriods,
            addEvents: that.addEvents,
            breakTypes:  this.breakTypes

        });

        this.$el.find('#pay-periods-form-modal').html(this.payPeriodsFormView.render().el);
        this.formModal.modal('open');
    }
});