var HomeView = Backbone.View.extend({
    breadcrumb: {},
    chartRendered: false,
    openOrders: 0,
    totalTransactions: 0,
    sequenceRows: 3,
    sequenceColumns: 4,
    sequencesTotal: 0,
    resetAccess: false,
    readAccess: false,
    resetCurrentAccess: false,
    zOutSummary: {},
    salesByItemType: {},
    noSalesCount: 0,
    creditCardCount: 0,
    creditCardTotal: 0,
    debitCardCount: 0,
    startingCash: 0,
    otherTips: 0,
    creditCardTips: 0,
    qtyItemTypes: {},
    resetReportsMapping: {},
    showCustomerCashSales: false,
    userBySalesRevenue: true,
    salesLabels: null,
    chosenSequence: '',
    chosenTill: '',
    sequences: {},
    dayStartTime: 0,
    dateRange: {},
    
    deliveryCount: 0,
    deliveryGuestCount: 0,
    deliveryTotal: 0,

    dineInCount: 0,
    dineInGuestCount: 0,
    dineInTotal: 0,

    takeOutCount: 0,
    takeOutGuestCount: 0,
    takeOutTotal: 0,

    chartSelectedLocations: [],
    tenderCodes: [],
    renderSalesLocations: false,

    chartDataColors: [
        '#d1d1d1',
        '#a156c4',
        '#ebc143',
        '#8097a2',
        '#39c7c1',
        '#000000'
    ],
    dataColorIndex: 5,
    labeledDataColors: {},

    events: {
        'click .quicklink-card-title': 'toggleCard',
        'click .ap-collection-item': 'toggleTillSelection',
        'click .generate-button': 'handleGenerateAction',
        'click #firstSeeMore' : 'showFirstTable',
        'click #secondSeeMore' : 'showSecondTable',
        'click #thirdSeeMore': 'showThirdTable',
        'click #fourthSeeMore': 'showFourthTable',
        'click #fifthSeeMore': 'showFifthTable',
        'click #sixthSeeMore': 'showSixthTable',
        'click #compSeeMore': 'showCompTable',
        'click #salesHourSeeMore' : 'showSalesHourTable',
        'click #salesByCategorySeeMore' : 'showSalesByCategoryTable',
        'click #salesByTypeSeeMore' : 'showSalesByTypeTable',
        'click #salesByUserSeeMore' : 'showSalesByUserTable',
        'click #salesByCustomerSeeMore' : 'showSalesByCustomerTable',
        'click #employeeHourSeeMore' : 'showEmployeeHoursTable',
        'click #locationsSeeMore' : 'showLocationsTable',
        'change #date-range-preset' : 'changeDateRange',
        'change #till-dropdown' : 'changeDateRange',
        'change #report-type-filter' : 'changeReportFilter',
        'click .choose-date-range-button': 'customDateRange',
        'keyup #reset-report-autocomplete': 'searchResetReportBySearchTerm',
        'click #byHourRevenue': 'showByHourRevenue',
        'click #byHourQuantity': 'showByHourQuantity',
        'click #topItemsByType': 'showTopItemsByType',
        'click #topItems': 'showTopItems',
        'click #showCashSales' : 'showCashSales',
        'click #hideCashSales' : 'hideCashSales',
        'click #userByRevenue' : 'showUserByRevenue',
        'click #userByHour' : 'showUserByHour',
        'click #exportToExcel' : 'exportToExcel',
        'click #emailReport' : 'openEmailReportModel',
        'click #sendEmailReport' : 'sendEmailReport',
        'click #sequence-modal-trigger': 'openSequenceModal',
        'click .sendSequence' : 'generateResetReport',
        'click .pagination-trigger': 'handlePageClickEvent',
        'click #pagination-back': 'handlePageBackEvent',
        'click #pagination-forward': 'handlePageForwardEvent',
        'click #locationIcon' : 'selectAllLocations',
        'click #salesByTypeTable thead, #salesHourTable thead': 'showHideDetailsCategoryChilde',
        'keyup #filterByItem' : 'searchItemBySearchTerm',
    },

    initialize: async function (options) {
        Number.prototype.toCurrency = function(fractionDigits = 0) {
            return this.valueOf().toLocaleString('en-US',{ maximumFractionDigits: fractionDigits, minimumFractionDigits: fractionDigits });
        };
        this.template = _.template(options.template);
        this.breadcrumb = options.breadcrumb;
        await this.getDayStartTime();
        await this.initializeSequenceModal();
    },

    render: function () {
        var that = this;
        App.breadCrumbToolTip = "Your main screen to see live sales, run reports, and reset tills";
        App.setBreadcrumbs(this.breadcrumb);
        
        $(document).ready(function () {
            $('.tooltipped').tooltip({delay: 0});
            $('select:not(#location-dropdown)').formSelect();
            $('.dropdown-trigger').dropdown();
            $('.quicklink-card-content').mCustomScrollbar({
                setHeight: 150,
                axis: 'y',
                scrollInertia: 1000,
                autoHideScrollbar: true
            });
            var pickerElement = document.querySelectorAll('.datepicker');
            var instances = M.Datepicker.init(pickerElement, {
                autoClose: true,
                container: 'body',
                format: 'yyyy-mm-ddT00:00:00',
                i18n: App.i18n
            });
            that.datepicker = instances;

        });

        return this;
    },

    isTabletDevice: function() {
        try {
            var deviceWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
            return deviceWidth < 769;
        } catch (e) {
            return false;
        }
    },

    toggleCard: function (e) {
        var element = $(e.currentTarget);
        $("html, body").animate({ scrollTop: $(document).height() }, "fast");
        
        var siblings = $(element).siblings();
        
        $('.quicklink-card-content, .quicklink-card-footer').not(siblings).hide();
        $(siblings).toggle();
    },

    toggleTillSelection: function (e) {
        var element = $(e.currentTarget);
        var tillHasOpenOrders = $(element).hasClass('ap-collection-item-disabled');
        if (tillHasOpenOrders === false) {
            var previouslySelected = $(element).hasClass('ap-light-blue');
            if ($(element).parent().hasClass('master-z-till-list') === false) {
                $(element).siblings().each(function() {
                    $(this).removeClass('ap-light-blue');
                    $(this).find('.ready, .open-orders, till-users').removeClass('white-text');
                    $(this).attr('data-selected', 'false');
                });
            }
            $(element).toggleClass('ap-light-blue');
            $(element).find('.ready, .open-orders, till-users').toggleClass('white-text');
            
            $(element).attr('data-selected', !previouslySelected ? 'true' : 'false');
            this.toggleButton(element);
        } else {
            M.toast({
                html: '{Literal}You cannot Z-out tills with open orders{/Literal}'
            });
        }
    },

    initializeSequenceModal: async function () {
        var sequencesPerPage = this.sequenceColumns * this.sequenceRows;
        await this.getSequences();
    },

    getSequences: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sequences',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.sequences = data.results; 
                that.getCustomers();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    getSequencesPagination:function (pageSize, pageNumber, callback, callbackArgs) {
        $("#sequence-modal-preloader").show();
        $("#sequences-wrapper").hide();
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sequences',
            data: {
                offset: pageSize,
                pageNumber: pageNumber,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                $("#sequence-modal-preloader").hide();
                $("#sequences-wrapper").show();
                callback(data.results, callbackArgs);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    $("#sequences-wrapper").show();
                    $("#sequence-modal-preloader").hide();
                    M.toast({
                        html: '{Literal}There was a problem fetching the sequences from the server{/Literal}'
                    });
                }
            }
        });
    },


    openSequenceModal: function () {
        this.initializePaginator();
        $('#sequence-modal').modal().modal('open');
    },

    initializePaginator: function () {
        this.getSequencesTotalCount();
    },

    renderPaginator: function (sequencesTotalCount) {
        $('.pagination-trigger').remove();

        this.pages = Math.ceil(1.0 * sequencesTotalCount / (this.sequenceRows * this.sequenceColumns));
        var currentPageElement = $('<li class="active ap-blue pagination-trigger" data-page="1"><a href="javascript:void(0)">1</a></li>');
        $("#pagination-back").after(currentPageElement);
        for (var i = 2; i <= this.pages; i++) {
            var lastElement = currentPageElement;
            currentPageElement = $('<li class="waves-effect pagination-trigger" data-page="' + i + '"><a href="javascript:void(0)">' + i + '</a></li>');
            $(lastElement).after(currentPageElement);
        }
        $("#sequence-pagination").show();
    },

    handlePageBackEvent: function (e) {
        var element = $(e.currentTarget);
        if ($(element).hasClass('disabled') === false) {
            var currentPage = parseInt($("#sequence-pagination").attr("data-current-page"));
            this.goToSequencePage(currentPage - 1, -1);
        }
    },

    handlePageForwardEvent: function (e) {
        var element = $(e.currentTarget);
        if ($(element).hasClass('disabled') === false) {
            var currentPage = parseInt($("#sequence-pagination").attr("data-current-page"));
            this.goToSequencePage(currentPage + 1, -1);
        }
    },

    handlePageClickEvent: function (e) {
        var element = $(e.currentTarget);
        var selectedPage = parseInt($(element).attr('data-page'));

        var currentPage = parseInt($("#sequence-pagination").attr("data-current-page"));
        this.goToSequencePage(selectedPage, currentPage);
    },

    goToSequencePage: function (selectedPage, currentPage) {
        if (selectedPage !== currentPage) {
            $("#selected-sequence").val('');
            var element = $(".pagination-trigger[data-page=" + selectedPage + "]");
            $('.pagination-trigger')
                .removeClass('ap-blue')
                .removeClass('active')
                .addClass('waves-effect');
            var offset = this.sequenceColumns * this.sequenceRows;
            var start = offset * (selectedPage - 1);
            var args = {
                selectedPage: selectedPage,
                element: element,
                parentView: this
            };
            this.getSequencesPagination(offset, selectedPage, this.renderPaginationChange, args);
        }
    },

    renderPaginationChange: function (sequences, args) {
        var that = args.parentView;
        var selectedPage = args.selectedPage;
        var element = args.element;
        var sequenceCollection = new SequenceCollection();
        for (var i = 0; i < sequences.length; i++) {
            sequenceCollection.add(new Sequence({
                id: sequences[i].id,
                till: sequences[i].till,
                startTime: sequences[i].start,
                endTime: sequences[i].end
            }));
        }
        
        $("#sequence-pagination").attr("data-current-page", selectedPage);

        $("#sequenceRow").html("");
        for (var i = 0; i < sequenceCollection.models.length; i++) 
        {
            var thisSequenceModel = sequenceCollection.models[i].attributes;
            var html = '';
            html += '<div class="col s12 m3">';
            html += '<div class="card-panel card-panel-entity z-depth-1 sequence-card hoverable waves-effect waves-light sendSequence" style="background-color: #ffffff" till-id="' + thisSequenceModel.till + '" data-id="' + thisSequenceModel.id + '" data-selected="0">';
            html += '<div class="card-panel-content">';
            html += '<div class="row sequence-title-badge">' + thisSequenceModel.id + '</div>';
            html += '<div class="row"> {Literal}Seq{/Literal}. #' + thisSequenceModel.id + '</div>';
            html += '<div class="row"> {Literal}Till:{/Literal} ' + thisSequenceModel.till + '</div>';
            html += '<div class="row"> {Literal}Start{/Literal}: ' + moment(thisSequenceModel.start).format('YYYY-MM-DD HH:mm') + '</div>';
            html += '<div class="row"> {Literal}End{/Literal}: ' + moment(thisSequenceModel.end).format('YYYY-MM-DD HH:mm') + '</div>';
            html += '</div></div></div>';
            $('#sequenceRow').append(html)
        }

        $(element).addClass('active').addClass('ap-blue').removeClass('waves-effect');
        if (selectedPage === 1) {
            $("#pagination-back").addClass('disabled').removeClass('waves-effect');
            $("#pagination-forward").removeClass('disabled').addClass('waves-effect');
        } else if (selectedPage === that.pages) {
            $("#pagination-back").removeClass('disabled').addClass('waves-effect');
            $("#pagination-forward").addClass('disabled').removeClass('waves-effect');
        } else {
            $("#pagination-back").removeClass('disabled').addClass('waves-effect');
            $("#pagination-forward").removeClass('disabled').addClass('waves-effect');
        }
    },

    // initializeSequenceModal: function () {
    //     $("#sequence-modal-preloader").hide();
    //     this.initializePaginator();
    //     var sequencesPerPage = this.sequenceColumns * this.sequenceRows;
    //     var sequences = this.getSequences(sequencesPerPage, 1, this.renderSequenceModal, { parentView: this });
    // },

    renderSequenceModal: function (sequences, args) {
        var that = args.parentView;
        that.sequenceCollection = new SequenceCollection();
        for (var i = 0; i < sequences.length; i++) {
            that.sequenceCollection.add(new Sequence({
                id: sequences[i].id,
                till: sequences[i].till,
                startTime: sequences[i].start,
                endTime: sequences[i].end
            }));
        }
        
        if (typeof that.sequenceTilesTemplate === 'undefined' || that.sequenceTilesTemplate === null) {
            $.get("templates/sequenceTiles.html").done(function (sequenceTilesTemplate) {
                that.sequenceTilesTemplate = sequenceTilesTemplate;
                that.sequenceTilesView = new SequenceTilesView({
                    template: that.sequenceTilesTemplate,
                    collection: that.sequenceCollection
                });
                $("#sequences-wrapper").html(that.sequenceTilesView.render().el);
            });
        } else {
            that.sequenceTilesView = new SequenceTilesView({
                template: that.sequenceTilesTemplate,
                collection: that.sequenceCollection
            });
            $("#sequences-wrapper").html(that.sequenceTilesView.render().el);
        }
        $("#sequence-modal-preloader").hide();

    },

    getSequencesTotalCount: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sequence-total-count',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var count = data.results;
                that.sequencesTotal = count;
                that.renderPaginator(count);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

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

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

    renderTills: function (tills, that) {
        var noTillsWarning = true;
        for (var i = 0; i < tills.length; i++) {
            if (typeof tills[i].hasOrders !== 'undefined' && tills[i].hasOrders === true) {
                noTillsWarning = false;
                break;
            }
        }
        that.$el.html(that.template({
            tills: tills,
            sequences: that.sequences,
            noTillsWarning: noTillsWarning
        }));

        $('select:not(#location-dropdown)').formSelect();
        $('.dropdown-trigger').dropdown();
        var pickerElement = document.querySelectorAll('.datepicker');
        var instances = M.Datepicker.init(pickerElement, {
            autoClose: true,
            container: 'body',
            format: 'yyyy-mm-ddT00:00:00',
            
            i18n: App.i18n
        });
    },

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

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

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.responseJSON.hasAccess == false) {
                    that.readAccess = false;
                }
            }
        });
        $.ajax({
            url: '/data/check-access',
            data: {
                accessName: (App.IDS_Z),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

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

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else if (e.responseJSON.hasAccess == false) {
                    that.resetAccess = false;
                }
            }
        });
        $.ajax({
            url: '/data/check-access',
            data: {
                accessName: (App.IDS_Z_CURRENT_TILL),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

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

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

    toggleButton: function (el) {
        var dataType = $(el).parent().attr('data-type');
        var elementSelected = $(el).attr('data-selected') === 'true';
        var oneOfSiblingsSelected = false;
        $(el).siblings().each(function() {
            oneOfSiblingsSelected = $(this).attr('data-selected') === 'true';
        });

        if (elementSelected || oneOfSiblingsSelected) {
            this.$el.find('.generate-button[data-type="' + dataType + '"]').removeClass('disabled');    
        } else {
            this.$el.find('.generate-button[data-type="' + dataType + '"]').addClass('disabled');    
        }        
    },

    openReportWindowWithPostRequest: function (winURL, params) {
        var winName='AccuPOS Report';
        var windowoption='resizable=yes,height=768,width=1024,location=0,menubar=0,scrollbars=1';
        var form = document.createElement("form");
        form.setAttribute("method", "post");
        form.setAttribute("action", winURL);
        form.setAttribute("target", winName);  
        for (var i in params) {
            if (params.hasOwnProperty(i)) {
                var input = document.createElement('input');
                input.type = 'text';
                input.name = i;
                input.value = params[i];
                form.appendChild(input);
            }
        }
        document.body.appendChild(form);
        window.open('', winName, windowoption);
        form.target = winName;
        form.submit();
        document.body.removeChild(form);           
    },

    handleGenerateAction: function (e) {
        var sessionToken = this.getCookie();
        var element = $(e.currentTarget);
        var type = $(element).attr('data-type');
        var that = this;
        var selectedTillsElements = this.$el.find('.ap-collection[data-type="' + type + '"]').find('.ap-collection-item[data-selected="true"]');
        var selectedTills = [];
        if (selectedTillsElements.length < 1) {
            return;
        }
        for (var i = 0; i < selectedTillsElements.length; i++) {
            selectedTills.push($(selectedTillsElements[i]).attr('data-id'));
        }
        
        if (type == 'x-out') {
            if (this.readAccess) {
                var params = {
                    selectedTill: selectedTills[0],
                    showGraphs: true,
                    token: sessionToken,
                    accessName: (App.IDS_X)
                };
                this.openReportWindowWithPostRequest('/data/get-x-out-report', params);
            }
            else {
                M.toast({ html: '{Literal}You do not have access to read cash tills{/Literal}' });
            }
        }
        else if (type == 'z-out') {
            if (this.resetCurrentAccess) {
                var tillTotal = this.$el.find('#z-out-total-cash').val();
                try {
                    tillTotal = parseFloat(tillTotal);
                } catch (e) {
                    tillTotal = 0.0;
                }
                var selectedTill = selectedTills[0];
                var params = {
                    selectedTill: selectedTill,
                    showGraphs: $('#z-out-show-graphs').is(':checked'),
                    tillTotal: tillTotal,
                    token: sessionToken,
                    accessName: (App.IDS_Z_CURRENT_TILL)
                };

                this.openReportWindowWithPostRequest('/data/get-z-out-report', params);
                var zShiftResetDiv = document.querySelector('.ap-collection[data-type=z-out]');
                zShiftResetDiv.querySelector(`[data-id="${selectedTill}"]`).remove();
                element.addClass('disabled');
                if(App.serverInfo.country == 'IL')
                    $('#z-out-message-modal').modal().modal('open');
            }
            else {
                M.toast({ html: '{Literal}You do not have access to reset the current cash tills{/Literal}' });
            }
        }
        else if (type == 'master-z') {
            if (this.resetAccess) {
                var params = {
                    selectedTills: selectedTills.join(','),
                    showGraphs: true,
                    token: sessionToken,
                    accessName: (App.IDS_Z)
                };
                this.openReportWindowWithPostRequest('/data/get-master-z-report', params);
                var zShiftResetDiv = document.querySelector('.ap-collection[data-type=master-z]');
                selectedTills.forEach( till => {
                    zShiftResetDiv.querySelector(`[data-id=${till}]`).remove();
                });
                element.addClass('disabled');
                if(App.serverInfo.country == 'IL')
                    $('#z-out-message-modal').modal().modal('open');
            }
            else {
                M.toast({ html: '{Literal}You do not have access to reset cash tills{/Literal}' });
            }
        }

        
    },

    renderCharts: function (currency, data) {
        var that = this;
        this.checkAccess();
        var shouldRenderCharts = typeof data.totalSales !== 'undefined' && data.totalSales > 0;
        
        if (!shouldRenderCharts) {
            this.$el.find('.no-data-message').show();
        } else {
            this.$el.find('.no-data-message').hide();
        }
        var salesByTime = data.salesByTimeData;

        var transactionByHourData = data.salesByTimeData.transactionByHourData;
        
        var salesByTenderTypeObj = data.salesByTenderType;
        
        var salesByItemTypeObj = data.salesByItemType;
        
        var salesByTimeColumns = (['Sales']).concat(salesByTime.salesData);
        var salesByTimeLabels = salesByTime.salesLabels;

        var noAMPMLabels = salesByTime.noAMPMLabels;

        var transactionByHourColumns = (['Sales']).concat(transactionByHourData);
        
        var salesByItemTypeColumns = ['Sales'];
        var salesByItemTypeLabels = [];
        for (var itemType in salesByItemTypeObj) {
            salesByItemTypeColumns.push(salesByItemTypeObj[itemType]);
            salesByItemTypeLabels.push(itemType);
        }

        var salesByTenderType = [];
        var salesByTenderTypeChart = [];
        var i = 0;
        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key) && obj[key] > 0) size++;
            }
            return size;
        };

        var size = Object.size(salesByTenderTypeObj);

        if(size > 0){
            //sort tenders
            salesByTenderTypeObj = Object.entries(salesByTenderTypeObj).sort((t1,t2) => t2[1] - t1[1]);
            var sorted = {};
            salesByTenderTypeObj.forEach((obj, i) => sorted[ (i+1) + ". "+ obj[0]] = obj[1]);
            salesByTenderTypeObj = sorted;

        }
        
        for (var tenderType in salesByTenderTypeObj) {
            if (!isNaN(Math.abs(parseFloat(salesByTenderTypeObj[tenderType]))) && Math.abs(parseFloat(salesByTenderTypeObj[tenderType])) != 0 && i < 5) {
                salesByTenderTypeChart.push(["{Literal}${/Literal}" + Math.abs(parseFloat(salesByTenderTypeObj[tenderType])).toCurrency() + " - " + tenderType, Math.abs(parseFloat(salesByTenderTypeObj[tenderType])).toFixed(0)]);
                i++;
            }
        }

        for (var tenderType in salesByTenderTypeObj) {
            if (!isNaN(Math.abs(parseFloat(salesByTenderTypeObj[tenderType]))) && Math.abs(parseFloat(salesByTenderTypeObj[tenderType])) != 0) {
                salesByTenderType.push(["{Literal}${/Literal}" + Math.abs(parseFloat(salesByTenderTypeObj[tenderType])).toCurrency(2) + " - " + tenderType, Math.abs(parseFloat(salesByTenderTypeObj[tenderType])).toCurrency(2)]);
            }
        }

        var salesByTimeColumnsEmpty = true;
        for (var i = 1; i < salesByTimeColumns.length; i++) {
            if (salesByTimeColumns[i] > 0) {
                salesByTimeColumnsEmpty = false;
            }
        }
        var salesChartType = 'spline';
        if(this.$el.find('#report-type-filter').val() == "zOutCloudSummary"){
            salesByTimeColumns = ["count"];
            salesByTimeLabels = [];
             Object.values(data.qtyItemTypes).map(i => salesByTimeColumns.push(i));
             Object.keys(data.qtyItemTypes).map(i => salesByTimeLabels.push(i));
            salesByTimeColumnsEmpty = false;
            salesChartType = 'bar'
        }
        if (salesByTimeColumnsEmpty ) {
            if (!this.chartRendered) {
                var that = this;
                var chart1 = c3.generate({
                    bindto: '#sales-line-chart',
                    size: {
                        height: 150,
                    },
                    legend: {
                        show: false
                    },
                    grid: {
                        y: {
                            show: true
                        }
                    },
                    data: {
                        colors: {
                            Sales: '#000000',
                        },
                        type: salesChartType,
                        columns: [ ],
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    point: {
                        show: false
                    },
                    axis: {
                        x: {
                            show: false,
                            type: 'category',
                            categories: salesByTimeLabels
                        },
                        y: {
                            tick: {
                                count: 5,
                                format: d3.format("d")
                            }
                        }
                    }
                });
            }
        }
        else {
            if (!this.chartRendered) {
                var that = this;
                var chart1 = c3.generate({
                    bindto: '#sales-line-chart',
                    size: {
                        height: 150,
                    },
                    legend: {
                        show: false
                    },
                    grid: {
                        y: {
                            show: true
                        }
                    },
                    data: {
                        colors: {
                            Sales: '#000000',
                        },
                        type: salesChartType,
                        colors: {
                            count: '#24c1e6'
                        },
                        columns: [ salesByTimeColumns ],
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    point: {
                        show: false
                    },
                    axis: {
                        x: {
                            show: false,
                            type: 'category',
                            categories: salesByTimeLabels
                        },
                        y: {
                            tick: {
                                count: 5,
                                format: d3.format("d")
                            }
                        }
                    },
                    bar: {
                        width: {
                            ratio: 0.75
                        }
                    }
                });
            }    
        }
        
        if (!this.chartRendered) {
            // var screenSize = this.isTabletDevice();
            
            if (salesByTenderTypeChart.length > 5) {
                var tenderTypesChart = c3.generate({
                    bindto: '#sales-donut-chart',
                    legend: {
                        show: false
                    },
                    size: {
                        height: 150
                    },
                    data: {
                        columns: salesByTenderTypeChart,
                        type: 'donut',
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    donut: {
                        title: ""
                    }
                });
            }
            else {
                var tenderTypesChart = c3.generate({
                    bindto: '#sales-donut-chart',
                    legend: {
                        position: 'right'
                    },
                    size: {
                        height: 150
                    },
                    data: {
                        columns: salesByTenderTypeChart,
                        type: 'donut',
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    donut: {
                        title: ""
                    }
                });
            }
            
            this.dataColorIndex = 0;
            this.labeledDataColors = {};
            if (salesByTimeColumnsEmpty) {
                var chart3 = c3.generate({
                    bindto: '#sales-bar-chart',
                    size: {
                        height: 150
                    },
                    grid: {
                        y: {
                            show: true
                        }
                    },
                    data: {
                        color: function (color, d) { return '#3754a0' },
                        columns: [],
                        type: 'bar',
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    legend: {
                        show: false
                    },
                    /*tooltip: {
                        format: {
                            title: function (d) { return 'Data ' + d; },
                            value: function (value, ratio, id) {
                                
                                return (value);
                            }
                //            value: d3.format(',') // apply this format to both y and y2
                        }
                    },*/
                    axis: {
                        x: {
                            show: false,
                            type: 'category',
                            categories: salesByTimeLabels
                        },
                        y: {
                            tick: {
                                format: d3.format(",d"),
                                count: 5
                            }
                        }
                    },
                    bar: {
                        width: {
                            ratio: 0.75
                        }
                    }
                });
            }
            else {
                var chart3 = c3.generate({
                    bindto: '#sales-bar-chart',
                    size: {
                        height: 150
                    },
                    grid: {
                        y: {
                            show: true
                        }
                    },
                    data: {
                        color: function (color, d) { return '#3754a0' },
                        columns: [salesByTimeColumns],
                        type: 'bar',
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    legend: {
                        show: false
                    },
                    /*tooltip: {
                        format: {
                            title: function (d) { return 'Data ' + d; },
                            value: function (value, ratio, id) {
                                
                                return (value);
                            }
                //            value: d3.format(',') // apply this format to both y and y2
                        }
                    },*/
                    axis: {
                        x: {
                            show: false,
                            type: 'category',
                            categories: salesByTimeLabels
                        },
                        y: {
                            tick: {
                                format: d3.format(",d"),
                                count: 5
                            }
                        }
                    },
                    bar: {
                        width: {
                            ratio: 0.75
                        }
                    }
                }); 
            }

            if(this.renderSalesLocations) {
                var labels = [];
                var values = [];

                    if(data.locationsSummary != undefined && Object.keys(data.locationsSummary).length > 0){
                        var index = 0;
                        Object.keys(data.locationsSummary).map(function (key) {
                            that.chartSelectedLocations.push({id: index, location: key, selected: true})
                            labels.push(key);
                            index++;
                        }); 

                        Object.values(data.locationsSummary).map(function (val) { 
                
                            // Using Number() to convert key to number type 
                            // Using obj[key] to retrieve key value 
                            values.push(val); 
                        });
                        values =  ['',...values];
                        // values = $('#location-dropdown').val();
                    }
                    
                    this.$el.find('#locationsSummaryContainer').show();
                    var chart3 = c3.generate({
                        bindto: '#locations-sales-bar-chart',
                        size: {
                            height: 230,
                        },
                        grid: {
                            y: {
                                show: true
                            }
                        },
                        data: {
                            selection: {
                                enabled: true,
                                multiple: true,
                            },
                            onclick: function(d, element) {
                                that.renderSalesLocations = false;
                                if(that.isFirstLocationClick){
                                    that.isFirstLocationClick = false;
                                    var barIndexes = chart3.data()[0].values.map( i => i.index);
                                    chart3.select('',barIndexes);
                                    chart3.unselect('',[d.index]);
                                    that.chartSelectedLocations.forEach( i => i.selected = false);
                                    that.chartSelectedLocations[d.index].selected = true;
                                } else {
                                    that.chartSelectedLocations[d.index].selected = !that.chartSelectedLocations[d.index].selected;
                                }
                                that.calculateDataBySelectedLocation();
                            },
                            color: function (color, d) { return '#3754a0' },
                            columns: values.length == 0 ? [] : [values],
                            type: 'bar',
                            empty: {
                                label: {
                                    text: "{Literal}No Data Available{/Literal}"
                                }
                            }
                        },
                        legend: {
                            show: false
                        },
                        /*tooltip: {
                            format: {
                                title: function (d) { return 'Data ' + d; },
                                value: function (value, ratio, id) {
                                    
                                    return (value);
                                }
                    //            value: d3.format(',') // apply this format to both y and y2
                            }
                        },*/
                        axis: {
                            x: {
                                tick: {
                                    multiline: false,
                                    rotate: -45,
                                },
                                show: true,
                                type: 'category',
                                categories: labels
                            },
                            y: {
                                tick: {
                                    format: d3.format(",d"),
                                    count: 5
                                }
                            }
                        },
                        bar: {
                            width: {
                                ratio: 0.75
                            }
                        }
                    });
                    this.locationsChart = chart3;
                    this.$el.find('#locations-sales-bar-chart').show();
            }   

            if (App.serverInfo.isFoodService) {
                var tipsByType = [];
                var tipsEmpty = false
                if (this.otherTips == undefined && this.creditCardTips == undefined && data.zOutSummary.autoGratuity == undefined) {
                    tipsEmpty = true;
                }
                else {
                    tipsByType[0] = ['{Literal}Other Tips{/Literal}', this.otherTips];
                    tipsByType[1] = ['{Literal}Credit Card Tips{/Literal}', this.creditCardTips];
                    tipsByType[2] = ['{Literal}Auto Gratuity{/Literal}', data.zOutSummary.autoGratuity];
                }
                
                if (tipsEmpty) {
                    var tenderTypesChart = c3.generate({
                        bindto: '#tips-bar-graph',
                        legend: {
                            position: 'right'
                        },
                        size: {
                            height: 150
                        },
                        data: {
                            colors: {
                                '{Literal}Other Tips{/Literal}': '#3754a0',
                                '{Literal}Credit Card Tips{/Literal}': '#24c1e6',
                                '{Literal}Auto Gratuity{/Literal}': '#11b5ae',
                            },
                            columns: [],
                            type: 'pie',
                            empty: {
                                label: {
                                    text: "{Literal}No Data Available{/Literal}"
                                }
                            }
                        },
                        donut: {
                            title: ""
                        }
                    });
                }
                else {
                    var tenderTypesChart = c3.generate({
                        bindto: '#tips-bar-graph',
                        legend: {
                            position: 'right'
                        },
                        size: {
                            height: 150
                        },
                        data: {
                            colors: {
                                '{Literal}Other Tips{/Literal}': '#3754a0',
                                '{Literal}Credit Card Tips{/Literal}': '#24c1e6',
                                '{Literal}Auto Gratuity{/Literal}': '#11b5ae',
                            },
                            columns: tipsByType,
                            type: 'pie',
                            empty: {
                                label: {
                                    text: "{Literal}No Data Available{/Literal}"
                                }
                            }
                        },
                        donut: {
                            title: ""
                        }
                    });
                }
                

                var test = [];
                test.push('Sales');
                test.push(parseInt(data.dineInTotal.toFixed(2)));
                test.push(parseInt(data.takeOutTotal.toFixed(2)));
                test.push(parseInt(data.deliveryTotal.toFixed(2)));

                var test1 = [];
                test1[0] = ['{Literal}Dine-In{/Literal}', parseInt(data.dineInTotal.toFixed(2))];
                test1[1] = ['{Literal}Take-Out{/Literal}', parseInt(data.takeOutTotal.toFixed(2))];
                test1[2] = ['{Literal}Delivery{/Literal}', parseInt(data.deliveryTotal.toFixed(2))];

                var diningEmpty = false;
                if (data.dineInTotal == 0 && data.takeOutTotal == 0 && data.deliveryTotal == 0) {
                    var tenderTypesChart = c3.generate({
                        bindto: '#dining-bar-graph',
                        legend: {
                            hide: true
                        },
                        size: {
                            height: 150
                        },
                        
                        data: {
                            columns: [], 
                            labels: {
                                show: true,
                                format: {
                                    Sales: d3.format('d'),
                                }  
                            },
                            type: 'bar',
                            empty: {
                                label: {
                                    text: "{Literal}No Data Available{/Literal}"
                                }
                            }
                        },
                        color: {
                            pattern: ['#3754a0', '#11b5ae', '#24c1e6']
                        },
                        axis: {
                            rotated: true,
                            x: {
                                type: 'category',
                                categories: ['{Literal}Dine-In{/Literal}', '{Literal}Take-Out{/Literal}', '{Literal}Delivery{/Literal}']
                            },
                            y: {
                                show: false,
                            }
                        },
                    });
                }
                else {
                    var tenderTypesChart = c3.generate({
                        bindto: '#dining-bar-graph',
                        legend: {
                            hide: true
                        },
                        size: {
                            height: 150
                        },
                        
                        data: {
                            columns: [test], 
                            labels: {
                                show: true,
                                format: {
                                    Sales: d3.format('d'),
                                }  
                            },
                            type: 'bar',
                            empty: {
                                label: {
                                    text: "{Literal}No Data Available{/Literal}"
                                }
                            }
                        },
                        color: {
                            pattern: ['#3754a0', '#11b5ae', '#24c1e6']
                        },
                        axis: {
                            rotated: true,
                            x: {
                                type: 'category',
                                categories: ['{Literal}Dine-In{/Literal}', '{Literal}Take-Out{/Literal}', '{Literal}Delivery{/Literal}']
                            },
                            y: {
                                show: false,
                            }
                        },
                    });
                }
                
                
            }
        }
        if (data.zOutSummary != '') {
            this.appendToTables(salesByTenderType, data.locationsSummary);
        }
       
    },

    getSalesData: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sales-data',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.zOutSummary = data.zOutSummary;
                that.salesByItemType = data.salesByItemType;
                that.noSalesCount = data.noSaleCount;
                that.creditCardCount = data.creditCardCount;
                that.creditCardTotal = data.creditCardTotal;
                that.debitCardCount = data.debitCardCount;
                that.startingCash = data.startingCash;
                that.otherTips = data.otherTips;
                that.creditCardTips = data.creditCardTips;
                that.qtyItemTypes = data.qtyItemTypes;

                var insertTotalTransactions = document.getElementById('transactionCount');
                if (data.totalTransactions == 0) {
                    insertTotalTransactions.value = 0;
                    that.totalTransactions = 0;
                }
                else {
                    insertTotalTransactions.value = data.totalTransactions;
                    that.totalTransactions = data.totalTransactions;
                }

                that.deliveryCount = data.deliveryCount;
                that.deliveryGuestCount = data.deliveryGuestCount;
                that.deliveryTotal = data.deliveryTotal;

                that.dineInCount = data.dineInCount;
                that.dineInGuestCount = data.dineInGuestCount;
                that.dineInTotal = data.dineInTotal;

                that.takeOutCount = data.takeOutCount;
                that.takeOutGuestCount = data.takeOutGuestCount;
                that.takeOutTotal = data.takeOutTotal;

                that.totalSales =  Math.round(data.totalSales * 100) / 100;
                that.largestTransaction = Math.round(data.largestTransaction * 100) / 100;
                that.totalItemsSold = data.totalItemsSold;

                that.cashTransactions = data.cashCount;

                var test = "{Literal}${/Literal}";
                document.getElementById('totalSales').value = test + that.totalSales.toCurrency();
                if (data.zOutSummary != '') {
                   document.getElementById('totalTender').value = test + data.zOutSummary.tenderingTotal.toCurrency();
                }
                

                var currency = 'USD';
                that.$el.find('.preloader-col').hide();
                that.$el.find('.chart-content').show();
                that.renderCharts(currency, data);

                //var test = document.getElementById("dates");
                var thruDate = new Date();
                var fromDate = new Date();

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

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

                dates.innerHTML = fromDate + "  -  " + thruDate;

                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
        this.$el.find('#loading').hide();
    }, 

    getCustomers: 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++) {
                    if (data.results[i].openOrderCount != 'undefined' && data.results[i].openOrderCount > 0) {
                        that.openOrders += (data.results[i].openOrderCount)
                    }
                }

                that.getTillsAndRender(that.renderTills);

                if(App.serverInfo.hasCloudReporting){
                    that.getLocationsAndRender(that.renderLocations, that);
                    that.getTenderTypes();
                }
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem getting customers{/Literal}.' });
                }
            }
        });
    },

    appendToTables: function (salesByTenderType, locationsSummary) {
        var that = this;
        var zOutSummary = this.zOutSummary;

        $("#discountTable tbody").empty();
        $('#discountTable tbody').append('<tr><td>{Literal}Comp Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  zOutSummary.compTotal.toFixed(2) + '</td></tr>');
        $('#discountTable tbody').append('<tr><td>{Literal}Sales Discount Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  zOutSummary.salesDiscountTotal.toFixed(2) + '</td></tr>');
        $('#discountTable tbody').append('<tr><td>{Literal}Price Change Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  zOutSummary.priceChangeTotal.toFixed(2) + '</td></tr>');
        var disCounts = (zOutSummary.compTotal + zOutSummary.salesDiscountTotal + zOutSummary.priceChangeTotal);
        $('#discountTable tbody').append('<tr><td>{Literal}Discounts Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  disCounts.toFixed(2) + '</td></tr>');

        $("#secondGraphTable tbody").empty();
        $('#secondGraphTable tbody').append('<tr><td>{Literal}No Sales Count{/Literal}</td><td style="color: black; float: right; direction: RTL;">' +  this.noSalesCount + '</td></tr>');
        $('#secondGraphTable tbody').append('<tr><td>{Literal}Credit Transactions{/Literal}</td><td style="color: black; float: right; direction: RTL;">' +  this.creditCardCount + '</td></tr>');
        $('#secondGraphTable tbody').append('<tr><td>{Literal}Debit Transactions{/Literal}</td><td style="color: black; float: right; direction: RTL;">' +  this.debitCardCount + '</td></tr>');
        $('#secondGraphTable tbody').append('<tr><td>{Literal}Debit Transactions{/Literal}</td><td style="color: black; float: right; direction: RTL;">' +  this.debitCardCount + '</td></tr>');
        $('#secondGraphTable tbody').append('<tr><td>{Literal}Cash Transactions{/Literal}</td><td style="color: black; float: right; direction: RTL;">' +  this.cashTransactions + '</td></tr>');

        if(this.renderSalesLocations) {
            $("#locationsGraphTable tbody").empty();
            if(locationsSummary != undefined){
                var locations = Object.keys(locationsSummary);
                locations.forEach( l => {
                    $('#locationsGraphTable tbody').append(
                        '<tr><td>'+ l +'</td><td style="color: black; float: right; direction: RTL;">' + locationsSummary[l].toFixed(2) + '</td></tr>');
                });
            }
        }
        
        $("#thirdGraphTable tbody").empty();
        $('#thirdGraphTable tbody').append('<tr><td>{Literal}Starting Cash{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  this.startingCash.toCurrency(2) + '</td></tr>');
        $('#thirdGraphTable tbody').append('<tr><td>{Literal}Total Cash{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  (this.startingCash + zOutSummary.netCash - zOutSummary.payoutsTotal).toCurrency(2) + '</td></tr>');
        $('#thirdGraphTable tbody').append('<tr><td><br></td></tr>');
        $('#thirdGraphTable tbody').append('<tr><td>{Literal}Payments On Account{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  zOutSummary.customerPayments.toCurrency(2) + '</td></tr>');
        $('#thirdGraphTable tbody').append('<tr><td>{Literal}Cash Paid Out{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.payoutsTotal.toCurrency(2)  + '</td></tr>');
        $('#thirdGraphTable tbody').append('<tr><td>{Literal}Net Cash{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.netCash.toCurrency(2)  + '</td></tr>');
        $('#thirdGraphTable tbody').append('<tr><td>{Literal}Total Credit Card{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + this.creditCardTotal.toCurrency(2)  + '</td></tr>');
        $("#thirdGraphTable tbody").append("<br>");
        for (var i = 0; i < salesByTenderType.length; i++) {
            var splitTenders = salesByTenderType[i][0].split("-")
            $('#tenderGraphTable').append('<tr><td>' + splitTenders[1] + '</td><td style="color: black; float: right; direction: RTL;">' +  splitTenders[0] + '</td></tr>');
        }
        

        $("#taxTable tbody").empty();
        $('#taxTable tbody').append('<tr><td>{Literal}Taxable{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.reportTaxable.toCurrency(2)  + '</td></tr>');
        $('#taxTable tbody').append('<tr><td>{Literal}Nontaxable{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.reportNontaxable.toCurrency(2)  + '</td></tr>');
        $('#taxTable tbody').append('<tr><td>{Literal}Tax Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.taxTotal.toCurrency(2)  + '</td></tr>');
        $('#taxTable tbody').append('<tr><td><br></td></tr>');
        $('#taxTable tbody').append('<tr><td>{Literal}Auto Gratuity Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' +  zOutSummary.autoGratuity.toCurrency(2)  + '</td></tr>');
        $('#taxTable tbody').append('<tr><td>{Literal}Customer Payment Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.customerPayments.toCurrency(2)  + '</td></tr>');
        $('#taxTable tbody').append('<tr><td><br></td></tr>');
        $('#taxTable tbody').append('<tr><td>{Literal}Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.tenderingTotal.toCurrency(2)  + '</td></tr>');

        if (App.serverInfo.isFoodService) {
            $("#fourthGraphTable tbody").empty();
            $('#fourthGraphTable tbody').append('<tr><td>{Literal}Credit Card Tips{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + this.creditCardTips.toCurrency(2)  + '</td></tr>');
            $('#fourthGraphTable tbody').append('<tr><td>{Literal}AutoGratuity{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.autoGratuity.toCurrency(2)  + '</td></tr>');
            $('#fourthGraphTable tbody').append('<tr><td>{Literal}Other Tips{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + this.otherTips.toCurrency(2)  + '</td></tr>');
            $('#fourthGraphTable tbody').append('<tr><td>{Literal}Total Tips{/Literal}</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + zOutSummary.tipsTotal.toCurrency(2)  + '</td></tr>');

            
            var diningTotal = this.deliveryTotal + this.dineInTotal + this.takeOutTotal;
            var diningChecks = this.deliveryCount  + this.dineInCount + this.takeOutCount;
            var diningGuests = this.deliveryGuestCount + this.dineInGuestCount + this.takeOutGuestCount;

            if (diningTotal != 0) {
                $("#fifthGraphTable tbody").empty();
                var dineInTotal = (((this.dineInTotal / diningTotal) * 100).toFixed(0)) + "%"
                $('#fifthGraphTable tbody').append('<tr><td>{Literal}Dine-In % of Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + dineInTotal + '</td></tr>');

                if (diningChecks != 0) {
                    var dineInChecks = (((this.dineInCount / diningChecks) * 100).toFixed(0)) + "%";
                    $('#fifthGraphTable tbody').append('<tr><td>{Literal}Dine-In % of Checks{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + dineInChecks + '</td></tr>');
                }

                if (diningGuests != 0) {
                    var dineInGuests = (((this.dineInGuestCount / diningGuests) * 100).toFixed(0)) + "%";
                    $('#fifthGraphTable tbody').append('<tr><td>{Literal}Dine-In % of Guests{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + dineInGuests + '</td></tr>');
                }

                $('#fifthGraphTable tbody').append('<tr><td><br></td></tr>');

                var takeOutTotal = (((this.takeOutTotal / diningTotal) * 100).toFixed(0)) + "%"
                $('#fifthGraphTable tbody').append('<tr><td>{Literal}Take-Out % of Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + takeOutTotal + '</td></tr>');

                if (diningChecks != 0) {
                    var takeOutChecks = (((this.takeOutCount / diningChecks) * 100).toFixed(0)) + "%";
                    $('#fifthGraphTable tbody').append('<tr><td>{Literal}Take-Out % of Checks{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + takeOutChecks + '</td></tr>');
                }

                if (diningGuests != 0) {
                    var takeOutGuests = (((this.takeOutGuestCount / diningGuests) * 100).toFixed(0)) + "%";
                    $('#fifthGraphTable tbody').append('<tr><td>{Literal}Take-Out % of Guests{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + takeOutGuests + '</td></tr>');
                }

                $('#fifthGraphTable tbody').append('<tr><td><br></td></tr>');

                var deliveryTotal = (((this.deliveryTotal / diningTotal) * 100).toFixed(0)) + "%";
                $('#fifthGraphTable tbody').append('<tr><td>{Literal}Delivery % of Total{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + deliveryTotal + '</td></tr>');

                if (diningChecks != 0) {
                    var deliveryChecks = (((this.deliveryCount / diningChecks) * 100).toFixed(0)) + "%";
                    $('#fifthGraphTable tbody').append('<tr><td>{Literal}Delivery % of Checks{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + deliveryChecks + '</td></tr>');
                }

                if (diningGuests != 0) {
                    var deliveryGuests = (((this.deliveryGuestCount / diningGuests) * 100).toFixed(0)) + "%";
                    $('#fifthGraphTable tbody').append('<tr><td>{Literal}Delivery % of Guests{/Literal}</td><td style="color: black; float: right; direction: RTL;">' + deliveryGuests + '</td></tr>');
                }
            }
        }

        const keys = Object.keys(this.salesByItemType)
        const values = Object.values(this.salesByItemType)

        const keys1 = Object.keys(this.qtyItemTypes)
        const values1 = Object.values(this.qtyItemTypes)
        
        $("#itemTypeTable tbody").empty();
        for (var i = 0; i < keys.length; i++) 
        {
           
            $('#itemTypeTable tbody').append('<tr><td>' + keys[i] + '</td> <td style="padding-left: 5px !important;">' + values1[i].toFixed(2) + '</td> <td style="color: black; float: right; direction: LTR;">{Literal}${/Literal}' + values[i].toCurrency(2) + '</td></tr>');
        }

        $('select:not(#location-dropdown)').formSelect();

        var pickerElement = document.querySelectorAll('.datepicker');
        var instances = M.Datepicker.init(pickerElement, {
            autoClose: true,
            container: 'body',
            format: 'yyyy-mm-ddT00:00:00',
            
            i18n: App.i18n
        });
        this.datepicker = instances;
    },

    showFirstTable: function () {
        if ($('#itemTypeTable').is(":visible")) {
            $('#itemTypeTable').hide();
            $('#discountTable').hide();
            $('#itemTypeTableHr').hide();
        }
        else {
            $('#itemTypeTable').show();
            $('#discountTable').show();
            $('#itemTypeTableHr').show();
            
        }
    },
    
    showSecondTable: function () {
        if ($('#secondGraphTable').is(":visible")) {
            $('#secondGraphTable').hide();
        }
        else {
            $('#secondGraphTable').show();
        }
    }, 

    showLocationsTable: function () {
        if ($('#locationsGraphTable').is(":visible")) {
            $('#locationsGraphTable').hide();
        }
        else {
            $('#locationsGraphTable').show();
        }
    },

    showThirdTable: function () {
        if ($('#thirdGraphTable').is(":visible")) {
            $('#thirdGraphTable').hide();
            $('#taxTable').hide();
            $('#taxTableHr').hide();
        }
        else {
            $('#thirdGraphTable').show();
            $('#taxTable').show();
            $('#taxTableHr').show();
        }
    },

    showFourthTable: function () {
        if ($('#fourthGraphTable').is(":visible")) {
            $('#fourthGraphTable').hide();
        }
        else {
            $('#fourthGraphTable').show();
        }
    },

    showFifthTable: function () {
        if ($('#fifthGraphTable').is(":visible")) {
            $('#fifthGraphTable').hide();
        }
        else {
            $('#fifthGraphTable').show();
        }
    },

    showSixthTable: function () {
        if ($('#sixthGraphTable').is(":visible")) {
            $('#sixthGraphTable').hide();
        }
        else {
            $('#sixthGraphTable').show();
        }
    },

    showCompTable: function() {
        if ($('#compReasonTable').is(":visible")) {
            $('#compReasonTable').hide();
        }
        else {
            $('#compReasonTable').show();
        }
    },

    showSalesHourTable: function() {
        if ($('#salesHourTable').is(":visible")) {
            $('#salesHourTable').hide();
        }
        else {
            $('#salesHourTable').show();
        }
    },

    showSalesByTypeTable: function () {
        if ($('#salesByTypeTable').is(":visible")) {
            $('#salesByTypeTable').hide();
            $('#filterByItemContainer').hide();
        }
        else {
            $('#salesByTypeTable').show();
            $('#filterByItemContainer').show();
        }
    },

    showSalesByCategoryTable: function() {
        if ($('#salesByCategoryTable').is(":visible")) {
            $('#salesByCategoryTable').hide();
        }
        else {
            $('#salesByCategoryTable').show();
        }
    },

    showSalesByUserTable: function() {
        if ($('#salesByUserTable').is(":visible")) {
            $('#salesByUserTable').hide();
        }
        else {
            $('#salesByUserTable').show();
        }
    },

    showSalesByCustomerTable: function() {
        if ($('#salesByCustomerTable').is(":visible")) {
            $('#salesByCustomerTable').hide();
        }
        else {
            $('#salesByCustomerTable').show();
        }
    },

    showEmployeeHoursTable: function () {
        if ($('#employeeHoursTable').is(":visible")) {
            $('#employeeHoursTable').hide();
        }
        else {
            $('#employeeHoursTable').show();
        }
    },

    changeDateRange: function (element) {
        var reportType = this.$el.find('#report-type-filter').val();
        var dateRange = this.getDateRange();

        if(this.isCloudReport()){
            var selectedDateRange = this.$el.find('#date-range-preset').val();
            if(selectedDateRange == "custom"){
                var dateRangeFormModal = this.$el.find('#date-range-form-modal').modal();
                dateRangeFormModal.modal("open");
            }

            return;
        }
        var that = this;
        var sessionToken = this.getCookie();
        var tillVal = this.$el.find('#till-dropdown').val();
        var tillName = this.$el.find('#till-dropdown option:selected').text();
        if (tillVal == "all") {
            tillName = "All Tills"
        }

        var dateRangeVal = this.$el.find('#date-range-preset').val();
        var reportType = this.$el.find('#report-type-filter').val();
        // if(element.target[0].id === "selectAllLocations") {
        //     this.selectAllLocations();

        //     if(this.$el.find("#location-dropdown option:selected").length === 0)
        //         return;
        // }

        if(dateRange == "custom"){ //&& element.target.id != "till-dropdown"){
            var fromDate = this.$el.find('#fromDate').val();
            var thruDate = this.$el.find('#thruDate').val();

            if(fromDate != '' && thruDate != '')
                this.customDateRange();
            else
                this.openCustomDateRangeModal();

            return;
        }

        that.$el.find('.signature-modal-trigger-preloader').addClass('active');
       
        // if (dateRange != "custom") 
        {
            $('#dashboardHeader').hide();
            $('#byHourHeader').hide();
            $('#byUserHeader').hide();
            $('#byCustomerHeader').hide();
            $('#byCategoryHeader').hide();
            $('#byTypeHeader').hide();
            $('#resetReportHeader').hide();
            $('#gratuityReportHeader').hide();
            $('#employeeHourHeader').hide();
            $('#cloudReportHeader').hide();
            $('#tillSelector').show();
            $('#exportToExcel').show();
            
            var reportType = this.$el.find('#report-type-filter').val();
            if (reportType == "zOutSummary") {
                $('#dashboardHeader').show();
              
                $('#tillSelector').show();
                if (tillVal == "all") {
                    $.ajax({
                        url: '/data/get-date-range-sales-data',
                        data: {
                            token: sessionToken,
                            fromDate: dateRange.fromDate,
                            thruDate: dateRange.thruDate,
                        },
                        dataType: 'json',
                        type: 'POST',
                        success: function (data) {
                            var dateRangeFormModal = that.$el.find('#date-range-form-modal').modal();
                            dateRangeFormModal.modal('close');
        
                            that.zOutSummary = data.zOutSummary;
        
                            that.salesByItemType = data.salesByItemType;
                            that.noSalesCount = data.noSaleCount;
                            that.creditCardCount = data.creditCardCount;
                            that.creditCardTotal = data.creditCardTotal;
                            that.debitCardCount = data.debitCardCount;
                            that.startingCash = data.startingCash;
                            that.otherTips = data.otherTips;
                            that.creditCardTips = data.creditCardTips;
                            that.qtyItemTypes = data.qtyItemTypes;
            
                            var insertTotalTransactions = document.getElementById('transactionCount');
                            if (data.totalTransactions == null) {
                                insertTotalTransactions.value = 0;
                                that.totalTransactions = 0;
                            }
                            else {
                                insertTotalTransactions.value = data.totalTransactions;
                                that.totalTransactions = data.totalTransactions;
                            }
            
                            that.deliveryCount = data.deliveryCount;
                            that.deliveryGuestCount = data.deliveryGuestCount;
                            that.deliveryTotal = data.deliveryTotal;
            
                            that.dineInCount = data.dineInCount;
                            that.dineInGuestCount = data.dineInGuestCount;
                            that.dineInTotal = data.dineInTotal;
            
                            that.takeOutCount = data.takeOutCount;
                            that.takeOutGuestCount = data.takeOutGuestCount;
                            that.takeOutTotal = data.takeOutTotal;
            
                            that.totalSales =  Math.round(data.totalSales * 100) / 100;
                            that.largestTransaction = Math.round(data.largestTransaction * 100) / 100;
                            that.totalItemsSold = data.totalItemsSold;
                            that.cashTransactions = data.cashCount;
                            var test = "{Literal}${/Literal}";
                            document.getElementById('totalSales').value = test + that.totalSales.toCurrency();
                            if (data.zOutSummary != '') {
                               document.getElementById('totalTender').value = test + data.zOutSummary.tenderingTotal.toCurrency();
                            }
                            
                            var currency = 'USD';
                            that.$el.find('.preloader-col').hide();
                            that.$el.find('.chart-content').show();
                            that.renderCharts(currency, data);
                            that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                        },
                        error: function (e) {
                            if (e.status == 523) {
                                window.location.href = "#/log-in";
                                location.reload();
                            }
                            else {
                                that.$el.find('.preloader-col').hide();
                                that.$el.find('.chart-content').show();
                                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                                M.toast({
                                    html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                                });
                            }
                        }
                    }); 
                }
                else {
                    this.getSalesDataDateRangeFromTill(dateRange.fromDate, dateRange.thruDate, tillName);
                }
            }
            else if (reportType == "byHour") {
                $('#byHourHeader').show();
                this.getSalesByHourData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
            else if (reportType == "byUser") {
                $('#byUserHeader').show();
                this.getSalesByUserData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
            else if (reportType == "customerSummary") {
                $('#byCustomerHeader').show();
                this.getSalesByCustomerData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
            else if (reportType == "itemCategory") {
                $('#byCategoryHeader').show();
                this.getSalesDataByCategory(tillName, dateRange.fromDate, dateRange.thruDate);
            }
            else if (reportType == "byType") {
                $('#byTypeHeader').show();
                this.getSalesByTypeData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
            else if (reportType == "gratuityReport") {
                $('#gratuityReportHeader').show();
                this.getGratuityData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
            else if (reportType == "employeeHour") {
                $('#tillSelector').hide();
                $('#employeeHourHeader').show();
                $('#exportToExcel').show();
                this.getEmployeeHourData(dateRange.fromDate, dateRange.thruDate);
            }
        }
    },

    customDateRange: function () {
        var reportType = this.$el.find('#report-type-filter').val();
        var that = this;
        var sessionToken = this.getCookie();
        var fromDate = this.$el.find('#fromDate').val();
        var thruDate = this.$el.find('#thruDate').val();

        var tillVal = this.$el.find('#till-dropdown').val();
        var tillName = this.$el.find('#till-dropdown option:selected').text();
        if (tillVal == "all") {
            tillName = "All Tills"
        }

        if (fromDate != '' && thruDate != '') {
            fromDate = moment(fromDate).hour(this.dayStartTime).minute(0).format("YYYY-MM-DD HH:mm:ss");
            thruDate = moment(thruDate).add(1, 'days').hour(this.dayStartTime - 1).minute(59).format("YYYY-MM-DD HH:mm:ss");

            this.$el.find('#dateRangeDisplay').html(toDateString(fromDate) + " - " + toDateString(thruDate));


            this.dateRange = {fromDate: fromDate, thruDate: thruDate};
            if(this.isCloudReport()){
                var dateRangeFormModal = that.$el.find('#date-range-form-modal').modal();
                dateRangeFormModal.modal("close");
                return;
            }

            this.$el.find('.signature-modal-trigger-preloader').addClass('active');
            M.toast({ html: '{Literal}Fetching Data From {/Literal}' + fromDate + ' {Literal}to{/Literal} ' + thruDate });

            $('#dashboardHeader').hide();
            $('#byHourHeader').hide();
            $('#byUserHeader').hide();
            $('#byCustomerHeader').hide();
            $('#byCategoryHeader').hide();
            $('#resetReportHeader').hide();
            $('#byTypeHeader').hide();
            $('#gratuityReportHeader').hide();
            $('#employeeHourHeader').hide();
            $('#tillSelector').show();
            $('#exportToExcel').show();

            if (reportType == "byHour") {
                $('#byHourHeader').show();
                this.getSalesByHourData(tillName,fromDate, thruDate);
            }
            else if (reportType == "byUser") {
                $('#byUserHeader').show();
                this.getSalesByUserData(tillName, fromDate, thruDate);
            }
            else if (reportType == "customerSummary") {
                $('#byCustomerHeader').show();
                this.getSalesByCustomerData(tillName, fromDate, thruDate);
            }
            else if (reportType == "byType") {
                $('#byTypeHeader').show();
                this.getSalesByTypeData(tillName, fromDate, thruDate);
            }
            else if (reportType == "itemCategory") {
                $('#byCategoryHeader').show();
                this.getSalesDataByCategory(tillName, fromDate, thruDate);
            }
            else if (reportType == "gratuityReport") {
                $('#gratuityReportHeader').show();
                this.getGratuityData(tillName, fromDate, thruDate);
            }
            else if (reportType == "employeeHour") {
                $('#employeeHourHeader').show();
                $('#tillSelector').hide();
                $('#exportToExcel').show();
                this.getEmployeeHourData(fromDate, thruDate);
            }
            else if (reportType == "zOutSummary") {
                $('#tillSelector').show();
                $('#locationSelector').hide();
                

                $('#dashboardHeader').show();
                if (tillVal == "all") {
                    $.ajax({
                        url: '/data/get-date-range-sales-data',
                        data: {
                            token: sessionToken,
                            fromDate: fromDate,
                            thruDate: thruDate,
                        },
                        dataType: 'json',
                        type: 'POST',
                        success: function (data) {
                            that.zOutSummary = data.zOutSummary;
        
                            that.salesByItemType = data.salesByItemType;
                            that.noSalesCount = data.noSaleCount;
                            that.creditCardCount = data.creditCardCount;
                            that.creditCardTotal = data.creditCardTotal;
                            that.debitCardCount = data.debitCardCount;
                            that.startingCash = data.startingCash;
                            that.otherTips = data.otherTips;
                            that.creditCardTips = data.creditCardTips;
                            that.qtyItemTypes = data.qtyItemTypes;
            
                            var insertTotalTransactions = document.getElementById('transactionCount');
                            if (data.totalTransactions == null) {
                                insertTotalTransactions.value = 0;
                                that.totalTransactions = 0;
                            }
                            else {
                                insertTotalTransactions.value = data.totalTransactions;
                                that.totalTransactions = data.totalTransactions;
                            }
            
                            that.deliveryCount = data.deliveryCount;
                            that.deliveryGuestCount = data.deliveryGuestCount;
                            that.deliveryTotal = data.deliveryTotal;
            
                            that.dineInCount = data.dineInCount;
                            that.dineInGuestCount = data.dineInGuestCount;
                            that.dineInTotal = data.dineInTotal;
            
                            that.takeOutCount = data.takeOutCount;
                            that.takeOutGuestCount = data.takeOutGuestCount;
                            that.takeOutTotal = data.takeOutTotal;
            
                            that.totalSales =  Math.round(data.totalSales * 100) / 100;
                            that.largestTransaction = Math.round(data.largestTransaction * 100) / 100;
                            that.totalItemsSold = data.totalItemsSold;
                            that.cashTransactions = data.cashCount;
            
                            var test = "{Literal}${/Literal}";
                            document.getElementById('totalSales').value = test + that.totalSales.toCurrency();
                            if (data.zOutSummary != '') {
                                document.getElementById('totalTender').value = test + data.zOutSummary.tenderingTotal.toCurrency();
                            }

                            var currency = 'USD';
                            that.$el.find('.preloader-col').hide();
                            that.$el.find('.chart-content').show();
                            that.renderCharts(currency, data);
                            that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                        },
                        error: function (e) {
                            if (e.status == 523) {
                                window.location.href = "#/log-in";
                                location.reload();
                            }
                            else {
                                that.$el.find('.preloader-col').hide();
                                that.$el.find('.chart-content').show();
                                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                                M.toast({
                                    html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                                });
                            }
                        },
                        complete: function(d) {
                            document.getElementById('fromDate').value = '';
                            document.getElementById('thruDate').value = '';
                        }
                    }); 
                }
                else {
                    this.getSalesDataDateRangeFromTill(fromDate, thruDate, tillName);
                }
            }
        }
        else {
            html: '{Literal}Both options must be defined{/Literal}'
        }

        var dateRangeFormModal = that.$el.find('#date-range-form-modal').modal();
        dateRangeFormModal.modal('close');
    },

    getSalesDataDateRangeFromTill: function (fromDate, thruDate, tillName) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-date-range-sales-data-by-till',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
                tillName: tillName
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var dateRangeFormModal = that.$el.find('#date-range-form-modal').modal();
                dateRangeFormModal.modal('close');

                that.zOutSummary = data.zOutSummary;

                that.salesByItemType = data.salesByItemType;
                that.noSalesCount = data.noSaleCount;
                that.creditCardCount = data.creditCardCount;
                that.creditCardTotal = data.creditCardTotal;
                that.debitCardCount = data.debitCardCount;
                that.startingCash = data.startingCash;
                that.otherTips = data.otherTips;
                that.creditCardTips = data.creditCardTips;
                that.qtyItemTypes = data.qtyItemTypes;

                var insertTotalTransactions = document.getElementById('transactionCount');
                if (data.totalTransactions == null) {
                    insertTotalTransactions.value = 0;
                    that.totalTransactions = 0;
                }
                else {
                    insertTotalTransactions.value = data.totalTransactions;
                    that.totalTransactions = data.totalTransactions;
                }

                that.deliveryCount = data.deliveryCount;
                that.deliveryGuestCount = data.deliveryGuestCount;
                that.deliveryTotal = data.deliveryTotal;

                that.dineInCount = data.dineInCount;
                that.dineInGuestCount = data.dineInGuestCount;
                that.dineInTotal = data.dineInTotal;

                that.takeOutCount = data.takeOutCount;
                that.takeOutGuestCount = data.takeOutGuestCount;
                that.takeOutTotal = data.takeOutTotal;

                that.totalSales =  Math.round(data.totalSales * 100) / 100;
                that.largestTransaction = Math.round(data.largestTransaction * 100) / 100;
                that.totalItemsSold = data.totalItemsSold;
                that.cashTransactions = data.cashCount;

                var test = "{Literal}${/Literal}";
                document.getElementById('totalSales').value = test + that.totalSales.toCurrency();
                if (data.zOutSummary != '') {
                   document.getElementById('totalTender').value = test + data.zOutSummary.tenderingTotal.toCurrency();
                }
                
                
                
                var currency = 'USD';
                that.$el.find('.preloader-col').hide();
                that.$el.find('.chart-content').show();
                that.renderCharts(currency, data);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            },
            complete: function(d) {
                document.getElementById('fromDate').value = '';
                document.getElementById('thruDate').value = '';
            }
        });
    },
    
    isCloudReport: function () {
        var reportType = this.$el.find('#report-type-filter').val();
        var cloudTypes = ['zOutCloudSummary', 'cloudSalesByHour', 'cloudSalesByItem'];
        return cloudTypes.includes(reportType);
    },

    changeReportFilter: function() {
        $('#sequenceSearch').hide();
        $('#dateRangeSelector').show();
        $('#tillSelector').show();
        $('#shift-wrapper').show();
        var that = this;
        var sessionToken = this.getCookie();
        var reportType = this.$el.find('#report-type-filter').val();
        if(!this.isCloudReport())
            this.$el.find('.signature-modal-trigger-preloader').addClass('active');

        var tillVal = this.$el.find('#till-dropdown').val();
        var tillName = this.$el.find('#till-dropdown option:selected').text();
        if (tillVal == "all") {
            tillName = "All Tills"
        }

        if (reportType != "resetReport" && !this.isCloudReport()) {
            var dateRangeVal = this.$el.find('#date-range-preset').val();
            if(dateRangeVal != "custom")
                this.getDateRange();
        }

        var dateRange = this.dateRange;
       
        $('#dashboardHeader').hide();
        $('#byHourHeader').hide();
        $('#byUserHeader').hide();
        $('#byCustomerHeader').hide();
        $('#byCategoryHeader').hide();
        $('#byTypeHeader').hide();
        $('#salesByType').hide();
        $('#resetReportHeader').hide();
        $('#gratuityReportHeader').hide();
        $('#employeeHourHeader').hide();
        $('#cloudReportHeader').hide();
        $('#locationsSalesContainer').hide();
        $('#locationsSummaryContainer').hide();
        $('#exportToExcel').show();
        $('#locations-sales2-bar-chart').hide();
        $('#locations-sales-bar-chart').hide();


        this.cloudData = [];

        if(this.isCloudReport()){
            $('#shift-wrapper').hide();
            $('#locationSelector').show();
            $('#tillSelector').hide();
            $('#transactionCountContainer').hide();
            this.$el.find('#getCloudReportsBtn').show();
            $('#cloudReportHeader').show();

            $('#compReasonGraph').hide();
            $('#salesByCategory').hide();
            $('#salesByCustomer').hide();
            $('#salesByUser').hide();
            $('#salesByType').hide();
            $('#employeeHourGraph').hide();
            $('#gratuityReportGraphs').hide();

            if(reportType == 'zOutCloudSummary'){
                $('#salesByHourGraph').hide();
                $('#initialGraphs').show();
                $('#locationsSummaryContainer').show();
            } else if(reportType == 'cloudSalesByHour') {
                $('#salesByHourGraph').show();
                $('#initialGraphs').hide();
                $('#locationsSalesContainer').show();
            } else if(reportType == 'cloudSalesByItem') {
                $('#salesByHourGraph').hide();
                $('#initialGraphs').hide();
                $('#salesByType').show();
                $('#locationsSalesContainer').show();
            }

            this.otherTips = undefined;
            this.creditCardTips = undefined;
            document.getElementById('totalSales').value = 0.0;
            document.getElementById('totalTender').value = 0.0;
            this.renderCharts('',this.emptyData);
        }
        else {
            this.$el.find('#getCloudReportsBtn').hide();
            $('#locationSelector').hide();
            $('#transactionCountContainer').show();
            $('#locationsSummaryContainer').hide();
        }

        if (reportType == "zOutSummary") {
            $('#compReasonGraph').hide();
            $('#salesByHourGraph').hide();
            $('#initialGraphs').show();
            $('#salesByCategory').hide();
            $('#salesByCustomer').hide();
            $('#salesByUser').hide();
            $('#salesByType').hide();
            $('#employeeHourGraph').hide();
            $('#gratuityReportGraphs').hide();
            $('#dashboardHeader').show();

            // if(reportType == "zOutSummary") {
                $('#tillSelector').show();
                $('#locationSelector').hide();
            // }
    
            if (tillName == "All Tills") {
                $.ajax({
                    url: '/data/get-date-range-sales-data',
                    data: {
                        token: sessionToken,
                        fromDate: this.dateRange.fromDate,
                        thruDate: this.dateRange.thruDate,
                    },
                    dataType: 'json',
                    type: 'POST',
                    success: function (data) {
                        var dateRangeFormModal = that.$el.find('#date-range-form-modal').modal();
                        dateRangeFormModal.modal('close');
    
                        that.zOutSummary = data.zOutSummary;
    
                        that.salesByItemType = data.salesByItemType;
                        that.noSalesCount = data.noSaleCount;
                        that.creditCardCount = data.creditCardCount;
                        that.creditCardTotal = data.creditCardTotal;
                        that.debitCardCount = data.debitCardCount;
                        that.startingCash = data.startingCash;
                        that.otherTips = data.otherTips;
                        that.creditCardTips = data.creditCardTips;
                        that.qtyItemTypes = data.qtyItemTypes;
        
                        var insertTotalTransactions = document.getElementById('transactionCount');
                        if (data.totalTransactions == null) {
                            insertTotalTransactions.value = 0;
                            that.totalTransactions = 0;
                        }
                        else {
                            insertTotalTransactions.value = data.totalTransactions;
                            that.totalTransactions = data.totalTransactions;
                        }
        
                        that.deliveryCount = data.deliveryCount;
                        that.deliveryGuestCount = data.deliveryGuestCount;
                        that.deliveryTotal = data.deliveryTotal;
        
                        that.dineInCount = data.dineInCount;
                        that.dineInGuestCount = data.dineInGuestCount;
                        that.dineInTotal = data.dineInTotal;
        
                        that.takeOutCount = data.takeOutCount;
                        that.takeOutGuestCount = data.takeOutGuestCount;
                        that.takeOutTotal = data.takeOutTotal;
        
                        that.totalSales =  Math.round(data.totalSales * 100) / 100;
                        that.largestTransaction = Math.round(data.largestTransaction * 100) / 100;
                        that.totalItemsSold = data.totalItemsSold;
                        that.cashTransactions = data.cashCount;
        
                        var test = "{Literal}${/Literal}";
                        document.getElementById('totalSales').value = test + that.totalSales.toCurrency();
                        if (data.zOutSummary != '') {
                           document.getElementById('totalTender').value = test + data.zOutSummary.tenderingTotal.toCurrency();
                        }
                        
                        var currency = 'USD';
                        that.$el.find('.preloader-col').hide();
                        that.$el.find('.chart-content').show();
                        that.renderCharts(currency, data);
                        that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    },
                    error: function (e) {
                        if (e.status == 523) {
                            window.location.href = "#/log-in";
                            location.reload();
                        }
                        else {
                            that.$el.find('.preloader-col').hide();
                            that.$el.find('.chart-content').show();
                            that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                            M.toast({
                                html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                            });
                        }
                    }
                }); 
            }
            else {
                this.getSalesDataDateRangeFromTill(dateRange.fromDate, dateRange.thruDate, tillName);
            }
        }
        else if (reportType == "byHour") {
            that.renderSalesLocations = false;
            $('#locationsSalesContainer').hide();
            if (dateRange != "custom") {
                $('#byHourHeader').show();
                this.getSalesByHourData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
        }
        else if (reportType == "byUser") {
            if (dateRange != "custom") {
                $('#byUserHeader').show();
                this.getSalesByUserData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
        }
        else if (reportType == "customerSummary") {
            if (dateRange != "custom") {
                $('#byCustomerHeader').show();
                this.getSalesByCustomerData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
        }
        else if (reportType == "byType") {
            if (dateRange != "custom") {
                $('#byTypeHeader').show();
                this.getSalesByTypeData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
        }
        else if (reportType == "itemCategory") {
            if (dateRange != "custom") {
                $('#byCategoryHeader').show();
                this.getSalesDataByCategory(tillName, dateRange.fromDate, dateRange.thruDate);
            }
        }
        else if (reportType == "gratuityReport") {
            if (dateRange != "custom") {
                $('#gratuityReportHeader').show();
                this.getGratuityData(tillName, dateRange.fromDate, dateRange.thruDate);
            }
        }
        else if (reportType == "employeeHour") {
            if (dateRange != "custom") {
                $('#tillSelector').hide();
                $('#employeeHourHeader').show();
                $('#exportToExcel').show();
                this.getEmployeeHourData(dateRange.fromDate, dateRange.thruDate);
            }
        }
        else if (reportType == "resetReport") {
            this.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            $('#compReasonGraph').hide();
            $('#salesByHourGraph').hide();
            $('#initialGraphs').show();
            $('#salesByCategory').hide();
            $('#salesByCustomer').hide();
            $('#salesByUser').hide();
            $('#employeeHourGraph').hide();
            $('#gratuityReportGraphs').hide();
            $('#dateRangeSelector').hide();
            $('#tillSelector').hide();
            $('#sequenceSearch').show();
            $('#resetReportHeader').show();
        }
    },

    getGratuityData: function(tillVal, fromDate, thruDate) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-gratuity-data',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
                tillVal: tillVal
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.generateGratuityReport(data.gratuityData);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    getEmployeeHourData: function (fromDate, thruDate) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-employee-hour-data',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.salesLabels = data.salesLabels;
                that.generateEmployeeReport(data.employeeHours);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    getSalesDataByCategory: function(tillVal, fromDate, thruDate) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sales-by-category-data',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
                tillVal: tillVal
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
            
                that.generateSalesByCategory(data.salesByCategory);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    getSalesByTypeData: function(tillVal, fromDate, thruDate) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sales-by-type-data',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
                tillVal: tillVal
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.generateSalesByType(data.salesByType);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    getSalesByCustomerData: function(tillVal, fromDate, thruDate) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sales-by-customer-data',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
                tillVal: tillVal
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
               
                that.generateSalesByCustomer(data.salesByCustomer);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    getSalesByUserData: function(tillVal, fromDate, thruDate) {
        if (this.userBySalesRevenue) {

        }
        else {

        }
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-sales-by-user-data',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
                tillVal: tillVal
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.salesLabels = data.salesLabels;
                that.generateSalesByUser(data.salesByUser);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    getSalesByHourData: function(tillVal, fromDate, thruDate) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-date-range-sales-data-by-till',
            data: {
                token: sessionToken,
                fromDate: fromDate,
                thruDate: thruDate,
                tillName: tillVal
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                
                var test = "{Literal}${/Literal}";
                if (data.zOutSummary != '') {
                    document.getElementById('totalSalesByHour').value = test + data.totalSales.toCurrency();
                }
                else {
                    document.getElementById('totalSalesByHour').value = "";
                }

                that.generateSalesByHour(data);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    generateGratuityReport: function (data) {
        this.$el.find('.chart-content').show();
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').hide();
        $('#initialGraphs').hide();
        $('#salesByCategory').hide();
        $('#salesByCustomer').hide();
        $('#salesByUser').hide();
        $('#employeeHourGraph').hide();
        $('#gratuityReportGraphs').show();
        
        $("#sixthGraphTable tbody").empty();
        $('#gratuity-report-bar-chart').empty();

        var newTimeArray = data;
        newTimeArray.sort((a, b) => (a.id < b.id) ? 1 : -1)

        for (var i = 0; i < newTimeArray.length; i++) {
            if (i != 0 && newTimeArray[i - 1] != undefined && newTimeArray[i] && newTimeArray[i].id == newTimeArray[i - 1].id) {
                newTimeArray[i].total =+ newTimeArray[i - 1].total;
                newTimeArray.splice(i - 1, 1);
            }
        }
        
        for (var i = 0; i < newTimeArray.length; i++) {
            $('#sixthGraphTable tbody').append('<tr><td>' + newTimeArray[i].id + '</td> <td>{Literal}${/Literal}' + newTimeArray[i].total.toFixed(2) + '</td></tr>');
        }

        var dataEmpty = false
        var gratuityArray = [];
        if (newTimeArray == []) {
            dataEmpty = true;
        }
        else {
            var test = [];
            if (newTimeArray.length > 10) {
                for (var i = 0; i < 10; i++) {
                    var test2 = [];
                    gratuityArray[i] = [newTimeArray[i].id, newTimeArray[i].total];
                    test2.push(newTimeArray[i].id);
                    test2.push(newTimeArray[i].total.toFixed(2));
                    test.push(test2);
                }
            }
            else {
                for (var i = 0; i < newTimeArray.length; i++) {
                    var test2 = [];
                    gratuityArray[i] = [newTimeArray[i].id, newTimeArray[i].total];
                    test2.push(newTimeArray[i].id);
                    test2.push(newTimeArray[i].total.toFixed(2));
                    test.push(test2);
                }
            }
            
        }

        if (dataEmpty) {
            var tenderTypesChart = c3.generate({
                bindto: '#gratuity-report-bar-chart',
                legend: {
                    position: 'right'
                },
                size: {
                    //height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: [],
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                }
            });
        }
        else {
            var tenderTypesChart = c3.generate({
                bindto: '#gratuity-report-bar-chart',
                
                size: {
                    height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: test,
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                axis: {
                    x: {
                        show: false,
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
            });
        }
    },

    generateSalesByUser: function(data) {
        this.$el.find('.chart-content').show();
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').hide();
        $('#initialGraphs').hide();
        $('#salesByCategory').hide();
        $('#salesByCustomer').hide();
        $('#salesByUser').show();
        $('#employeeHourGraph').hide();
        $('#gratuityReportGraphs').hide();
        
        $("#salesByUserTable tbody").empty();
        $('#sales-by-user-pie-chart').empty();

        var newTimeArray = data;
        newTimeArray.sort((a, b) => (a.id < b.id) ? 1 : -1)
        
        for (var i = 0; i < newTimeArray.length; i++) {
            $('#salesByUserTable tbody').append('<tr><td>' + newTimeArray[i].id + '</td> <td>{Literal}${/Literal}' + newTimeArray[i].total.toCurrency(2) + '</td> <td style="color: black; direction: RTL;">' + (newTimeArray[i].percent * 100).toFixed(0) + '%</td></tr>');
        }

        if (this.userBySalesRevenue) {
            var salesByUser = [];
            var dataEmpty = false

            if (newTimeArray == []) {
                dataEmpty = true;
            }
            else {
                var test = [];
                if ( newTimeArray.length > 10) {
                    for (var i = 0; i < 10; i++) {
                        var test2 = [];
                        salesByUser[i] = [newTimeArray[i].id, newTimeArray[i].total];
                        test2.push(newTimeArray[i].id);
                        test2.push(newTimeArray[i].total.toFixed(2));
                        test.push(test2);
                    }
                }
                else {
                    for (var i = 0; i < newTimeArray.length; i++) {
                        var test2 = [];
                        salesByUser[i] = [newTimeArray[i].id, newTimeArray[i].total];
                        test2.push(newTimeArray[i].id);
                        test2.push(newTimeArray[i].total.toFixed(2));
                        test.push(test2);
                    }
                }
                
            }

            if (dataEmpty) {
                var tenderTypesChart = c3.generate({
                    bindto: '#sales-by-user-pie-chart',
                    legend: {
                        position: 'right'
                    },
                    size: {
                        //height: 150
                    },
                    data: {
                        color: {
                            pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                        },
                        columns: [],
                        type: 'bar',
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    }
                });
            }
            else {
                var tenderTypesChart = c3.generate({
                    bindto: '#sales-by-user-pie-chart',
                    
                    size: {
                        height: 150
                    },
                    data: {
                        color: {
                            pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                        },
                        columns: test,
                        type: 'bar',
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    axis: {
                        x: {
                            show: false,
                        },
                        y: {
                            tick: {
                                format: d3.format(",d"),
                                count: 5
                            }
                        }
                    },
                });
            }
        }
        else {

            if (newTimeArray == []) {
                dataEmpty = true;
            }
            else {
                for (var i = 0; i < newTimeArray.length; i++) {
                    var objectArray = [];
                    var j = 0;
                    for (var key in newTimeArray[i].invoiced) {

                        thisHour = moment(newTimeArray[i].invoiced[key], "hh A").format("hh A");
                        objectArray[j] = thisHour;
                        j++;
                    }

                    newTimeArray[i].invoiced = objectArray;
                    newTimeArray[i].invoiced.sort();
                }

                dataArray = [];

                // I don't know why I wrote it this way but it works. Whoops
                for (var i = 0; i < newTimeArray.length; i++) {
                    var midnight = 0;
                    var oneAM = 0;
                    var twoAM = 0;
                    var threeAM = 0;
                    var fourAM = 0;
                    var fiveAM = 0;
                    var sixAM = 0;
                    var sevenAM = 0;
                    var eightAM = 0;
                    var nineAM = 0;
                    var tenAM = 0;
                    var elevenAM = 0;
                    var noon = 0;
                    var onePM = 0;
                    var twoPM = 0;
                    var threePM = 0;
                    var fourPM = 0;
                    var fivePM = 0;
                    var sixPM = 0;
                    var sevenPM = 0;
                    var eightPM = 0;
                    var ninePM = 0;
                    var tenPM = 0;
                    var elevenPM = 0;
                    
                    if (newTimeArray[i] != undefined) {
                        for (var j = 0; j < newTimeArray[i].invoiced.length; j++) {
                            if (newTimeArray[i].invoiced[j] == "12 AM") {
                                midnight++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "01 AM") {
                                oneAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "02 AM") {
                                twoAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "03 AM") {
                                threeAM++
                            }
                            else if (newTimeArray[i].invoiced[j] == "04 AM") {
                                fourAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "05 AM") {
                                fiveAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "06 AM") {
                                sixAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "07 AM") {
                                sevenAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "08 AM") {
                                eightAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "09 AM") {
                                nineAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "10 AM") {
                                tenAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "11 AM") {
                                elevenAM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "12 PM") {
                                noon++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "01 PM") {
                                onePM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "02 PM") {
                                twoPM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "03 PM") {
                                threePM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "04 PM") {
                                fourPM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "05 PM") {
                                fivePM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "06 PM") {
                                sixPM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "07 PM") {
                                sevenPM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "08 PM") {
                                eightPM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "09 PM") {
                                ninePM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "10 PM") {
                                tenPM++;
                            }
                            else if (newTimeArray[i].invoiced[j] == "11 PM") {
                                elevenPM++;
                            }
                        }
                    }
                    dataArray[i] = ([""+ newTimeArray[i].id, midnight, oneAM, twoAM, threeAM, fourAM, fiveAM, sixAM, sevenAM, eightAM, nineAM, tenAM, elevenAM, noon, onePM, twoPM, threePM, fourPM, fivePM, sixPM, sevenPM, eightPM, ninePM, tenPM, elevenPM]);
                }
            }

            if (!dataEmpty) {

                var chart3 = c3.generate({
                    bindto: '#sales-by-user-pie-chart',
                    size: {
                        height: 150
                    },
                    grid: {
                        y: {
                            show: true
                        }
                    },
                    data: {
                        columns: dataArray,
                        type: 'bar'
                    },
                    legend: {
                        show: false
                    },
                    axis: {
                        x: {
                            tick: {
                                multiline: false,
                                rotate: 60,
                            },
                            type: 'category',
                            categories: salesLabels
                        },
                        y: {
                            tick: {
                                format: d3.format(",d"),
                                count: 5
                            }
                        }
                    },
                    bar: {
                        width: {
                            ratio: 0.75
                        }
                    }
                });     
            }
            else {
                var tenderTypesChart = c3.generate({
                    bindto: '#sales-by-user-pie-chart',
                    legend: {
                        position: 'right'
                    },
                    size: {
                        //height: 150
                    },
                    data: {
                        color: {
                            pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                        },
                        columns: [],
                        type: 'pie',
                        empty: {
                            label: {
                                text: "{Literal}No Data Available{/Literal}"
                            }
                        }
                    },
                    donut: {
                        title: ""
                    }
                });
            }
        }

        
    },

    generateSalesByCustomer: function(data) {
        this.$el.find('.chart-content').show();
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').hide();
        $('#initialGraphs').hide();
        $('#salesByCategory').hide();
        $('#salesByUser').hide();
        $('#employeeHourGraph').hide();
        $('#gratuityReportGraphs').hide();
        $('#salesByCustomer').show();
        $("#salesByCustomerTable tbody").empty();

        var finalArray = [];
        var test = data;
        //var checkArray = data;
        var combinedArray = [];

        

        if (this.showCustomerCashSales) {
            for (var i = 0; i < test.length; i++) {
                var thisCustomer = test[i];
                checkArray = [];
                checkArray = data;
                
                if (test[i] != undefined) {
                    for (var t = 0; t < checkArray.length; t++) {
                        if (checkArray[t] != undefined) {
                            if (thisCustomer.id == checkArray[t].id && t != i) {
                                thisCustomer.nonTaxable = thisCustomer.nonTaxable + checkArray[t].nonTaxable;
                                thisCustomer.total = thisCustomer.total + checkArray[t].total;
                                thisCustomer.taxable = thisCustomer.taxable + checkArray[t].taxable;
                                thisCustomer.subTotal = thisCustomer.subTotal + checkArray[t].subTotal;
                                delete checkArray[t];
                            }
                        }
                    }  

                    combinedArray.push(thisCustomer);
                }
            }
        }
        else {
            for (var i = 0; i < test.length; i++) {
                var thisCustomer = test[i];
                checkArray = [];
                checkArray = data;
                
                if (test[i] != undefined) {
                    if (test[i].id != "Cash Sales" && test[i].id != "") {
                        for (var t = 0; t < checkArray.length; t++) {
                            if (checkArray[t] != undefined) {
                                if (thisCustomer.id == checkArray[t].id && t != i) {
                                    
                                    thisCustomer.nonTaxable = thisCustomer.nonTaxable + checkArray[t].nonTaxable;
                                    thisCustomer.total = thisCustomer.total + checkArray[t].total;
                                    thisCustomer.taxable = thisCustomer.taxable + checkArray[t].taxable;
                                    thisCustomer.subTotal = thisCustomer.subTotal + checkArray[t].subTotal;
                                    delete checkArray[t];
                                }
                            }
                        }  

                        combinedArray.push(thisCustomer);
                    }
                }
            }
        }

        combinedArray.sort((a, b) => (a.total < b.total) ? 1 : -1)

        if (combinedArray.length > 10) {
            for (var i = 0; i < 10; i++) {
                if (combinedArray[i].companyName == "") {
                    combinedArray[i].companyName = "{Literal}N/A{/Literal}"
                }
                if (combinedArray[i].id == "") {
                    combinedArray[i].id = "{Literal}N/A{/Literal}"
                }
                $('#salesByCustomerTable tbody').append('<tr><td>' + combinedArray[i].companyName + '</td> <td>' + combinedArray[i].id + '</td><td>{Literal}${/Literal}' + combinedArray[i].taxable.toCurrency(2) + '</td><td>{Literal}${/Literal}' + combinedArray[i].subTotal.toCurrency(2) + '</td><td>{Literal}${/Literal}' + combinedArray[i].total.toCurrency(2) + '</td></tr>');                
            }
        }
        else {
            for (var i = 0; i < combinedArray.length; i++) {
                if (combinedArray[i].companyName == "") {
                    combinedArray[i].companyName = "{Literal}N/A{/Literal}"
                }
                if (combinedArray[i].id == "") {
                    combinedArray[i].id = "{Literal}N/A{/Literal}"
                }
                $('#salesByCustomerTable tbody').append('<tr><td>' + combinedArray[i].companyName + '</td> <td>' + combinedArray[i].id + '</td><td>{Literal}${/Literal}' + combinedArray[i].taxable.toFixed(2) + '</td><td>{Literal}${/Literal}' + combinedArray[i].subTotal.toFixed(2) + '</td><td>{Literal}${/Literal}' + combinedArray[i].total.toFixed(2) + '</td></tr>');                
            }
        }

        
        var salesByCustomer = [];
        var dataEmpty = false
        if (combinedArray == []) {
            dataEmpty = true;
        }
        else {
            var test = [];
            if (combinedArray.length > 10) {
                for (var i = 0; i < 10; i++) {
                    if (combinedArray[i].companyName == "" && combinedArray[i].id == "") {
                        combinedArray[i].companyName = "{Literal}N/A{/Literal}"
                    }
                    else if (combinedArray[i].companyName == "Cash Sales") {
                        combinedArray[i].companyName = "{Literal}Cash Sales{/Literal}"
                    }
                    var test2 = [];
                    test2.push(combinedArray[i].companyName);
                    test2.push(combinedArray[i].total.toFixed(2));
                    test.push(test2);
                    salesByCustomer[i] = [combinedArray[i].companyName, combinedArray[i].total];
                }
            }
            else {
                for (var i = 0; i < combinedArray.length; i++) {
                    if (combinedArray[i].companyName == "" && combinedArray[i].id != "Cash Sales") {
                        combinedArray[i].companyName = "{Literal}N/A{/Literal}"
                    }
                    else if (combinedArray[i].id == "Cash Sales" || combinedArray[i].companyName == "{Literal}N/A{/Literal}") {
                        combinedArray[i].companyName = "{Literal}Cash Sales{/Literal}"
                    }
                    var test2 = [];
                    test2.push(combinedArray[i].companyName);
                    test2.push(combinedArray[i].total.toFixed(2));
                    test.push(test2);
                    salesByCustomer[i] = [combinedArray[i].companyName, combinedArray[i].total];
                }
            }

        }

        if (dataEmpty) {
            var tenderTypesChart = c3.generate({
                bindto: '#sales-by-customer-pie-chart',
                legend: {
                    position: 'right'
                },
                size: {
                    //height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: [],
                    type: 'pie',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                donut: {
                    title: ""
                }
            });
        }
        else {
            var tenderTypesChart = c3.generate({
                bindto: '#sales-by-customer-pie-chart',
                size: {
                    height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: test,
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                axis: {
                    x: {
                        show: false,
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
            });
        }
    },

    generateSalesByType: function (data, isCloud = false) {
        this.$el.find('.chart-content').show();
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').hide();
        $('#initialGraphs').hide();
        $('#salesByCategory').hide();
        $('#salesByType').show();
        $('#salesByUser').hide();
        $('#employeeHourGraph').hide();
        $('#gratuityReportGraphs').hide();
        $('#salesByCustomer').hide();
        $("#salesByTypeTable").empty();
        var chartDataByType = "{Literal}${/Literal}";
        dataLength = data.length;
        if (dataLength != 0) {
            var typeTotal = 0; 
            for (var i = 0; i < dataLength; i++) {
                typeTotal = typeTotal + data[i].typeTotal;
            }
            document.getElementById('totalSalesType').value = chartDataByType + typeTotal.toCurrency();
        }

        if(isCloud) {
            var groupByItem = [];
            var lineItems = data.map( i => {return i.lineItems});
            lineItems.forEach( item => {
                if(item.length != undefined )
                    item.forEach( l => {
                        if(groupByItem[l.id] == undefined)
                            groupByItem[l.id] = [];
                        groupByItem[l.id].push(l)
                    });
                else {
                    if(groupByItem[item.id] == undefined)
                            groupByItem[item.id] = [];
                    groupByItem[item.id].push(item);
                }
            });

            const itemIds = Object.keys(groupByItem);
            for (var i = 0; i < itemIds.length; i++) {
                var lineItems = groupByItem[itemIds[i]];
                var appendMe = '<thead data-id="'+ lineItems[0].id +'"><tr class="highlight-hover"><th><span class="material-icons" style="color: gray; position: relative;top:6px">keyboard_arrow_down</span><span>' + lineItems[0].id + ' / ' +  lineItems[0].itemDescription +'</span></th><th></th><th></th><th></th><th></tr></thead><tbody style="display: none;">';
                appendMe = appendMe + '<tr><td><i>{Literal}Location{/Literal}</i></td><td></td><td><i>{Literal}Quantity{/Literal}</i></td><td><i>{Literal}Total{/Literal}</i></td></tr>';
                var total = 0;

                for (var t = 0; t < lineItems.length; t++) {
                    appendMe = appendMe + '<tr data-id="'+ lineItems[t].id +'"><td>' + lineItems[t].locationCode + '</td><td></td><td>' + lineItems[t].itemQuantity.toCurrency(1) + '</td><td style="direction:ltr">{Literal}${/Literal}' + lineItems[t].itemTotal.toCurrency(2) + '</td></tr>';
                    total = total + lineItems[t].itemTotal;
                }

                appendMe = appendMe + '<tr><td></td><td></td><td></td><td>{Literal}${/Literal}' + total.toCurrency(2) + '</td></tr>';
                appendMe = appendMe + '</tbody>';
                $('#salesByTypeTable').append(appendMe);
            }
        }
        else {
            for (var i = 0; i < data.length; i++) {
                if (data[i].type == "") {
                    data[i].type = "{Literal}N/A{/Literal}"
                }
                var appendMe = '<thead data-type="'+ data[i].type +'"><tr class="highlight-hover"><th><span class="material-icons" style="color: gray; position: relative;top:6px">keyboard_arrow_down</span><span>' + data[i].type + '</span></th><th></th><th></th><th></th><th></tr></thead><tbody style="display: none;">';
                appendMe = appendMe + '<tr><td><i>{Literal}Item Id{/Literal}</i></td><td><i>{Literal}Description{/Literal}</i></td><td><i>{Literal}Quantity{/Literal}</i></td><td><i>{Literal}Total{/Literal}</i></td></tr>';
                var total = 0;
                if (data[i].lineItems.length == undefined) {
                    appendMe = appendMe + '<tr data-id='+ data[i].lineItems.id +' data-type='+ data[i].lineItems.itemType +'><td>' + data[i].lineItems.id + '</td><td>' + data[i].lineItems.itemDescription + '</td><td>' + data[i].lineItems.itemQuantity.toCurrency(1) + '</td><td style="direction:ltr">{Literal}${/Literal}' + data[i].lineItems.itemTotal.toCurrency(2) + '</td></tr>';
                    total = total + data[i].lineItems.itemTotal;
                }
                else {
                    for (var t = 0; t < data[i].lineItems.length; t++) {
                        appendMe = appendMe + '<tr data-id='+ data[i].lineItems[t].id +' data-type='+ data[i].lineItems.itemType +'><td>' + data[i].lineItems[t].id + '</td><td>' + data[i].lineItems[t].itemDescription + '</td><td>' + data[i].lineItems[t].itemQuantity.toCurrency(1) + '</td><td style="direction:ltr">{Literal}${/Literal}' + data[i].lineItems[t].itemTotal.toCurrency(2) + '</td></tr>';
                        total = total + data[i].lineItems[t].itemTotal;
                    }
                }

                appendMe = appendMe + '<tr><td></td><td></td><td></td><td>{Literal}${/Literal}' + total.toCurrency(2) + '</td></tr>';
                appendMe = appendMe + '</tbody>';
                $('#salesByTypeTable').append(appendMe);
            }
        }

        // var typeByTotal = [];
        var dataEmpty = false
        if (data == []) {
            dataEmpty = true;
        }
        else {
            var itemsData = [];
            data.sort((a, b) => (a.typeTotal < b.typeTotal) ? 1 : -1);
            var dataLen = data.length;
            // if(dataLen > 10)
            //     dataLen = 10;

            var chartDataByType = [];
            for (var i = 0; i < dataLen; i++) {
                if(data[i].lineItems.length != undefined && data[i].lineItems.length > 0)
                    itemsData.push(...data[i].lineItems);
                else
                    itemsData.push(data[i].lineItems[0]);
                var thisItemData = [];
                if (data[i].type == "")
                    data[i].type = "{Literal}N/A{/Literal}";
                
                thisItemData.push(data[i].type);
                thisItemData.push(data[i].typeTotal);
                chartDataByType.push(thisItemData);
                chartDataByType = chartDataByType.filter((v,i,a)=>a.findIndex(t=>(t[0] === v[0]))===i); // clean duplicates
                if(chartDataByType.length == 10)
                    break;
            }


            itemsData.sort((a, b) => (a.itemTotal < b.itemTotal) ? 1 : -1);
            var chartDataByItem = [];
            for (var i = 0; i < dataLen; i++) {
                if(itemsData[i] == undefined)
                    continue;
                var thisItemData = [];
                if(itemsData[i].itemDescription != undefined)
                    thisItemData.push(itemsData[i].itemDescription);
                else
                    thisItemData.push(i);
                thisItemData.push(itemsData[i].itemTotal);
                chartDataByItem.push(thisItemData);
                chartDataByItem = chartDataByItem.filter((v,i,a)=>a.findIndex(t=>(t[0] === v[0]))===i); // clean duplicates
                if(chartDataByItem.length == 10)
                    break;
            }
        }

        if (dataEmpty) {
            var tenderTypesChart = c3.generate({
                bindto: '#sales-by-type-bar-chart',
                legend: {
                    position: 'right'
                },
                size: {
                    height: 150
                },
                data: {
                    colors: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: [],
                    type: 'pie',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                donut: {
                    title: ""
                }
            });
        }
        else {
            var tenderTypesChart = c3.generate({
                bindto: '#sales-by-type-bar-chart',
                size: {
                    height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: chartDataByType,
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                axis: {
                    x: {
                        show: false,
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
            });

            c3.generate({
                bindto: '#sales-by-item-bar-chart',
                size: {
                    height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: chartDataByItem,
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                axis: {
                    x: {
                        show: false,
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
            });
        }
    },

    generateEmployeeReport: function (data) {
        this.$el.find('.chart-content').show();
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').hide();
        $('#initialGraphs').hide();
        $('#salesByCategory').hide();
        $('#employeeHourGraph').show();
        $('#salesByUser').hide();
        $('#gratuityReportGraphs').hide();
        $('#salesByCustomer').hide();
        $("#employeeHoursTable").empty();
        dataLength = data.length;
        var totalHours = 0;
        if (dataLength != 0) {
            for (var i = 0; i < dataLength; i++) {
                var thisEmployee = data[i];
                thisEmployee.totalHours = 0;
                for (var t = 0; t < thisEmployee.times.length; t++) {
                    if (thisEmployee.times[t].in != undefined && thisEmployee.times[t].out != undefined) {

                        var hours = this.diff_hours(thisEmployee.times[t].in, thisEmployee.times[t].out);
                        totalHours +=  hours
                        thisEmployee.totalHours += hours;
                    }
                }
            }
            
            totalHours = totalHours.toFixed(2);

            data.sort((a, b) => (a.name > b.name) ? 1 : -1)
            for (var i = 0; i < data.length; i++) {
                var appendMe = '<thead><tr><th>' + data[i].name + '</th></tr></thead><tbody>';
                appendMe = appendMe + '<tr><td><i>{Literal}In{/Literal}</i></td><td><i>{Literal}Out{/Literal}</i></td><td><i>{Literal}Total{/Literal}</i></td></tr>';
                var total = 0;
                for (var t = 0; t < data[i].times.length; t++) {
                    var inTime = new Date(data[i].times[t].in);
                    var out = new Date(data[i].times[t].out);
                    var total = this.getTimeDifference(data[i].times[t].in, data[i].times[t].out);
                    if (inTime.getHours() == 0) {
                        var timeStart = inTime.getHours();
                        var timeEnd = out.getHours();
                        var hourDiff = timeEnd - timeStart;   
                        if (hourDiff > 12) {
                            inTime.setHours(12);
                            var test = moment(inTime).format("HH:mm:ss.S YYYY-DD-MM");
                            data[i].times[t].in = test.toLocaleString();
                        }
                    }
                    if (inTime > out || data[i].times[t].in == "" || data[i].times[t].out == "") {
                        appendMe = appendMe + '<tr style="color: red;"><td style="padding-left: 40px !important;">' + data[i].times[t].in + '</td><td style="padding-left: 40px !important;">' + data[i].times[t].out + '</td><td>' + total + '</td></tr>';
                    }
                    else {
                        appendMe = appendMe + '<tr><td style="padding-left: 40px !important;">' + data[i].times[t].in + '</td><td style="padding-left: 40px !important;">' + data[i].times[t].out + '</td><td>' + total + '</td></tr>';
                    }
                }
    
                appendMe = appendMe + '<tr><td></td><td></td><td></td></tr>';
                appendMe = appendMe + '</tbody>';
                $('#employeeHoursTable').append(appendMe);
            }

            data.sort((a, b) => (a.totalHours < b.totalHours) ? 1 : -1)
            // var allEmployeeHours = 0;
            // for (var i = 0; i < dataLength; i++) {
            //     allEmployeeHours += data[i].totalHours;
            // }
            var totalEmployeeHours = document.getElementById("totalEmployeeHours");
            totalEmployeeHours.value = totalHours;

            if (data.length > 10) {
                var test = [];
                for (var i = 0; i < 10; i++) {
                    var test2 = [];
                    test2.push(data[i].name);
                    test2.push(data[i].totalHours);
                    test.push(test2);
                }
            }
            else {
                var test = [];
                for (var i = 0; i < data.length; i++) {
                    var test2 = [];
                    test2.push(data[i].name);
                    test2.push(data[i].totalHours);
                    test.push(test2);
                }
            }

            var tenderTypesChart = c3.generate({
                bindto: '#employee-hour-bar-chart',
                size: {
                    height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: test,
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                axis: {
                    x: {
                        show: false,
                    },
                    y: {
                        tick: {
                            format: d3.format(",.2f"),
                            count: 5
                        }
                    }
                },
            });

        }
        else {
            var tenderTypesChart = c3.generate({
                bindto: '#employee-hour-bar-chart',
                legend: {
                    position: 'right'
                },
                size: {
                    height: 150
                },
                data: {
                    colors: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: [],
                    type: 'pie',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                donut: {
                    title: ""
                }
            });
        }
    },

    diff_hours: function (dt2, dt1) 
    {
        if(dt2 == "" || dt1 == "")
            return 0;
        dt1 = new Date(dt1);
        dt2 = new Date(dt2);
        var timeStart = dt2.getTime();
        var timeEnd = dt1.getTime();
        var diff = Math.abs(timeEnd - timeStart);
        var hourDiff = Number.parseFloat(diff / 3600000);

        return hourDiff;          
    },

    getTimeDifference: function (dt2, dt1) 
    {
        if(dt2 == "" || dt1 == "")
            return "00:00";
        dt1 = new Date(dt1);
        dt2 = new Date(dt2);
        var timeStart = dt2.getTime();
        var timeEnd = dt1.getTime();
        var diff = Math.abs(timeEnd - timeStart);
        var hourDiff = Number.parseInt(diff / 3600000);
        var mod = 1;
        if(hourDiff > 0)
            mod = hourDiff;
        var minDiff = Math.round(((diff / 3600000) % mod) * 60);
        var hourDiff = hourDiff.toString()
        var minDiff = minDiff.toString()
       
        if(hourDiff.length === 1)
            hourDiff = "0" + hourDiff;
        if (minDiff.length === 1)
            minDiff = "0" + minDiff;

        return hourDiff + ":" + minDiff
    },

    generateSalesByCategory: function (data) {
        this.$el.find('.chart-content').show();
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').hide();
        $('#initialGraphs').hide();
        $('#salesByCategory').show();
        $('#salesByUser').hide();
        $('#employeeHourGraph').hide();
        $('#gratuityReportGraphs').hide();
        $('#salesByCustomer').hide();
        $("#salesByCategoryTable").empty();
        var test = "{Literal}${/Literal}";
        dataLength = data.length;
        if (dataLength != 0) {
            var categoryTotal = 0; 
            for (var i = 0; i < dataLength; i++) {
                categoryTotal = categoryTotal + data[i].categoryTotal;
            }
            document.getElementById('totalSalesCategory').value = test + categoryTotal.toCurrency();
        }

        for (var i = 0; i < data.length; i++) {
            if (data[i].category == "") {
                data[i].category = "{Literal}No Category{/Literal}"
            }
            var appendMe = '<thead><tr><th>' + data[i].category + '</th></tr></thead><tbody>';
            appendMe = appendMe + '<tr><td><i>{Literal}Item Id{/Literal}</i></td><td><i>{Literal}Description{/Literal}</i></td><td><i>{Literal}Quantity{/Literal}</i></td><td><i>{Literal}Total{/Literal}</i></td></tr>';
            var total = 0;
            if (data[i].lineItems.length == undefined) {
                appendMe = appendMe + '<tr><td>' + data[i].lineItems.id + '</td><td>' + data[i].lineItems.itemDescription + '</td><td>' + data[i].lineItems.itemQuantity + '</td><td>{Literal}${/Literal}' + data[i].lineItems.itemTotal.toFixed(2) + '</td></tr>';
                total = total + data[i].lineItems.itemTotal;
            }
            else {
                for (var t = 0; t < data[i].lineItems.length; t++) {
                    appendMe = appendMe + '<tr><td>' + data[i].lineItems[t].id + '</td><td>' + data[i].lineItems[t].itemDescription + '</td><td>' + data[i].lineItems[t].itemQuantity + '</td><td>{Literal}${/Literal}' + data[i].lineItems[t].itemTotal.toFixed(2) + '</td></tr>';
                    total = total + data[i].lineItems[t].itemTotal;
                }
            }

            appendMe = appendMe + '<tr><td></td><td></td><td></td><td>{Literal}${/Literal}' + total.toFixed(2) + '</td></tr>';
            appendMe = appendMe + '</tbody>';
            $('#salesByCategoryTable').append(appendMe);
        }

        var categoryByTotal = [];
        var dataEmpty = false
        if (data == []) {
            dataEmpty = true;
        }
        else {
            data.sort((a, b) => (a.categoryTotal < b.categoryTotal) ? 1 : -1)

            if (data.length > 10) {
                var test = [];
                for (var i = 0; i < 10; i++) {
                    var test2 = [];
                    if (data[i].category == "") {
                        data[i].category = "{Literal}No Category{/Literal}"
                    }
                    test2.push(data[i].category);
                    test2.push(data[i].categoryTotal.toFixed(2));
                    test.push(test2);
                    categoryByTotal[i] = [data[i].category, data[i].categoryTotal];
                }
            }
            else {
                var test = [];
                for (var i = 0; i < data.length; i++) {
                    var test2 = [];
                    if (data[i].category == "") {
                        data[i].category = "{Literal}No Category{/Literal}"
                    }
                    test2.push(data[i].category);
                    test2.push(data[i].categoryTotal.toFixed(2));
                    test.push(test2);
                    categoryByTotal[i] = [data[i].category, data[i].categoryTotal];
                }
            }
        }

        if (dataEmpty) {
            var tenderTypesChart = c3.generate({
                bindto: '#sales-by-category-pie-chart',
                legend: {
                    position: 'right'
                },
                size: {
                    height: 150
                },
                data: {
                    colors: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: [],
                    type: 'pie',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                donut: {
                    title: ""
                }
            });
        }
        else {
            var tenderTypesChart = c3.generate({
                bindto: '#sales-by-category-pie-chart',
                size: {
                    height: 150
                },
                data: {
                    color: {
                        pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                    },
                    columns: test,
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                axis: {
                    x: {
                        show: false,
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
            });
        }
    },

    
    generateSalesByHour: function (data) {
        this.$el.find('.chart-content').show();
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').show();
        $('#initialGraphs').hide();
        $('#salesByCategory').hide();
        $('#salesByUser').hide();
        $('#employeeHourGraph').hide();
        $('#gratuityReportGraphs').hide();
        $('#salesByCustomer').hide();

        var salesByTime = data.salesByTimeData;
        var salesByTimeColumns = (['Sales']).concat(salesByTime.salesData);
        var salesLabels = salesByTime.salesLabels;
        this.salesLabels = salesByTime.salesLabels;
       
        var salesByTimeColumnsEmpty = true;
        for (var i = 1; i < salesByTimeColumns.length; i++) {
            if (salesByTimeColumns[i] > 0) {
                salesByTimeColumnsEmpty = false;
            }
        }

        var salesByQuantity = data.salesByTimeData;
        var salesByQuantityColumns = (['Sales']).concat(salesByQuantity.quantityByHourData);
        var salesByQuantityLabels = salesByQuantity.salesLabels;

        if (salesByTimeColumnsEmpty) {
            var chart3 = c3.generate({
                bindto: '#sales-by-hour-bar-chart',
                size: {
                    height: 150
                },
                grid: {
                    y: {
                        show: true
                    }
                },
                data: {
                    color: function (color, d) { return '#3754a0' },
                    columns: [],
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                legend: {
                    show: false
                },
                axis: {
                    x: {
                        tick: {
                            multiline: false,
                            rotate: 60,
                        },
                        type: 'category',
                        categories: salesLabels
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
                bar: {
                    width: {
                        ratio: 0.75
                    }
                }
            });
            var chart3 = c3.generate({
                bindto: '#sales-by-hour-quantity-bar-chart',
                size: {
                    height: 150
                },
                grid: {
                    y: {
                        show: true
                    }
                },
                data: {
                    color: function (color, d) { return '#3754a0' },
                    columns: [],
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                legend: {
                    show: false
                },
                axis: {
                    x: {
                        tick: {
                            multiline: false,
                            rotate: 60,
                        },
                        type: 'category',
                        categories: salesLabels
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
                bar: {
                    width: {
                        ratio: 0.75
                    }
                }
            });
            $("#salesHourTable").empty();
        }
        else {
            var chart3 = c3.generate({
                bindto: '#sales-by-hour-bar-chart',
                size: {
                    height: 150
                },
                grid: {
                    y: {
                        show: true
                    }
                },
                data: {
                    color: function (color, d) { return '#3754a0' },
                    columns: [salesByTimeColumns],
                    type: 'bar'
                },
                legend: {
                    show: false
                },
                axis: {
                    x: {
                        tick: {
                            multiline: false,
                            rotate: 60,
                        },
                        type: 'category',
                        categories: salesLabels
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
                bar: {
                    width: {
                        ratio: 0.75
                    }
                }
            }); 

            var chart3 = c3.generate({
                bindto: '#sales-by-hour-quantity-bar-chart',
                size: {
                    height: 150
                },
                grid: {
                    y: {
                        show: true
                    }
                },
                data: {
                    color: function (color, d) { return '#3754a0' },
                    columns: [salesByQuantityColumns],
                    type: 'bar'
                },
                legend: {
                    show: false
                },
                axis: {
                    x: {
                        tick: {
                            multiline: false,
                            rotate: 60,
                        },
                        type: 'category',
                        categories: salesLabels
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
                bar: {
                    width: {
                        ratio: 0.75
                    }
                }
            }); 

            $("#salesHourTable").empty();

            var newTimeArray = data.saleByTimeArray;
            newTimeArray.sort((a, b) => (a.date < b.date) ? 1 : -1)
            var lastDate = "";
            var tableContent = "";
            for (var i = 0; i < newTimeArray.length; i++) {
                // var thisHour = moment(newTimeArray[i].hour, "hh A").format("hh A");
                var thisHour = newTimeArray[i].hour;
                if(this.isCloudReport)
                    thisHour = newTimeArray[i].hourFormatted;
                    
                var thisDate = newTimeArray[i].date.split(" ")[0];
                if(lastDate != thisDate){
                    var dateHead = "";
                    if(i > 0)
                        dateHead = "</tbody>";
                        
                    dateHead += '<thead><tr class="highlight-hover"><th><span class="material-icons" style="color: gray; position: relative;top:6px">keyboard_arrow_down</span><span>' + thisDate + '</span></th><th></th><th></th><th></tr></thead><tbody style="display: none;">';
                    dateHead += '<tr><td>{Literal}Day{/Literal}</td><td>{Literal}Hour{/Literal}</td><td>{Literal}Transactions{/Literal}</td><td>{Literal}Total{/Literal}</td></tr>';
                    tableContent += dateHead;
                }

                tableContent += '<tr><td>' + thisDate + '</td> <td >' + thisHour + '</td> <td>'+ newTimeArray[i].qty.toCurrency(1) +'</td> <td style="color: black; direction: ltr;">{Literal}${/Literal}' + newTimeArray[i].total.toCurrency(2) + '</td></tr>';
                lastDate = thisDate
            }
            tableContent += "</tbody>";

            $('#salesHourTable').append(tableContent);
        }
        
    },

    generateLocationsChart: function(locationsSummary, onBarClickHandler){
        var that = this;

            var labels = [];
            var values = [];
            // var locationLabels = $('#location-dropdown').val();

            if(locationsSummary != undefined && Object.keys(locationsSummary).length > 0){
                var index = 0;
                Object.keys(locationsSummary).map(function (key) {
                    var locationObj = {id: index, location: key, selected: true};
                    // if(index == 0)
                    //     locationObj.selected = true;
                    that.chartSelectedLocations.push(locationObj);
                    labels.push(key);
                    index++;
                });

                Object.values(locationsSummary).map(function (val) { 
        
                    // Using Number() to convert key to number type 
                    // Using obj[key] to retrieve key value 
                    values.push(val);
                });
                values =  ['',...values];
            }
            // labels = $('#location-dropdown').val();
                
            var chart3 = c3.generate({
                bindto: '#locations-sales2-bar-chart',
                size: {
                    height: 230,
                },
                grid: {
                    y: {
                        show: true
                    }
                },
                data: {
                    selection: {
                        enabled: true,
                        multiple: true,
                    },
                    onclick: function(d, element) {
                        that.renderSalesLocations = false;
                        if(that.isFirstLocationClick){
                            that.isFirstLocationClick = false;
                            var barIndexes = chart3.data()[0].values.map( i => i.index);
                            chart3.select('',barIndexes);
                            chart3.unselect('',[d.index]);
                            that.chartSelectedLocations.forEach( i => i.selected = false);
                            that.chartSelectedLocations[d.index].selected = true;
                        } else {
                            that.chartSelectedLocations[d.index].selected = !that.chartSelectedLocations[d.index].selected;
                        }
                        onBarClickHandler(false, that);
                    },
                    color: function (color, d) { return '#3754a0' },
                    columns: values.length == 0 || !that.renderSalesLocations ? [] : [values],
                    type: 'bar',
                    empty: {
                        label: {
                            text: "{Literal}No Data Available{/Literal}"
                        }
                    }
                },
                legend: {
                    show: false
                },
                axis: {
                    x: {
                        tick: {
                            multiline: false,
                            rotate: -45,
                        },
                        type: 'category',
                        categories: labels,
                    },
                    y: {
                        tick: {
                            format: d3.format(",d"),
                            count: 5
                        }
                    }
                },
                bar: {
                    width: {
                        ratio: 0.75
                    }
                }
            });
            
            var columnsToUnselect = [];
            for (let i = 0; i < labels.length; i++) {
                if (i > 0)
                    columnsToUnselect.push(i);
                
            }
            
            $('#locations-sales2-bar-chart').show();
            // chart3.select([''], columnsToUnselect);

    },

    getCompReasonData: function (tillVal, fromDate, thruDate) {
        var that = this;
        var sessionToken = this.getCookie();

        $.ajax({
            url: '/data/get-comp-reason-data',
            data: {
                token: sessionToken,
                tillVal: tillVal,
                fromDate: fromDate,
                thruDate: thruDate
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.generateCompReasons(data);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching data from the server{/Literal}'
                    });
                }
            }
        });
    },

    generateCompReasons: function (data) {
        $('#compReasonGraph').show();
        $('#initialGraphs').hide();
        $('#salesByHourGraph').hide()

        var totalCompReasons = document.getElementById("totalCompReasons");
        totalCompReasons.value = data.totalCompReasons;

        var compArray = [];
        iterator = 0;
        categoryArray = [];

        for (var key in data.compReasons) {
            compArray[iterator] = [key + ' - {Literal}${/Literal}' + data.compReasons[key], data.compReasons[key]];
            categoryArray[iterator] = key;
            iterator++;
        }

        var tenderTypesChart = c3.generate({
            bindto: '#comps-bar-chart',
            legend: {
                position: 'right'
            },
            size: {
                height: 150
            },
            data: {
                color: {
                    pattern: ['#24c1e6', '#3754a0', '#11b5ae', '#5e8acc', '#017f9d']
                },
                columns: compArray,
                type: 'pie'
            },
            donut: {
                title: ""
            }
        });

        $("#compReasonTable tbody").empty();
        const keys = Object.keys(data.compReasons)
        const values = Object.values(data.compReasons)

        for (var i = 0; i < keys.length; i++) 
        {
            $('#compReasonTable tbody').append('<tr><td>' + keys[i] + '</td><td style="color: black; float: right; direction: RTL;">{Literal}${/Literal}' + values[i].toFixed(2) + '</td></tr>');
        }
    },

    searchResetReportBySearchTerm: function(e) {
        this.initAutoComplete();
        var element = $(e.currentTarget);
        var searchTerm = $(element).val();
        var that = this;
        if (searchTerm.trim().length > 0) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(function() {
                that.getResetReportsBySearchTerm(searchTerm);
            }, 300);
        }
    },
    
    getResetReportsBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-reset-reports',
            data: {
                searchTerm: searchTerm,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var results = data.results;
                var items = {};
                for (var i = 0; i < results.length; i++) {
                    var endDate = moment(results[i].start).format('YYYY-MM-DD');
                    var till = results[i].till;
                    var sequence = results[i].id;
                    items['Till ' + till + ' / #' + sequence + ' / ' + endDate] = null;
                    that.resetReportsMapping['Till ' + till + ' / #' + sequence + ' / ' + endDate] = { till: till, sequence: sequence };
                }
                
                that.resetReportSearchAutocomplete.updateData(items);
                that.resetReportSearchAutocomplete.open();
                
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    generateResetReport: function (e) {
        $('#compReasonGraph').hide();
        $('#salesByHourGraph').hide();
        $('#initialGraphs').show();
        $('#salesByCategory').hide();
        $('#salesByCustomer').hide();
        $('#salesByUser').hide();
        $('#sequenceSearch').show();
        $('#employeeHourGraph').hide();
        $('#gratuityReportGraphs').hide();
        var that = this;
        var sessionToken = this.getCookie();

        var element = $(e.currentTarget);
        var till = $(element).attr('till-id');
        var sequence = $(element).attr('data-id');

        this.chosenSequence = sequence;
        this.chosenTill = till;

        $('#sequence-modal').modal().modal('close');
        this.$el.find('.signature-modal-trigger-preloader').addClass('active');
        $.ajax({
            url: '/data/get-reset-report-data',
            data: {
                token: sessionToken,
                reset: sequence,
                tillName: till
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var dateRangeFormModal = that.$el.find('#date-range-form-modal').modal();
                dateRangeFormModal.modal('close');

                that.zOutSummary = data.zOutSummary;

                that.salesByItemType = data.salesByItemType;
                that.noSalesCount = data.noSaleCount;
                that.creditCardCount = data.creditCardCount;
                that.creditCardTotal = data.creditCardTotal;
                that.debitCardCount = data.debitCardCount;
                that.startingCash = data.startingCash;
                that.otherTips = data.otherTips;
                that.creditCardTips = data.creditCardTips;
                that.qtyItemTypes = data.qtyItemTypes;

                var insertTotalTransactions = document.getElementById('transactionCount');
                if (data.totalTransactions == null) {
                    insertTotalTransactions.value = 0;
                    that.totalTransactions = 0;
                }
                else {
                    insertTotalTransactions.value = data.totalTransactions;
                    that.totalTransactions = data.totalTransactions;
                }

                that.deliveryCount = data.deliveryCount;
                that.deliveryGuestCount = data.deliveryGuestCount;
                that.deliveryTotal = data.deliveryTotal;

                that.dineInCount = data.dineInCount;
                that.dineInGuestCount = data.dineInGuestCount;
                that.dineInTotal = data.dineInTotal;

                that.takeOutCount = data.takeOutCount;
                that.takeOutGuestCount = data.takeOutGuestCount;
                that.takeOutTotal = data.takeOutTotal;

                that.totalSales =  Math.round(data.totalSales * 100) / 100;
                that.largestTransaction = Math.round(data.largestTransaction * 100) / 100;
                that.totalItemsSold = data.totalItemsSold;
                that.cashTransactions = data.cashCount;

                var test = "{Literal}${/Literal}";
                document.getElementById('totalSales').value = test + that.totalSales.toCurrency();
                if (data.zOutSummary != '') {
                   document.getElementById('totalTender').value = test + data.zOutSummary.tenderingTotal.toCurrency();
                }
                
                var currency = 'USD';
                that.$el.find('.preloader-col').hide();
                that.$el.find('.chart-content').show();
                that.renderCharts(currency, data);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },

    showByHourRevenue: function() {
        $('#sales-by-hour-quantity-bar-chart-wrapper').hide();
        $('#sales-by-hour-bar-chart-wrapper').show();
    },

    showByHourQuantity: function() {
        $('#sales-by-hour-bar-chart-wrapper').hide();
        $('#sales-by-hour-quantity-bar-chart-wrapper').show();
    },
    showTopItemsByType: function() {
        $('#sales-by-item-bar-chart-wrapper').hide();
        $('#sales-by-type-bar-chart-wrapper').show();
        $('#itemsChartTitle').html('{Literal}Top 10 Item Types{/Literal}');
    },

    showTopItems: function() {
        $('#sales-by-item-bar-chart-wrapper').show();
        $('#sales-by-type-bar-chart-wrapper').hide();
        $('#itemsChartTitle').html('{Literal}Top 10 Items{/Literal}');
    },

    hideCashSales: function() {
        var tillVal = this.$el.find('#till-dropdown').val();
        var tillName = this.$el.find('#till-dropdown option:selected').text();
        if (tillVal == "all") {
            tillName = "All Tills"
        }
        var dateRange = this.getDateRange();
        this.showCustomerCashSales = false;

        this.getSalesByCustomerData(tillName, dateRange.fromDate, dateRange.thruDate);
    },

    showCashSales: function() {
        var tillVal = this.$el.find('#till-dropdown').val();
        var tillName = this.$el.find('#till-dropdown option:selected').text();
        if (tillVal == "all") {
            tillName = "All Tills"
        }
        var dateRange = this.getDateRange();
        this.showCustomerCashSales = true;

        if (dateRange != "custom") {
            this.getSalesByCustomerData(tillName, dateRange.fromDate, dateRange.thruDate);
        }
    },

    showUserByRevenue: function() {
        var tillVal = this.$el.find('#till-dropdown').val();
        var tillName = this.$el.find('#till-dropdown option:selected').text();
        if (tillVal == "all") {
            tillName = "All Tills"
        }
        var dateRange = this.getDateRange();

        if (dateRange != "custom") {
            this.userBySalesRevenue = true;
            this.getSalesByUserData(tillName, dateRange.fromDate, dateRange.thruDate);
        }
    },

    showUserByHour: function() {
        var tillVal = this.$el.find('#till-dropdown').val();
        var tillName = this.$el.find('#till-dropdown option:selected').text();
        if (tillVal == "all") {
            tillName = "All Tills"
        }
        var dateRange = this.getDateRange();

        if (dateRange != "custom") {
            this.userBySalesRevenue = false;
            this.getSalesByUserData(tillName, dateRange.fromDate, dateRange.thruDate);
        }
    },

    exportToExcel: function() {
        var dateRange = this.getDateRange();
        if(dateRange === "custom")
        {
            var fromDate = this.$el.find('#fromDate').val();
            var thruDate = this.$el.find('#thruDate').val();
            dateRange = {
                fromDate: moment(fromDate).hour(this.dayStartTime).minute(0).format("YYYY-MM-DD HH:mm:ss"),
                thruDate: moment(thruDate).add(1, 'days').hour(this.dayStartTime - 1).minute(59).format("YYYY-MM-DD HH:mm:ss")
            }
        }
        var reportType = this.$el.find('#report-type-filter').val();
        var tillVal = this.$el.find('#till-dropdown').val();
        if (tillVal == "all") {
            tillVal = "All Tills"
        }

        if (reportType == "zOutSummary") {
            var params = {
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
                sequence: null,
                till: tillVal,
                showGraphs: "true",
                exportToExcel: "true",
                location: this.$el.find('#location-dropdown option:selected').val(),
                isCloud: reportType == "zOutCloudSummary"
            }
            
            this.openReportWindowWithPostRequest('/data/generate-z-out-summary-report', params)
        }
        else if (reportType == "zOutCloudSummary") {
            var params = {
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
                sequence: null,
                showGraphs: "true",
                exportToExcel: "true",
                location: this.$el.find('#location-dropdown option:selected').val(),
            }
            
            this.openReportWindowWithPostRequest('/data/generate-z-out-cloud-summary-report', params)
        }
        else if (reportType == "cloudSalesByItem") {
            var params = {
                reportName: 'sales-by-item-type',
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
                sequence: null,
                showGraphs: "true",
                exportToExcel: "true",
                selectedLocations: this.$el.find('#location-dropdown option:selected').val(),
            }
            
            this.openReportWindowWithPostRequest('/data/cloud-report', params)
        }
        else if (reportType == "byHour") {
            var params = {
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
                sequence: null,
                till: tillVal,
                showGraphs: "true",
                exportToExcel: "true"
            }
            
            this.openReportWindowWithPostRequest('/data/generate-sales-by-hour-report', params)
        }
        else if (reportType == "byUser") {
            var params = {
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
                sequence: null,
                till: tillVal,
                showGraphs: "true",
                exportToExcel: "true"
            }
            
            this.openReportWindowWithPostRequest('/data/generate-sales-by-user-report', params)
        }
        else if (reportType == "customerSummary") {
            var params = {
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
                sequence: null,
                till: tillVal,
                showGraphs: "true",
                exportToExcel: "true"
            }
            
            this.openReportWindowWithPostRequest('/data/generate-sales-by-customer-summary-report', params)
        }
        else if (reportType == "itemCategory") {
            var params = {
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
                sequence: null,
                till: tillVal,
                showGraphs: "true",
                exportToExcel: "true"
            }

            this.openReportWindowWithPostRequest('/data/generate-sales-by-item-category-report', params)
        }
        else if (reportType == "resetReport") {
            var sequence = this.chosenSequence;
            var till = this.chosenTill;

            var params = {
                exportToExcel: "true",
                sequence: sequence,
                showGraphs: "true",
                till: till
            }

            this.openReportWindowWithPostRequest('/data/generate-reset-report', params)
        }
        else if (reportType == "employeeHour") {
            var sequence = this.chosenSequence;
            var till = this.chosenTill;

            var params = {
                exportToExcel: "true",
                fromDate: dateRange.fromDate,
                toDate: dateRange.thruDate,
            }

            this.openReportWindowWithPostRequest('/data/generate-employee-hour-report', params)
        }
    },


    openReportWindowWithPostRequest: function (winURL, params) {
        var winName='AccoPOS Report';
        var windowoption='resizable=yes,height=768,width=1024,location=0,menubar=0,scrollbars=1';
        var form = document.createElement("form");
        var sessionToken = this.getCookie();
        form.setAttribute("method", "post");
        form.setAttribute("token", sessionToken);
        form.setAttribute("action", winURL);
        form.setAttribute("target", winName);  
        for (var i in params) {
            if (params.hasOwnProperty(i)) {
                var input = document.createElement('input');
                input.type = 'text';
                input.name = i;
                input.value = params[i];
                form.appendChild(input);
            }
        }
        document.body.appendChild(form);
        window.open('', winName, windowoption);
        form.target = winName;
        form.submit();
        document.body.removeChild(form);           
    },

    openEmailReportModel: function() {
        if (App.serverInfo.companyEmail != "") {
            var checkEmailCookie = this.getEmailCookie("AccuPOSEmailCookie");
            if (checkEmailCookie != null || checkEmailCookie != "") {
                var emailValue = document.getElementById("emailInfo");
                emailValue.value = checkEmailCookie;
            }
            $('#email-report-modal').modal().modal('open');
        }
        else {
            M.toast({
                html: '{Literal}Please define a company email under receipt settings to email this report{/Literal}'
            });
        }
    },

    sendEmailReport: function() {
        var tillVal = this.$el.find('#till-dropdown').val();
        var email = this.$el.find('#emailInfo').val();
        if (email == "") {
            M.toast({
                html: '{Literal}An email is required{/Literal}'
            });
        }
        else {
            this.saveCookie(email);
            var splitEmail = [];
            if (email.includes(";")) {
                splitEmail = email.split(";");
                for (var i = 0; i < splitEmail.length; i++) {
                    splitEmail[i] = splitEmail[i].trim();
                }
            }
            else {
                splitEmail[0] = email;
            }

            var reportType = this.$el.find('#report-type-filter').val();
            var reportContent = "<div>"; 
            var reportTitle = "";   

            var location = this.getSelectedLocations();
            var emailReportTitle = document.getElementById('report-title');
            sequence = "N/A";

           if (reportType == "byHour") {
                emailReportTitle.innerHTML = "Sales by Hour Report";
                reportTitle = "Sales by Hour Report";
                signatureFileName = "sales_by_hour"
            }
            else if (reportType == "byUser") {
                emailReportTitle.innerHTML = "Sales by User Report";
                reportTitle = "Sales by User Report";
                signatureFileName = "sales_by_user"
            }
            else if (reportType == "customerSummary") {
                emailReportTitle.innerHTML = "Sales by Customer Report";
                reportTitle = "Sales by Customer Report";
                signatureFileName = "sales_by_customer"
            }
            else if (reportType == "itemCategory") {
                emailReportTitle.innerHTML = "Sales by Item Category Report";
                reportTitle = "Sales by Item Category Report";
                signatureFileName = "sales_by_item_category"
            }
            else if (reportType == "zOutSummary") {
                emailReportTitle.innerHTML = "Z Reset Summary Report";
                reportTitle = "Z Out Summary Report";
                signatureFileName = "z_out_summary"
            }
            else if (reportType == "zOutCloudSummary") {
                emailReportTitle.innerHTML = "Z Out Cloud Summary Report";
                reportTitle = "Z Out Cloud Summary Report";
                signatureFileName = "z_out_cloud_summary"
            }
            else if (reportType == "cloudSalesByHour") {
                emailReportTitle.innerHTML = "Sales By Hour Cloud Report";
                reportTitle = "Sales By Hour Cloud Report";
                signatureFileName = "cloud_sales_by_hour"
            }
            else if (reportType == "cloudSalesByItem") {
                emailReportTitle.innerHTML = "Sales By Item Cloud Report";
                reportTitle = "Sales By Item Cloud Report";
                signatureFileName = "cloud_sales_by_item"
            }
            else if (reportType == "resetReport") {
                emailReportTitle.innerHTML = "Z Reset Summary Report";
                signatureFileName = "z_reset_summary"
                reportTitle = "Z Reset Summary Report";
                sequence = this.chosenSequence;
            }
            else if (reportType == "byType") {
                emailReportTitle.innerHTML = "Sales by Item Type Report";
                reportTitle = "Sales by Item Type Report";
                signatureFileName = "sales_by_item_type"
            }
            else if (reportType == "gratuityReport") {
                emailReportTitle.innerHTML = "Employee Gratuity Report";
                reportTitle = "Employee Gratuity Report";
                signatureFileName = "gratuity_report"
            }
            else if (reportType == "employeeHour") {
                emailReportTitle.innerHTML = "Employee Hour Report";
                reportTitle = "Employee Hour Report";
                signatureFileName = "employee_hour_report"
            }

            $('#emailReportTemplate').show();

            reportContent = reportContent + document.getElementById('emailReportTemplate').innerHTML;

            $('#emailReportTemplate').hide();

            reportContent = reportContent + "</div>"

            var dateRange = this.getDateRange();
            if (dateRange == 'custom') {
                var fromDate = this.$el.find('#fromDate').val();
                var thruDate = this.$el.find('#thruDate').val();
                this.dateRange =  {
                    fromDate: moment(fromDate).hour(this.dayStartTime).minute(0).format("YYYY-MM-DD HH:mm:ss"),
                    thruDate: moment(thruDate).add(1, 'days').hour(this.dayStartTime - 1).minute(59).format("YYYY-MM-DD HH:mm:ss")
                }
            }
            if (reportContent != null) {
                for (var i = 0; i < splitEmail.length; i++) {
                    var that = this;
                    $.ajax({
                        url: '/email_report.html',
                        data: {
                            till: tillVal,
                            reportContent: reportContent,
                            emailAddress:  (splitEmail[i]),
                            reportTitle: reportTitle,
                            fromDate: this.dateRange.fromDate,
                            thruDate: this.dateRange.thruDate,
                            signatureFileName: signatureFileName,
                            sequence: sequence,
                            location: location
                        },
                        dataType: 'json',
                        type: 'POST',
                        success: function (data) {
    
                        },
                        error: function (e) {
                            if (e.status == 523) {
                                window.location.href = "#/log-in";
                                location.reload();
                            }
                        }
                    });
                    M.toast({
                        html: '{Literal}Exported Successfully{/Literal}'
                    });
                    
                }

            }
        }
        $('#email-report-modal').modal().modal('close');
    },

    saveCookie: function (email) {
        var days = 30;
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = "AccuPOSEmailCookie=" + (email || "")  + expires + "; path=/";

    },

    getEmailCookie: function (cname) {
        var nameEQ = cname + "=";
        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);
        }
        return null;
    },

    arrayRemove: function(arr, value) {

        return arr.filter(function(ele){
            return ele != value;
        });
     
    },

    openCustomDateRangeModal: function() {
        var dateRangeFormModal = this.$el.find('#date-range-form-modal').modal();
            dateRangeFormModal.modal('open');
    },

    getDateRange: function() {
        var dateRangeVal = this.$el.find('#date-range-preset').val();
        var reportType = this.$el.find('#report-type-filter').val();
        var now = new Date();
        now.setHours(0,0,0,0);
        var fromDate;
        var thruDate;
        if (dateRangeVal == "custom" && reportType != "resetReport") {
        //     var dateRangeFormModal = this.$el.find('#date-range-form-modal').modal();
        //     dateRangeFormModal.modal('open');
            return "custom";
        }
        if (dateRangeVal == "today") {
           
            fromDate = moment(now).hour(this.dayStartTime).minute(0);
            thruDate = moment(now).add(1, 'days').hour(this.dayStartTime - 1).minute(59);
        }
        else if (dateRangeVal == "yesterday") {
            fromDate = moment(now).subtract(1, 'days').hour(this.dayStartTime).minute(0);
            thruDate = moment(now).hour(this.dayStartTime - 1).minute(59);
        }
        else if (dateRangeVal == "thisWeek") {
            if(App.serverInfo.country == 'IL'){
                fromDate = moment(now).startOf('week').hour(this.dayStartTime).minute(0);
                thruDate = moment(now).endOf('week').add(1, 'days').hour(this.dayStartTime - 1).minute(59);
            }
            else {
                fromDate = moment(now).startOf('isoWeek').hour(this.dayStartTime).minute(0);
                thruDate = moment(now).endOf('isoWeek').add(1, 'days').hour(this.dayStartTime - 1).minute(59);
            }
        }
        else if (dateRangeVal == "previousWeek") {
            if(App.serverInfo.country == 'IL'){
                fromDate = moment(now).subtract(7, 'days').startOf('week').hour(this.dayStartTime).minute(0);
                thruDate = moment(now).subtract(7, 'days').endOf('week').add(1, 'days').hour(this.dayStartTime - 1).minute(59);
            }
            else {
                fromDate = moment(now).subtract(7, 'days').startOf('isoWeek').hour(this.dayStartTime).minute(0);
                thruDate = moment(now).subtract(7, 'days').endOf('isoWeek').add(1, 'days').hour(this.dayStartTime - 1).minute(59); 
            }
        }
        else if (dateRangeVal == "thisMonth") {
            fromDate = moment(now).startOf('month').hour(this.dayStartTime).minute(0);
            thruDate = moment(now).endOf('month').add(this.dayStartTime, 'hours').minute(59);
        }
        else if (dateRangeVal == "previousMonth") {
            fromDate = moment(now).subtract(1, 'month').startOf('month').hour(this.dayStartTime).minute(0);
            thruDate = moment(now).subtract(1, 'month').endOf('month').add(this.dayStartTime, 'hours').minute(59);
        }
        else if (dateRangeVal == "previous3Months") {
            fromDate = moment().quarter(moment().quarter() - 1).startOf('quarter').hour(this.dayStartTime).minute(0);
            thruDate = moment().quarter(moment().quarter() - 1).endOf('quarter').add(this.dayStartTime, 'hours').minute(59);
        }
        else if(dateRangeVal == "this3Months") {

            fromDate = moment().quarter(moment().quarter()).startOf('quarter').hour(this.dayStartTime).minute(0);
            thruDate = moment().quarter(moment().quarter()).endOf('quarter').add(this.dayStartTime, 'hours').minute(59);
        }

        if(fromDate != undefined && thruDate != undefined)
            this.$el.find('#dateRangeDisplay').html(toDateString(fromDate.toDate()) + " - " + toDateString(thruDate.toDate()));

        
        // M.toast({ html: '{Literal}Fetching Data From {/Literal}' + fromDate.format('YYYY-MM-DD') + ' {Literal}to{/Literal} ' + thruDate.format('YYYY-MM-DD') });
        this.dateRange = {
            fromDate: fromDate.format('YYYY-MM-DD HH:mm:00'),
            thruDate: thruDate.format('YYYY-MM-DD HH:mm:59')
        }
            
        return this.dateRange;

    },

    getLocationsAndRender: function(callback){
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-locations',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                App.cloudLocations = data.results;
                callback(data.results, that);
            },
            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}'
                    });
                }
            }
        });
    },
    renderLocations: function (locations, that) {
        locations.forEach( function(location) {
            $("#locationSelector select").append(`<option value="${location}">${location}</option>`);
            });

        $('#location-dropdown').formSelect();
        $("#locationSelector .select-wrapper ul").prepend(
            '<li id="loadCloudReport"><a class="waves-effect waves-light btn ap-blue" style="height:55px"><i class="material-icons white-text">cloud</i>{Literal}Load Locations{/Literal}</a></li>');

        $("#loadCloudReport").on('click', () => { that.getCloudData()});
    },
    getDayStartTime: async function(){
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-company-info',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.dayStartTime = data.company_info.dayStart;
            },
            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}'
                    });
                }
            }
        })
    },
    selectAllLocations: function() {
        var that = this;
        var selectAll = this.$el.find("#locationIcon").attr("all") === "true";
        this.$el.find('#location-dropdown option').each( (i,e) => {
            e.selected = selectAll;
        });
        this.$el.find('#location-dropdown').formSelect();
        this.$el.find("#locationIcon").attr("all", !selectAll);

        $("#locationSelector .select-wrapper ul").prepend(
            '<li id="loadCloudReport"><a class="waves-effect waves-light btn ap-blue" style="height:55px"><i class="material-icons white-text">cloud</i>{Literal}Load Locations{/Literal}</a></li>');

        $("#loadCloudReport").on('click', () => { that.getCloudData()});

        if(selectAll)
            this.getCloudData();
    },
    getSelectedLocations: function() {
        var selectedLocations = "";
        if(App.serverInfo.hasCloudReporting){
            selectedLocations = this.$el.find('#location-dropdown').val();

            if(selectedLocations.length > 1 && selectedLocations[0] === 'all')
                selectedLocations.splice(0, 1);

            selectedLocations = selectedLocations.join(";");
        }
        return selectedLocations;
    },
  
    getCloudData: function() {
        var that = this;
        var locations = that.getSelectedLocations();
        if(locations == undefined || locations == ""){
            $("#locationSelector input").addClass("invalid");
            M.toast({ html: '{Literal}Select Location{/Literal}'});
            return;
        }

        if(!that.dateRange.fromDate)
            this.getDateRange();

        var reportType = this.$el.find('#report-type-filter').val();

        if(reportType == 'zOutCloudSummary')
            url = '/data/get-date-range-sales-cloud-data';
        else if(reportType == 'cloudSalesByHour')
            url = '/data/get-date-range-sales-by-hour-cloud-data';
        else if(reportType == 'cloudSalesByItem')
            url = '/data/get-date-range-sales-by-item-cloud-data';

        M.toast({ html: '{Literal}Fetching Data From {/Literal}' + that.dateRange.fromDate + ' {Literal}to{/Literal} ' + that.dateRange.thruDate });
        that.$el.find('.signature-modal-trigger-preloader').addClass('active');

        $.ajax({
            url: url,
            data: {
                token: that.getCookie(),
                fromDate: that.dateRange.fromDate,
                thruDate: that.dateRange.thruDate,
                location: locations
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var dateRangeFormModal = that.$el.find('#date-range-form-modal').modal();
                dateRangeFormModal.modal("close");
                that.cloudData = data;
                var isFirstRun = true;
                that.renderSalesLocations = true;
                that.isFirstLocationClick = true;
                if(reportType == 'zOutCloudSummary')
                    that.calculateDataBySelectedLocation(isFirstRun);
                else if(reportType == 'cloudSalesByHour')
                    that.calculateSalesByHourBySelectedLocation(isFirstRun);
                else if(reportType == 'cloudSalesByItem')
                    that.calculateSalesByItemBySelectedLocation(isFirstRun);
                
                // var currency = 'USD';
                that.$el.find('.preloader-col').hide();
                that.$el.find('.chart-content').show();
                // that.renderCharts(currency, data);
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('.preloader-col').hide();
                    that.$el.find('.chart-content').show();
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                    M.toast({
                        html: '{Literal}There was a problem fetching cloud data{/Literal}'
                    });
                }
            }
        });
    },

    getTenderTypes: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-tender-types',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
               that.tenderCodes = 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 data from the server{/Literal}'
                    });
                }
            }
        });

    },

    calculateDataBySelectedLocation: function(isFirstRun = false) {
        var that = this;
        var data = JSON.parse(JSON.stringify(this.cloudData));
        data.totalSales = 0;
        data.qtyItemTypes = {};
        if(!data.locationsSummary)
            data.locationsSummary = {};
        data.salesByTenderType = {};
        data.saleByTimeArray = [];
        if(!data.salesByTimeData)
            data.salesByTimeData = {};
        data.salesByTimeData.salesData = [] ;
        data.zOutSummary = {
            reportTaxable: 0,
            voidQuantityTotal: 0,
            voidTotal: 0,
            tipsTotal: 0,
            priceChangeTotal: 0,
            taxTotal: 0,
            taxes: [],
            vat2Tax: 0,
            autoGratuity: 0,
            customerPayments: 0,
            reportNontaxable: 0,
            compTotal: 0,
            payoutsTotal: 0,
            tipsPaid: 0,
            voids: [],
            salesDiscountTotal: 0,
            itemTotal: 0,
            tenders: [],
            vatTaxes: [],
            tenderingTotal: 0,
            itemQuantityTotal: 0,
            netCash: 0,
            guestCount: 0,
            vat1Tax: 0,
            items: [],
            creditCardTotal: 0         
        };

        if(data.zOutCloudSummary && data.zOutCloudSummary.itemTypeSummary){
            for( let item of data.zOutCloudSummary.itemTypeSummary) {
                var thisSelectedLocation = that.chartSelectedLocations.find( l => l.location == item.location);
                if(!isFirstRun && !thisSelectedLocation.selected)
                    continue;

                data.totalSales += item.total;

                var typeQty = data.qtyItemTypes[item.itemType];
                if(typeQty == undefined)
                    data.qtyItemTypes[item.itemType] = 0;

                data.qtyItemTypes[item.itemType] +=  item.quantity;

                var typeTotal = data.salesByItemType[item.itemType];
                if(typeTotal == undefined)
                    data.salesByItemType[item.itemType] = 0;

                data.salesByItemType[item.itemType] +=  item.total;
                
                data.zOutSummary.items.push({
                    total: item.total,
                    quantity: item.quantity,
                    name: item.itemType
                });
            };
        }

        if(data.zOutCloudSummary && data.zOutCloudSummary.tendersSummary) {
            for( let item of data.zOutCloudSummary.tendersSummary) {
                var thisSelectedLocation = that.chartSelectedLocations.find( l => l.location == item.location);
                if(!isFirstRun && !thisSelectedLocation.selected)
                    continue;

                data.zOutSummary.tenderingTotal += item.amount;

                var locationTotal = data.locationsSummary[item.location];
                if(locationTotal == undefined){
                    data.locationsSummary[item.location] = 0;
                }
                data.locationsSummary[item.location] += item.amount;

                var tenderTotal = data.salesByTenderType[item.tenderDescription];
                if(tenderTotal == undefined){
                    data.salesByTenderType[item.tenderDescription] = 0;
                }
                data.salesByTenderType[item.tenderDescription] += item.amount;

                data.zOutSummary.tenders.push({
                    total: item.amount,
                    name: item.tenderDescription
                });
            };
        }

      


        that.zOutSummary = data.zOutSummary;

        that.salesByItemType = data.salesByItemType;
        that.noSalesCount = 0;
        that.creditCardCount = 0;
        that.creditCardTotal = data.creditCardTotal;
        that.debitCardCount = 0;
        that.startingCash = 0;
        that.otherTips = 0;
        that.creditCardTips = 0;
        that.qtyItemTypes = data.qtyItemTypes;

        var insertTotalTransactions = document.getElementById('transactionCount');
        if (data.totalTransactions == null) {
            insertTotalTransactions.value = 0;
            that.totalTransactions = 0;
        }
        else {
            insertTotalTransactions.value = data.totalTransactions;
            that.totalTransactions = data.totalTransactions;
        }

        that.deliveryCount = data.deliveryCount;
        that.deliveryGuestCount = data.deliveryGuestCount;
        that.deliveryTotal = data.deliveryTotal;

        that.dineInCount = data.dineInCount;
        that.dineInGuestCount = data.dineInGuestCount;
        that.dineInTotal = data.dineInTotal;

        that.takeOutCount = data.takeOutCount;
        that.takeOutGuestCount = data.takeOutGuestCount;
        that.takeOutTotal = data.takeOutTotal;

        that.totalSales =  Math.round(data.totalSales * 100) / 100;
        that.largestTransaction = Math.round(data.largestTransaction * 100) / 100;
        that.totalItemsSold = data.totalItemsSold;
        that.cashTransactions = data.cashCount;
        var test = "{Literal}${/Literal}";
        document.getElementById('totalSales').value = test + that.totalSales.toCurrency();
        if (data.zOutSummary.tenderingTotal != undefined) {
            document.getElementById('totalTender').value = test + data.zOutSummary.tenderingTotal.toCurrency();
        }

        var currency = 'USD';

        that.renderCharts(currency, data);
    },

    calculateSalesByHourBySelectedLocation: function (isFirstRun, that = this) {
        var data = JSON.parse(JSON.stringify(that.cloudData));
        var locationsSummary = data.locationsSummary;

        if(isFirstRun && locationsSummary != undefined && Object.keys(locationsSummary).length > 0){
            that.chartSelectedLocations = [];
            var index = 0;
            Object.keys(locationsSummary).map(function (key) {
                var locationObj = {id: index, location: key, selected: true};
                // if(index == 0)
                //     locationObj.selected = true;
                that.chartSelectedLocations.push(locationObj);
                index++;
            });

            that.generateLocationsChart(locationsSummary, that.calculateSalesByHourBySelectedLocation);
        }
        
        var saleByTimeArray = [];
        var quantityByHourData = new Array(24).fill(0);
        var salesData = new Array(24).fill(0);
        if(data && data.saleByTimeArray) {
            for( let item of data.saleByTimeArray ) {
                var thisSelectedLocation = that.chartSelectedLocations.find( l => l.location == item.locationCode);
                if( thisSelectedLocation.selected) {
                    // data.locationsSummary[item.locationCode] += item.total;
                    saleByTimeArray.push(item);
                    salesData[item.hour] += item.total;
                    quantityByHourData[item.hour] += item.qty
                }

            };
        }

        data.salesByTimeData.salesData = salesData;
        data.saleByTimeArray = saleByTimeArray;
        data.salesByTimeData.quantityByHourData = quantityByHourData;

        that.generateSalesByHour(data);
    },

    calculateSalesByItemBySelectedLocation: function (isFirstRun, that = this) {
        var data = JSON.parse(JSON.stringify(that.cloudData));

        if(isFirstRun && data.locationsSummary != undefined && Object.keys(data.locationsSummary).length > 0){
            that.chartSelectedLocations = [];
            var index = 0;
            Object.keys(data.locationsSummary).map(function (key) {
                var locationObj = {id: index, location: key, selected: true};
                // if(index == 0)
                //     locationObj.selected = true;
                that.chartSelectedLocations.push(locationObj);
                index++;
            });

            that.generateLocationsChart(data.locationsSummary, that.calculateSalesByItemBySelectedLocation);
        }

        var salesByType = [];
        if(that.cloudData && that.cloudData.salesByType) {
            for( let item of that.cloudData.salesByType ) {
                var thisSelectedLocation = that.chartSelectedLocations.find( l => l.location == item.locationCode);
                if( thisSelectedLocation.selected) {
                    salesByType.push(item);
                }

            };
        }
        
        that.generateSalesByType(salesByType, true);
    },

    emptyData: {
        "salesByTimeData": {
            "transactionByHourData": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            ],
            "noAMPMLabels": ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23"
            ],
            "salesData": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            ],
            "salesLabels": ["12AM","1AM","2AM","3AM","4AM","5AM","6AM","7AM","8AM","9AM","10AM","11AM","12PM","1PM","2PM","3PM","4PM","5PM","6PM","7PM","8PM","9PM","10PM","11PM"
            ]
        },
        "totalTransactions": 0,
        "deliveryGuestCount": 0,
        "returnSales": 0,
        "cashCount": 0,
        "takeOutGuestCount": 0,
        "salesByItemType": {},
        "creditCardTotal": 0,
        "openSales": 0,
        "dineInGuestCount": 0,
        "deliveryCount": 0,
        "totalItemsSold": 0,
        "dineInTotal": 0,
        "startingCash": 0,
        "salesByTenderType": {},
        "deliveryTotal": 0,
        "zOutSummary": "",
        "debitCardCount": 0,
        "largestTransaction": 0,
        "takeOutTotal": 0,
        "totalSales": 0,
        "qtyItemTypes": {},
        "takeOutCount": 0,
        "creditCardCount": 0,
        "noSaleCount": 0,
        "dineInCount": 0,
        // "dineInTotal": 0,
        // "takeOutTotal": 0,
        // "deliveryTotal": 0
    },
   
    showHideDetailsCategoryChilde: function(e) {
        $(e.currentTarget.nextSibling).toggle();
    },

    filterItems: function() {
        var filterText = $('#filterByItem').val();
        var autocomplete = $('#filterByItem')[0].M_Autocomplete;
        var itemsMap = autocomplete.itemsMap;
        var selectedItemId = itemsMap[filterText];
        var rows = $('#salesByTypeTable tbody tr');
        var heads = $('#salesByTypeTable thead');

        if(filterText == "") {
            for(var row of rows) {
                $(row).show();
            }
            for(var thead of heads) {
                $(thead).show();
            }
        }
        else {
            // filterText = filterText.toLowerCase();
            for(var row of rows) {
                var tds = $(row).find('td');
                if(tds[0].textContent == "{Literal}Item Id{/Literal}")
                    continue;

                var itemId = row.dataset.id;
                if(itemId != selectedItemId || filterText == ''){
                    $(row).hide();
                }
                else {
                    $(row).show();
                    $(row).parent().show();
                }
            }

            for (const thead of heads) {
                var id = thead.dataset.id;
                if((id != undefined && id != selectedItemId))
                    $(thead).hide();
                else
                    $(thead).show();
            }
        }
    },

    searchItemBySearchTerm: function(element) {
        var element = $(element.currentTarget);
        var searchTerm = $(element).val();
        var that = this;
        if (searchTerm.trim().length > 0) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(function() { 
                that.getItemsBySearchTerm(searchTerm); 
            }, 400);
        }
        else
            that.filterItems();
    },
    
    getItemsBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();

        var elems = document.querySelector('#filterByItem');
        this.itemsAutocomplete = M.Autocomplete.init(elems, {
            minLength: 1,
            limit: 20,
            sortFunction: function (a, b, inputString) {
                return a.indexOf(inputString) - b.indexOf(inputString);
            },
            onAutocomplete: that.filterItems
        });

        $.ajax({
            url: '/data/get-items-by-search-term',
            data: {
                token: sessionToken,
                searchTerm: searchTerm
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var results = data.results;
                var itemsMap = {};
                items = {};
                for (var i = 0; i < data.results.length; i++) {
                    items[results[i].itemCode + ' / ' + results[i].itemDescription] = null;
                    itemsMap[results[i].itemCode + ' / ' + results[i].itemDescription] = results[i].itemCode;
                }
                that.itemsAutocomplete.itemsMap = itemsMap;
                that.itemsAutocomplete.updateData(items);
                that.itemsAutocomplete.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {

                }
            }
        });
    },

});