var ReportsView = Backbone.View.extend({
    sequenceRows: 3,
    sequenceColumns: 4,
    pages: 0,
    sequenceTilesTemplate: null,
    bySequence: false,
    prefillState: false,
    itemMapping: {},
    resetReportsMapping: {},
    selectedTill: "",
    transactionFilter: [],
    tenderTypes: [],
    paymentTypeMapping: [],
    itemTypes: [],
    employees: [],
    tills: [],
    accessCloudReporting: false,
    getPayPeriodInfo: {},
    dayStartTime: 0,
    

    events: {
        'change .report-by-selector': 'toggleReportBySelector',
        'click .pagination-trigger': 'handlePageClickEvent',
        'click #pagination-back': 'handlePageBackEvent',
        'click #pagination-forward': 'handlePageForwardEvent',
        'click #sequence-modal-accept': 'applySequenceSelection',
        'click .run-report': 'runReport',
        'change select': 'validateSelect',
        'change #report-category': 'changeReportCategory',
        'change #report-type': 'changeReportType',
        'change #date-range-preset': 'prefillRangePreset',
        'click .autocomplete-content li': 'selectItemFromAutocompleteList',
        'keyup #user-search-autocomplete': 'searchUserBySearchTerm',
        'keyup #employee-search-autocomplete': 'searchEmployeeBySearchTerm',
        'keyup #customer-search-autocomplete': 'searchCustomerBySearchTerm',
        'keyup #customer-filter-autocomplete': 'searchCustomerBySearchTerm',
        'keyup #item-type-search-autocomplete': 'searchItemTypeBySearchTerm',
        'keyup #customer-type-search-autocomplete': 'searchCustomerTypeBySearchTerm',
        'keyup #reset-report-autocomplete': 'searchResetReportBySearchTerm',
        'keyup #adjustment-session-search-autocomplete': 'searchAdjustmentSessionsBySearchTerm',
        'keyup #item-category-search-autocomplete': 'searchItemCategoriesBySearchTerm',
        'click #signatures-modal-trigger': 'validateAndOpenSingatureModal',
        'click .signature-order-row': 'getOrderSignature',
        'change #report-start-time': 'checkIfEmptyStartDate',
        'change #report-end-time': 'checkIfEmptyEndDate',
        'click #signature-dismiss': 'dismissSignaturesModal',
        'click #signature-ok': 'saveSignaturesModal',
        'change #whole-day-time': 'toggleWholeDay',
        'change #transaction-filter-dropdown' : 'changeTransactionFilter',
        'click .advanced' : 'showAdvancedFilters',
        'change #item-filter-dropdown': 'changeItemFilter',
        'change #amount-filter-dropdown': 'changeAmountFilter',
        'click #pay-period-forward, #pay-period-back': 'nextPrevPayPeriod',
        'click #selectAllLocations' : 'selectUnselectAllLocations'
    },

    breadcrumb: {},
    chartRendered: false,
    chartDataColors: [
        '#d1d1d1',
        '#a156c4',
        '#ebc143',
        '#8097a2',
        '#39c7c1'
    ],
    dataColorIndex: 0,
    labeledDataColors: {},
    locations: [],

    initialize: async function (options) {
        this.options = options;
        this.template = _.template(options.template, {
            isFoodService: App.serverInfo.isFoodService
        });
        this.sequenceTilesTemplate = options.sequenceTilesTemplate;
        this.breadcrumb = options.breadcrumb;

        this.sequenceCollection = new SequenceCollection();
        this.sequenceTilesView = options.sequenceTilesView;
        await this.getLocations();
        await this.getTills();
        await this.initializeSequenceModal();
        await this.checkAccess();
        await this.getPayPeriodInfo();
        await this.getDayStartTime();

    },

    dismissSignaturesModal: function () {
        this.signatureModal.close();
    },
 
    saveSignaturesModal: function () {
        if (!this.selectedSignatureOrder) {
            M.toast({html: '{Literal}Please select a signature first or click Cancel to dismiss{/Literal}'});
        } else {
            this.signatureModal.close();
        }
    },

    render: function () {
        var that = this;
        
        this.$el.html(this.template({
            isFoodService: App.serverInfo.isFoodService,
            locations: that.locations
        }));
        App.breadCrumbToolTip = "Run various reports on your POS, such as an individual transaction or a list of your items"; 
        App.setBreadcrumbs(this.breadcrumb);
        $('.tooltipped').tooltip();
        
        $(document).ready(function () {
            that.initStartDateTimePickers();
            that.initEndDateTimePickers();
            that.$el.find('#date-range-preset').val("0");
            // that.$el.find('#locations-preset').val("0");
            that.initAutoComplete();

            that.$el.find('#items-autocomplete-placeholder input').keyup(function () {
                that.searchItemBySearchTerm(this);
            });

            that.initSignatureModal();
            // that.$el.find('#date-range-preset').formSelect();
            // that.$el.find('#locations-preset').formSelect();
            // that.$el.find('#filter-type-dropdown').formSelect();
            
            that.$el.find('#filter-type-dropdown').on('change', () => {
                var selectedFilterList =  that.$el.find('#filter-type-dropdown').val();
                that.$el.find('.advanced-filter').hide();
                selectedFilterList.forEach( filter => {
                    that.$el.find('#' + filter).show();
                })
                
            })
        });

        return this;
    },


    initSignatureModal: function () {
        var elems = document.querySelector('#signatures-modal');
        this.signatureModal = M.Modal.init(elems, {});
    },

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

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

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

    validateAndOpenSingatureModal: function () {
        this.$el.find('.signature-img-wrapper').html("");
        if (!this.selectedStartTime || !this.selectedEndTime) {
            M.toast({html: '{Literal}A start time and an end time must be selected first{/Literal}'});
        }
        else if (this.selectedEndTime.getTime() < this.selectedStartTime.getTime()) {
            M.toast({html: '{Literal}The end date cannot be sooner than the start date{/Literal}'});
        } else {
            this.getSignatureOrders();
        }
    },

    checkIfEmptyStartDate: function () {
        var value = this.$el.find('#report-start-time').val();
        if (value.trim() === '') {
            this.selectedStartTime = null;
        }
    },

    checkIfEmptyEndDate: function () {
        var value = this.$el.find('#report-end-time').val();
        if (value.trim() === '') {
            this.selectedEndTime = null;
        }
    },

    toggleWholeDay: function () {
        var checked = document.getElementById('whole-day-time').checked;
        var momentStart = moment(this.selectedStartTime).hour(this.dayStartTime).minute(0).second(1);
        var momentEnd = moment(this.selectedEndTime).add(1, 'days').hour(this.dayStartTime - 1).minute(59);
        this.selectedStartTime = momentStart.toDate();
        this.selectedEndTime = momentEnd.toDate();
        this.$el.find('#report-start-timepicker').val(momentStart.format('hh:mm a'));
        this.$el.find('#report-end-timepicker').val(momentEnd.format('hh:mm a'));
        if (checked) {
            this.$el.find('#report-start-timepicker').attr('disabled', '');
            this.$el.find('#report-end-timepicker').attr('disabled', '');
        } else {
            this.$el.find('#report-start-timepicker').removeAttr('disabled');
            this.$el.find('#report-end-timepicker').removeAttr('disabled');
        }
    },

    initAutoComplete: function () {
        var that = this;

        var baseOptions = {
            minLength: 1,
            limit: 20,
            sortFunction: function (a, b, inputString) {
                return a.indexOf(inputString) - b.indexOf(inputString);
            }
        };

        var itemOptions = _.extend({
            onAutocomplete: function (selection) { 
                if (!that.itemSearchAutocompleteSelection) {
                    that.itemSearchAutocompleteSelection = [];
                }
                that.itemSearchAutocompleteSelection.push(that.itemMapping[selection]); 
            }
        }, baseOptions);

        var userOptions = _.extend({
            onAutocomplete: function (selection) { that.userSearchAutocompleteSelection = selection; } 
        }, baseOptions);
        var employeeOptions = _.extend({
            onAutocomplete: function (selection) { that.employeeSearchAutocompleteSelection = selection; } 
        }, baseOptions);
        var customerOptions = _.extend({
            onAutocomplete: function (selection) { that.selectCustomerFromAutocompleteList(selection); }
        }, baseOptions);
        var transactionsFilterCustomerOptions = _.extend({
            onAutocomplete: function (selection) { that.selectCustomerFilterFromAutocompleteList(selection); }
        }, baseOptions);
        var itemTypeOptions = _.extend({
            onAutocomplete: function (selection) { that.itemTypeSearchAutocompleteSelection = selection; } 
        }, baseOptions);
        var customerTypeOptions = _.extend({
            onAutocomplete: function (selection) { that.customerTypeSearchAutocompleteSelection = selection; }
        }, baseOptions);
        var adjustmentSessionOptions = _.extend({
            onAutocomplete: function (selection) { that.adjustmentSessionSearchAutocompleteSelection = selection; }
        }, baseOptions);
        var itemCategoriesOptions = _.extend({
            onAutocomplete: function (selection) { that.itemCategoriesSearchAutocompleteSelection = selection; }
        }, baseOptions);

        var resetReportOptions = _.extend({
            onAutocomplete: function (selection) {
                var inputEl = document.getElementById('reset-report-autocomplete');
                inputEl.dataset.till = that.resetReportsMapping[selection].till;
                inputEl.dataset.sequence = that.resetReportsMapping[selection].sequence;
                
                that.resetReportSearchAutocompleteSelection = selection; 
            }
        }, baseOptions);
        
        //this.itemSearchAutocomplete = M.Autocomplete.init(document.querySelector('#item-search-autocomplete'), itemOptions);
        var chipCallback = function (a, b) {
                
            that.selectedItems = [];
            
            var data = [];
            $.each(this.chipsData, function (key, value) {
                data.push(that.itemMapping[value.tag]);
            });
            that.selectedItems = data;
        };
        this.itemSearchAutocomplete = M.Chips.init(document.querySelector('#item-search-autocomplete'), {
            autocompleteOptions: itemOptions,
            onChipAdd: chipCallback,
            onChipDelete: chipCallback,
            placeholder: '{Literal}Filter by items{/Literal}',
            secondaryPlaceholder: '+{Literal}Item{/Literal}',
        });

        this.userSearchAutocomplete = M.Autocomplete.init(document.querySelector('#user-search-autocomplete'), userOptions);
        this.employeeSearchAutocomplete = M.Autocomplete.init(document.querySelector('#employee-search-autocomplete'), employeeOptions);
        this.customerSearchAutocomplete = M.Autocomplete.init(document.querySelector('#customer-search-autocomplete'), customerOptions);
        this.transactionsReportcustomerSearchAutocomplete = M.Autocomplete.init(document.querySelector('#customer-filter-autocomplete'), transactionsFilterCustomerOptions);
        this.itemTypeSearchAutocomplete = M.Autocomplete.init(document.querySelector('#item-type-search-autocomplete'), itemTypeOptions);
        this.customerTypeSearchAutocomplete = M.Autocomplete.init(document.querySelector('#customer-type-search-autocomplete'), customerTypeOptions);
        this.adjustmentSessionSearchAutocompleteSelection = M.Autocomplete.init(document.querySelector('#adjustment-session-search-autocomplete'), customerTypeOptions);
        this.resetReportSearchAutocomplete = M.Autocomplete.init(document.querySelector('#reset-report-autocomplete'), resetReportOptions);
        this.itemCategoriesSearchAutocomplete = M.Autocomplete.init(document.querySelector('#item-category-search-autocomplete'), itemCategoriesOptions);
    },

    searchUserBySearchTerm: function(e) {
        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.getUsersBySearchTerm(searchTerm);
            }, 300);
        }
    },

    searchEmployeeBySearchTerm: function(e) {
        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.getEmployeesBySearchTerm(searchTerm);
            }, 300);
        }
    },

    searchItemBySearchTerm: function(element) { 
        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);
        }
    },

    searchCustomerBySearchTerm: function(e) {
        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.getCustomersBySearchTerm(searchTerm, e.target);
            }, 300);
        }
    },

    searchResetReportBySearchTerm: function(e) {
        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);
        }
    },

    searchItemTypeBySearchTerm: function(e) {
        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.getItemTypesBySearchTerm(searchTerm);
            }, 300);
        }
    },

    searchCustomerTypeBySearchTerm: function(e) {
        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.getCustomerTypesBySearchTerm(searchTerm);
            }, 300);
        }
    },

    searchAdjustmentSessionsBySearchTerm: function(e) {
        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.getAdjustmentSessionsBySearchTerm(searchTerm);
            }, 300);
        }
    },

    searchItemCategoriesBySearchTerm: function(e) {
        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.getItemCategoriesBySearchTerm(searchTerm);
            }, 300);
        }
    },

    selectItemFromAutocompleteList: function (e) {
        var element = $(e.currentTarget);
    },

    getUsersBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-users-by-search-term',
            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++) {
                    items[results[i].id] = null;
                }
                that.userSearchAutocomplete.updateData(items);
                that.userSearchAutocomplete.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },
    getEmployeesBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-employees-by-search-term',
            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++) {
                    items[results[i].value] = null;
                }
                console.log(items)
                that.employeeSearchAutocomplete.updateData(items);
                that.employeeSearchAutocomplete.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    getSignatureOrders: function () {
        var amountFrom = null;
        var amountTo = null;
        var startingDate = moment(this.selectedStartTime).format('YYYY-MM-DD HH:mm');
        var endingDate = moment(this.selectedEndTime).format('YYYY-MM-DD HH:mm');
        this.$el.find('.signature-modal-trigger-preloader').addClass('active');
        this.$el.find('#signatures-modal-trigger').attr('disabled', '');
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-orders-with-signatures',
            data: {
                amountFrom: amountFrom,
                amountTo: amountTo,
                startingDate: startingDate,
                endingDate: endingDate,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var orders = data.results;
                that.$el.find('#signatures-modal-trigger').removeAttr('disabled');
                that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                that.renderSignatureOrders(orders);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    that.$el.find('#signatures-modal-trigger').removeAttr('disabled');
                    that.$el.find('.signature-modal-trigger-preloader').removeClass('active');
                }
            }
        });
    },

    renderSignatureOrders: function (orders) {
        var preloaderHtml = this.$el.find(".preloader-template").html();
        var tableContent = this.$el.find('#signatures-modal').find('signatureCards');
        $('#signatureCards').html('');
        if (orders.length > 0) {
            for (var i = 0; i < orders.length; i++) {
                var order = orders[i];
                var html = '';
                html += '<div class="col s12 m3">';
                html += '<div class="signature-order-row card-panel card-panel-entity z-depth-1 sequence-card hoverable waves-effect waves-light" style="background-color: #ffffff" data-order-id="' + order.tenderId + '">';
                html += '<div><div class="row price truncate" style="font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Server{/Literal}: ' + order.server + '</div>'
                html += '<div class="row description truncate" style="color: #3970b7;">' + order.receiptDate + '</div>'
                html += '<div class="row price truncate" style="font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Time{/Literal}: ' + order.receiptTime + '</div>';
                html += '<div class="row price truncate" style="font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Order #{/Literal}: ' + order.orderNumber + '</div>';

                $('#signatureCards').append(html);
            }
        } else {
            var row = $('<tr>');
            var cell = $('<td colspan="7">');
            var noDataMessage = $('<div>').addClass('no-data-message').addClass('center-align');
            $(noDataMessage).html('There are no relevant orders to show in the selected time range.');
            cell.append(noDataMessage);
            $(row).append(cell);
            $('#signatureCards').append(row);
        }
        this.signatureModal.open();
    },

    getOrderSignature: function (e) {
        
        var element = $(e.currentTarget);
        $(element).find('.preloader-wrapper').addClass('active');
        var orderId = $(element).attr("data-order-id");
        var that = this;
        that.$el.find('.signature-img-wrapper').html("");
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-signature-by-tender-id',
            data: {
                tenderId: orderId,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.selectedSignatureOrder = orderId;
                var html = $('<div class="ap-badge">Order #' + orderId + '&nbsp</div>');
                that.$el.find('.selected-signature-text').html(html);
                var imagePath = data.imagePath;
                var img = $('<img>');
                $(img).attr('src', '/img/' + imagePath + '?' + Date.now());
                $(img).addClass('signature');

                $(element).find('.preloader-wrapper').removeClass('active');
                that.$el.find('.signature-img-wrapper').append(img);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    $(element).find('.preloader-wrapper').removeClass('active');
                }
            }
        });
    },

    getCustomersBySearchTerm: function(searchTerm, element) {
        this.customerMapping = {};
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-customers-by-search-term',
            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++) {
                    items[results[i].id + ' / ' + results[i].name + ' / ' +  results[i].phone] = null;
                    that.customerMapping[results[i].id + ' / ' + results[i].name + ' / ' +  results[i].phone] = { id: results[i].id, name: results[i].name, phone: results[i].phone };
                }

                var instance = M.Autocomplete.getInstance(element);
                instance.updateData(items);
                instance.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    getItemTypesBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        this.itemTypeMapping = {};
        
        $.ajax({
            url: '/data/get-item-types-by-search-term',
            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++) {
                    items[results[i]] = null;
                    that.itemTypeMapping[results[i]] = { name: results[i] };
                }
                that.itemTypeSearchAutocomplete.updateData(items);
                that.itemTypeSearchAutocomplete.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    getAdjustmentSessionsBySearchTerm: function (searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-adjustment-sessions-by-search-term',
            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++) {
                    items[results[i]] = null;
                }
                that.adjustmentSessionSearchAutocompleteSelection.updateData(items);
                that.adjustmentSessionSearchAutocompleteSelection.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    getItemCategoriesBySearchTerm: function (searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-item-categories-by-search-term',
            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++) {
                    items[results[i]] = null;
                }
                that.itemCategoriesSearchAutocomplete.updateData(items);
                that.itemCategoriesSearchAutocomplete.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    getCustomerTypesBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-customer-types-by-search-term',
            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++) {
                    items[results[i]] = null;
                }
                that.customerTypeSearchAutocomplete.updateData(items);
                that.customerTypeSearchAutocomplete.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

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

    getItemsBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-items-by-search-term',
            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 itemSearchBy = results[i].itemDescription + " / " + results[i].itemCode;
                    items[itemSearchBy] = null;
                    that.itemMapping[itemSearchBy] = results[i].itemCode;
                }
                that.itemSearchAutocomplete.autocomplete.updateData(items);
                that.itemSearchAutocomplete.autocomplete.open();
                
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    validateTransactionReport: function() {
        var valid = true;

        var reportStartDateValue = this.$el.find('#report-start-time').val();
        var reportEndDateValue = this.$el.find('#report-end-time').val();
        var reportStartTimeValue = this.$el.find('#report-start-timepicker').val();
        var reportEndTimeValue = this.$el.find('#report-end-timepicker').val();

        if (this.bySequence === false) {
            var reportStartTime = this.$el.find('#report-start-time').val();
            if (reportStartDateValue === null || reportStartDateValue === '') {
                this.$el.find('#report-start-time').addClass('invalid');
                valid = false;
            }
            var reportEndTime = this.$el.find('#report-end-time').val();
            if (reportEndDateValue === null || reportEndDateValue === '') {
                this.$el.find('#report-end-time').addClass('invalid');
                valid = false;
            }
            if (reportStartTimeValue === null || reportStartTimeValue === '') {
                this.$el.find('#report-start-timepicker').addClass('invalid');
                valid = false;
            }
            if (reportEndTimeValue === null || reportEndTimeValue === '') {
                this.$el.find('#report-end-timepicker').addClass('invalid');
                valid = false;
            }
            if (valid) {
                if (typeof this.selectedStartTime !== 'undefined' && typeof this.selectedEndTime !== 'undefined') {
                    if (this.selectedStartTime.getTime() > this.selectedEndTime.getTime()) {
                        M.toast({html: '{Literal}The end date cannot be sooner than the start date{/Literal}'});
                        valid = false;
                    }
                }
            }
        } 
        else {

            var selectedSequence = this.$el.find('#reset-report-autocomplete').attr('data-sequence');
            if (selectedSequence === undefined || selectedSequence === null || selectedSequence === '' || selectedSequence.length === 0) {
                this.$el.find('#sequence-error-msg').show();
                valid = false;
            }
            
        }

        return valid;
    },

    validateReport: function () {
        var valid = true;
        var reportCategory = this.$el.find('#report-category').val();
        var reportSettings = this.getReportSettingsByCategoryAndType(reportCategory, this.reportType);
        var reportFilters = reportSettings.length > 0 ? reportSettings[0].filters : [];
        
        var reportStartDateValue = this.$el.find('#report-start-time').val();
        var reportEndDateValue = this.$el.find('#report-end-time').val();
        var reportStartTimeValue = this.$el.find('#report-start-timepicker').val();
        var reportEndTimeValue = this.$el.find('#report-end-timepicker').val();



        if (reportCategory === null || reportCategory === '') {
            this.$el.find('#report-category').closest('.select-wrapper').addClass('invalid');
            valid = false;
        }
        var reportType = this.$el.find('#report-type').val();
        if (reportType === null || reportType === '') {
            this.$el.find('#report-type').closest('.select-wrapper').addClass('invalid');
            valid = false;
        }

        if (reportCategory == "cloudData" && !this.accessCloudReporting) {
            M.toast({html: '{Literal}You do not have access to Cloud Reporting{/Literal}'});
            valid = false;
        }

        for (var i = 0; i < reportFilters.length; i++) {
            var thisFilter = reportFilters[i];
            if (thisFilter == "customer" && reportCategory == "general") {
                var customerFilter = this.$el.find('#customer-search-autocomplete').val();
                if (customerFilter == "") {
                    M.toast({html: '{Literal}A customer is required {/Literal}'});
                    return false;
                }
            }
        }
      
        if (this.bySequence === false) {
            if (reportFilters.indexOf('timeRange') > -1) {
                
                var reportStartTime = this.$el.find('#report-start-time').val();
                if (reportStartDateValue === null || reportStartDateValue === '') {
                    this.$el.find('#report-start-time').addClass('invalid');
                    valid = false;
                }
                var reportEndTime = this.$el.find('#report-end-time').val();
                if (reportEndDateValue === null || reportEndDateValue === '') {
                    this.$el.find('#report-end-time').addClass('invalid');
                    valid = false;
                }
                if (reportStartTimeValue === null || reportStartTimeValue === '') {
                    this.$el.find('#report-start-timepicker').addClass('invalid');
                    valid = false;
                }
                if (reportEndTimeValue === null || reportEndTimeValue === '') {
                    this.$el.find('#report-end-timepicker').addClass('invalid');
                    valid = false;
                }
                if (valid) {
                    if (typeof this.selectedStartTime !== 'undefined' && typeof this.selectedEndTime !== 'undefined') {
                        if (this.selectedStartTime.getTime() > this.selectedEndTime.getTime()) {
                            M.toast({html: '{Literal}The end date cannot be sooner than the start date{/Literal}'});
                            valid = false;
                        }
                    }
                }
            }
            if (reportFilters.indexOf("locations") > -1) {
                var locations = this.$el.find('#locations-preset').val();
                if (locations === null || locations === '') {
                    this.$el.find('#locations-preset').addClass('invalid');
                    valid = false;
                }
            }
        } else {
            var selectedSequence = this.$el.find('#reset-report-autocomplete').attr('data-sequence');
            if (selectedSequence === undefined || selectedSequence === null || selectedSequence === '' || selectedSequence.length === 0) {
                this.$el.find('#sequence-error-msg').show();
                valid = false;
            }
        }

        return valid;
    },

    prefillRangePreset: function (e) {
        this.prefillState = true;
        var element = $(e.currentTarget);
        var rangeValue = $(element).val();

        var now = new Date();
        // if (delta !== 1) {
            now.setHours(0);
            now.setMinutes(0);
        // }
        // var startDate = moment(now);
        // var endDate = moment(now).hour(23 + this.startDayTime).minute(59);
        var startDate;
        var endDate;

        if (rangeValue == "today" || rangeValue == null) {
           
            startDate = moment(now).hour(this.dayStartTime).minute(0);
            endDate = moment(now).add(1, 'days').hour(this.dayStartTime - 1).minute(59);
        }
        else if (rangeValue == "yesterday") {
            startDate = moment(now).subtract(1, 'days').hour(this.dayStartTime).minute(0);
            endDate = moment(now).hour(this.dayStartTime - 1).minute(59);
        }
        else if (rangeValue == "thisWeek") {
            // startDate = moment(now).subtract(7, 'days').hour(this.dayStartTime).minute(0);
            // endDate = moment(now).add(1, 'days').hour(this.dayStartTime - 1).minute(59);
            if(App.serverInfo.country == 'IL'){
                startDate = moment(now).startOf('week').hour(this.dayStartTime).minute(0);
                endDate = moment(now).endOf('week').add(1, 'days').hour(this.dayStartTime - 1).minute(59);
            }
            else {
                startDate = moment(now).startOf('isoWeek').hour(this.dayStartTime).minute(0);
                endDate = moment(now).endOf('isoWeek').add(1, 'days').hour(this.dayStartTime - 1).minute(59);
            }
        }
        else if (rangeValue == "previousWeek") {
            // startDate = moment(now).subtract(14, 'days').hour(this.dayStartTime).minute(0);
            // endDate = moment(now).subtract(6, 'days').hour(this.dayStartTime - 1).minute(59);
            if(App.serverInfo.country == 'IL'){
                startDate = moment(now).subtract(7, 'days').startOf('week').hour(this.dayStartTime).minute(0);
                endDate = moment(now).subtract(7, 'days').endOf('week').add(1, 'days').hour(this.dayStartTime - 1).minute(59);
            }
            else {
                startDate = moment(now).subtract(7, 'days').startOf('isoWeek').hour(this.dayStartTime).minute(0);
                endDate = moment(now).subtract(7, 'days').endOf('isoWeek').add(1, 'days').hour(this.dayStartTime - 1).minute(59); 
            }
        }
        else if (rangeValue == "thisMonth") {
            startDate = moment(now).startOf('month').hour(this.dayStartTime).minute(0);
            endDate = moment(now).endOf('month').add(this.dayStartTime, 'hours').minute(59);
        }
        else if (rangeValue == "previousMonth") {
            startDate = moment(now).subtract(1, 'month').startOf('month').startOf('month').hour(this.dayStartTime).minute(0);
            endDate = moment(now).subtract(1, 'month').endOf('month').add(this.dayStartTime, 'hours').minute(59);
        }
        else if (rangeValue == "previous3Months") {
            startDate = moment().quarter(moment().quarter() - 1).startOf('quarter').hour(this.dayStartTime).minute(0);
            endDate = moment().quarter(moment().quarter() - 1).endOf('quarter').add(this.dayStartTime, 'hours').minute(59);
        }
        else if(rangeValue == "this3Months") {
            startDate = moment().quarter(moment().quarter()).startOf('quarter').hour(this.dayStartTime).minute(0);
            endDate = moment().quarter(moment().quarter()).endOf('quarter').add(this.dayStartTime, 'hours').minute(59);
        }
        this.reportStartDatePicker.setDate(startDate.toDate());
        this.reportEndDatePicker.setDate(endDate.toDate());
        
        this.$el.find('#report-start-time').val(startDate.format('YYYY-MM-DD'));
        this.$el.find("label[for='report-start-time']").addClass('active');
        this.$el.find('#report-end-time').val(endDate.format('YYYY-MM-DD'));
        this.$el.find("label[for='report-end-time']").addClass('active');

        this.$el.find('#report-start-timepicker').val(startDate.format('hh:mm a'));
        this.$el.find("label[for='report-start-timepicker']").addClass('active');
        this.$el.find('#report-end-timepicker').val(endDate.format('hh:mm a'));
        this.$el.find("label[for='report-end-timepicker']").addClass('active');
        
        
        this.selectedStartTime = startDate.toDate();
        this.selectedEndTime = endDate.toDate();
        
        this.prefillState = false;
    },

    runReport: function () {
        var category = this.$el.find("#report-category").val();
        if (category === "transactions") {
            if (this.validateTransactionReport()) {
                var request = this.generateTransactionReport();
                var request2 = this.generateReport();
                if(request2.reportTypeSettings.action == 'transactions-logs')
                    request['generateLogsReport'] = true;
                else
                    request['generateLogsReport'] = false;

                var url = 'generate-transaction-report';
                // if($('#export-detailed-report:checked').length > 0)
                //     url = 'generate-detailed-transaction-report';
                
                this.openReportWindowWithPostRequest('/data/' + url, request);
            }
        }
        else {
            if (this.validateReport()) {
                var request = this.generateReport();
                
                if (request.valid) {
                    var reportTypeSettings = request.reportTypeSettings;
                    var filters = request.filterValues;
                    this.openReportWindowWithPostRequest('/data/' + reportTypeSettings.action, filters);
        //            M.toast({
        //                html: '{Literal}Validation succeeded{/Literal}'
        //            });
       //         } else {
       //             M.toast({
       //                 html: '{Literal}Validation failed{/Literal}...'
       //             });
                }
                
            } else {
                var errorToastHtml = '{Literal}Some of the required fields are missing{/Literal}'
                M.toast({
                    html: errorToastHtml
                });
            }
        }
    },

    openReportWindowWithPostRequest: function (winURL, params) {
        var winName='AccuPOS Report' + Math.floor(Math.random() * 1000);
        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);
        params['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);
    },

    generateTransactionReport: function () {
        var instance = M.FormSelect.getInstance($('#transaction-filter-dropdown'));
        this.transactionFilter = instance.getSelectedValues();

        var allTransactions = false;
        var voids = false;
        var cancels = false;
        var comps = false;
        var discounts = false;

        for (var i = 0; i < this.transactionFilter.length; i++) {
            if (this.transactionFilter[i] === "all") {
                allTransactions = true;
            }
            else if (this.transactionFilter[i] === "voids") {
                voids = true;
            }
            else if (this.transactionFilter[i] === "cancels") {
                cancels = true;
            }
            else if (this.transactionFilter[i] === "discounts") {
                discounts = true;
            }
            else if (this.transactionFilter[i] === "comps") {
                comps = true;
            }
        }

        var tenderType = "";
        var itemType = "";
        var employee = [];
        var transactionAmountFilter = "";
        var fromAmount = "";
        var toAmount = "";
        var amount = "";
        var itemAmountFilter = "";
        var fromAmountItem = "";
        var toAmountItem = "";
        var invoiceNumber = "";
        var itemAmount = "";
        var sequence = "";
        var fromDate = "";
        var toDate = "";
        var till = "";
        var customer = "";
        var voidsOnly = false;
		var reopensOnly = false;
		var changes = false;

        var advanced = this.$el.find('.advanced:checked').length > 0
        if (advanced) {
           
            
            
            itemType = this.$el.find('#item-type-filter-dropdown option:selected').text();

            transactionAmountFilter = this.$el.find('#amount-filter-dropdown').val();
            if (transactionAmountFilter === "fromToAmount") {
                fromAmount = this.$el.find('#fromAmount').val();
                toAmount = this.$el.find('#toAmount').val();
            }
            else {
                amount = this.$el.find('#amount').val();
            }

            itemAmountFilter = this.$el.find('#item-filter-dropdown').val();
            if (itemAmountFilter === "fromToItem") {
                fromAmountItem = this.$el.find('#fromAmountItem').val();
                toAmountItem = this.$el.find('#toAmountItem').val();
            }
            else {
                itemAmount = this.$el.find('#itemAmount').val();
            }

            invoiceNumber = this.$el.find('#invoiceNumber').val();
            var filterTypeList = this.$el.find('#filter-type-dropdown').val();
            if(filterTypeList.includes("tillFilter") )
            {
                // var instance = M.FormSelect.getInstance(this.$el.find('#till-filter-dropdown'));
                till = this.$el.find('#till-filter-dropdown').val();
            }
            if(filterTypeList.includes("employeeFilter"))
            {
                // var instance = M.FormSelect.getInstance(this.$el.find('#employee-filter-dropdown'));
                employee = this.$el.find('#employee-filter-dropdown').val();
            }
            if(filterTypeList.includes("customerFilter"))
            {
                customer = this.$el.find('#customer-filter-autocomplete').val();
            }
            if(filterTypeList.includes("tenderFilter"))
            {
                tenderType = this.$el.find('#tender-type-filter-dropdown').val();
            }
            if(filterTypeList.includes("amountFilter"))
            {
                fromAmount = this.$el.find('#amountFromFilterFrom').val();
                toAmount = this.$el.find('#amountToFilterFrom').val();
            }
            if(filterTypeList.includes("voidsFilter"))
            {
                voidsOnly = true;
            }
			if(filterTypeList.includes("reopenedFilter"))
            {
                reopensOnly = true;
            }
            if(filterTypeList.includes("changesFilter"))
            {
                changes = true;
            }
        }

        if (this.bySequence) {
                sequence = document.getElementById('reset-report-autocomplete').dataset.sequence;
                till = document.getElementById('reset-report-autocomplete').dataset.till;
        }
        else {
            valid = this.validateTimeTange();
            if (valid) {
                fromDate = document.getElementById('report-start-time').value + ' ' + moment(this.selectedStartTime).format('HH:mm');      
                toDate = document.getElementById('report-end-time').value + ' ' + moment(this.selectedEndTime).format('HH:mm');
            } else {
                alert("Dates validation error");
            }
        }

        var transactionObject = {
            sequence: sequence,
            fromDate: fromDate,
            toDate: toDate,
            allTransactions: allTransactions,
            voids: voidsOnly,
			reopens: reopensOnly,
			changes: changes,
            cancels: cancels,
            comps: comps,
            discounts: discounts,
            tenderType: tenderType,
            itemType: itemType,
            employee: [employee],
            transactionAmountFilter: transactionAmountFilter,
            fromAmount: fromAmount, 
            toAmount: toAmount,
            amount: amount,
            itemAmountFilter: itemAmountFilter,
            fromAmountItem: fromAmountItem,
            toAmountItem: toAmountItem,
            invoiceNumber: invoiceNumber,
            itemAmount: itemAmount,
            till: till,
            customer: customer,
            exportToExcel: this.$el.find('#export-to-xlsx:checked').length > 0
        }

        return transactionObject;
    },

    generateReport: function () {
        var hasFilter = function (filters, filter) {
            return filters.indexOf(filter) > -1;
        };
        var filterValues = {};
        var category = this.$el.find("#report-category").val();
        var type = this.$el.find("#report-type").val();
        
        var reportTypeSettings = this.getReportSettingsByCategoryAndType(category, this.reportType);
        var valid = true;
        
        if (reportTypeSettings.length > 0) {
            reportTypeSettings = reportTypeSettings[0];
            if (reportTypeSettings.action !== '') {
                var action = reportTypeSettings.action;
                var filters = reportTypeSettings.filters;
                if (hasFilter(filters, 'timeRange') && !this.bySequence) {
                    valid = this.validateTimeTange();
                    if (valid) {
                        filterValues = _.extend({
                            fromDate: document.getElementById('report-start-time').value + ' ' + moment(this.selectedStartTime).format('HH:mm'),
                            toDate: document.getElementById('report-end-time').value + ' ' + moment(this.selectedEndTime).format('HH:mm'),
                            sequence: ""
                        }, filterValues);
                    } else {
                        // invalidate
                        alert("Dates validation error");
                    }
                } 
                else if (hasFilter(filters, 'timeRange') && this.bySequence) {
                    filterValues = _.extend({
                        fromDate: "",
                        toDate: ""
                    }, filterValues);
                }
                
                if (hasFilter(filters, 'sequence') && this.bySequence) {
                    // var newSelectedSequence = this.selectedSequence.substring(0,this.selectedSequence.indexOf("(") - 1);
                    // var selectedTill = this.selectedSequence.substring(this.selectedSequence.indexOf("(") + 1, this.selectedSequence.length - 1);
                    var inputEl = document.getElementById('reset-report-autocomplete');
                    filterValues = _.extend({
                        sequence: inputEl.dataset.sequence
                    }, filterValues);

                    filterValues = _.extend({
                        till: inputEl.dataset.till
                    }, filterValues);
                }

                if (hasFilter(filters, 'till') && this.bySequence) {
                    filterValues = _.extend({
                        till: this.selectedTill
                    }, filterValues);
                }
                else if (hasFilter(filters, 'till') && !this.bySequence) {
                    filterValues = _.extend({
                        till: ""
                    }, filterValues);
                }

                if (hasFilter(filters, 'signatures')) {
                    valid = this.validateSignature();
                    if (valid) {
                        filterValues = _.extend({
                            receiptId: this.selectedSignatureOrder,
                            signatureWidth: "500"
                        }, filterValues);       
                    } else {
                        // invalidate
                        alert("Signature validation error");
                    }
                }
                if (hasFilter(filters, 'item')) {
                    if (typeof this.selectedItems !== 'undefined' && this.selectedItems !== null && this.selectedItems.length > 0) {
                        filterValues = _.extend({
                            itemCodes: this.selectedItems.join(';')
                        }, filterValues);
                    }
                }
                if (hasFilter(filters, 'user')) {
                    var user = this.$el.find('#user-search-autocomplete').val();
                        filterValues = _.extend({
                            selectedUserName: user
                        }, filterValues);
                }
                if (hasFilter(filters, 'employee')) {
                    var employee = this.$el.find('#employee-search-autocomplete').val();
                        filterValues = _.extend({
                            selectedUserName: employee
                        }, filterValues);
                }
                if (hasFilter(filters, 'customer')) {
                    filterValues = _.extend({
                        selectedCustomer: this.$el.find('#customer-search-autocomplete').val()
                    }, filterValues);
                }
                if (hasFilter(filters, 'adjustmentSession')) {
                    filterValues = _.extend({
                        sessionID: this.$el.find('#adjustment-session-search-autocomplete').val(),
                        selectedRow: 0
                    }, filterValues);
                }
                
                if (hasFilter(filters, 'exportToExcel')) {
                    filterValues = _.extend({
                        exportToExcel: this.$el.find('#export-to-xlsx:checked').length > 0
                    }, filterValues);
                }
                if (hasFilter(filters, 'summarizeByCategory')) {
                    filterValues = _.extend({
                        summarizeByCategory: this.$el.find('#summarize-by-category:checked').length > 0
                    }, filterValues);
                }
                if (hasFilter(filters, 'showGraphs')) {
                    filterValues = _.extend({
                        showGraphs: this.$el.find('#show-graphs:checked').length > 0
                    }, filterValues);
                }
                if (hasFilter(filters, 'locations')) {
                    var selectedLocations = this.$el.find('#locations-preset').val();
                    if(selectedLocations.length > 1 && selectedLocations[0] === 'all')
                        selectedLocations.splice(0, 1);
                    filterValues = _.extend({
                        selectedLocations: selectedLocations.join(";"),
                    }, filterValues);
                }
                if (hasFilter(filters, 'itemType')) {
                    filterValues = _.extend({
                        selectedItemTypes: this.$el.find('#item-type-search-autocomplete').val(),
                    }, filterValues);
                }
                if (hasFilter(filters, 'customersWithBalance')) {
                    filterValues = _.extend({
                        customersWithBalance: this.$el.find('#customers-with-balance:checked').length > 0,
                    }, filterValues);
                }
                if (hasFilter(filters, 'itemCategory')) {
                    filterValues = _.extend({
                        selectedItemCategories: this.$el.find('#item-category-search-autocomplete').val(),
                    }, filterValues);
                }
                // if (hasFilter(filters, 'resetReport')) {
                //     if (typeof this.resetReportSearchAutocompleteSelection === 'undefined' || this.resetReportSearchAutocompleteSelection === null) {
                //         filterValues = _.extend({
                //             sequence: this.selectedSequence,
                //             till:  this.selectedTill
                //         }, filterValues); 

                //     } else {
                //         var value = this.resetReportSearchAutocompleteSelection;
                //         var mapped = this.resetReportsMapping[value];
                //         if (typeof mapped !== 'undefined' && mapped !== null) {
                //             filterValues = _.extend({
                //                 sequence: mapped.sequence,
                //                 till: mapped.till
                //             }, filterValues);
                //         }
                //     }
                // } 
                if (hasFilter(filters, 'cloudData')) {
                    filterValues = _.extend({
                        reportName: type
                    }, filterValues);
                }
                if (hasFilter(filters, 'showPayTypeTotals')) {
                    filterValues = _.extend({
                        showPayTypeTotals: document.getElementById('show-pay-type-totals').checked
                    }, filterValues);
                }
                if (hasFilter(filters, 'showItemDetails')) {
                    filterValues = _.extend({
                        showItemDetails: document.getElementById('show-item-details').checked
                    }, filterValues);
                }
            }
        }
        return {
            valid: valid,
            reportTypeSettings: reportTypeSettings,
            filterValues: filterValues
        };
    },

    validateTimeTange: function() {
        var valid = false;
        valid = typeof this.selectedStartTime !== 'undefined' && this.selectedStartTime !== null;
        valid = typeof this.selectedEndTime !== 'undefined' && this.selectedEndTime !== null;
        return valid;
    },

    validateSignature: function() {
        return typeof this.selectedSignatureOrder !== 'undefined' && this.selectedSignatureOrder !== null;
    },

    validateSelect: function (e) {
        var element = $(e.currentTarget);
        $(element).closest('.select-wrapper').removeClass('invalid');
    },

    initStartDateTimePickers: function () {
        /**
         * 0 = beginning point
         * 1 = date picked
         * 2 = hour picked
         * 3 = minute picked
         */
        var dayStartHour = this.dayStartTime.toString().length === 2 ? this.dayStartTime : "0" + this.dayStartTime;
        this.startDateTimeProgress = 0;
        var reportStartDatePickerElement = document.querySelector('#report-start-time');
        var reportStartTimePickerElement = document.querySelector('#report-start-timepicker');
        var that = this;
        this.reportStartTimePicker = M.Timepicker.init(reportStartTimePickerElement, {
            autoClose: true,
            defaultTime:  dayStartHour + ':00',
            
            onSelect: function(hour, minute) {
                that.startDateTimeProgress = that.startDateTimeProgress === 2 ? 3 : 2;
                if(this.amOrPm === 'AM' && hour == 12)
                    hour = 0;
                hour += (this.amOrPm === 'PM' && hour < 12 ? 12 : 0);            
                that.selectedStartTime.setHours(hour);
                that.selectedStartTime.setMinutes(minute);
                //$('#report-start-time').val(moment(that.selectedStartTime).format('YYYY-MM-DD hh:mma'));
                that.$el.find('.report-link-column a').removeClass('preset-selected');
            },
            onOpenStart: function () {
                this.$el.find('.timepicker-close').each(function () {
                    if ($(this).html() === 'Ok') {
                        $(this).hide();
                    }
                });
            },
            onCloseStart: function() {
                if (that.startDateTimeProgress !== 3) {
                    var previousValue = $('#report-start-time').attr("data-previous");
                    if (previousValue !== null && previousValue !== '') {
                        
                    } else {
                        
                        $("label[for='report-start-time']").removeClass('active');
                        $('#report-start-time').val($('#report-start-time').attr("data-previous"));
                    }
                }
                that.startDateTimeProgress = 0;
            }
        });
        this.reportStartDatePicker = M.Datepicker.init(reportStartDatePickerElement, {
            autoClose: true,
            format: 'yyyy-mm-dd',
            i18n: App.i18n,
            isRTL: App.rtl,
            firstDay: App.rtl ? 0 : 1,
            onSelect: function(date) {
                if (!that.prefillState) {
                    var hours = that.selectedStartTime.getHours();
                    var mins = that.selectedStartTime.getMinutes();
                    that.selectedStartTime = date;
                    var checked = document.getElementById('whole-day-time').checked;
                    if(checked)
                        that.selectedStartTime.setHours(that.dayStartTime);
                    else {
                        that.selectedStartTime.setHours(hours);
                        that.selectedStartTime.setMinutes(mins);
                    }
                    that.startDateTimeProgress = 1;
                }
            },
            onOpen: function () {
                $('#report-start-time').attr("data-previous", $('#report-start-time').val());
            }
        });
    },

    initEndDateTimePickers: function () {
        /**
         * 0 = beginning point
         * 1 = date picked
         * 2 = hour picked
         * 3 = minute picked
         */
        var dayStartHour = this.dayStartTime.length == 2 ? this.dayStartTime : "0" + this.dayStartTime;
        this.endDateTimeProgress = 0;
        var reportEndDatePickerElement = document.querySelector('#report-end-time');
        var reportEndTimePickerElement = document.querySelector('#report-end-timepicker');
        var that = this;
        this.reportEndTimePicker = M.Timepicker.init(reportEndTimePickerElement, {
            autoClose: true,
            defaultTime: dayStartHour + ':00',
            onSelect: function(hour, minute) {
                that.endDateTimeProgress = that.endDateTimeProgress === 2 ? 3 : 2;
                if(this.amOrPm === 'AM' && hour == 12)
                    hour = 0;
                hour += (this.amOrPm === 'PM' && hour < 12 ? 12 : 0);
                that.selectedEndTime.setHours(hour);
                that.selectedEndTime.setMinutes(minute);
                //$('#report-end-time').val(moment(that.selectedEndTime).format('YYYY-MM-DD hh:mma'));
                that.$el.find('.report-link-column a').removeClass('preset-selected');
            },
            onOpenStart: function () {
                this.$el.find('.timepicker-close').each(function () {
                    if ($(this).html() === 'Ok') {
                        $(this).hide();
                    }
                });
            },
            onCloseStart: function() {
                if (that.endDateTimeProgress !== 3) {
                    var previousValue = $('#report-end-time').attr("data-previous");
                    if (previousValue !== null && previousValue !== '') {
                        
                    } else {
                        $("label[for='report-end-time']").removeClass('active');
                        $('#report-end-time').val($('#report-end-time').attr("data-previous"));
                    }
                }
                that.endDateTimeProgress = 0;
            }
        });
        this.reportEndDatePicker = M.Datepicker.init(reportEndDatePickerElement, {
            autoClose: true,
            format: 'yyyy-mm-dd',
            i18n: App.i18n,
            isRTL: App.rtl,
            firstDay: App.rtl ? 0 : 1,
            onSelect: function(date) {
                if (!that.prefillState) {
                    var hours = that.selectedEndTime.getHours();
                    var mins = that.selectedEndTime.getMinutes();
                    that.selectedEndTime = date;
                    that.selectedEndTime.setHours(hours);
                    that.selectedEndTime.setMinutes(mins);
                    that.endDateTimeProgress = 1;
                }
            },
            onOpen: function () {
                $('#report-end-time').attr("data-previous", $('#report-end-time').val());
            }
        });
    },

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

    renderPaginator: function (sequencesTotalCount) {
        $('.pagination-trigger').remove();
        if (sequencesTotalCount > this.sequenceRows * this.sequenceColumns) {

            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();
        } else {
            $("#sequence-pagination").hide();
        }
    },

    applySequenceSelection: function () {
        var selectedSequence = $("#selected-sequence").val();
        var sequenceNumber =  $("#selected-sequence").attr('data-sequence');
        sequenceNumber = Number.parseInt(sequenceNumber);

        if (selectedSequence === null || selectedSequence === '') {
            M.toast({
                html: '{Literal}No Sequence was selected{/Literal}'
            });
        }
        else if(sequenceNumber == NaN || sequenceNumber < 0) {
            M.toast({  html: '{Literal}Invalid Sequence Number{/Literal}' });
        } 
        else {
            // $("#selected-sequence").attr('data-value', selectedSequence);

            for (var i = 0; i < this.sequencesTotal; i++) {
                if (this.sequenceCollection.models[i] != undefined ) {
                    if (typeof this.sequenceCollection.models[i].attributes.id === "string") {
                        this.sequenceCollection.models[i].attributes.id = this.sequenceCollection.models[i].attributes.sequence
                    }
                    var thisSequence = `${this.sequenceCollection.models[i].attributes.id} (${this.sequenceCollection.models[i].attributes.till})`
                    if (thisSequence == selectedSequence) {
                         var selectedTill = this.sequenceCollection.models[i].attributes.till;
                         var endDate = this.sequenceCollection.models[i].attributes.endTime
                    }
                }
            }
            var inputEl = document.getElementById('reset-report-autocomplete');
            inputEl.dataset.till = document.getElementById('selected-sequence').dataset.till;
            inputEl.dataset.sequence = document.getElementById('selected-sequence').dataset.sequence;
            var endDate = document.getElementById('selected-sequence').dataset.endDate;
            inputEl.value = '{Literal}Till{/Literal} ' + inputEl.dataset.till + ' / #' + inputEl.dataset.sequence + ' / ' + toDateString(endDate);

            // $("#selected-sequence").html('<div class="ap-badge">Sequence #' + selectedSequence + '&nbsp</div>');
            this.$el.find('#sequence-error-msg').hide();
            M.Modal.getInstance($("#sequence-modal")).close();
        }
    },

    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.getSequences(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++)
        {   
            var thisSequence = sequences[i];
            for (var j = i; j < sequences.length; j++) {
                if (thisSequence.id == sequences[j].id)
                {
                    sequences[i].sequence = sequences[i].id;
                    sequences[i].id = sequences[i].id + " (" + sequences[i].till+ ")";
                    break;
                }
            }
        }
        for (var i = 0; i < sequences.length; i++) {
            sequenceCollection.add(new Sequence({
                id: sequences[i].id,
                till: sequences[i].till,
                startTime: sequences[i].start,
                sequence: sequences[i].sequence,
                endTime: sequences[i].end
            }));
        }
        $("#sequence-pagination").attr("data-current-page", selectedPage);
        that.sequenceTilesView.collection.reset(sequenceCollection.models);
        $(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');
        }
        $("#sequence-modal-preloader").hide();
    },

    toggleReportBySelector: function () {
        // if(document.getElementById('report-type').value == 'reset-reports')
        //     return;
        var selectedValue = $(".report-by-selector:checked").val();
        if (selectedValue === 'by-date-time') {
            this.$el.find("#by-sequence-fields").hide();
            this.$el.find("#by-time-fields").show();
            $('a[data-filter-class="conditional-report-filter"][data-filter="timeRange"]').parent().show();
            this.bySequence = false;
            if(document.getElementById('report-type').value != 'reset-reports')
                this.$el.find('#dateRangePreset').show();

            this.$el.find('#by-time-fields').show();
            this.$el.find('#by-sequence-filters').hide();
        } else if (selectedValue === 'by-sequence') {
            $('a[data-filter-class="conditional-report-filter"][data-filter="timeRange"]').parent().hide();
            this.$el.find("#by-sequence-fields").show();
            this.$el.find("#by-time-fields").hide();
            this.$el.find('#dateRangePreset').hide();
            this.bySequence = true;
            this.$el.find('#by-time-fields').hide();
            this.$el.find('#by-sequence-filters').show();
            //M.Modal.getInstance($("#sequence-modal")).open();
        }
    },

    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;
        for (var i = 0; i < sequences.length; i++)
        {   
            var thisSequence = sequences[i];
            for (var j = i; j < sequences.length; j++) {
                if (thisSequence.id == sequences[j].id)
                {
                    sequences[i].sequence = sequences[i].id;
                    sequences[i].id = sequences[i].id + " (" + sequences[i].till+ ")";
                    break;
                }
            }
        }
        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,
                sequence: sequences[i].sequence,
                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();

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

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

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

    changeReportCategory: function (e) {
        var element = $(e.currentTarget);
        var category = $(element).val();
        var reportTypes = this.getReportTypes()[category];
        var typeSelect = this.$el.find('#report-type');
        $(typeSelect).html("");
        $(typeSelect).removeAttr('disabled');
        var option = $('<option>');
        $(option).attr('disabled', '');
        $(option).attr('selected', '');
        $(option).html('{Literal}Select a Type{/Literal}');
        $(option).val('');
        $(typeSelect).append(option);

        for (var i = 0; i < reportTypes.length; i++) {
            var reportType = reportTypes[i];
            if (App.serverInfo.isFoodService || !reportType.hideOnRetail) {
                option = $('<option>');
                $(option).val(reportType.value);
                $(option).html(reportType.label);
                $(option).attr('data-category', category);
                $(typeSelect).append(option);
            }
        }

        var reportCategory = this.$el.find('#report-category').val();
        if (reportCategory == "transactions") 
        {
            // $('#report-type-dropdown').hide();
            // document.querySelector('#report-type-dropdown select').disabled = true;
            var selectedElement = $('#report-type option[value=all-transactions]');
            selectedElement.attr('selected', 'selected');
            this.changeReportType({currentTarget: $('#report-type') });
            document.getElementById('transaction-filters').style.visibility = '';
            document.getElementById('transaction-advanced-filters-toggle').style.display = 'block';
        }
        else {
            // $('#report-type-dropdown').show();
            document.querySelector('#report-type-dropdown select').disabled = false;
            document.getElementById('transaction-filters').style.visibility = 'hidden';
            document.getElementById('transaction-advanced-filters-toggle').style.display = 'none';
            document.querySelector('#transaction-advanced-filters-toggle input').checked = false;
            document.querySelector('.advanced-transaction-filters').style.display = 'none';
        }
       
        $(typeSelect).formSelect();
    },

    getReportSettingsByCategoryAndType: function (category, reportType) {
        if (typeof this.getReportTypes()[category] === 'undefined') {
            return [];
        }
        return this.getReportTypes()[category].filter(function(e) {
            return e.value === reportType;
        });
    },

    changeReportType: function (e) {
        var element = $(e.currentTarget).find(':selected');
        var category = $(element).attr('data-category');
        this.reportType = $(element).val();
        this.sequenceFilterEnabled = true;
        var that = this;
        var reportTypeSettings = this.getReportSettingsByCategoryAndType(category, this.reportType);
            
        if (reportTypeSettings.length === 1) {
            reportTypeSettings = reportTypeSettings[0];
            var selectors = [
                'input[data-filter-class="conditional-report-filter"]:not(:checkbox)',
                'input[data-filter-class="conditional-report-filter"].whole-day',
                'input[data-filter-class="conditional-report-filter"].form-switch-settings',
                'div.chips',
                'select[data-filter-class="conditional-report-filter"]',
                '[data-filter-class="conditional-report-filter"]',
                'a.waves-effect'
            ];
            var excelOrCharts = false;
            this.$el.find(selectors.join(',')).each(function () {
                var currentFilterType = $(this).attr('data-filter');
                if (reportTypeSettings.filters.indexOf(currentFilterType) < 0) {
                    if ($(this).hasClass('hide-filter') || $(this).attr('id') === 'date-range-preset1' || $(this).attr('id') === 'locations-preset') {                        
                        if ($(this).hasClass("form-switch")) {
                            if (!excelOrCharts) {
                                $(this).parent().parent().parent().hide();
                            }
                            $(this).parent().parent().hide();
                        } else if ($(this).hasClass('whole-day') || $(this).hasClass('form-switch-settings')) {
                            $(this).parent().parent().hide();
                        } else if ($(this).attr('id') === 'date-range-preset1') {
                            $(this).formSelect();
                            $(this).parent().parent().hide();
                        } else if ($(this).attr('id') === 'locations-preset') {
                            $(this).removeAttr('disabled');
                            $(this).formSelect();
                            $("#locationsParentModel").css("display", "none")
                            
                        }  else {
                            $(this).parent().hide();
                        }
                    }
                    // $(this).attr('disabled', '');
                    if ($(this).attr('id') === 'by-sequence-radio-button') {
                        that.sequenceFilterEnabled = false;
                    }
                } else {     
                    if ($(this).hasClass('hide-filter') || $(this).attr('id') === 'date-range-preset1' || $(this).attr('id') === 'locations-preset') {
                        if ($(this).hasClass("form-switch")) {
                            excelOrCharts = true;
                            $(this).parent().parent().parent().show();
                            $(this).parent().parent().show();
                        } else if ($(this).hasClass('whole-day') || $(this).hasClass('form-switch-settings')) {
                            $(this).parent().parent().show();
                        } else if ($(this).attr('id') === 'date-range-preset1') {
                            $(this).removeAttr('disabled');
                            $(this).formSelect();
                            $(this).parent().parent().show();
                        } else if ($(this).attr('id') === 'locations-preset') {
                            $(this).removeAttr('disabled');
                            $(this).formSelect();
                            $("#locationsParentModel").css("display", "block")
                        }  else {
                            $(this).parent().show();
                        }
                    }
                    $(this).removeAttr('disabled');
                }
            });
            // this.toggleWholeDay();
            var checked = document.getElementById('whole-day-time').checked;
      
            if (checked) {
                this.$el.find('#report-start-timepicker').attr('disabled', '');
                this.$el.find('#report-end-timepicker').attr('disabled', '');
            } else {
                this.$el.find('#report-start-timepicker').removeAttr('disabled');
                this.$el.find('#report-end-timepicker').removeAttr('disabled');
            }

            if (!that.sequenceFilterEnabled) {
                this.$el.find("#by-date-time-radio-button").prop("checked", true);
                this.toggleReportBySelector();
                $('#viewByBlock').hide();
            }
            else {
                $('#viewByBlock').show();
            }
        }

        if (this.reportType === 'employee-hour-report') {
            if(App.serverInfo.country != 'IL') {
                
                if(that.getPayPeriodInfo.periodDuration > 0){
                    var startDate = moment(that.getPayPeriodInfo.periodEnd).hour(0).minute(0).subtract(that.getPayPeriodInfo.periodDuration - 1, 'days');
                    var endDate = moment(that.getPayPeriodInfo.periodEnd).hour(23).minute(59);
                }
                else {
                    var startDate = moment().hour(0).minute(0).startOf('month');
                    var endDate = moment().hour(23).minute(59).endOf('month');
                }
                this.$el.find('#report-start-time').val(startDate.format('YYYY-MM-DD'));
                this.$el.find('#report-end-time').val(endDate.format('YYYY-MM-DD'));
                that.selectedStartTime = startDate.toDate();
                that.selectedEndTime = endDate.toDate();
            }
        }
        else
            $("#payPeriodButtons").hide();

        if(this.reportType === 'inventory-transaction')
            this.itemSearchAutocomplete.options.limit = 1;
        else
            this.itemSearchAutocomplete.options.limit = 10;

        for (let i = 0; i < this.itemSearchAutocomplete.chipsData.length; i++) {
            this.itemSearchAutocomplete.deleteChip(i)
            
        }

        if(document.getElementById('report-type').value == 'reset-reports') {
            document.querySelectorAll('input[name="view-by-group"]').forEach( el => el.disabled = true)
            document.getElementById('by-sequence-radio-button').checked = true;
        }
        else {
            document.querySelectorAll('input[name="view-by-group"]').forEach( el => el.disabled = false)
            document.getElementById('by-date-time-radio-button').checked = true;
        }

        this.toggleReportBySelector();

    },

    getReportTypes: function () {
        var full = (location.port ? ':'+location.port: '');
        var reportTypes = {};
        
        reportTypes["general"] = [{
                    value: 'reset-reports',
                    action: 'generate-reset-report',
                    label: '{Literal}Reset Reports{/Literal}',
                    hideOnRetail: false,
                    filters: ['exportToExcel', 'showGraphs', 'sequence']
                },
                {
                    value: 'z-out-summary-report',
                    label: '{Literal}Z-Out Summary Report{/Literal}',
                    action: 'generate-z-out-summary-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'till']
                },
                {
                    value: 'customer-statement-report',
                    label: '{Literal}Customer Statement{/Literal}',
                    action: 'generate-customer-statement-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'customer']
                },
                {
                    value: 'account-receivables-by-date-range-report',
                    label: '{Literal}Account Receivables By Date Range{/Literal}',
                    action: 'generate-account-receivables-by-date-range-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'exportToExcel']
                },
                {
                    value: 'signature-receipt-report',
                    label: '{Literal}Signature Receipt Report{/Literal}',
                    action: 'generate-signature-receipt-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'signatures']
                },
                {
                    value: 'employee-hour-report',
                    label: '{Literal}Employee Hour Report{/Literal}',
                    action: 'generate-employee-hour-report',
                    hideOnRetail: false,
                    filters: ['payPeriodButtons', 'timeRange', 'employee', 'exportToExcel', 'showPayTypeTotals']
                },
                {
                    value: 'comps-by-reason-report',
                    label: '{Literal}Comps/Discounts by Reason Report{/Literal}',
                    action: 'generate-comps-by-reason-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence']
                },
                {
                    value: 'gratuity-report',
                    label: '{Literal}Gratuity Report{/Literal}',
                    action: 'generate-gratuity-report',
                    hideOnRetail: true,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'user', 'till']
                },
                {
                    value: 'sales-tax-report',
                    label: '{Literal}Sales Tax Report{/Literal}',
                    action: 'generate-sales-tax-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                },
                {
                    value: 'z-out-periodic-report',
                    label: '{Literal}Z-out Periodic Report{/Literal}',
                    action: 'generate-z-out-periodic-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'exportToExcel']
                },
                {
                    value: 'out-of-balance-transactions-report',
                    label: '{Literal}Out Of Balance Transactions Report{/Literal}',
                    action: 'generate-out-of-balance-transactions-report',
                    hideOnRetail: false,
                    filters: ['timeRange']
                },
                {
                    value: 'checks-report',
                    label: '{Literal}Checks Report{/Literal}',
                    action: 'generate-checks-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence']
                },
                /*{
                    value: 'gift-card-detail-report',
                    label: '{Literal}Gift Card Detail Report{/Literal}',
                    action: 'report-not-supported',
                    hideOnRetail: true,
                    filters: ['giftCardNumber']
                },*/
            ];

            if(App.serverInfo.hasDesktopAccounting && App.serverInfo.country == 'IL') {
                reportTypes["general"].push(
                    {
                    value: 'movein-report',
                    label: '{Literal}Movein Report{/Literal}',
                    action: 'generate-movein-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence']
                    }
                )
            }

            if(!App.serverInfo.isFoodService) {   
                var compsReport = reportTypes.general.find( i => i.value == 'comps-by-reason-report');
                compsReport.label = '{Literal}Discounts by Reason Report{/Literal}';
            }

            if(App.serverInfo.hideCustomerStatementReport) {
                reportTypes.general = reportTypes.general.filter( i => i.value != 'customer-statement-report');
            }
                
        reportTypes["transactions"] = [{
                    value: 'all-transactions',
                    label: '{Literal}All Transactions{/Literal}',
                    action: 'generate-transactions-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'till', 'exportToExcel']
                },
                {
                    value: 'transactions-logs',
                    label: '{Literal}Transactions Logs{/Literal}',
                    action: 'transactions-logs',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'till', 'exportToExcel']
                },
                // {
                //     value: 'cancelled',
                //     label: '{Literal}Cancelled{/Literal}',
                //     action: 'generate-cancelled-transactions-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                // },
                // {
                //     value: 'discounted',
                //     label: '{Literal}Discounted{/Literal}',
                //     action: 'generate-transactions-with-discounts-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                // },
                // {
                //     value: 'with-comp-reasones',
                //     label: '{Literal}With Comp Reasons{/Literal}',
                //     action: 'generate-comps-by-reason-report',
                //     hideOnRetail: true,
                //     filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                // },
                // {
                //     value: 'with-comp-by-user',
                //     label: '{Literal}With Comp by User{/Literal}',
                //     action: 'generate-transactions-with-comp-by-user',
                //     hideOnRetail: true,
                //     filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'user', 'till']
                // },
                // {
                //     value: 'credit-cards',
                //     label: '{Literal}Credit Cards{/Literal}',
                //     action: 'generate-credit-card-transactions-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                // },
                // {
                //     value: 'by-customer',
                //     label: '{Literal}By Customer{/Literal}',
                //     action: 'generate-transactions-by-customer-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'sequence', 'exportToExcel', 'customer', 'till'], 
                // },
                // {
                //     value: 'accounts-receivable',
                //     label: '{Literal}Accounts Receivable{/Literal}',
                //     action: 'generate-accounts-receivable-transactions-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                // }
            ];
        reportTypes["sales"] = [{
                    value: 'by-item-summary',
                    label: '{Literal}By Item Summary{/Literal}',
                    action: 'generate-sales-by-item-summary-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'item', 'till', 'user']
                },
                {
                    value: 'gross-margin',
                    label: '{Literal}Gross Margin{/Literal}',
                    action: 'generate-gross-margin-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'item', 'till', 'user']
                },
                {
                    value: 'by-type',
                    label: '{Literal}By Type{/Literal}',
                    action: 'generate-sales-by-type-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'itemType', 'till']
                },
                {
                    value: 'by-hour',
                    label: '{Literal}By Hour{/Literal}',
                    action: 'generate-sales-by-hour-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'till']
                },
                {
                    value: 'by-hour-per-day',
                    label: '{Literal}By Hour Per Day{/Literal}',
                    action: 'generate-sales-by-hour-per-day-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'till']
                },
                {
                    value: 'by-types-by-hour',
                    label: '{Literal}By Types and Hour{/Literal}',
                    action: 'generate-sales-by-type-and-hour-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                },
                {
                    value: 'top-10-items-by-hour',
                    label: '{Literal}Top 10 Items by Hour{/Literal}',
                    action: 'generate-sales-top-10-items-by-hour-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'till']
                },
                {
                    value: 'by-user',
                    label: '{Literal}By User{/Literal}',
                    action: 'generate-sales-by-user-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'showGraphs', 'till']
                },
                {
                    value: 'by-user-by-type',
                    label: '{Literal}By User and Type{/Literal}',
                    action: 'generate-sales-by-user-and-type-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'till', 'showItemDetails']
                },
                {
                    value: 'server-summary',
                    label: App.serverInfo.isFoodService ? '{Literal}Server Summary{/Literal}' : 
                        '{Literal}Sales Rep. Summary{/Literal}',
                    action: 'generate-sales-server-summary-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'user', 'till']
                },
                {
                    value: 'driver-summary',
                    label: '{Literal}Driver Summary{/Literal}' ,
                    action: 'generate-sales-driver-summary-report',
                    hideOnRetail: true,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'user', 'till']
                },
                {
                    value: 'by-customer-summary',
                    label: '{Literal}By Customer Summary{/Literal}',
                    action: 'generate-sales-by-customer-summary-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'customer', 'till']
                },
                {
                    value: 'by-customer-detailed',
                    label: '{Literal}By Customer - Detailed{/Literal}',
                    action: 'generate-sales-by-customer-detailed-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'customer', 'till']
                },
                {
                    value: 'by-item-category',
                    label: '{Literal}By Item Category{/Literal}',
                    action: 'generate-sales-by-item-category-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'itemCategory', 'till']
                },
                {
                    value: 'by-customer-type',
                    label: '{Literal}By Customer Type{/Literal}',
                    action: 'generate-sales-by-customer-type-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'sequence', 'exportToExcel', 'showGraphs', 'customerType', 'till']
                }
            ];
        reportTypes["list"] = [{
                    value: 'customers-list',
                    label: '{Literal}Customers List{/Literal}',
                    action: 'generate-customers-list-report',
                    hideOnRetail: false,
                    filters: ['exportToExcel', 'customersWithBalance']
                },
                {
                    value: 'active-sale-prices',
                    label: '{Literal}Active Sale Prices{/Literal}',
                    action: 'generate-active-sale-prices-list-report',
                    hideOnRetail: false,
                    filters: []
                },
                {
                    value: 'loyalty-program',
                    label: '{Literal}Loyalty Program{/Literal}',
                    action: 'generate-loyalty-program-list-report',
                    hideOnRetail: true,
                    filters: []
                }
            ];
        reportTypes["inventory"] = [{
                    value: 'items-list',
                    label: '{Literal}Items List{/Literal}',
                    action: 'generate-items-list-report',
                    hideOnRetail: false,
                    filters: ['exportToExcel', 'itemType']
                },
                {
                    value: 'items-value',
                    label: '{Literal}Items Value{/Literal}',
                    action: 'generate-items-value-report',
                    hideOnRetail: false,
                    filters: ['exportToExcel', 'itemType']
                },
                {
                    value: 'stock-items',
                    label: '{Literal}Stock Items{/Literal}',
                    action: 'generate-stock-items-report',
                    hideOnRetail: false,
                    filters: ['adjustmentSession']
                },
                {
                    value: 'inventory-counts',
                    label: '{Literal}Inventory Counts{/Literal}',
                    action: 'generate-inventory-counts-report',
                    hideOnRetail: false,
                    filters: []
                },
                {
                    value: 'inventory-adjustments',
                    label: '{Literal}Inventory Adjustments{/Literal}',
                    action: 'generate-inventory-adjustments-report',
                    hideOnRetail: false,
                    filters: ['adjustmentSession']
                },
                {
                    value: 'inventory-transaction',
                    label: '{Literal}Inventory Transaction{/Literal}',
                    action: 'generate-inventory-transaction-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'item']
                }
            ];
        if(App.serverInfo.hasCloudReporting) {
                reportTypes["cloudData"] = [{
                    value: 'sales-by-item-type',
                    label: '{Literal}Sales by Item Type{/Literal}',
                    action: 'cloud-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'showGraphs', 'itemType', 'locations', 'cloudData']
                },
                // {
                //     value: 'z-out-cloud-summary-report',
                //     label: '{Literal}Z-Out Summary{/Literal}',
                //     action: 'generate-z-out-cloud-summary-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'locations', 'cloudData']
                // },
                // {
                //     value: 'sales-by-item-category',
                //     label: '{Literal}Sales by Item Category{/Literal}',
                //     action: 'cloud-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'showGraphs', 'itemCategory', 'locations', 'cloudData']
                // },
                // {
                //     value: 'sales-with-comps',
                //     label: '{Literal}Sales with Comps{/Literal}',
                //     action: 'cloud-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'showGraphs', 'locations', 'cloudData']
                // },
                // {
                //     value: 'sales-with-discounts',
                //     label: '{Literal}Sales with Discounts{/Literal}',
                //     action: 'cloud-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'showGraphs', 'locations', 'cloudData']
                // },
                {
                    value: 'sales-by-hour',
                    label: '{Literal}Sales by Hour{/Literal}',
                    action: 'cloud-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'showGraphs', 'locations', 'cloudData']
                },
                {
                    value: 'tender-total-summary',
                    label: '{Literal}Tender Total Summary{/Literal}',
                    action: 'cloud-report',
                    hideOnRetail: false,
                    filters: ['timeRange', 'showGraphs', 'locations', 'cloudData']
                },
                // {
                //     value: 'food-service-statistics',
                //     label: '{Literal}Food Service Statistics{/Literal}',
                //     action: 'cloud-report',
                //     hideOnRetail: false,
                //     filters: ['timeRange', 'showGraphs', 'locations', 'cloudData']
                // }
            ]
        }

        return reportTypes;
    },

    changeTransactionFilter: function(e) {
        var instance = M.FormSelect.getInstance($('#transaction-filter-dropdown'));
        this.transactionFilter = instance.getSelectedValues();
    },

    showAdvancedFilters: function() {
        var advanced = this.$el.find('.advanced:checked').length > 0
        if (0 === 0) {
            this.getTenderTypes().then(() => {
                var typeSelect = this.$el.find('#tender-type-filter-dropdown');
                $(typeSelect).html("");
                // var option = $('<option>');
                // $(option).attr('disabled', '');
                // $(option).attr('selected', '');
                // $(option).html('{Literal}None{/Literal}');
                // $(option).val('');
                // $(typeSelect).append(option);

                var allCreditValues = this.tenderTypes.map( i => { 
                    if(i.paymentType == 'C' || i.paymentType == 'D')
                        return i.id;
                });
                allCreditValues.push('allCredit');
                allCreditValues = allCreditValues.filter(i => i != undefined).join(";");
                var option = $('<option>');
                $(option).html('{Literal}All Credit Transactions{/Literal}');
                $(option).val(allCreditValues);
                $(typeSelect).append(option);
                tenders = this.tenderTypes;

                for (var i = 0; i < this.tenderTypes.length; i++) {
                    option = $('<option>');
                    $(option).val(this.tenderTypes[i].id);
                    $(option).html(this.tenderTypes[i].tenderName);
                    $(typeSelect).append(option);

                }
                $(typeSelect).formSelect();
            });

            this.getItemTypes().then(()=> {
                var typeSelect = this.$el.find('#item-type-filter-dropdown');
                $(typeSelect).html("");
                var option = $('<option>');
                $(option).attr('disabled', '');
                $(option).attr('selected', '');
                $(option).html('{Literal}None{/Literal}');
                $(option).val('');
                $(typeSelect).append(option);
                for (var i = 0; i < this.itemTypes.length; i++) {
                    option = $('<option>');
                    $(option).val(this.itemTypes[i]);
                    $(option).html(this.itemTypes[i]);
                    $(typeSelect).append(option);
                }
                $(typeSelect).formSelect();
            });

            this.getEmployees().then(() => {
                var typeSelect = this.$el.find('#employee-filter-dropdown');
                // var instance = M.FormSelect.getInstance($(typeSelect));
                // instance.destroy();
                $(typeSelect).html("");
                var option = $('<option>');
                $(option).attr('disabled', '');
                $(option).attr('selected', '');
                $(option).html('{Literal}Select Employee{/Literal}');
                $(option).val('');
                $(typeSelect).append(option);
                for (var i = 0; i < this.employees.length; i++) {
                    option = $('<option>');
                    $(option).val(this.employees[i]);
                    $(option).html(this.employees[i]);
                    $(typeSelect).append(option);
                }

                $(typeSelect).formSelect();
            });

            this.getTills().then(() => {
                var typeSelect = this.$el.find('#till-filter-dropdown');
                // var instance = M.FormSelect.getInstance($(typeSelect));
                // instance.destroy();
                $(typeSelect).html("");
                var option = $('<option>');
                $(option).attr('disabled', '');
                $(option).attr('selected', '');
                $(option).html('{Literal}Select Till{/Literal}');
                $(option).val('');
                $(typeSelect).append(option);
                for (var i = 0; i < this.tills.length; i++) {
                    option = $('<option>');
                    $(option).val(this.tills[i].id);
                    $(option).html(this.tills[i].name);
                    $(typeSelect).append(option);
                }

                $(typeSelect).formSelect();
            });

            if (advanced) {
                $('.advanced-transaction-filters').show();
            }
            else {
                $('.advanced-transaction-filters').hide();
            }
        }
        else {
            if (advanced) {
                $('.advanced-transaction-filters').show();
            }
            else {
                $('.advanced-transaction-filters').hide();
            }
        }
    },

    getPayPeriodInfo: async function() {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-pay-period-info',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.getPayPeriodInfo = data.payPeriodInfo;
            },
            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}'
                    });
                }
            }
        });
    },

    getEmployees: async function() {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-pos-users',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.renderEmployees(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}'
                    });
                }
            }
        });

        await this.sleep(100);
    },

    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.renderTenderTypes(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}'
                    });
                }
            }
        });

        await this.sleep(100);
    },

    getItemTypes: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-item-types',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.renderItemTypes(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}'
                    });
                }
            }
        });

        await this.sleep(100);
    },

    getLocations: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-locations',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.renderLocations(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}'
                    });
                }
            }
        });
    },

    getTills: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-tills',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.tills = 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}'
                    });
                }
            }
        });
    },


    sleep: function (ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    },

    renderEmployees: async function (data) {
        var that = this;
        data.sort(function (a, b) {
            return a.id.toLowerCase() < b.id.toLowerCase() ? -1 : (a.id.toLowerCase() > b.id.toLowerCase() ? 1 : 0);
        });

        for (var i = 0; i < data.length; i++) {
            var currentEmployee = data[i];

            that.employees[i] = currentEmployee.id;
        }
    },

    renderTenderTypes: async function (data) {
        var that = this;
        data.sort(function (a, b) {
            return a.paymentType.toLowerCase() < b.paymentType.toLowerCase() ? -1 : (a.paymentType.toLowerCase() > b.paymentType.toLowerCase() ? 1 : 0);
        });
        that.tenderTypes = data;

        // for (var i = 0; i < data.length; i++) {
        //     var currentTenderTypes = data[i];
        //     if (typeof currentTenderTypes.paymentType !== 'undefined') {
        //         currentTenderTypes.paymentTypeName = this.paymentTypeMapping[currentTenderTypes.paymentType];
        //     }
        //     that.tenderTypes[i] = currentTenderTypes.tenderName;
        // }
    },

    renderLocations: async function(data) {
        var that = this;
        data.sort(function (a, b) {
            return a.toLowerCase() < b.toLowerCase() ? -1 : (a.toLowerCase() > b.toLowerCase() ? 1 : 0);
        });

        for (var i = 0; i < data.length; i++) {
            var currentLocation = data[i];
            that.locations[i] = currentLocation;
        }

        $("#locations-preset").html("");
        // option = $('<option selected>');
        // $(option).val("all");
        // $(option).html("{Literal}All Locations{/Literal}");
        // $("#locations-preset").append(option);
        for (var i = 0; i < that.locations.length; i++) 
        {
            var option = $('<option>');
            $(option).val(that.locations[i]);
            $(option).html(that.locations[i]);
            $("#locations-preset").append(option);
        }

        $("#locations-preset").formSelect();
        $("#selectAllLocations").removeClass( "disabled");
    },

    renderItemTypes: async function(data) {
        var that = this;
        data.sort(function (a, b) {
            return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0);
        });

        for (var i = 0; i < data.length; i++) {
            var currentItemType = data[i];
            that.itemTypes[i] = currentItemType.name;
        }
    },

    changeItemFilter: function() {
        var itemType = this.$el.find('#item-filter-dropdown').val();
        if (itemType == "fromToItem") {
            $('#fromAmountInputItem').show();
            $('#toAmountInputItem').show();
            $('#itemAmountInputItem').hide();
        }
        else {
            $('#fromAmountInputItem').hide();
            $('#toAmountInputItem').hide();
            $('#itemAmountInputItem').show();
        }
    },

    changeAmountFilter: function () {
        var amountFilter = this.$el.find('#amount-filter-dropdown').val();
        if (amountFilter == "fromToAmount") {
            $('#fromAmountInputAmount').show();
            $('#toAmountInputAmount').show();
            $('#amountInputAmount').hide();
        }
        else {
            $('#fromAmountInputAmount').hide();
            $('#toAmountInputAmount').hide();
            $('#amountInputAmount').show();
        }
    },

    selectCustomerFromAutocompleteList: function (selection) {
        var that = this;
        var customerSearchAutocomplete = document.getElementById('customer-search-autocomplete');

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };
        
        for (var i = 0; i < Object.size(that.customerMapping); i++) {
            if (Object.entries(that.customerMapping)[i][0].trim() == selection.trim()) {
                customerSearchAutocomplete.value = Object.entries(that.customerMapping)[i][1].id;
            }
        }
    },

    selectCustomerFilterFromAutocompleteList: function (selection) {
        var that = this;
        var transactionReportCustomerSearchAutocomplete = document.getElementById('customer-filter-autocomplete');

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };
        
        for (var i = 0; i < Object.size(that.customerMapping); i++) {
            if (Object.entries(that.customerMapping)[i][0].trim() == selection.trim()) {
                transactionReportCustomerSearchAutocomplete.value = Object.entries(that.customerMapping)[i][1].id;
            }
        }
    },

    selectItemTypeFromAutocompleteList: function (selection) {
        var that = this;
        var itemId = document.getElementById('item-type-search-autocomplete');

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };
        
        for (var i = 0; i < Object.size(that.itemTypeMapping); i++) {
            if (Object.entries(that.itemTypeMapping)[i][0] == selection) {
                itemId.value = Object.entries(that.itemTypeMapping)[i][1].id;
            }
        }
    },

    nextPrevPayPeriod: function (event) {
        var that = this;
        var startDate = this.$el.find('#report-start-time').val();
        var endDate = this.$el.find('#report-end-time').val();
        startDate = moment(startDate).hour(0).minute(0);
        endDate = moment(endDate).hour(23).minute(59);
        if($(event.target).hasClass('forward')) {
            if(that.getPayPeriodInfo.periodDuration > 0){
                startDate = startDate.add(that.getPayPeriodInfo.periodDuration + 1, 'days');
                endDate = endDate.add(that.getPayPeriodInfo.periodDuration, 'days');
            } else {
                startDate = startDate.add(1,'months');
                endDate = endDate.add(1,'months').endOf('month');
            }
            
        } else if($(event.target).hasClass('back')){
            if(that.getPayPeriodInfo.periodDuration > 0){
                startDate = startDate.subtract(that.getPayPeriodInfo.periodDuration + 1, 'days');
                endDate = endDate.subtract(that.getPayPeriodInfo.periodDuration, 'days');
            } else {
                startDate = startDate.subtract(1,'months');
                endDate = endDate.subtract(1,'months').endOf('month');
            }
        }

        this.$el.find('#report-start-time').val(startDate.format('YYYY-MM-DD'));
        this.$el.find('#report-end-time').val(endDate.format('YYYY-MM-DD'));

        that.selectedStartTime = startDate.toDate();
        that.selectedEndTime = endDate.toDate();
    },

    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;
                that.prefillRangePreset({ currentTarget: that.$el.find('#date-range-preset') });

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

    selectUnselectAllLocations: function() {
        this.$el.find('#locations-preset option').each( (i,e) => {
            e.selected = true;
        });
        this.$el.find('#locations-preset').formSelect();        
        ;
    }
});