var ItemsView = Backbone.View.extend({
    fullCollection: {},
    deletionModal: {},
    itemsRows: 3,
    itemsColumns: 4,
    pages: 0,
    itemTypesTotal: 0,
    advancedOptionSwitch: 0,
    sort: 0,
    cards: true,
    itemsCollectionCut: {},
    currentPageIndex: null,
    selectedPageIndex: 1,
    canAddDelete: false,
    changeItems: false,
    addedItem: false,
    shownItems: [],
    appendItem: false,
    initialLoad: 0,
    lastSearchState: { searchText: '', isInactiveOnly: false, searchField: '' },
    lastSearchText: '',
    isNewSearch: true,
    searchItemsTotal: 0,
    offset: 1,
    file: undefined,
    itemId: '',
    menuKeySets: [],
    courses:[],
    itemAttributes:[],

    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .pagination-trigger': 'handlePageClickEvent',
        'click #pagination-back': 'handlePageBackEvent',
        'click #pagination-forward': 'handlePageForwardEvent',
        'click .edit-items-trigger': 'editItems',
        'click #add-items-button': 'addItems',
        'click .save-button': 'saveItems',
        'click .save-add-button': 'saveAddAnother',
        'click .search-items-button': 'pullItems',
        'click .sort-by-button': 'sortSearch',
        'change #advanced': 'advancedOptions',
        'click .optional-button': 'optionalInfo',
        'keyup #id' : 'validateId',
        'keyup #description' : 'validateDescription',
        'keyup #price' : 'validatePrice',
        'keyup #secondPrice' : 'validateSecondPrice',
        'keyup #altDescription' : 'validateAltDescription',
        'keyup #priceLevel2' : 'validateForm',
        'keyup #priceLevel3' : 'validateForm',
        'keyup #priceLevel4' : 'validateForm',
        'keyup #priceLevel5' : 'validateForm',
        'click .save-item-type-button' : 'chooseNewItemType',
        'click .save-item-category-button' : 'chooseNewCategory',
        'click .save-item-sales-account-button' : 'chooseNewSalesAccount',
        'change #productLine1' : 'chooseProductLine',
        'keyup #searchText': 'enterToSearch',
        'blur #id': 'checkIfItemExists',
        'click #description': 'fillInDescription', //changed to fix multiple calls in android,
        'change #attribute1, #attribute2' : 'fillAttributeCodes',
        'click #editButton' : 'toggleSelectionMode',
        'click #selectAll' : 'selectAll',
        'click .floating-menu-button-fixed ul' : 'onFloatingButtonsEmptySpaceClick',
        'click #openBulkEditItemsModal' : 'openBulkEditItemsModal',
        'click #saveBulkEdit' : 'bulkUpdateItems',
    },

    breadcrumb: {},

    itemsStyleMapping: {},

    styles: [
        'ap-blue',
    ],

    selectionMode: {
        active: false,
        selectedItemsList:[],
        selectAll: false,
    },

    initialize: async function (options) {
        this.offset = this.itemsColumns * this.itemsRows;
        this.options = options;
        this.template = _.template(options.template);
        this.itemsFormTemplate = options.itemsFormTemplate;
        this.breadcrumb = options.breadcrumb;
        this.collection = options.collection;
        this.listenTo(this.collection, 'reset', this.render);
        this.listenTo(this.collection, 'remove', this.render);
        this.listenTo(this.collection, 'add', this.render);
        this.model = options.model;
        await this.checkAccess();
        this.getItemAttributes();
        this.initItemTypes();
        this.initializePaginator();
        this.getCourses();
    },

    render: function () {

        this.$el.html(this.template({
            items: this.collection.toJSON(),
            itemTypes: this.itemTypes,
            choiceGroups: this.choiceGroups,
            category: this.category,
            menuPages: this.menuPages,
            menuKeySets: this.menuKeySets,
            productLine: this.productLine,
            salesAccounts: this.salesAccounts,
            vatCode: this.vatCode,
            selectionMode: this.selectionMode
        }));

        App.breadCrumbToolTip = "Create, manage, and edit your items"

        App.setBreadcrumbs(this.breadcrumb);

        this.deletionModal = $(".modal").modal();
        var that = this;
        $(document).ready(function(){
            $('.modal').modal();
            $('select').formSelect();
            $('.tooltipped').tooltip();
            var elems = document.querySelectorAll('.fixed-action-btn');
            var instances = M.FloatingActionButton.init(elems, {direction: App.rtl ? 'right' : 'left', hoverEnabled: false});
            that.selectionMode['instance'] = instances[1];
            if(that.selectionMode.active)
                that.selectionMode.instance.open();
            if(that.collection.length === 0)
                document.getElementById("searchText").focus();
        });
        this.formModal = this.$el.find('#items-form-modal').modal();
        
        $(document).on('keydown', 'input, select', function(e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
              ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select,button,select').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    form.submit();
                }
                return false;
            }
        });

        if (this.appendItem) {
            var html = '<div id="itemCards"><div class="col m2" style="width: 16.6666666667%; left: auto; right: auto;">'
            html += '<div class="card-panel card-panel-entity z-depth-2 sequence-card hoverable waves-effect waves-light" style="background-color: #ffffff" data-id="'+ that.itemsFormView.model.attributes.id + '" data-selected="0">'
            html += '<div> <div class="row itemDescription truncate" style="font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}ID#{/Literal} '+ that.itemsFormView.model.attributes.id  + '</div>';
            html += '<div> <div class="row description truncate" style="color: #3970b7; font-size: 1rem;">' + that.itemsFormView.model.attributes.description  + '</div>';
            html += '<div class="row type truncate" style="font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Type:{/Literal}' + that.itemsFormView.model.attributes.type + '</div>'
            html += '<div class="row price truncate" style="font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Price:{/Literal}' + that.itemsFormView.model.attributes.priceLevel1 + '</div>'
            html += '<div class="row truncate">';
            html += '<div class="discount" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Discount:{/Literal}' + that.itemsFormView.model.attributes.allowDiscount + '</div>'
            html += '<div class="category" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Category:{/Literal}' + that.itemsFormView.model.attributes.categoryName + '</div>'
            html += '<div class="taxable" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Taxable:{/Literal}' + that.itemsFormView.model.attributes.taxable + '</div>'
            html += '<div class="inactive" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Inactive:{/Literal}' + that.itemsFormView.model.attributes.inactive + '</div>'
            html += '<div class="allowDiscount" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Allow Discount:{/Literal}' + that.itemsFormView.model.attributes.allowDiscount + '</div>'
            html += '<div class="price2" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Price Level 2:{/Literal}' + that.itemsFormView.model.attributes.priceLevel2 + '</div>'
            html += '<div class="price3" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Price Level 3:{/Literal}' + that.itemsFormView.model.attributes.priceLevel3 + '</div>'
            html += '<div class="price4" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Price Level 4:{/Literal}' + that.itemsFormView.model.attributes.priceLevel4 + '</div>'
            html += '<div class="price5" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Price Level 5:{/Literal}' + that.itemsFormView.model.attributes.priceLevel5 + '</div>'
            html += '<div class="costId" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Cost{/Literal}' + that.itemsFormView.model.attributes.cost + '</div>'
            html += '<div class="isStock" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Track Stock:{/Literal}' + that.itemsFormView.model.attributes.isStock + '</div>'
            html += '<div class="scale" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Scalable:{/Literal}' + that.itemsFormView.model.attributes.scale + '</div>'
            html += '<div class="noPartialQuantity" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}No Partial Quantity:{/Literal}' + that.itemsFormView.model.attributes.noPartialQuantity + '</div>'
            html += '<div class="serialized" style="display: none; font-size: .95rem; margin-bottom: 0px; color: gray;">{Literal}Has Serial{/Literal} #:' + that.itemsFormView.model.attributes.serialized + '</div>'
            html += '</div>';
            html += '</div>';
            html += '<div class="edit" style="display: none"><a href="javascript:void(0)" class="btn-floating btn-large waves-effect waves-light ap-dark-blue edit-items-trigger" data-id="' + that.itemsFormView.model.attributes.id + '"> <i class="material-icons">edit</i> </a> </div>'
            html += '</div></div></div>' 
            $('#items-wrapper').append(html);
            this.appendItem = false;
        }

        return this;
    },
    
    
    /*--------------------------------------Search Card Options---------------------------------------------- */

    showSearchItems: function (filteredItems) {
        var that = this;
        var searchText = this.isNewSearch ? this.$el.find('#searchText').val() : this.lastSearchState.searchText;
        this.shownItems = filteredItems;
        if(searchText === '' && this.isNewSearch)
            M.toast({ html: '{Literal}Showing all items{/Literal}...' });
            
        if (filteredItems.length > 0) {
            this.collection.reset(filteredItems);
            if(this.isNewSearch)
                that.renderPaginator();
            else
                this.renderPaginationChange();

            that.cards = false;
            $('#itemBlock').fadeIn();
            $("select").formSelect();

            $('#itemBlock').fadeIn();
            $('#paginationBlock').fadeIn();
        }
        else {
            this.collection.reset();
            $('#paginationBlock').hide();
            M.toast({ html: '{Literal}No search results found{/Literal}' }); 
        }
    },

    pullItems: function(e) {
        var that = this;
        if(e != undefined)
            that.isNewSearch = $(e.currentTarget).attr("id") === 'searchText' || $(e.currentTarget).closest(".search").length === 1;
        if(that.isNewSearch)
            that.selectedPageIndex = 1;

        var searchText = this.isNewSearch ? this.$el.find('#searchText').val() :  this.lastSearchState.searchText;
        var showInactiveOnly = this.isNewSearch ? this.$el.find('#showInactiveOnly input:checked').length > 0 : this.lastSearchState.isInactiveOnly;
        var searchField = this.isNewSearch ? this.$el.find('#searchField').val() : this.lastSearchState.searchField;

       
        var sessionToken = this.getCookie();
        document.getElementById("searchText").blur();

        $.ajax({
            url: '/data/search-items',
            data: {
                token: sessionToken,
                searchBy: searchField,
                searchText: searchText,
                showInactiveOnly: showInactiveOnly,
                offset: this.offset,
                pageNumber: this.selectedPageIndex
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.lastSearchState.searchText = searchText;
                that.lastSearchState.isInactiveOnly = showInactiveOnly;
                that.lastSearchState.searchField = searchField;
                that.searchItemsTotal = data.results[1].searchItemsTotal;
                that.showSearchItems(data.results[0]);
                if(that.searchItemsTotal)
                    that.showEdiButton();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem fetching item types from the server{/Literal}' });
                }
            }
        });
    },
    
    sortSearch: function () {
        var sortBy = this.$el.find('#sortBy1').val();
        if (sortBy == 0) {
            sort = 1; 
            filtered = this.collection.sortBy("description");
            this.collection.reset(filtered);
            this.getItemsTotalCount();
            $('.sortBy').show();
            $('.sortByButton').show();
            $("#items-pagination").remove();
        }
        else if (sortBy == 1) {
            sort = 2; 
            filtered = this.collection.sortBy("description").reverse();
            this.collection.reset(filtered);
            this.getItemsTotalCount();
            $('.sortBy').show();
            $('.sortByButton').show();
            $("#items-pagination").remove();
        }
        else if (sortBy == 2) {
            sort = 0; 
            filtered = this.collection.sortBy("id");
            this.collection.reset(filtered);
            this.getItemsTotalCount();
            $('.sortBy').show();
            $('.sortByButton').show();
            $("#items-pagination").remove();
        }
        else if (sortBy == 3) {
            sort = 3; 
            filtered = this.collection.sortBy("id").reverse();
            this.collection.reset(filtered);
            this.getItemsTotalCount();
            $('.sortBy').show();
            $('.sortByButton').show();
            $("#items-pagination").remove();
        }
        $('#itemBlock').fadeIn();
        $('#paginationBlock').show();
    },

    enterToSearch: function (e) {
        if (e.keyCode == 13) {
            this.$el.find(".search-items-button").trigger("click");
        }
    }, 

    /*-------------------------------------------Initialize/Render Options---------------------------------------------- */
  
    initItemTypes:  function () {
        this.getItemTypes();
    },

    getItemTypes: 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 item types from the server{/Literal}' });
                }
            }
        });
    },
    
    renderItemTypes: function (data) {
        var that = this;
        that.itemTypes = [];
        for (var i = 0; i < data.length; i++) {
            if(data[i].name != "{Literal}Create New Item Type{/Literal}")
                that.itemTypes.push(data[i]);
        }

        that.itemTypes.sort(function (a, b) {
            return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0);
        });
        
        this.initProductLine();
    },

    initProductLine: function() {
        this.getProductLine();
    },

    getProductLine: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-product-lines',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.menuKeySets = [];

                for (var i = 0; i < data.results.length; i++) {
                    var newObj = {};
                    newItemType = data.results[i].type

                    newObj.id = newItemType;
                    newObj.name = newItemType;

                    // that.itemTypes.push(newObj);
                    var keysetName = data.results[i].keysetName;
                    if(keysetName != undefined && keysetName != "")
                        that.menuKeySets.push(keysetName)
                }
                // that.getItemTypeTotalCount(that.itemTypes);
                that.productLine = data.results;
                that.renderProductLine(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 item types from the server{/Literal}' });
                }
            }
        });
    },

    renderProductLine: function (data) {
        var that = this;
        for (var i = 0; i < data.length; i++) {
            var currentProductLine = data[i];
        }
        this.initChoiceGroups();
    },

    initChoiceGroups:  function () {
        this.getChoiceGroups();
    },

    getChoiceGroups: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-choice-groups',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.choiceGroups = data.results;
                that.renderChoiceGroups(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 choice groups from the server{/Literal}' });
                }
            }
        });
    },
    
    renderChoiceGroups: function (data) {
        var that = this;
        for (var i = 0; i < data.length; i++) {
            var currentChoiceGroup = data[i];
        }
        this.initCategory();
    },

    initCategory:  function () {
        this.getCategory();
    },  

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

    renderCategory: function (data) {
        var that = this;
        that.category = [];
        for (var i = 0; i < data.length; i++) {
            if(data[i].name != "{Literal}Create New Item Category{/Literal}")
                that.category.push(data[i]);
        }
        this.initSalesAccounts();
    },

    initSalesAccounts: function () {
        this.getGlAccounts();
    },

    // getSalesAccounts: function () {
    //     var that = this;
    //     var sessionToken = this.getCookie();
    //     $.ajax({
    //         url: '/data/get-sales-accounts',
    //         data: {
    //             token: sessionToken
    //         },
    //         dataType: 'json',
    //         type: 'POST',
    //         success: function (data) {
    //             that.salesAccounts = data.results;
    //             that.renderSalesAccounts(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 sales accounts from the server{/Literal}' });
    //             }
    //         }
    //     });
    // },

    renderSalesAccounts: function (data) {
        var that = this;
        for (var i = 0; i < data.length; i++) {
            var currentSalesAccounts = data[i];
        }
        this.initvatCode();
    },

    initializeCounter: function () {
        this.getItemTypeTotalCount();
    },

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

    initvatCode: function() {
        this.getvatCode();
    },

    getvatCode: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-vat-codes',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.vatCode = data.results;
                that.rendervatCode(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 taxes from the server{/Literal}' });
                }
            }
        });
    },

    rendervatCode: function (data) {
        var that = this;
        for (var i = 0; i < data.length; i++) {
            var currentvatCode = data[i];
        }
        this.initMenuPages();
    },

    initMenuPages: function() {
        this.getMenuPages();
    },

    getMenuPages: function() {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-menu-pages',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.menuPages = data.results;
                that.renderMenuPages(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 menu pages from the server{/Literal}' });
                }
            }
        });
    },

    getCourses: function() {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-course-names',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.courses = [];
                for (let i = 0; i < data.results.length; i++) {
                    if(data.results[i].name != '')
                        that.courses.push(data.results[i])
                }
                
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem fetching course names from the server{/Literal}' });
                }
            }
        });
    },

    renderMenuPages: function (data) {
        this.checkAccess();
        // this.initItems();
    },


    /*--------------------------------------Form Options---------------------------------------------- */

    editItems: function (e) {
        this.addedItem = false;
        if (this.changeItems) {
            var element = $(e.currentTarget);
            var id = $(element).attr('data-id');
            var item = this.collection.get(id);
            this.advancedOptionSwitch = 0;

            if (item !== null && item !== '' && item !== undefined) {
                this.itemsFormView = new ItemsFormView({
                    template: this.itemsFormTemplate,
                    model: item,
                    itemTypes: this.itemTypes,
                    choiceGroups: this.choiceGroups,
                    category: this.category,
                    menuPages: this.menuPages,
                    menuKeySets: this.menuKeySets,
                    salesAccounts: this.salesAccounts,
                    productLine: this.productLine,
                    vatCode: this.vatCode,
                    courses: this.courses,
                    itemAttributes: this.itemAttributes
                });
                this.formModal = this.$el.find('#items-form-modal').modal('open');
                this.$el.find('#items-form-modal').html(this.itemsFormView.render().el);
                this.$el.find('select').formSelect();
                // this.formModal.modal('open');
                $("#quantity").attr("disabled", true);
            }
            else if (item === undefined) {
                var thisItem = this.collection.models[0];
                this.itemsFormView = new ItemsFormView({
                    template: this.itemsFormTemplate,
                    model: thisItem,
                    itemTypes: this.itemTypes,
                    choiceGroups: this.choiceGroups,
                    category: this.category,
                    menuPages: this.menuPages,
                    menuKeySets: this.menuKeySets,
                    salesAccounts: this.salesAccounts,
                    productLine: this.productLine,
                    vatCode: this.vatCode,
                    courses: this.courses,
                    itemAttributes: this.itemAttributes
                });
                this.formModal = this.$el.find('#items-form-modal').modal('open');
                this.$el.find('#items-form-modal').html(this.itemsFormView.render().el);
                this.$el.find('select').formSelect();
                // this.formModal.modal('open');
                $("#quantity").attr("disabled", true);
            }
            else {
                M.toast({ html: '{Literal}There was a problem fetching data from the server{/Literal}' });
            }
        }
        else {
            M.toast({ html: '{Literal}You do not have access to edit items{/Literal}' });
        }
    },

    addAnotherItem: function () {
        if (this.canAddDelete) {
            var productLine = this.itemsFormView.model.attributes.productLine;
            var type = this.itemsFormView.model.attributes.type;
            var category = this.itemsFormView.model.attributes.category;
            var menuPage = this.itemsFormView.model.attributes.menuPage;
            var vatCode = this.itemsFormView.model.attributes.vatCode;

            var salesAccount = this.itemsFormView.model.attributes.salesAccount;
            var choiceGroup = this.itemsFormView.model.attributes.choiceGroup;
            var allowDiscount = this.itemsFormView.model.attributes.allowDiscount;
            var isStock = this.itemsFormView.model.attributes.isStock;
            var scale = this.itemsFormView.model.attributes.scale;
            var noPartialQuantity = this.itemsFormView.model.attributes.noPartialQuantity;
            var serialized = this.itemsFormView.model.attributes.serialized;
            var cost = this.itemsFormView.model.attributes.cost;

            this.addedItem = true;
            this.advancedOptionSwitch = 0;
            this.isCreateMode = true;
            var items = new Items();

            items.attributes.type = type;
            items.attributes.productLine = productLine;
            items.attributes.category = category;
            items.attributes.menuPage = menuPage;
            items.attributes.vatCode = vatCode
            items.attributes.cost = cost;
            

            items.attributes.salesAccount = salesAccount;
            items.attributes.choiceGroup = choiceGroup;
            items.attributes.allowDiscount = allowDiscount;
            items.attributes.isStock = isStock;
            items.attributes.scale = scale;
            items.attributes.noPartialQuantity = noPartialQuantity;
            items.attributes.serialized = serialized;

            this.itemsFormView = new ItemsFormView({
                template: this.itemsFormTemplate,
                model: items,
                itemTypes: this.itemTypes,
                choiceGroups: this.choiceGroups,
                category: this.category,
                menuPages: this.menuPages,
                menuKeySets: this.menuKeySets,
                salesAccounts: this.salesAccounts,
                productLine: this.productLine,
                vatCode: this.vatCode,
                isCreateMode: this.isCreateMode,
                courses: this.courses,
                itemAttributes: this.itemAttributes
            });

            this.$el.find('#items-form-modal').html(this.itemsFormView.render().el);
            this.$el.find('select').formSelect();
            this.$el.find("select[required]").css({
                display: "block", 
                position: 'absolute',
                visibility: 'hidden'
            });
            setTimeout(() => {$('#items-form-modal').modal('open')}, 100);
            // this.formModal = this.$el.find('#items-form-modal').modal('open');
            // this.formModal.modal('open');
            $('#productLine1').show(); 
            $("#id").removeAttr('disabled')
        }
        else {
            M.toast({ html: '{Literal}You do not have access to add items{/Literal}' });
        }
    },

    addItems: function () {
        if (this.canAddDelete) {
            this.addedItem = true;
            this.advancedOptionSwitch = 0;
            this.isCreateMode = true;
            var items = new Items();
            this.itemsFormView = new ItemsFormView({
                template: this.itemsFormTemplate,
                model: items,
                itemTypes: this.itemTypes,
                choiceGroups: this.choiceGroups,
                category: this.category,
                menuPages: this.menuPages,
                menuKeySets: this.menuKeySets,
                salesAccounts: this.salesAccounts,
                productLine: this.productLine,
                vatCode: this.vatCode,
                isCreateMode: this.isCreateMode,
                courses: this.courses,
                itemAttributes: this.itemAttributes
            });
    
            this.$el.find('#items-form-modal').html(this.itemsFormView.render().el);
            this.$el.find('select').formSelect();
            this.$el.find("select[required]").css({
                display: "block", 
                position: 'absolute',
                visibility: 'hidden'
            });  
            this.formModal = this.$el.find('#items-form-modal').modal('open');
            // this.formModal.modal('open');
            $('#productLine1').show(); 
            $("#id").removeAttr('disabled')
        }
        else {
            M.toast({ html: '{Literal}You do not have access to add items{/Literal}' });
        }
    },

    /*--------------------------------------Card Options---------------------------------------------- */

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

    highlightCard: function (e) {
        if(this.selectionMode.active){
            const input = e.currentTarget.querySelector('input');
            input.checked = !input.checked;
            const itemId = e.currentTarget.dataset.id;
            const description = e.currentTarget.dataset.description;
            const itemDetail = {id:itemId, description: description};
            if(input.checked){
                this.selectionMode.selectedItemsList.push(itemDetail);
            } else {
                var index = this.selectionMode.selectedItemsList.indexOf(itemDetail);
                this.selectionMode.selectedItemsList.splice(index, 1);
            }

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

    advancedOptions: function() {
        if (this.advancedOptionSwitch % 2 == 0) {
            $('#price0').hide(); 
            // $('#category2').hide(); 
            $('#productLine1').hide(); 
            // $('#category1').show(); 
            $('#choiceGroup1').show(); 
            // if (App.serverInfo.hasAccounting) {
            //     $('.sales').show(); 
            // }
            $('#altDescription1').show(); 
            $('#availability1').show(); 
            var availability1 = this.$el.find('#availability1').val();
            if (availability1 == "WARN") {
                $('#available1').show(); 
            }
            $('#quantity1').show(); 
            $('#price1').show(); 
            $('#price2').show(); 
            $('#price3').show(); 
            $('#price4').show(); 
            $('#price5').show(); 
            $('#costId').show(); 
            $('#allowDiscount1').show(); 
            $('#isStock1').show(); 
            $('#inactive1').show();
            $('#scale1').show();
            $('#useTare1').show();
            $('#noPartialQuantity1').show(); 
            $('#serialized1').show();
            if (App.serverInfo.hasVatTax) {
                $('#taxable1').show();
            } 
            else {
                $('#taxable2').show(); 
            }

            document.getElementById('altDescription').scrollIntoView({ behavior: 'smooth', block: 'center' });
            this.advancedOptionSwitch++;
        } 
        else {
            if (this.itemsFormView.model.attributes.id == "") {
                $('#productLine1').show(); 
            }
            $('#price0').show(); 
            // $('#category1').hide(); 
            // $('#category2').show();
            $('#choiceGroup1').hide(); 
            // $('.sales').hide();
            $('#altDescription1').hide(); 
            //$('#availability1').hide(); 
            //$('#available1').hide(); 
            //$('#quantity1').hide(); 
            $('#price1').hide(); 
            $('#price2').hide(); 
            $('#price3').hide(); 
            $('#price4').hide(); 
            $('#price5').hide();
            $('#costId').hide();
            $('#allowDiscount1').hide(); 
            $('#isStock1').hide(); 
            $('#inactive1').hide();
            $('#scale1').hide(); 
            $('#useTare1').hide();
            $('#noPartialQuantity1').hide(); 
            $('#serialized1').hide(); 
            $('#taxable1').hide(); 
            $('#taxable2').hide(); 
            document.getElementById('id').scrollIntoView({ behavior: 'smooth', block: 'center' });
            this.advancedOptionSwitch++;

        } 
    },

    optionalInfo: function() {
        $('.discount').hide();
        $('.category').hide();
        $('.taxable').hide();
        $('.inactive').hide();
        $('.allowDiscount').hide();
        $('.price2').hide();
        $('.price3').hide();
        $('.price4').hide();
        $('.price5').hide();
        $('.isStock').hide();
        $('.scale').hide();
        $('.noPartialQuantity').hide();
        $('.serialized').hide();

        var optional = this.$el.find('#optional1').val();

        if (optional == 1) {
            $('.category').show();
        }
        else if (optional == 2) {
            $('.taxable').show();
        }
        else if (optional == 3) {
            $('.inactive').show();
        }
        else if (optional == 0) {
            $('.discount').show();
        }
        else if (optional == 5) {
            $('.allowDiscount').show();
        }
        else if (optional == 6) {
            $('.price2').show();
        }
        else if (optional == 7) {
            $('.price3').show();
        }
        else if (optional == 8) {
            $('.price4').show();
        }
        else if (optional == 9) {
            $('.price5').show();
        }
        else if (optional == 10) {
            $('.isStock').show();
        }
        else if (optional == 11) {
            $('.scale').show();
        }
        else if (optional == 12) {
            $('.noPartialQuantity').show();
        }
        else if (optional == 4) {
            $('.serialized').show();
        }


    },
    
    /*------------------------------ Pagination Stuff ------------------------------------*/

    initializePaginator: function () {
        // this.getItemsTotalCount();
    },

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

        this.pages = Math.ceil(1.0 * this.searchItemsTotal / (this.itemsRows * this.itemsColumns));
        if(this.pages == 1) {
            $("#items-pagination").hide();
            return;
        }
        
        if (this.pages > 10 & this.selectedPageIndex > 5) {
            if (this.pages < this.selectedPageIndex + 6) {
                var start = this.selectedPageIndex - 4;
                var currentPageElement = $('<li class="waves-effect pagination-trigger" data-page="' + start + '"><a href="javascript:void(0)">' + start + '</a></li>');
                $("#pagination-back").after(currentPageElement);
                for (var i = this.selectedPageIndex - 3; 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>');
                    if (this.selectedPageIndex === i) {
                        $(currentPageElement).addClass('active').addClass('ap-blue');
                    }
                    $(lastElement).after(currentPageElement);
                }
            }
            else {
                var start = this.selectedPageIndex - 4;
                var currentPageElement = $('<li class="waves-effect pagination-trigger" data-page="' + start + '"><a href="javascript:void(0)">' + start + '</a></li>');
                $("#pagination-back").after(currentPageElement);
                for (var i = this.selectedPageIndex - 3; i <= this.selectedPageIndex + 5; i++) {
                    var lastElement = currentPageElement;
                    currentPageElement = $('<li class="waves-effect pagination-trigger" data-page="' + i + '"><a href="javascript:void(0)">' + i + '</a></li>');
                    if (this.selectedPageIndex === i) {
                        $(currentPageElement).addClass('active').addClass('ap-blue');
                    }
                    $(lastElement).after(currentPageElement);
                }
            }
        } 
        else if (this.pages > 10 & this.selectedPageIndex < 6) {
            var currentPageElement = $('<li class="pagination-trigger" data-page="1"><a href="javascript:void(0)">1</a></li>');
            if (this.selectedPageIndex === 1) {
                $(currentPageElement).addClass('active').addClass('ap-blue');
            }
            $("#pagination-back").after(currentPageElement);
            for (var i = 2; i <= 10; i++) {
                var lastElement = currentPageElement;
                currentPageElement = $('<li class="waves-effect pagination-trigger" data-page="' + i + '"><a href="javascript:void(0)">' + i + '</a></li>');
                if (this.selectedPageIndex === i) {
                    $(currentPageElement).addClass('active').addClass('ap-blue');
                }
                $(lastElement).after(currentPageElement);
            }
        }
        else {
            var currentPageElement = $('<li class="pagination-trigger" data-page="1"><a href="javascript:void(0)">1</a></li>');
            if (this.selectedPageIndex === 1) {
                $(currentPageElement).addClass('active').addClass('ap-blue');
            }
            $("#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>');
                if (this.selectedPageIndex === i) {
                    $(currentPageElement).addClass('active').addClass('ap-blue');
                }
                $(lastElement).after(currentPageElement);
            }
        }
        
        if (this.initialLoad <= 1 ) {
            this.initialLoad++;
        }
        else {
            $('#searchText').attr('readonly', 'readonly'); // Force keyboard to hide on input field.
            $('#searchText').attr('disabled', 'true'); // Force keyboard to hide on textarea field.
            setTimeout(function() {
                $('#searchText').blur();  //actually close the keyboard
                // Remove readonly attribute after keyboard is hidden.
                $('#searchText').removeAttr('readonly');
                $('#searchText').removeAttr('disabled');
            }, 100);
        }
        
        $("#items-pagination").show();
    },

    handlePageBackEvent: function (e) {
        var element = $(e.currentTarget);
        if (!$(element).hasClass('disabled')) {
            var currentPage = parseInt($("#items-pagination").attr("data-current-page"));
            this.isNewSearch = false;
            this.selectedPageIndex--;
            this.pullItems();
            // this.goToItemsPage(this.selectedPageIndex, -1);

        }
    },

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

    handlePageClickEvent: function (e) {
        var element = $(e.currentTarget);
        var selectedPage = parseInt($(element).attr('data-page'));
        this.selectedPageIndex = parseInt($(element).attr('data-page'));
        var currentPage = parseInt($("#items-pagination").attr("data-current-page"));
        this.isNewSearch = false;
        this.pullItems();
    },

    goToItemsPage: function (selectedPage, currentPage) {
        var element = $(".pagination-trigger[data-page=" + selectedPage + "]");
        var offset = this.itemsColumns * this.itemsRows;
        var args = {
            selectedPage: selectedPage,
            element: element,
            parentView: this
        };       
    },
    
    renderPaginationChange: function (items, args) {
        this.cards = true;
        this.renderPaginator();

        $('.modal').modal();
        $('select').formSelect();
        $("#items-pagination").attr("data-current-page", this.selectedPageIndex);
        
        if (this.selectedPageIndex === 1 && this.fullCollection.length >= this.collection.length) {
            $('#itemBlock').fadeIn();
            $('#paginationBlock').show();
            $("#pagination-back").addClass('disabled').removeClass('waves-effect');
            $("#pagination-forward").removeClass('disabled').addClass('waves-effect');
        } else if (this.selectedPageIndex === 1) {
            $("#pagination-back").addClass('disabled').removeClass('waves-effect');
            $("#pagination-forward").removeClass('disabled').addClass('waves-effect');
        } else if (this.selectedPageIndex === this.pages) {
            $('#itemBlock').fadeIn();
            $('#paginationBlock').show();
            $("#pagination-back").removeClass('disabled').addClass('waves-effect');
            $("#pagination-forward").addClass('disabled').removeClass('waves-effect');
        } else {
            $('#itemBlock').fadeIn();
            $('#paginationBlock').show();
            $("#pagination-back").removeClass('disabled').addClass('waves-effect');
            $("#pagination-forward").removeClass('disabled').addClass('waves-effect');
        }

        $("#items-modal-preloader").hide();
    },

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

                }
            }
        });
    },

    /*--------------------------------------Initialize/Render Items---------------------------------------------- */
    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);
        }
    },

    initItems:  function () {
        var itemsPerPage = this.itemsColumns * this.itemsRows;
        // var fullItems = this.getItemsFull();
        var items = this.getItems(itemsPerPage, 1, { parentView: this });
    },

    getItems: function (pageSize, pageNumber, callbackArgs) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-items',
            data: {
                items: that.items,
                offset: pageSize,
                pageNumber: pageNumber,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                if (typeof data.results !== 'undefined') {
                    for (var i = 0; i < data.results.length; i++) {
                        var itemTypeId = data.results[i].type;
                        var categoryId = data.results[i].category;                       
                        if (typeof that.itemTypes !== 'undefined') {
                            var itemType = that.itemTypes.filter(
                                function (element) {
                                    return element.id === itemTypeId;
                                }
                            );
                            if (itemType.length > 0) {
                                data.results[i].itemTypeName = itemType[0].name;
                            } else {
                                data.results[i].itemTypeName = 'N/A';    
                            }
                        } else {
                            data.results[i].itemTypeName = 'N/A';
                        }

                        if (typeof that.category !== 'undefined') {
                            var category = that.category.filter(
                                function (element) {
                                    return element.id === categoryId;
                                }
                            );
                            if (category.length > 0) {
                                data.results[i].categoryName = category[0].name;
                            } else {
                                data.results[i].categoryName = 'N/A';    
                            }
                        }
                        else {
                            data.results[i].categoryName = 'N/A';
                        }
                    }
                }
                that.renderItems(data.results);
                that.renderPaginationChange(data.results, callbackArgs);
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {

                }
            }
        });
    },

    getItemsFull: function () {
        var that = this;
        var showInactiveOnly = this.$el.find('#showInactiveOnly input:checked').length > 0;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-items-full',
            data: {
                token: sessionToken,
                showInactiveOnly: showInactiveOnly
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                if (typeof data.results !== 'undefined') {
                    for (var i = 0; i < data.results.length; i++) {
                        var itemTypeId = data.results[i].type;
                        var categoryId = data.results[i].category;                       
                        if (typeof that.itemTypes !== 'undefined') {
                            var itemType = that.itemTypes.filter(
                                function (element) {
                                    return element.id === itemTypeId;
                                }
                            );
                            if (itemType.length > 0) {
                                data.results[i].itemTypeName = itemType[0].name;
                            } else {
                                data.results[i].itemTypeName = 'N/A';    
                            }
                        } else {
                            data.results[i].itemTypeName = 'N/A';
                        }

                        if (typeof that.category !== 'undefined') {
                            var category = that.category.filter(
                                function (element) {
                                    return element.id === categoryId;
                                }
                            );
                            if (category.length > 0) {
                                data.results[i].categoryName = category[0].name;
                            } else {
                                data.results[i].categoryName = 'N/A';    
                            }
                        }
                        else {
                            data.results[i].categoryName = 'N/A';
                        }
                    }
                }
                that.fullCollectionMethod(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}'
                    });
                }
            }
        });
    },

    fullCollectionMethod: function (data) {
        var collection = new ItemsCollection();
        for (var i = 0; i < data.length; i++) {
            var currentItems = data[i];
            collection.add(new Items(currentItems));
        }
    },

    renderItems: function (data) {
        var that = this;
        this.generateItemsStyleMapping(data);

        data.sort(function (a, b) {
            return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
        });
        
        itemsCollectionCut = new ItemsCollection();
        for (var i = 0; i < data.length; i++) {
            var currentItems = data[i];
            currentItems.cardStyleClass = that.itemsStyleMapping[data[i].id];
            itemsCollectionCut.add(new Items(currentItems));
        }
        that.collection == itemsCollectionCut.models;
    },

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

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

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

        $.ajax({
            url: '/data/check-access',
            data: {
                accessName: (App.IDS_MODIFY_ITEMS),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

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

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

    /*--------------------------------------Update/Save Model---------------------------------------------- */

    getFormValues: function () {
        var id = this.$el.find('#id').val().trim();
        id = this.removeSpecial(id);

        var description = this.$el.find('#description').val();
        description = this.removeSpecial(description);

        var type = this.$el.find('#item-type-dropdown option:selected').text();
        var typeValue = this.$el.find('#item-type-dropdown').val();
        if (typeValue == "{Literal}Create New Item Type{/Literal}")
            type = ""

        var price = this.$el.find('#secondPrice').val();
        var priceLevel2 = this.$el.find('#priceLevel2').val();
        var priceLevel3 = this.$el.find('#priceLevel3').val();
        var priceLevel4 = this.$el.find('#priceLevel4').val();
        var priceLevel5 = this.$el.find('#priceLevel5').val();
        var cost = this.$el.find('#cost').val();
        var choiceGroup =  this.$el.find('#choice-group-dropdown option:selected').val();
        var choiceGroupValue = this.$el.find('#choice-group-dropdown').val();
        if (choiceGroupValue == "None")
            choiceGroup = "";

        var altDescription =  this.$el.find('#altDescription').val();
        altDescription = this.removeSpecial(altDescription);
        var category = this.$el.find('#item-category-dropdown2 option:selected').text();
        var categoryValue = this.$el.find('#item-category-dropdown2').val();
        if (categoryValue == "{Literal}Create New Item Category{/Literal}")
            category = "";

        var menuPage = this.$el.find('#menu-page-dropdown option:selected').val();
        // var menuPageValue = this.$el.find('#menu-page-dropdown').val();
        // if (menuPageValue == "Choose Menu Page")
            // menuPage = "";

        var productLine = this.$el.find('#product-line-dropdown option:selected').val();
        
        var salesAccount = this.$el.find('#sales-account-dropdown option:selected').text();
        if(salesAccount == "{Literal}Create New Sales Account{/Literal}")
            salesAccount = "";
        var accountingCode = this.$el.find('#accountingCode').val();
        accountingCode = this.removeSpecial(accountingCode);
        var allowDiscount = this.$el.find('.allowDiscount:checked').length > 0;
        var isStock = this.$el.find('.isStock:checked').length > 0;
        var inactive = this.$el.find('.inactive:checked').length > 0;
        var scale = this.$el.find('.scale:checked').length > 0;
        var useTare = this.$el.find('.useTare:checked').length > 0;
        var serialized = this.$el.find('.serialized:checked').length > 0;
        var noPartialQuantity = this.$el.find('.noPartialQuantity:checked').length > 0;
        
        if (vatCode != 0)
            var vatCode = this.$el.find('#vat-tax-dropdown option:selected').text();
        else
            var vatCode = ""

        var quantity = this.$el.find('#quantity').val();
        var availability = this.$el.find('#availability-dropdown').val();
        var warnAvailableNumber = this.$el.find('#warnAvailableNumber').val();
        var available = this.$el.find('#available').val();
        var courseName = this.$el.find('#courseName select').val();

        if (!App.serverInfo.hasVatTax)
            var taxable = this.$el.find('.taxable:checked').length > 0;
        else
            var taxable = true;

        var detailedDescription = this.$el.find('#detialedDesc').val();
        detailedDescription = this.removeSpecial(detailedDescription);
        const file = document.querySelectorAll("#image input")[0].files[0];

        var imageUrl = "";
        if(file)
            imageUrl = file.name.substring(0, file.name.lastIndexOf('.'));
        else {
            imageUrl = document.querySelectorAll("#image img")[0].src;
            imageUrl = imageUrl.substring(imageUrl.lastIndexOf('/') + 1, imageUrl.lastIndexOf('.'));
            imageUrl = imageUrl == "logo" ? "" : imageUrl;
        }
        
        this.file =file;
        this.itemId = id;

        var updatedModel = {
            id: id,
            accountingCode: accountingCode,
            description: description,
            price: parseFloat(price),
            type: type,
            productLine: productLine,
            priceLevel1: parseFloat(price),
            priceLevel2: parseFloat(priceLevel2),
            priceLevel3: parseFloat(priceLevel3),
            priceLevel4: parseFloat(priceLevel4),
            priceLevel5: parseFloat(priceLevel5),
            cost: parseFloat(cost),
            choiceGroup: choiceGroup,
            altDescription: altDescription,
            itemCategory: category,
            menuPage: menuPage,
            salesAccount: salesAccount,
            allowDiscount: allowDiscount,
            isStock: isStock,
            inactive: inactive,
            scale: scale,
            useTare: useTare,
            serialized: serialized,
            noPartialQuantity: noPartialQuantity,
            vatCode: vatCode,
            taxable: taxable,
            onHand: quantity,
            trackAvailableOption: availability,
            available: available,
            warnAvailableNumber: warnAvailableNumber,
            itemTypeName: type,
            categoryName: category,
            category: category,
            courseName: courseName,
            itemExtended: {
                detailedDescription: detailedDescription,
                imageUrl: imageUrl
            }
        };
        this.itemsFormView.model.set(updatedModel);
    },

    validateId: function (e) {
        var validateItemId = this.$el.find("#id").val().trim();
        if (validateItemId.trim().length < 1) {
            this.$el.find("#id").addClass("invalid");
        }
        else {
            var iChars = "`~!@#$%^&*_+=[]{};,<>/?*\\";
            for (var i = 0; i < validateItemId.length; i++) {
                if (iChars.indexOf(validateItemId.charAt(i)) != -1) {
                    this.$el.find("#id").addClass("invalid");
                    break;
                }
            }
        }
    },

    validateDescription: function (e) { 
        var id = this.$el.find('#id').val();            
        var description = this.$el.find('#description').val();

        var validateDescription = this.$el.find("#description").val();
        if (validateDescription.trim().length < 1) {
            this.$el.find("#description").addClass("invalid");
        }
        else {
            var iChars = "`~!@^*_+=[]{};<>?*\\";
            for (var i = 0; i < validateDescription.length; i++) {
                if (iChars.indexOf(validateDescription.charAt(i)) != -1) {
                    this.$el.find("#description").addClass("invalid");
                    break;
                }
            }
        }
    },

    validatePrice: function () {
        var validatePrice = this.$el.find("#price").val(); 

        var price = document.getElementById('price');
        var secondPrice = document.getElementById('secondPrice');

        if (validatePrice.trim().length < 1) {
            this.$el.find("#price").addClass("invalid");
        }
        else if (validatePrice.indexOf("-") > -1 || validatePrice.indexOf('e') > -1) {
            this.$el.find("#price").addClass("invalid");
        }
        else if (validatePrice > 999999) {
            this.$el.find("#price").addClass("invalid");
        }
        else {
            secondPrice.value = price.value;
        }
    },

    validateSecondPrice: function () {
        var price = document.getElementById('price');
        var secondPrice = document.getElementById('secondPrice');

        var validateSecondPrice = this.$el.find("#secondPrice").val(); 
        if (validateSecondPrice.trim().length < 1) {
            this.$el.find("#secondPrice").addClass("invalid");
        }
        else if (validateSecondPrice.indexOf("-") > -1 || validateSecondPrice.indexOf('e') > -1) {
            this.$el.find("#secondPrice").addClass("invalid");
        }
        else if (validateSecondPrice > 999999) {
            this.$el.find("#secondPrice").addClass("invalid");
        }
        else {
            price.value = secondPrice.value;
        }
    },

    validateAltDescription: function () {
        var validateAltDescription = this.$el.find("#altDescription").val();
        var iChars = "`~!@#^*()_+=[]{};,<>?*\\";
        for (var i = 0; i < validateAltDescription.length; i++) {
            if (iChars.indexOf(validateAltDescription.charAt(i)) != -1) {
                this.$el.find("#altDescription").addClass("invalid");
                break;
            }
        }
    },

    validateForm: async function () {
        var valid = true;

        var validateDescription = this.$el.find("#description").val();
        if (validateDescription.trim().length < 1) {
            this.$el.find("#description").addClass("invalid");
            valid = false;
        }
        else {
            var iChars = "`~!@#^*_+=[]{};<>?*\\";
            for (var i = 0; i < validateDescription.length; i++) {
                if (iChars.indexOf(validateDescription.charAt(i)) != -1) {
                    this.$el.find("#description").addClass("invalid");
                    valid = false;
                    break;
                }
            }
        }

        var validateItemId = this.$el.find("#id").val().trim();
        if(this.addedItem && validateItemId != ''){
            var isItemExists =  await this.checkIfItemExists();
                
            if (validateItemId.length < 1  || isItemExists) {
                this.$el.find("#id").addClass("invalid");
                valid = false;
            }
            else {
                var iChars = "`~!@#^&*_+=[]{};,<>/?*\\";
                for (var i = 0; i < validateItemId.length; i++) {
                    if (iChars.indexOf(validateItemId.charAt(i)) != -1) {
                        this.$el.find("#id").addClass("invalid");
                        valid = false;
                        break;
                    }
                }
            }
        }
        
        if (this.advancedOptionSwitch % 2 == 0) {
            var validatePrice = this.$el.find("#price").val(); 
            if (validatePrice.trim().length < 1) {
                this.$el.find("#price").addClass("invalid");
                valid = false;
            }
            else if (validatePrice.indexOf("-") > -1 || validatePrice.indexOf('e') > -1) {
                this.$el.find("#price").addClass("invalid");
                valid = false;
            }
            else if (validatePrice > 999999) {
                this.$el.find("#price").addClass("invalid");
                valid = false;
            }
        }
        else if (this.advancedOptionSwitch % 2 != 0) {
            var validateSecondPrice = this.$el.find("#secondPrice").val(); 
            if (validateSecondPrice.trim().length < 1) {
                this.$el.find("#secondPrice").addClass("invalid");
                valid = false;
            }
            else if (validateSecondPrice.indexOf("-") > -1 || validateSecondPrice.indexOf('e') > -1) {
                this.$el.find("#secondPrice").addClass("invalid");
                valid = false;
            }
            else if (validateSecondPrice > 999999) {
                this.$el.find("#secondPrice").addClass("invalid");
                valid = false;
            }

            var validateAltDescription = this.$el.find("#altDescription").val();
            var iChars = "`~!@#^*()_+=[]{}:;,<>.?*\\\'\"";
            for (var i = 0; i < validateAltDescription.length; i++) {
                if (iChars.indexOf(validateAltDescription.charAt(i)) != -1) {
                    this.$el.find("#altDescription").addClass("invalid");
                    valid = false;
                    break;
                }
            }
            this.$el.find("#priceLevel2").val();
            var valuePriceLevel2 = document.getElementById('priceLevel2');
            var valuePriceLevel3 = document.getElementById('priceLevel3');
            var valuePriceLevel4 = document.getElementById('priceLevel4');
            var valuePriceLevel5 = document.getElementById('priceLevel5');

            if (valuePriceLevel2.value == '' || valuePriceLevel2.value < 0 || valuePriceLevel2.value > 999999) {
                valuePriceLevel2.value = 0;
            }

            if (valuePriceLevel3.value == '' || valuePriceLevel3.value < 0 || valuePriceLevel3.value > 999999) {
                valuePriceLevel3.value = 0;
            }

            if (valuePriceLevel4.value == '' || valuePriceLevel4.value < 0 || valuePriceLevel4.value > 999999) {
                valuePriceLevel4.value = 0;
            }

            if (valuePriceLevel5.value == '' || valuePriceLevel5.value < 0 || valuePriceLevel5.value > 999999) {
                valuePriceLevel5.value = 0;
            }
        }

        
        var attributeEl = document.getElementById('attribute1');
        var attributeE2 = document.getElementById('attribute2');
        var attribute1Value = attributeEl.value;
        var attribute2Value = attributeE2.value;
        if(attribute2Value != '' && attribute1Value == attribute2Value){
            attributeE2.parentElement.classList.add('invalid');
            valid = false;
        } else {
            attributeE2.parentElement.classList.remove('invalid');
        }

        return valid;
    },

    saveAddAnother: function () {
        var that = this;
        if (this.addedItem) {
            if (this.advancedOptionSwitch % 2 == 0) {
                this.$el.find('#productLine1 option:selected').text();

                if ($('#productLine1:visible').length != 0 && this.$el.find('#productLine1 option:selected').text() == "Choose Product Line") {
                    M.toast({
                        html: '{Literal}You must choose a product line{/Literal}'
                    });
                }
                else {
                    var response = this.saveItems();
                    response.finally(() => { that.addAnotherItem();})

                    // var delayInMilliseconds = 1000; //1 second
                    // setTimeout(function() {
                    //     that.addAnotherItem();
                    // }, delayInMilliseconds);
                }
            }
            else {
                var response = this.saveItems();
                response.finally(() => {that.addAnotherItem();})

                // var delayInMilliseconds = 1000; //1 second
                // setTimeout(function() {
                //     that.addAnotherItem();
                // }, delayInMilliseconds);
            }
        }
        else {
            var response = this.saveItems();
            response.finally(() => {that.addAnotherItem();})

            // var delayInMilliseconds = 1000; //1 second
            // setTimeout(function() {
            //     that.addItems();
            // }, delayInMilliseconds);
        }

    },

    getSelectedAttributes: function() {
        // var attributeNumber1 = document.getElementById('attribute1').value
        // var attributeNumber2 = document.getElementById('attribute2').value;
        
        var attributeSKUs1El = document.getElementById('attributeSKUs1');
        var attributeSKUs2El = document.getElementById('attributeSKUs2');

        var instance1 = M.FormSelect.init(attributeSKUs1El, {});
        var instance2 = M.FormSelect.init(attributeSKUs2El, {});
        var selectedAttributesSKUs1 = instance1.getSelectedValues().slice(1);
        var selectedAttributesSKUs2 = instance2.getSelectedValues().slice(1);
        
        var retObj = {
            // attributeNumber1: attributeNumber2,
            // attributeNumber2: attributeNumber2,
            attributes1: selectedAttributesSKUs1.toString(),
            attributes2: selectedAttributesSKUs2.toString()
        };

        return retObj;
    },

    saveItems: async function (){
        var items;
        var that = this;
        var validation = await this.validateForm();
        var updateCollection = that.collection;
        if (this.addedItem) {
            if (this.advancedOptionSwitch % 2 == 0) {
                var test = this.$el.find('#productLine1 option:selected').text();
                if ($('#productLine1:visible').length != 0 && test == "Choose Product Line") {
                    M.toast({
                        html: '{Literal}You must choose a product line{/Literal}'
                    });
                }
                else {
                    if(validation) {
                        this.getFormValues();
                        var productLine = this.itemsFormView.model.attributes.productLine ;
                        var attributes = this.getSelectedAttributes();
                        var sessionToken = this.getCookie();
                        return $.ajax({
                            url: '/data/save-items',
                            data: {
                                accessName: (App.IDS_MODIFY_ITEMS),
                                productLine: productLine,
                                attributes1: attributes.attributes1,
                                attributes2: attributes.attributes2,
                                item: JSON.stringify(that.itemsFormView.model.toJSON()),
                                token: sessionToken
                            },
                            dataType: 'json',
                            type: 'POST',
                
                            success: function (data) {
                                that.appendItem = true;
                                that.itemsFormView.model.attributes.id = data.lastSavedItem.id;
                                that.collection.add(that.itemsFormView.model);
                                // that.fullCollection.add(that.itemsFormView.model);
                                that.formModal.modal('close');
                                
                                M.toast({ html: '{Literal}Item updated successfully{/Literal}' });
                                that.isCreateMode = false;
                                that.uploadFile();
                            },
                
                            error: function (e) {
                                if (e.status == 523) {
                                    window.location.href = "#/log-in";
                                    location.reload();
                                }
                                else {
                                    M.toast({ html: '{Literal}There was a problem saving this item{/Literal}' });
                                }
                            }
                        });
                    }
                }
            }
            else {
                if(validation) {
                    this.getFormValues();
                    var productLine = this.itemsFormView.model.attributes.productLine ;
                    var attribute1 = document.getElementById('attribute1').value;
                    var attribute2 = document.getElementById('attribute2').value;
                    var sessionToken = this.getCookie();
                    return $.ajax({
                        url: '/data/save-items',
                        data: {
                            accessName: (App.IDS_MODIFY_ITEMS),
                            productLine: productLine,
                            attribute1: attribute1,
                            attribute2: attribute2,
                            item: JSON.stringify(that.itemsFormView.model.toJSON()),
                            token: sessionToken
                        },
                        dataType: 'json',
                        type: 'POST',
            
                        success: function (data) {
                            that.appendItem = true;
                            that.itemsFormView.model.attributes.id = data.lastSavedItem.id;
                            that.collection.add(that.itemsFormView.model);
                            // that.fullCollection.add(that.itemsFormView.model);
                            that.formModal.modal('close');
                            M.toast({ html: '{Literal}Item updated successfully{/Literal}' });
                            that.isCreateMode = false;
                            that.uploadFile();
                        },
            
                        error: function (e) {
                            if (e.status == 523) {
                                window.location.href = "#/log-in";
                                location.reload();
                            }
                            else {
                                M.toast({ html: '{Literal}There was a problem saving this item{/Literal}' });
                            }
                        }
                    }); 
                }
            }
        }
        else {
            if(validation) {
                this.getFormValues();
                var productLine = this.itemsFormView.model.attributes.productLine ;
                var attribute1 = document.getElementById('attribute1').value
                var attribute2 = document.getElementById('attribute2').value;
                var sessionToken = this.getCookie();
                var updateCollection = that.collection;
                // var updateFullCollection = that.fullCollection;
                return $.ajax({
                    url: '/data/save-items',
                    data: {
                        accessName: (App.IDS_MODIFY_ITEMS),
                        productLine: productLine,
                        attribute1: attribute1,
                        attribute2: attribute2,
                        item: JSON.stringify(that.itemsFormView.model.toJSON()),
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',
        
                    success: function (data) {
                        updateCollection.add(that.itemsFormView.model);
                        //updateFullCollection.add(that.itemsFormView.model);
                        that.formModal.modal('close');
                        that.isNewSearch = false;
                        that.pullItems();
                        M.toast({ html: '{Literal}Item updated successfully{/Literal}' });
                        that.isCreateMode = false;
                        that.uploadFile();
                    },
        
                    error: function (e) {
                        if (e.status == 523) {
                            window.location.href = "#/log-in";
                            location.reload();
                        }
                        else {
                            M.toast({ html: '{Literal}There was a problem saving this item{/Literal}' });
                        }
                    }
                });

                // var id = that.itemsFormView.model.attributes.id.trim();

                // var descriptionHTML = document.getElementById(id + 'Description');
                // descriptionHTML.innerHTML = that.itemsFormView.model.attributes.description;

                // var typeHTML = document.getElementById(id + 'Type');
                // typeHTML.innerHTML = "{Literal}Type: {/Literal}" + that.itemsFormView.model.attributes.type;

                // var priceHTML = document.getElementById(id + 'Price');
                // priceHTML.innerHTML = "{Literal}Price: {/Literal}" + that.itemsFormView.model.attributes.priceLevel1;

                // var allowDiscountHTML = document.getElementById(id + 'AllowDiscount');
                // allowDiscountHTML.innerHTML = "{Literal}Allow Discount: {/Literal}" + that.itemsFormView.model.attributes.allowDiscount;

                // var price2HTML = document.getElementById(id + 'Price2');
                // price2HTML.innerHTML = "{Literal}Price Level 2: {/Literal}" + that.itemsFormView.model.attributes.priceLevel2;

                // var price3HTML = document.getElementById(id + 'Price3');
                // price3HTML.innerHTML = "{Literal}Price Level 3: {/Literal}" + that.itemsFormView.model.attributes.priceLevel3;

                // var price4HTML = document.getElementById(id + 'Price4');
                // price4HTML.innerHTML = "{Literal}Price Level 4: {/Literal}" + that.itemsFormView.model.attributes.priceLevel4;

                // var price5HTML = document.getElementById(id + 'Price5');
                // price5HTML.innerHTML = "{Literal}Price Level 5: {/Literal}" + that.itemsFormView.model.attributes.priceLevel5;

                // var isStockHTML = document.getElementById(id + 'IsStock');
                // isStockHTML.innerHTML = "{Literal}Track Stock: {/Literal}" + that.itemsFormView.model.attributes.isStock;

                // var scaleHTML = document.getElementById(id + 'Scale');
                // scaleHTML.innerHTML = "{Literal}Scalable: {/Literal}" + that.itemsFormView.model.attributes.scale;

                // var noPartialQuantityHTML = document.getElementById(id + 'NoPartialQuantity');
                // noPartialQuantityHTML.innerHTML = "{Literal}No Partial Quantity: {/Literal}" + that.itemsFormView.model.attributes.noPartialQuantity;

                // var serializedHTML = document.getElementById(id + 'Serialized');
                // serializedHTML.innerHTML = "{Literal}Serialized: {/Literal}" + that.itemsFormView.model.attributes.serialized;

                // var taxableHTML = document.getElementById(id + 'Taxable');
                // taxableHTML.innerHTML = "{Literal}Taxable: {/Literal}" + that.itemsFormView.model.attributes.taxable;

                // var categoryHTML = document.getElementById(id + 'Category');
                // categoryHTML.innerHTML = "{Literal}Category: {/Literal}" + that.itemsFormView.model.attributes.category;
            }
            else {
                M.toast({ html: '{Literal}Some of the required fields are missing or invalid{/Literal}' });
            }
           // this.render();
        }
    },

    /*--------------------------------------Delete Modals---------------------------------------------- */

    chooseNewCategory: function () {
        var itemCategory = this.$el.find('#itemCategoryName').val();
        that = this;
        var isTaken = false;

        if (itemCategory != '' && itemCategory != undefined && itemCategory != null) {
            for (var i in that.category) {
                if (that.category[i].name === itemCategory) {
                    isTaken = true;
                    break;
                }
            }

            if (isTaken) {
                M.toast({ html: '{Literal}This Item Category is already defined{/Literal}' });
            }
            else {
                that.category.push({id: that.category.length, name: itemCategory});
                this.itemsFormView.model.attributes.category = this.$el.find('#itemCategoryName').val();
                this.reopenModal();
            }
        }
        else {
            M.toast({ html: '{Literal}Please enter a valid Item Category name{/Literal}' });
        }
    },

    chooseNewItemType: function () {
        var itemType = this.$el.find('#itemTypeName').val().trim();
        that = this;
        var isTaken = false;
        if (itemType != '' && itemType != undefined && itemType != null) {
                 
            for (var i in that.itemTypes) {
                if (that.itemTypes[i].name === itemType) {
                    isTaken = true;
                    break;
                }
            }

            if (isTaken) {
                M.toast({ html: '{Literal}This Item Type is already defined{/Literal}' });
            }
            else {
                that.itemTypes.push({id: that.itemTypes.length, name: itemType});
                this.itemsFormView.model.attributes.type = itemType;
                this.reopenModal();
            }
        }
        else {
            M.toast({ html: '{Literal}Please enter a valid Item Type name{/Literal}' });
        }
    },
    chooseNewSalesAccount: function () {
        var salesAccount = this.$el.find('#itemSalesAccountNew').val().trim();
        that = this;
        if (salesAccount != '' && salesAccount != undefined && salesAccount != null) {
            that.salesAccounts.push(salesAccount);
            this.itemsFormView.model.attributes.salesAccounts = salesAccount;
            this.reopenModal();
        }
        else {
            M.toast({ html: '{Literal}Please enter a valid Sales Account{/Literal}' });
        }
    },

    reopenModal: function () {       
        var id = this.itemsFormView.model.attributes.id;
        var items = this.collection.get(id);
        if (this.advancedOptionSwitch % 2 != 0) {
            this.itemsFormView.model.attributes.id = this.$el.find('#id').val();            
            this.itemsFormView.model.attributes.description = this.$el.find('#description').val();
            this.itemsFormView.model.attributes.vatCode = this.$el.find('#vat-tax-dropdown option:selected').text();
            this.itemsFormView.model.attributes.altDescription = this.$el.find('#altDescription').val();
            if (this.$el.find('#secondPrice').val() != "") {
                this.itemsFormView.model.attributes.priceLevel1 = this.$el.find('#secondPrice').val();
            }
            else {
                this.itemsFormView.model.attributes.priceLevel1 = this.$el.find('#price').val();
            }
            
            this.itemsFormView.model.attributes.priceLevel2 = this.$el.find('#priceLevel2').val();
            this.itemsFormView.model.attributes.priceLevel3 = this.$el.find('#priceLevel3').val();
            this.itemsFormView.model.attributes.priceLevel4 = this.$el.find('#priceLevel4').val();
            this.itemsFormView.model.attributes.priceLevel5 = this.$el.find('#priceLevel5').val();
            this.itemsFormView.model.attributes.cost = this.$el.find('#cost').val();

            // if (this.$el.find('#item-category-dropdown2 option:selected').text() == "Create New Item Category") {
                // this.itemsFormView.model.attributes.category = this.$el.find('#itemCategoryName').val();
            // }
            // else {
                // this.itemsFormView.model.attributes.category = this.$el.find('#item-category-dropdown2 option:selected').text();
            // }
        }
        else {
            this.itemsFormView.model.attributes.id = this.$el.find('#id').val();
            this.itemsFormView.model.attributes.description = this.$el.find('#description').val();
            if (this.$el.find('#secondPrice').val() != "") {
                this.itemsFormView.model.attributes.priceLevel1 = this.$el.find('#secondPrice').val();
            }
            else {
                this.itemsFormView.model.attributes.priceLevel1 = this.$el.find('#price').val();
            }
            // if (this.$el.find('#item-category-dropdown2 option:selected').text() == "Create New Item Category") {
                // this.itemsFormView.model.attributes.category = this.$el.find('#itemCategoryName').val();
            // }
            // else {
                // this.itemsFormView.model.attributes.category = this.$el.find('#item-category-dropdown2 option:selected').text();
            // }
        }
        

        if (this.$el.find('#item-type-dropdown option:selected').val() == "Create New Item Type") {
            this.itemsFormView.model.attributes.type = this.$el.find('#itemTypeName').val();
        }
        else {
            this.itemsFormView.model.attributes.type = this.$el.find('#item-type-dropdown option:selected').text();
        }

        this.itemsFormView.model.attributes.menuPage = this.$el.find('#menu-page-dropdown option:selected').val();

        if (this.collection.get(id) !== null && this.collection.get(id) !== '' && this.collection.get(id) != undefined) {
            this.itemsFormView = new ItemsFormView({
                template: this.itemsFormTemplate,
                model: this.itemsFormView.model,
                itemTypes: this.itemTypes,
                choiceGroups: this.choiceGroups,
                category: this.category,
                menuPages: this.menuPages,
                menuKeySets: this.menuKeySets,
                salesAccounts: this.salesAccounts,
                productLine: this.productLine,
                vatCode: this.vatCode,
                advancedOptionSwitch: this.advancedOptionSwitch,
                courses: this.courses,
                itemAttributes: this.itemAttributes
            });
            $('#items-form-modal').modal().modal('close'); 
            this.$el.find('#items-form-modal').html(this.itemsFormView.render().el);
            this.$el.find('select').formSelect();
            this.formModal = this.$el.find('#items-form-modal').modal('open');
            // this.formModal.modal('open');
        }
        else {
            var items = new Items();
            this.itemsFormView = new ItemsFormView({
                template: this.itemsFormTemplate,
                model: this.itemsFormView.model,
                itemTypes: this.itemTypes,
                choiceGroups: this.choiceGroups,
                category: this.category,
                menuPages: this.menuPages,
                menuKeySets: this.menuKeySets,
                salesAccounts: this.salesAccounts,
                productLine: this.productLine,
                vatCode: this.vatCode,
                advancedOptionSwitch: this.advancedOptionSwitch,
                courses: this.courses,
                itemAttributes: this.itemAttributes
            });
            $('#items-form-modal').modal().modal('close'); 
            this.$el.find('#items-form-modal').html(this.itemsFormView.render().el);
            this.$el.find('select').formSelect();
            this.$el.find("select[required]").css({
                display: "block", 
                position: 'absolute',
                visibility: 'hidden'
            });  
            this.formModal = this.$el.find('#items-form-modal').modal('open');
            // this.formModal.modal('open');
        }
    },

    chooseProductLine: function () {
        var productLineId = this.$el.find('#productLine1 option:selected').val();
        var that = this;
        if (productLineId != '{Literal}None{/Literal}') {
            var productLineValue = {};
            for (var i = 0; i < this.productLine.length; i++) {
                if (this.productLine[i].id == productLineId) {
                    productLineValue = (this.productLine[i]);
                    var id = this.$el.find('#id').val();
                    var description = this.$el.find('#description').val();
                    var price = this.$el.find('#price').val();

                    this.itemsFormView.model.attributes.id = this.$el.find('#id').val();            
                    this.itemsFormView.model.attributes.description = this.$el.find('#description').val();
                    this.itemsFormView.model.attributes.vatCode = productLineValue['vatCode'];
                    this.itemsFormView.model.attributes.altDescription = this.$el.find('#altDescription').val();
                    this.itemsFormView.model.attributes.priceLevel1 = this.$el.find('#price').val();
                    this.itemsFormView.model.attributes.priceLevel2 = this.$el.find('#priceLevel2').val();
                    this.itemsFormView.model.attributes.priceLevel3 = this.$el.find('#priceLevel3').val();
                    this.itemsFormView.model.attributes.priceLevel4 = this.$el.find('#priceLevel4').val();
                    this.itemsFormView.model.attributes.priceLevel5 = this.$el.find('#priceLevel5').val();
                    this.itemsFormView.model.attributes.cost = this.$el.find('#cost').val();
                    this.itemsFormView.model.attributes.category = productLineValue['category'];
                    this.category.push({id: that.category.length, name: productLineValue['category']});

                    this.itemsFormView.model.attributes.menuPage = productLineValue['menuKeyPage'];
                    this.itemsFormView.model.attributes.menuKeySet = productLineValue['keysetName'];

                    this.itemsFormView.model.attributes.inactive = this.$el.find('.inactive:checked').length > 0
                    this.itemsFormView.model.attributes.productLine  = productLineId;
                    this.itemsFormView.model.attributes.type = productLineValue['type'];
                    this.itemsFormView.model.attributes.choiceGroup = productLineValue['choiceGroup'];
                    this.itemsFormView.model.attributes.salesAccount = productLineValue['salesAccount'];
                    this.itemsFormView.model.attributes.allowDiscount = productLineValue['allowDiscount'];
                    this.itemsFormView.model.attributes.isStock = productLineValue['isStock'];
                    this.itemsFormView.model.attributes.scale = productLineValue['scale'];
                    this.itemsFormView.model.attributes.serialized = productLineValue['serialized'];
                    this.itemsFormView.model.attributes.taxable = productLineValue['taxable'];
                    this.itemsFormView.model.attributes.noPartialQuantity = productLineValue['noPartialQuantity'];
                    this.itemsFormView.model.attributes.vatCode = productLineValue['vatCode'];
                    this.itemsFormView.model.attributes.attribute1 = productLineValue['attribute1'];
                    this.itemsFormView.model.attributes.attribute2 = productLineValue['attribute2'];

                    if(!this.menuPages.includes(productLineValue['menuKeyPage']))
                        this.menuPages.push(productLineValue['menuKeyPage']);

                    this.itemsFormView = new ItemsFormView({
                        template: this.itemsFormTemplate,
                        model: this.itemsFormView.model,
                        itemTypes: this.itemTypes,
                        choiceGroups: this.choiceGroups,
                        category: this.category,
                        menuPages: this.menuPages,
                        menuKeySets: this.menuKeySets,
                        salesAccounts: this.salesAccounts,
                        productLine: this.productLine,
                        vatCode: this.vatCode,
                        advancedOptionSwitch: this.advancedOptionSwitch, 
                        isCreateMode: this.isCreateMode,
                        courses: this.courses,
                        itemAttributes: this.itemAttributes
                    });

                    $('#items-form-modal').modal().modal('close'); 
                    this.$el.find('#items-form-modal').html(this.itemsFormView.render().el);
                    this.$el.find('select').formSelect();
                    this.$el.find("select[required]").css({
                        display: "block", 
                        position: 'absolute',
                        visibility: 'hidden'
                    });  
                    this.formModal = this.$el.find('#items-form-modal').modal('open');
                    // this.formModal.modal('open');
                    break;
                }
            }
        }
    },

    fillDescription: function() {
        var id = this.$el.find('#id').val();            
        var description = this.$el.find('#description').val();

        if (id != "" && description == "") {
            var descriptionValue = document.getElementById("description");
            descriptionValue.value = id;
            descriptionValue.select();
        }
    },

    checkIfItemExists: async function () {
        var id = this.$el.find('#id').val(); 
        var sessionToken = this.getCookie();

        return await $.ajax({
            url: '/data/check-if-item-exists',
            data: {
                id: id,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: data => {
                var isItemExists = data;
                if(isItemExists)
                    M.toast({ html: '{Literal}An Item with this ID already exists{/Literal}' });
            },

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

    fillInDescription: function() {
        var id = this.$el.find('#id').val();            
        var description = this.$el.find('#description').val();

        if (id != "" && description == "") {
            var descriptionValue = document.getElementById("description");
            descriptionValue.value = id;
            descriptionValue.select();
        }
    },

    uploadFile: function() {
        // const file = document.querySelectorAll("#image input")[0]?.files[0];
        if(!this.file)
            return;

        var sessionToken = this.getCookie();
        var data = new FormData();
        data.append('token', sessionToken);
        data.append('itemCode', this.itemId);
        data.append('fileSize:' + this.file.size, this.file);

        $.ajax({
            url: '/data/upload-item-image',
            data: data,
            contentType: false,
            processData: false,
            type: 'POST',

            success: data => {
                if(!data.success)
                    M.toast({ html: '{Literal}Error: Image not saved{/Literal}' });
                else {
                    M.toast({ html: '{Literal}Image saved{/Literal}' });
                      this.$el.find("#image img").remove();
                    //   this.$el.find("#image").append('<img src="/Images/' + items.itemExtended.imageUrl +'.png" alt="{Literal}no image{/Literal}">');
                }
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },
    getGlAccounts: async function () {
        var that = this;
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/get-gl-accounts",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if(data.success){
                    that.salesAccounts = data.glAccounts.salesAccountList;
                    that.salesAccounts = that.salesAccounts.sort( (a,b) => a > b ? 1 : -1);
                    that.renderSalesAccounts(that.salesAccounts); 
                }
                else
                    M.toast({ html: "{Literal}There was a problem fetching data from the server{/Literal}"});
            },
            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}"});
                }
            },
        });
    },

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

    fillAttributeCodes: function(e) {
        if(e.currentTarget.id == 'attribute1')
            var attributeCodesSelect = document.getElementById('attributeSKUs1');
        else if(e.currentTarget.id == 'attribute2')
            var attributeCodesSelect = document.getElementById('attributeSKUs2');

        var selectedAttributeNumber = e.currentTarget.value;
        var selectedItemAttributes = App.itemsView.itemAttributes[selectedAttributeNumber];
        var options = '<option selected disabled>{Literal}Select Options{/Literal}</option>';
        selectedItemAttributes.forEach( a => {
            options += `<option selected value="${a.skuComponent}">${a.skuComponent} | ${a.descriptionComponent}</option>`
        });

        attributeCodesSelect.innerHTML = options;
        $('select').formSelect();
        App.itemsView.validateForm();
    },

    toggleSelectionMode: function() {
        this.selectionMode.active = !this.selectionMode.active;
        var itemElList = document.querySelectorAll('.item-checkbox');
        itemElList.forEach( el => {
            if(this.selectionMode.active)
                el.classList.remove('hide');
            else {
                el.classList.add('hide');
                this.selectionMode.selectedItemsList = [];
                el.querySelector('input').checked = false;
            }
        });
    },

    showEdiButton: function() {
        document.getElementById('editButton').classList.remove('hide');
    },
    hideEdiButton: function() {
        document.getElementById('editButton').classList.add('hide');
    },

    selectAll: function(event) {
        var checkboxElList = document.querySelectorAll('.item-checkbox input');
        checkboxElList.forEach( el => {
            el.checked = true;
            const itemDetails = {id: el.dataset.id, description: el.dataset.description}
            this.selectionMode.selectedItemsList.push(itemDetails);
        });
    },

    onFloatingButtonsEmptySpaceClick: function(e) {
        if(e.target.nodeName == 'UL') {
            this.toggleSelectionMode();
        }
    },

    openBulkEditItemsModal: function() {
        var that = this;
        var selectedItemsTable = document.querySelector('#selectedItemsList tbody');
        var html = '';
        this.selectionMode.selectedItemsList.forEach( selectedItem => {
            html += `<tr><td>${selectedItem.id}</td><td>${selectedItem.description}</td></tr>`;
        })

        selectedItemsTable.innerHTML = html;

        var modalEl = document.getElementById('items-bulk-edit-form-modal');
        var instance = M.Modal.init(modalEl, 
            {onCloseEnd: function () { that.toggleSelectionMode();} });
        instance.open();
    },

    getBulkEditValues: function() {
        var price1 = document.getElementById('price1').value;
        var price2 = document.getElementById('price2').value;
        var price3 = document.getElementById('price3').value;
        var price4 = document.getElementById('price4').value;
        var price5 = document.getElementById('price5').value;

        return {price: price1, priceLevel1: price1, priceLevel2: price2, priceLevel3: price3, priceLevel4: price4, priceLevel5: price5 }
    },

    bulkUpdateItems: function() {
        var that = this;
        var itemData = this.getBulkEditValues();
        var selectedItemCodes = this.selectionMode.selectedItemsList.map( x=> {return x.id});
        $.ajax({
            url: '/data/bulk-update-items',
            data: {
                token: getCookie(),
                updateData: JSON.stringify({ itemData: itemData, selectedItemCodes: selectedItemCodes}),
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                if(data.success){   
                    M.toast({ html: '{Literal}Items updated{/Literal}' });
                    that.selectionMode.selectedItemsList = [];
                    selectionMode.active = false;
                }
                else
                    M.toast({ html: '{Literal}There was a problem updating items{/Literal}' });

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

    removeSpecial: function(text) {
        var newText = text.replaceAll('\"', "&quot;");
        newText = newText.replaceAll('\'', "&apos;");
        return newText;
    }

});
