var PosKeysMobileView = Backbone.View.extend({
    that: this,
    breadcrumb: {},
    occupiedCells: {},
    chosenKey: {},
    chosenKeyId: '',
    currentKeySet: '',
    currentPage: '',
    currentPageColor: '',
    itemsStyleMapping: {},
    itemMapping: {},
    saleDiscounts: [],
    newPage: '',
    keysObject: {},
    pagesObject: {},
    addedKey: {},
    itemTypeList: [],
    itemCategoryList: [],

    pages: [],
    keySet: [],

    currentDraggedOver: null,

    events: {
        'keyup #itemSearch': 'searchItemBySearchTerm',

        'mouseup .grid-stack-item-content': 'showMenu',
        'mouseup .ui-resizable-handle': 'showMenu',
        'click .edit-modal-trigger': 'openEditModal',
        'click .delete-modal-trigger': 'openDeleteModal',
        'click .delete-modal-trigger-direct': 'openDeleteModalDirect',
        'click #deleteKey': 'deleteKey',
        'contextmenu .grid-stack' : 'preventDefault',
        'click .addKeyButton' : 'createNew',

        'click #itemCard' : 'showItems',
        'click #pageCard, #subPageCard' : 'showPages',
        'click #labelCard' : 'showLabelPage',
        'click #priceLevelCard' : 'showPriceLevel',
        'click #changeKeySetCard' : 'showKeySetPage',
        'click #tareCard' : 'showTare',
        'click #saleDiscountCard' : 'showSaleDiscount',
        'click #upchargeCard' : 'showSaleUpcharge',
        'click #itemDiscountCard' : 'showItemDiscount',
        'click #saleDiscountCard2' : 'showSaleDiscount2',

        'change #page-selector' : 'changePage',
        'change #key-set-selector' : 'changeKeySet',

        'click #editPageName': 'openEditNameModal',
        'click #addKeySetButton': 'openAddKeySetModal',
        'click .save-menu-page-button' : 'saveNewMenuPage',
        'click #addPageButton' : 'addNewPage',
        'click #addPageByItemTypeButton, #itemTypeCard' : 'addNewPageByItemType',
        'click .save-new-page-button' : 'saveNewPage',
        'click .save-new-page-by-item-type-button' : 'addMenuKeysByItemType',
        'click .save-page-name-button' : 'savePageName',
        'click .save-key-button' : 'saveEditedKey',
        'click .save-keys-button' : 'saveKeys',
        'click .save-key-set-button1': 'addKeySet',
        //'click .delete-page-trigger': 'openDeletePageModal',
        //'click #delete-page-button': 'deletePage',

        'click .pagesCards, .subPagesCards' : 'choosePageCard',
        'click .save-label-button' : 'choosePageLabel',
        'click .save-tare-button' : 'chooseTareLabel',
        'click .save-sale-reprice-button' : 'chooseRepriceLabel',
        'click .save-price-level-button' : 'choosePriceLevel',
        'click .save-key-set-button' : 'chooseKeysetCards',
        'click .save-item-button' : 'chooseItemCard',
        'click .save-item-discount-button' : 'chooseItemDiscount',
        'click .save-sale-discount-button' : 'chooseSaleDiscount',
        'click .save-sale-upcharge-button' : 'chooseUpchargeLabel',

        'click .cancel-key-set-button1' : 'closeNewModals',
        'click .cancel-new-page-button' : 'closeNewModals',
        'click .cancel-items-button' : 'closeNewModals',
        'click .cancel-pages-button' : 'closeNewModals',
        'click .cancel-label-button' : 'closeNewModals',
        'click .cancel-price-level-button' : 'closeNewModals',
        'click .cancel-key-set-button' : 'closeNewModals',
        'click .cancel-tare-button' : 'closeNewModals',
        'click .cancel-item-discount-button' : 'closeNewModals',
        'click .cancel-sale-reprice-button' : 'closeNewModals',
        'click .card-panel-entity': 'highlightCard',
        // 'click .edit': 'openEditModal',
        'change #columnsView': 'updateColumnsSize',
        'click .page-type.page-key-card, .sub-page-type.page-key-card': 'loadPageOnPageKeyClick',
        'change input[name="typeCategoryGroup"]': 'typeCategoryGroupSelect'

    },

    dataChangedAndNotSaved: false,

    initialize: async function (options) {
        this.options = options;
        this.template = _.template(options.template);
        await this.getItemTypeList();
        await this.getItemCategoryList();
        this.breadcrumb = options.breadcrumb;
        this.posKeyFormTemplate = options.posKeyFormTemplate;
        this.model = options.model;
        await this.getMenuKeys();
        this.changeKeySet();
        // await this.getItemKeys();
        // await this.getKeySet();

    },

    updateColumnsSize: function() {
        var size = document.getElementById('columnsView').value;
        var menuKeyCardsList = document.querySelectorAll('.menu-key-card');
        menuKeyCardsList.forEach( el => {
            el.style.width = ((100 / size) - 1) + '%';
        } );

        var elems = document.querySelectorAll('.menukey-label-img');
        if(size == 3)
            elems.forEach( el => el.classList.remove('hide'));
        else
            elems.forEach( el => el.classList.add('hide'));


        elems = document.querySelectorAll('.edit-delete .delete-modal-trigger');
        if(size < 5)
            elems.forEach( el => el.classList.remove('hide'));
        else
            elems.forEach( el => el.classList.add('hide'));


    },

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

    render: function () {
        this.gridInit = true;
        
        var that = this;
        $('select').formSelect();
        var sessionToken = this.getCookie();

        if (that.newPage != '') {
            
            $("#page-selector").val(that.newPage);
            $("#page-selector option[value=" + that.newPage + "]").attr('selected', 'selected');
            // $("#page-selector").change();
        }

        $(document).ready(function () {
            that.$el.html(that.template({
                items: that.items,
                keySet: that.keySet,
                pages: that.pages,
                currentPage: that.currentPage,
                currentPageColor: that.currentPageColor,
                currentKeyset: that.currentKeyset,
                itemTypeList: that.itemTypeList,
                itemCategoryList: that.itemCategoryList
            }));
            // that.initItems(); 
            $('.tooltipped').tooltip();
            $('select').formSelect();
            $('.fixed-action-btn').floatingActionButton();

            $(document.body).click(function (e) {
                var target = e.target;
                //that.$el.find('.floating-menu').hide();
                if (!$(target).hasClass('grid-stack-item-content')) {
                    that.$el.find('.floating-menu').hide();
                }
            });
            

            $('select').formSelect();
            that.editModal = that.$el.find('#pos-key-edit-modal').modal();
            that.deleteModal = that.$el.find('#pos-key-delete-modal').modal();

            const draggableElements = document.querySelectorAll('.draggable');
            draggableElements.forEach(element => {
                element.setAttribute('draggable', 'true');
                element.addEventListener('dragstart', that.handleDragStart);
                element.addEventListener('dragover', that.handleDragOver);
                element.addEventListener('dragenter', that.handleDragEnter);
                element.addEventListener('dragleave', that.handleDragLeave);
                element.addEventListener('dragend', that.handleDragEnd);
                element.addEventListener('drop', that.handleDrop);
                
                element.addEventListener('touchstart', (e) => { that.handleTouchDragStart(e, that)});
                element.addEventListener('touchmove', (e) => { that.handleTouchDragMove(e,that)});
                element.addEventListener('touchend', (e) => { that.handleTouchDragEnd(e, that) });

            });
            
            that.renderItems();
    
        });
        App.breadCrumbToolTip = "Create, manage, and edit your POS Menu Keys"
        App.setBreadcrumbs(this.breadcrumb);
        
        return this;
    },

    
    handleDragEnd: function (e) {
        this.style.opacity = '1';
        const draggableElements = document.querySelectorAll('.draggable');
        draggableElements.forEach(element => {
            element.classList.remove('dragged-over');
        });
    },
    
    handleDragOver: function (e) {
        e.preventDefault();

        // var el = e.target.closest('.menu-key-card');
        // el.classList.add('dragged-over');
        return false;
    },
    
    handleDragEnter: function(e) {
        var el = e.target.closest(currentDraggedClass + '.draggable');
        if(el)
            el.classList.add('dragged-over');
        // this.currentDraggedOver = el;
    },
    
    handleDragLeave: function(e) {
        if (e.currentTarget.contains(e.relatedTarget))
            return;
        var el = e.target.closest(currentDraggedClass + '.draggable');
        if(el)
            el.classList.remove('dragged-over');
    },

    currentDraggedClass: '',

    handleDragStart: function (e) {
        if(this.classList.contains('menu-type'))
            currentDraggedClass = '.menu-type';
        else if(this.classList.contains('page-type'))
            currentDraggedClass = '.page-type';
        else if(this.classList.contains('sub-page-type'))
            currentDraggedClass = '.sub-page-type';
        this.style.opacity = '0.4';
      
        dragSrcEl = this;
      
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', this.innerHTML);
    },
      
    handleDrop: function (e) {
        e.stopPropagation(); // Stops some browsers from redirecting.
        e.preventDefault();

        var currentClassName = currentDraggedClass.replace('.', '');
        if (dragSrcEl !== this && this.classList.contains(currentClassName)) {
            dragSrcEl.innerHTML = this.innerHTML;
            this.innerHTML = e.dataTransfer.getData('text/html');
        }
        
        return false;

    },

    draggedItemCopy: null,
    // elementUnderTouch: null,
    currentDropTarget: null,
    draggedItem: null,

    handleTouchDragStart: function(e, that) {
        var el = e.currentTarget;
        if(el.classList.contains('menu-type'))
            that.currentDraggedClass = '.menu-type';
        else if(el.classList.contains('page-type'))
            that.currentDraggedClass = '.page-type';
        else if(el.classList.contains('sub-page-type'))
            that.currentDraggedClass = '.sub-page-type';
        const touchLocation = e.targetTouches[0];

        that.draggedItemCopy = document.createElement('div');
        that.draggedItem = e.target.closest(that.currentDraggedClass + '.draggable');
        that.draggedItem.style.opacity = '0.4';
        that.draggedItemCopy.innerHTML = that.draggedItem.innerHTML;
        that.draggedItemCopy.id = 'dragged';
        that.draggedItemCopy.classList.add('menu-key-card');
        that.draggedItemCopy.style.opacity = '0.4';
        that.draggedItemCopy.style.width = '10%';
        that.draggedItemCopy.style.zIndex = 999;
        that.draggedItemCopy.style.left = `${touchLocation.pageX}px`;
        that.draggedItemCopy.style.top = `${touchLocation.pageY}px`;
        that.currentDropTarget = that.draggedItemCopy;
        that.draggedItemCopy.style.position = 'absolute';
        // document.getElementById('menu-keys').insertAdjacentElement('beforeend', draggedItemCopy);
    },

    isDraggedItemInserted: false,

    handleTouchDragMove: function(e, that) {
        e.preventDefault();
        if(!that.isDraggedItemInserted){
            document.getElementById('menu-keys').insertAdjacentElement('beforeend', that.draggedItemCopy);
            that.isDraggedItemInserted = true;
        }
        const touchLocation = e.targetTouches[0];
        that.draggedItemCopy.style.left = `${touchLocation.pageX}px`;
        that.draggedItemCopy.style.top = `${touchLocation.pageY}px`;

        //     var wrapper = document.getElementById('menu-keys');
        // draggedItemCopy.style.top = `${touchLocation.pageY - (draggedItemCopy.offsetWidth )}px`;
        // draggedItemCopy.style.left = `${touchLocation.pageX - (wrapper.offsetLeft) - (draggedItemCopy.offsetHeight / 2)}px`;
        // draggedItemCopy.style.width = `${16}%`;

        const elements = document.elementsFromPoint(touchLocation.clientX, touchLocation.clientY);
        if(elements.length > 1)
            var elementUnderTouch = elements[1].closest(that.currentDraggedClass + '.draggable');
        else
            return;

        // elementUnderTouch = elementUnderTouch.closest('.menu-key-card');

        if (elementUnderTouch && elementUnderTouch !== that.draggedItemCopy) {
            if (that.currentDropTarget !== elementUnderTouch) {
                if (that.currentDropTarget) {
                    that.currentDropTarget.classList.remove('dragged-over');
                }
                that.currentDropTarget = elementUnderTouch;
                that.currentDropTarget.classList.add('dragged-over');
            }
        }
    },

    handleTouchDragEnd: function(e, that) {
        that.currentDropTarget.classList.remove('dragged-over');
        
        var dropTarget = document.elementFromPoint(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
        dropTarget = dropTarget.closest(that.currentDraggedClass + '.draggable');
        if (dropTarget && dropTarget.classList.contains('draggable')) {
            const dropTargetCopy = dropTarget.innerHTML;
            dropTarget.innerHTML = that.draggedItem.innerHTML;
            dropTarget.id = ''
            that.draggedItem.innerHTML = dropTargetCopy;
        }
        
        that.draggedItem.style.opacity = '1';
        var draggedEl = document.getElementById('dragged');
        if(draggedEl)
            draggedEl.remove();
        that.isDraggedItemInserted = false;
    },

    showItems: function () {
        var itemFormModal = this.$el.find('#item-form-modal').modal();
        itemFormModal.modal('open');
    },

    getCurrentKeySet: function() {
        var keySet = this.$el.find('#key-set-selector option:selected').text();
        if (keySet == "MAIN" || keySet == "ראשי" || keySet === undefined) {
            keySet = "";
        }

        return keySet;
    },

    showPages: function (e) {
        console.log(e.currentTarget);
        var that = this;
        var pageModal = this.$el.find('#page-form-modal').modal();
        var keySet = this.getCurrentKeySet();
        
        var pageSelector = that.$el.find('#pagesFormModalBoxes');
        $(pageSelector).html("");
        if (that.pagesObject[keySet] == undefined) {
            that.pagesObject[keySet] = ["MAIN"]
        }

        var className = 'pagesCards';
        if(e.currentTarget.id == 'subPageCard')
            className = 'subPagesCards';

        for (var i = 0; i < that.pagesObject[keySet].length; i++) {
            var pageName =  that.pagesObject[keySet][i];
            var html = ""
            html += '<div class="' + className + '" description-id="' +  pageName + '">'
            html += '<div class="col s12 m4 xl4"><div class="card-panel card-panel-entity z-depth-1 sequence-card hoverable white-text waves-effect waves-light " style="background-color: #3970b7" data-id="' + pageName + '" data-selected="0" > '
            html += '<div class="row description truncate" style="position: relative; right: 13px; bottom: 8px; height: 48px; ">'
            html += '&nbsp;&nbsp;' + pageName
            html += '</div></div><div class="row itemDescription truncate"></div><div class="row price truncate"></div></div></div>'
            $(pageSelector).append(html);
        }
        
        
        pageModal.modal('open');
    },

    showLabelPage: function () {
        var modal = this.$el.find('#label-form-modal').modal();
        modal.modal('open');
    },

    showPriceLevel: function () {
        var modal = this.$el.find('#price-level-form-modal').modal();
        modal.modal('open');
        $('select').formSelect();
    },

    showKeySetPage: function () {
        var modal = this.$el.find('#key-set-form-modal').modal();
        modal.modal('open');
    },

    showTare: function () {
        var modal = this.$el.find('#tare-form-modal').modal();
        modal.modal('open');
    },

    showSaleDiscount: function () {
        var modal = this.$el.find('#sale-reprice-form-modal').modal();
        modal.modal('open');
    },
    showSaleUpcharge: function () {
        var upchargeItems;
        var that = this;
        document.getElementById('saleUpchargeText').value = '';
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-items-by-type',
            data: {
                token: sessionToken,
                itemType: 'UPCHARGE'
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                const upchargeItems = data;

                const upchargeItemsSelectEl = document.getElementById('saleUpchargePercent');
                var html = '<option></option>';
                upchargeItems.forEach( item => {
                    var description = (item.price * 100) + '% | ' + item.description;
                    html += `<option value="${item.id}">${description}</option>`;
                });
                upchargeItemsSelectEl.innerHTML = html;
                $('select').formSelect();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Problem fetching Items by Type{/Literal}' });
                }
            }
        });
        
        var modal = this.$el.find('#sale-upcharge-form-modal').modal();
        modal.modal('open');
    },

    showSaleDiscount2: async function() {
        var that = this;
        var sessionToken = this.getCookie();
        await $.ajax({
            url: '/data/get-item-discounts',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                that.saleDiscounts = data.discounts;
            },

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

        $('select').on('contentChanged', function() {
            $(this).material_select();
          });
        if (that.saleDiscounts.length > 0) {
            let saleSelect = document.getElementById('sales-discount-option');
            saleSelect.innerHTML = '';
            for (var i = 0; i < that.saleDiscounts.length; i++) {
                saleSelect.options[saleSelect.options.length] = new Option('' + that.saleDiscounts[i].id + ' | ' + that.saleDiscounts[i].percent * 100 + '%', '' + that.saleDiscounts[i].id);
                saleSelect.dataset.percent = that.saleDiscounts[i].percent;
            }
            $('select').formSelect();
        }

        var modal = this.$el.find('#sale-discount-form-modal').modal();
        modal.modal('open');
    },

    showItemDiscount: function () {
        var modal = this.$el.find('#item-discount-form-modal').modal();
        modal.modal('open');
    },

    preventDefault: function(e) {
        e.preventDefault();
    },

    createNew: function (e) {
        e.preventDefault();
        var target = e.target;
        var that = this;

        this.currentKeySet = this.$el.find('#key-set-selector option:selected').text();
        if (this.currentKeySet == "MAIN" || this.currentKeySet == "ראשי" ) {
            this.currentKeySet = "";
        }

        this.currentPage = this.$el.find('#page-selector option:selected').text();

        if (target.classList.length < 3){
            that.formModal = document.getElementById('pos-key-form-modal');
            that.formModal = M.Modal.init(that.formModal, {onCloseEnd: ()=> {
                var modals = M.Modal.init(document.querySelectorAll('.modal'), {});
                modals.forEach( m => {
                    m.close();
                })
            }});
            that.formModal.open();

            $('#item-form-modal').hide();
            $('#page-form-modal').hide();
            $('#label-form-modal').hide();
            $('#price-level-form-modal').hide();
            $('#key-set-form-modal').hide();
            $('#tare-form-modal').hide();
            $('#sale-reprice-form-modal').hide();
            $('#item-discount-form-modal').hide();
            $('#sale-discount-form-modal').hide();

            var newKeySetName = document.getElementById('newKeySetName');
            newKeySetName.value = "";
            var newPageName = document.getElementById('newPageName');
            newPageName.value = "";
            var itemSearch = document.getElementById('itemSearch');
            itemSearch.value = "";
            var itemText = document.getElementById('itemText');
            itemText.value = "";
            var label = document.getElementById('label');
            label.value = "";
            var priceLevelText = document.getElementById('priceLevelText');
            priceLevelText.value = "";
            var keySetText = document.getElementById('keySetText');
            keySetText.value = "";
            var tareText = document.getElementById('tareText');
            tareText.value = "";
            var tareWeight = document.getElementById('tareWeight');
            tareWeight.value = "";
            var saleRepriceText = document.getElementById('saleRepriceText');
            saleRepriceText.value = "";
            var saleRepricePercent = document.getElementById('saleRepricePercent');
            saleRepricePercent.value = "";
            var itemDiscountTextForm = document.getElementById('itemDiscountTextForm');
            itemDiscountTextForm.value = "";
            var itemDiscountPercent = document.getElementById('itemDiscountPercent');
            itemDiscountPercent.value = "";
            var saleDiscountTextForm = document.getElementById('saleDiscountTextForm');
            saleDiscountTextForm.value = "";
        }
    },

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

    getItemKeys: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-menu-keys',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.items = data.results;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Problem fetching Item Keys{/Literal}' });
                }
            }
        });
    },
    
    openEditModal: function (e) {
        var that = this;
        var page = this.$el.find('#page-selector option:selected').text(); 
        var keySet = this.getCurrentKeySet();

        this.chosenKeyId = e.target.closest('.card-panel').dataset.id;

        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].id == this.chosenKeyId && this.items[i].keysetName == keySet)
            {
                if (this.items[i].page == page) {
                    this.chosenKey = this.items[i];
                    break;
                }
                else if (this.items[i].page == "TOP") {
                    this.chosenKey = this.items[i];
                    break;
                }
            }
        }

        $('#itemForm').hide();
        $('#pageForm').hide();
        $('#percentForm').hide();
        $('#priceLevelForm').hide();
        $('#tareForm').hide();
        $('#keysetForm').hide();
        $('#itemDiscountForm').hide();
        $('#saleDiscountForm').hide();

        if (this.chosenKey.type == "Item" || this.chosenKey.type == "I") {
            var itemVal = document.getElementById('itemButtonText');
            itemVal.value = this.chosenKey.name;

            document.getElementById('itemId').value = this.chosenKey.id;

            if (this.chosenKey.cr) {
                $('.cr').prop('checked', true);
            }
            else {
                $('.cr').prop('checked', false);
            }

            if (this.chosenKey.noRepeat) {
                $('.noRepeat').prop('checked', true);
            }
            else {
                $('.noRepeat').prop('checked', false);
            }


            this.editModal.modal('open');
            $('#itemForm').show();
        }
        else if (this.chosenKey.type == "Page" || this.chosenKey.type == "P") {
            var pageSelector = that.$el.find('#page-form-selector');
            $(pageSelector).html("");
            
            var foundPage = false;
            for (var i = 0; i < that.pagesObject[keySet].length; i++) {
                var pageName =  that.pagesObject[keySet][i];
                if (pageName.toUpperCase() == that.chosenKey.text.toUpperCase()) {
                    foundPage = true;
                    option = $('<option>');
                    $(option).attr('selected', '');
                    $(option).html(pageName);
                    if(pageName.toUpperCase() == "MAIN")
                        pageName = "";
                    $(option).val(pageName);
                    $(pageSelector).append(option);
                }
                else {
                    option = $('<option>');
                    $(option).val(pageName);
                    $(option).html(pageName);
                    $(pageSelector).append(option);
                }
            }
            if (!foundPage) {

            }
            //for (var i = 0; i < ) {

            //}
    
            $(pageSelector).formSelect();

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

            document.getElementById('pageId').value = this.chosenKey.id;

            var colorInput = document.querySelector(`#color-picker [data-imagename="${this.chosenKey.imageName}"]`);
            if(colorInput)
                colorInput.checked = true;
           

            this.editModal.modal('open');
            $('#pageForm').show();
        }
        else if (this.chosenKey.type == "SaleDiscount" || this.chosenKey.type == "S") {

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

            var discountPercent = document.getElementById('discountPercent');
            discountPercent.value = this.chosenKey.text;

            document.getElementById('discountPercentId').value = this.chosenKey.id;


            this.editModal.modal('open');
            $('#percentForm').show();
        }
        else if (this.chosenKey.type == "GeneralDiscount" || this.chosenKey.type == "G" 
            || this.chosenKey.type == "UpCharge"|| this.chosenKey.type == 'U') {
            var saleDiscountText = document.getElementById('saleDiscountText');
            saleDiscountText.value = this.chosenKey.name;

            var saleDiscount = document.getElementById('saleDiscount');
            saleDiscount.value = this.chosenKey.text;
            if(this.chosenKey.type == "UpCharge"|| this.chosenKey.type == 'U')
                document.getElementById('saleDiscountForm').dataset.type = 'U';
            else if(this.chosenKey.type == "GeneralDiscount" || this.chosenKey.type == "G")
                document.getElementById('saleDiscountForm').dataset.type = 'G';

            document.getElementById('saleDiscountId').value = this.chosenKey.type;

            this.editModal.modal('open');
            $('#saleDiscountForm').show();
        }
        else if (this.chosenKey.type == "ItemDiscount" || this.chosenKey.type == "S" || this.chosenKey.type == "D") {

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

            var itemDiscount = document.getElementById('itemDiscount');
            itemDiscount.value = this.chosenKey.text;

            document.getElementById('itemDiscountId').value = this.chosenKey.id;

            this.editModal.modal('open');
            $('#itemDiscountForm').show();
        }
        else if (this.chosenKey.type == "Level" || this.chosenKey.type == "L") {

            var priceLevelButtonText = document.getElementById('priceLevelButtonText');
            priceLevelButtonText.value = this.chosenKey.name;
            $("#price-level-selector").val(this.chosenKey.text);

            document.getElementById('priceLevelId').value = this.chosenKey.id;
            

            this.editModal.modal('open');
            $('#priceLevelForm').show();
            this.$el.find(".select-dropdown").trigger("click");
        }
        else if (this.chosenKey.type == "Tare" || this.chosenKey.type == "#") {
            var tareWeight = document.getElementById('editTareWeight');
            tareWeight.value = this.chosenKey.text;
            
            var tareText = document.getElementById('editTareText');
            tareText.value = this.chosenKey.name;

            document.getElementById('tareId').value = this.chosenKey.id;

            this.editModal.modal('open');
            $('#tareForm').show();
        }
        else if (this.chosenKey.type == "Keyset" || this.chosenKey.type == "k") {
            var keySetText = document.getElementById('editKeysetText');
            keySetText.value = this.chosenKey.name;
            var keyText = this.chosenKey.text;
            if(keyText.toUpperCase() == "MAIN")
                keyText = "";
            document.getElementById('key-set-form-selector').value = keyText;
            // $('#key-set-form-selector option[value="'+ this.chosenKey.text +'"]').attr("selected",true);
            $('#key-set-form-selector').formSelect();
            document.getElementById('keySetId').value = this.chosenKey.id;


            this.editModal.modal('open');
            $('#keysetForm').show();
        }
        else {
            M.toast({ html: '{Literal}This key does not have a valid key type. Cannot open.{/Literal}' });
        }
    },

    openDeleteModal: function (e) {
        var currentKeyId = e.target.closest('.card-panel').dataset.id;
        this.chosenKeyId = currentKeyId;
        this.deleteModal.modal('open');
    },

    openDeleteModalDirect: function (e) {
        this.deleteModal.modal('open');
    },  

    getMenuKeys: async function() {
        var that = this;
        return $.ajax({
            url: '/data/get-menu-keys',
            data: {
                token: getCookie()
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {


                data.keySets.push("");
                for (var i = 0; i < data.keySets.length; i++) {
                    var keyArray = [];
                    for (var t = 0; t < data.keys.length; t++) {
                        var addToKeySet = false;
                        if (data.keys[t].keysetName == data.keySets[i]) {
                            addToKeySet = true;
                        }
                        if (addToKeySet) {
                            keyArray.push(data.keys[t]);
                        }
                    }
                    that.keysObject[data.keySets[i]] = keyArray;
                }

                for (var i = 0; i < data.keySets.length; i++) {
                    var pagesArray = [];
                    for (var t = 0; t < data.keys.length; t++) {
                        var addToKeySet = false;
                        if (data.keys[t].keysetName == data.keySets[i]) {
                            addToKeySet = true;
                        }
                        if (!pagesArray.includes(data.keys[t].page) && addToKeySet && data.keys[t].page != "LEFT" && data.keys[t].page != "LEFTF" && data.keys[t].page != "RIGHT" && data.keys[t].page != "RIGHTF") {
                            pagesArray.push(data.keys[t].page);
                        }
                    }
                    that.pagesObject[data.keySets[i]] = pagesArray;
                }
                //that.$el.find('#page-selector').formSelect();
                
                
                that.items = data.keys.sort((b,a) => b.row - a.row || b.column - a.column);
                that.pages = that.pagesObject[""];
                that.keySet = data.keySets;
                
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Occurred a problem while rendering this page{/Literal}' });
                }
            }
        });
    },

    /*-----------------------------------------------------------------------------------------------------------------------------------------*/


    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.pages = data.results;
                that.$el.find('#page-selector').formSelect();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Problem fetching Menu Pages{/Literal}' });
                }
            }
        });
    },

    touchHandler: function(e) {
        e.preventDefault();
    },

    getKeySet: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-menu-keys',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.keySet = data.keySets;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Problem fetching Key Set{/Literal}' });
                }
            }
        });
    },

    initItems:  function () {
        var fullItems = this.getItemsFull();
    },

    getItemsFull: function () {
        var that = this;
        var sessionToken = this.getCookie();
        that.renderItems();
    },

    renderItems: function () {
        var that = this;
        var itemCollection = {};

        $('select').formSelect();

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

    searchItemBySearchTerm: function(element) {
        var element = $(element.currentTarget);
        var searchTerm = $(element).val();
        var that = this;
        if (searchTerm.trim().length > 0) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(function() { 
                that.getItemsBySearchTerm(searchTerm); 
            }, 400);
        }
        // that.$el.find("input.autocomplete").trigger("click"); 
    },

    getItemsBySearchTerm: function(searchTerm) {
        var that = this;
        $.ajax({
            url: '/data/get-items-by-search-term',
            data: {
                searchTerm: searchTerm,
                token: this.getCookie()
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var results = data.results;
                var items = {};
                for (var i = 0; i < results.length; i++) {
                    //items[results[i].itemDescription] = null;
                    var autocompleteDisplayItem = results[i].itemDescription + ' / ' + results[i].itemType + ' / ' + results[i].itemCategory + ' / ' + results[i].itemCode ;
                    items[autocompleteDisplayItem] = null;
                    that.itemMapping[autocompleteDisplayItem] = { description: results[i].itemDescription, id: results[i].itemCode };
                }
                that.itemsAutocomplete.updateData(items);  
                that.itemsAutocomplete.open();
                // that.$el.find("input.autocomplete").trigger("click"); 
                  
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                }
            }
        });
    },

    selectItemFromAutocompleteList: function (selection) {
        var that = this;
        var itemId = document.getElementById('itemSearch');
        var itemDesc = document.getElementById('itemText');

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

    /*-----------------------------------------------------------------------------------------------------------------------------------------*/

    changePage: function () {
        var that = this;
        var page = this.$el.find('#page-selector option:selected').text(); 
        var keySet = this.$el.find('#key-set-selector option:selected').text();
        if (keySet.toUpperCase() == "MAIN" || keySet == "ראשי") {
            keySet = "";
        }

        this.currentPage = page;
        this.currentKeyset = keySet;
        this.currentPageColor = this.items.find( i => i.page == 'TOP' && i.text == page)?.imageName;
       
        this.render();
    },

    changeKeySet: function () {
        var that = this;
        var page = "MAIN"
        var keySet = this.getCurrentKeySet();

        this.currentPage = page;
        this.currentKeyset = keySet;
        this.currentPageColor = this.items.find( i => i.page == 'TOP' && i.text == page)?.imageName;

        this.pages = that.pagesObject[keySet];

        var pageSelector = that.$el.find('#page-selector');
        $(pageSelector).html("");

        for (var i = 0; i < that.pagesObject[keySet].length; i++) {
            var pageName = that.pagesObject[keySet][i];

            if (pageName != "TOP") {
                if (pageName == page) {
                    option = $('<option>');
                    $(option).attr('selected', '');
                    $(option).val(pageName);
                    $(option).html(pageName);
                    $(pageSelector).append(option);
                }
                else {
                    option = $('<option>');
                    $(option).val(pageName);
                    $(option).html(pageName);
                    $(pageSelector).append(option);
                }
            }
        }
   
        $(pageSelector).formSelect();
        
        this.render();
    },
    choosePriceLevel: function (e) {
        var priceLevelText = this.$el.find('#priceLevelText').val();
        var priceLevel = this.$el.find('#price-level-dropdown').val();
        var priceLevelId = this.$el.find('#priceLevelId').val();
        
        if (priceLevelText != null && priceLevelText != '' && priceLevelText != undefined) { 
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: priceLevelText,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'L',
                text: priceLevel,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black",
                imageUrl: 'Level'
            };
            this.addNewPosKey(updatedModel);
            $('#pos-key-form-modal').modal().modal('close');
        }
    },

    chooseItemCard: function (e) {
        var itemSearch = this.$el.find('#itemSearch').val();
        var itemText = this.$el.find('#itemText').val();
        if (itemSearch != null && itemSearch != '' && itemText != '' && itemText != null) { 
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: itemText,
                row:  row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'I',
                text: itemSearch,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black"
            }

            this.addNewPosKey(updatedModel);

            $('#pos-key-form-modal').modal().modal('close');
            
        }
        else {
            M.toast({ html: '{Literal}A button name and item are required{/Literal}' });
        }
    },

    choosePageCard: function (e) {
        var element = e.currentTarget;
        var itemId = $(element).attr('description-id');
        if(element.classList.contains('pagesCards')) {
            var nextKeyPlace = document.querySelectorAll('.page-type').length + 1;
            var page = 'TOP';
        }
        else {
            var nextKeyPlace = document.querySelectorAll('.sub-page-type').length + 1;
            var page = this.currentPage;
        }

        var updatedModel = {
            id: 0,
            name: itemId,
            row: 1,
            column: nextKeyPlace,
            width: 1,
            height: 1,
            imageName: 'posBtn01',
            type: 'P',
            text: itemId,
            cr: true,
            keysetName: this.currentKeySet,
            page: page,
            noRepeat: false,
            keyNumber: Math.floor(Math.random() * 100) + 1,
            noSync: false,
            isActive: true,
            textColor: "Black"
        }

        this.addNewPosKey(updatedModel);
        $('#pos-key-form-modal').modal().modal('close');

    },

    choosePageLabel: function () {
        var that = this;
        var label = this.$el.find('#label').val();
        if (label != null && label != '' && label != undefined) { 
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);
            
            var updatedModel = {
                id: 0,
                name: label,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01.0',
                type: 'I',
                text: label,
                textColor: 0,
                cr: false,
                keysetName: that.currentKeySet,
                page: that.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black"
            }            
            this.addNewPosKey(updatedModel);
            $('#pos-key-form-modal').modal().modal('close');

        }
        else {
            M.toast({ html: '{Literal}Please enter label name{/Literal}' });
        }
        
    },

    chooseTareLabel: function () {
        var tareText = this.$el.find('#tareText').val();
        var tareWeight = this.$el.find('#tareWeight').val();

        if (tareText != null && tareText != '' && tareText != undefined && tareWeight != null && tareWeight != '' && tareWeight != undefined) { 
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: tareText,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: '#',
                text: tareWeight,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black",
                imageUrl: 'Tare'
            }

            this.addNewPosKey(updatedModel);
            $('#pos-key-form-modal').modal().modal('close');

        }
        else if (tareText == '') {
            M.toast({ html: '{Literal}Please enter label name{/Literal}' });
        }
        else if (tareWeight == '') {
            M.toast({ html: '{Literal}Please enter desired weight{/Literal}' });
        }
    },

    chooseSaleDiscount: function () {
        var saleDiscountText = this.$el.find('#saleDiscountTextForm').val();
        var saleDiscountPercentLabel = this.$el.find('#sales-discount-option').val();
        var percent = document.getElementById('sales-discount-option').dataset.percent;
        percent = Number.parseFloat(percent);
        if(percent < 0 || percent > 1 || percent == NaN) {
            if(percent == NaN)
                console.log('sales-discount-option is Nan');
            M.toast({ html: '{Literal}Please choose a valid percent{/Literal}' });
        }
        else if (saleDiscountText != '' && saleDiscountText != undefined && saleDiscountPercentLabel != '') {
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: saleDiscountText,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'G',
                text: saleDiscountPercentLabel,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black"
            }
            this.addNewPosKey(updatedModel)
            $('#pos-key-form-modal').modal().modal('close');
        }
        else if (saleDiscountText == '') {
            M.toast({ html: '{Literal}Please enter label name{/Literal}' });
        }
        else if (saleDiscountPercentLabel == '')  {
            M.toast({ html: '{Literal}Please enter a discount percent{/Literal}' });
        }
    },

    chooseRepriceLabel: function () {
        var saleRepriceText = this.$el.find('#saleRepriceText').val();
        var saleRepricePercent = this.$el.find('#saleRepricePercent').val();

        if(saleRepricePercent < 0 || saleRepricePercent > 100) {
            M.toast({ html: '{Literal}Please choose a valid percent{/Literal}' });
        }
        else if (saleRepriceText != '' && saleRepriceText != undefined && saleRepricePercent != '') {
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: saleRepriceText,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'S',
                text: saleRepricePercent,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black",
                imageUrl: 'SaleDiscount'
            };
            this.addNewPosKey(updatedModel);
            $('#pos-key-form-modal').modal().modal('close');

        }
        else if (saleRepriceText == '') {
            M.toast({ html: '{Literal}Please enter label name{/Literal}' });
        }
        else if (saleRepricePercent == '')  {
            M.toast({ html: '{Literal}Please enter a discount percent{/Literal}' });
        }
    },

    chooseUpchargeLabel: function () {
        var saleUpchargeText = this.$el.find('#saleUpchargeText').val();
        var saleUpchargeItemId = this.$el.find('#saleUpchargePercent').val();

        if(saleUpchargeItemId.length == 0) {
            M.toast({ html: '{Literal}Please select Up charge item{/Literal}' });
        }
        else if (saleUpchargeText != '' && saleUpchargeText != undefined && saleUpchargeItemId != '') {
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: saleUpchargeText,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'U',
                text: saleUpchargeItemId,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black",
                imageUrl: 'UpCharge'
            };
            this.addNewPosKey(updatedModel);
            $('#sale-upcharge-form-modal').modal().modal('close');
            $('#pos-key-form-modal').modal().modal('close');
        }
        else if (saleUpchargeText == '') {
            M.toast({ html: '{Literal}Please enter label name{/Literal}' });
        }
        else if (saleUpchargeItemId == '')  {
            M.toast({ html: '{Literal}Please select a upcharge percent{/Literal}' });
        }
    },

    chooseItemDiscount: function () {
        var itemDiscountText = this.$el.find('#itemDiscountTextForm').val();
        var itemDiscountPercent = this.$el.find('#itemDiscountPercent').val();

        if(itemDiscountPercent < 0 || itemDiscountPercent > 100) {
            M.toast({ html: '{Literal}Please choose a valid percent{/Literal}' });
        }

        else if (itemDiscountText != '' && itemDiscountText != undefined && itemDiscountPercent != '') {
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: itemDiscountText,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'D',
                text: itemDiscountPercent,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black"
            };
            this.addNewPosKey(updatedModel);
            $('#pos-key-form-modal').modal().modal('close');
        }
        else if (saleRepriceText == '') {
            M.toast({ html: '{Literal}Please enter label name{/Literal}' });
        }
        else if (saleRepricePercent == '')  {
            M.toast({ html: '{Literal}Please enter a discount percent{/Literal}' });
        }
    },

    chooseKeysetCards: function (e) {
        var that = this;
        var keySetText = this.$el.find('#keySetText').val();
        var keySet = this.$el.find('#change-key-set-select option:selected').text();
        var keySetValue = this.$el.find('#change-key-set-select').val();
        
        if (keySetText != null && keySetText != '' && keySetText != undefined && keySetValue != 'chooseKeySet') { 
            if (keySet == "MAIN") {
                keySet = "";
            }
            
            
            $('#pos-key-form-modal').modal().modal('close');
            var nextKeyPlace = document.querySelectorAll('.menu-key-card').length + 1;
            var col = 1 + nextKeyPlace % 7;
            var row = 3 + Math.floor(nextKeyPlace / 7);

            var updatedModel = {
                id: 0,
                name: keySetText,
                row: row,
                column: col,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'k',
                text: keySet,
                cr: true,
                keysetName: this.currentKeySet,
                page: this.currentPage,
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true,
                textColor: "Black"
            };
            this.addNewPosKey(updatedModel);
        }
        else if (keySetValue == 'chooseKeySet') {
            M.toast({ html: '{Literal}Please choose a Key Set{/Literal}' });
        }
        else if (keySetText == '') {
            M.toast({ html: '{Literal}Please enter a button name{/Literal}' });
        }
        
    },

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

        $.ajax({
            url: '/data/add-pos-key',
            data: {
                menuKey: JSON.stringify(updatedModel),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                updatedModel.id = data.id;
                that.items.push(updatedModel);
                that.addedKey = updatedModel;
                M.toast({ html: '{Literal}Menu Key added successfully{/Literal}' });
                that.render();
            },

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

    deleteKey: function (e) {
        var that = this;
        var page = this.$el.find('#page-selector option:selected').text(); 
        var keySet = this.$el.find('#key-set-selector option:selected').text();

        var thisKeysetMenuKeys = this.items.filter( i => i.keysetName == that.currentKeySet);

        if(( page == 'MAIN' || page == '') && thisKeysetMenuKeys?.length == 1) {
            M.toast({ html: '{Literal}MAIN page should have at least one key{/Literal}' });
            return;
        }
        
        if (keySet == "MAIN" || keySet == "ראשי") {
            keySet = "";
        }
        
        var sessionToken = this.getCookie();
        var keyIndex = "";
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].id == this.chosenKeyId && this.items[i].keysetName == keySet)
            {
                keyIndex = i;
                this.chosenKey = this.items[i];
            }
        }

        
        $.ajax({
            url: '/data/remove-menu-key',
            data: {
                buttonId: that.chosenKeyId,
                keySetName: keySet,
                page: page,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                if (keyIndex != "") {
                    that.items.splice(keyIndex , 1);  
                }
                M.toast({ html: '{Literal}Menu Key removed successfully{/Literal}' });

                that.render();
            },

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

    saveNewMenuPage: function () {
        var menuPage = this.$el.find('#menuPageName').val();
        that = this;
        var isTaken = false;
        if (menuPage != '' && menuPage != undefined && menuPage != null) {
            for (var i in that.pages) {
                if (that.pages[i] === menuPage) {
                    isTaken = true;
                    break;
                }
            }

            if (isTaken) {
                M.toast({ html: '{Literal}This Menu Page is already defined{/Literal}' });
            }
            else {
                this.newPage = menuPage;
                that.pages.push(menuPage);  
            }
        }
        else {
            M.toast({ html: '{Literal}Please enter a valid Menu Page name{/Literal}' });
        }
    },

    openEditNameModal: function () {
        var currentPage = this.$el.find('#page-selector option:selected').text();
        var pageName = document.getElementById('pageName'); 
        pageName.value = currentPage;

        var pageNameModal = this.$el.find('#edit-page-name-modal').modal();
        pageNameModal.modal('open');
    },

    openDeletePageModal: function (e) {
        var deletePageModal = this.$el.find('#delete-page-modal').modal();
        deletePageModal.modal('open');
    },

    addNewPage: function () {
        var newPageModal = this.$el.find('#new-page-form-modal').modal();
        newPageModal.modal('open');
    },

    addNewPageByItemType: function (e) {
        if(e.currentTarget.id == 'itemTypeCard') {
            var currentPage = this.$el.find('#page-selector option:selected').text();
            document.getElementById('newPageNameByItemType').value = currentPage;
            document.getElementById('newPageNameByItemType').disabled = true;
        }
        else if(e.currentTarget.id == 'addPageByItemTypeButton'){
            document.getElementById('newPageNameByItemType').value = '';
            document.getElementById('newPageNameByItemType').disabled = false;
        }
        var newPageModal = this.$el.find('#new-page-by-item-type-form-modal').modal();
        newPageModal.modal('open');
    },

    openAddKeySetModal: function () {
        var newRoomModal = this.$el.find('#new-key-set-modal').modal();
        newRoomModal.modal('open');
    },

    saveNewPage: function () {
        var that = this;
        var sessionToken = this.getCookie();
        var newPageName = this.$el.find('#newPageName').val();
        var keySetName = this.$el.find('#key-set-selector option:selected').text();
        if (keySetName == "MAIN" || keySetName == "ראשי") {
            keySetName = "";
        }
        if (newPageName == "") {
            M.toast({ html: '{Literal}A Page Name Must Be Defined{/Literal}' });
        }
        else {
            var foundName = false;
            for (var i = 0; i < this.pages.length; i++) {
                if (this.pages[i] == newPageName) {
                    foundName = true;
                }
            }

            if (foundName == true) {
                M.toast({ html: '{Literal}This Page Name Is Already Defined{/Literal}' });
            }
            else {
                this.pages.unshift(newPageName);
                that.pagesObject[keySetName].push(newPageName);
                this.newPage = newPageName;
                var updatedModel = {
                    id: 0,
                    name: 'New Button',
                    row: 3,
                    column: 1,
                    width: 1,
                    height: 1,
                    imageName: 'posBtn01',
                    type: 'I',
                    text: 'New Button',
                    cr: true,
                    keysetName: keySetName,
                    page: newPageName,
                    noRepeat: false,
                    keyNumber: Math.floor(Math.random() * 100) + 1,
                    noSync: false,
                    isActive: true
                }

                $.ajax({
                    url: '/data/add-pos-key',
                    data: {
                        menuKey: JSON.stringify(updatedModel),
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',
        
                    success: function (data) {
                        M.toast({ html: '{Literal}Page added successfully{/Literal}' });
                        
                        keySetName = that.$el.find('#key-set-selector option:selected').text();
                        if (keySetName == "MAIN" || keySetName == "ראשי") {
                            keySetName = '';
                        }

                        
                        var elements = document.getElementById("page-selector").options;

                        var pageSelector = that.$el.find('#page-selector');
                        $(pageSelector).html("");

                        if (that.pagesObject[keySetName] != undefined) {
                            for (var i = 0; i < that.pagesObject[keySetName].length; i++) {
                                var pageName = that.pages[i];
                                
                                if (pageName != "TOP") {
                                    if (pageName == newPageName) {
                                        option = $('<option>');
                                        $(option).attr('selected', '');
                                        $(option).val(pageName);
                                        $(option).html(pageName);
                                        $(pageSelector).append(option);
                                    }
                                    else {
                                        option = $('<option>');
                                        $(option).val(pageName);
                                        $(option).html(pageName);
                                        $(pageSelector).append(option);
                                    } 
                                }
                            }
                        }
                        else {
                            that.pagesObject[keySetName] = [];
                            that.pagesObject[keySetName].push("");
                            that.pagesObject[keySetName].push(newPageName);
                            for (var i = 0; i < that.pagesObject[keySetName].length; i++) {
                                var pageName = that.pages[i];
                    
                                if (pageName != "TOP") {
                                    if (pageName == newPageName) {
                                        option = $('<option>');
                                        $(option).attr('selected', '');
                                        $(option).val(pageName);
                                        $(option).html(pageName);
                                        $(pageSelector).append(option);
                                    }
                                    else {
                                        option = $('<option>');
                                        $(option).val(pageName);
                                        $(option).html(pageName);
                                        $(pageSelector).append(option);
                                    }
                                }
                            }
                        }
                        
                        updatedModel.id = data.id;
                        that.items.push(updatedModel);
                        $(pageSelector).formSelect();
                        that.changePage();
                    },
        
                    error: function (e) {
                        if (e.status == 523) {
                            window.location.href = "#/log-in";
                            location.reload();
                        }
                        else {
                            M.toast({ html: '{Literal}There was a problem deleting this page{/Literal}' });
                        }
                    }
                });
            }
        }
    },

    addMenuKeysByItemType: function () {
        var that = this;
        var sessionToken = this.getCookie();
        var itemType = '';
        var itemCategory = '';
        if(document.getElementById('typeRadioBtn').checked)
            itemType = document.getElementById('itemTypeSelect').value;
        else if(document.getElementById('categoryRadioBtn').checked)
            itemCategory = document.getElementById('itemCategorySelect').value;

        

        var pageName = this.$el.find('#newPageNameByItemType').val();
        var addNewPage = !this.pages.includes(pageName);
        var keySetName = this.$el.find('#key-set-selector option:selected').text();

        if (keySetName == "MAIN" || keySetName == "ראשי") {
            keySetName = "";
        }
        if (pageName == "") {
            M.toast({ html: '{Literal}A Page Name Must Be Defined{/Literal}' });
        }
        else {
            // var foundName = false;
            // for (var i = 0; i < this.pages.length; i++) {
            //     if (this.pages[i] == pageName) {
            //         foundName = true;
            //     }
            // }

            // if (foundName == true) {
            //     M.toast({ html: '{Literal}This Page Name Is Already Defined{/Literal}' });
            // }
            // else {
             

                $.ajax({
                    url: '/data/add-menu-keys-by-item-type',
                    data: {
                        addNewPage: addNewPage,
                        pageName: pageName,
                        keySetName: keySetName,
                        itemType: itemType,
                        itemCategory: itemCategory,
                        token: sessionToken
                    },
                    dataType: 'json',
                    type: 'POST',
        
                    success: async function (data) {
                        M.toast({ html: '{Literal}Page added successfully{/Literal}' });
                        await that.getMenuKeys();
                        that.render();
                    },
        
                    error: function (e) {
                        if (e.status == 523) {
                            window.location.href = "#/log-in";
                            location.reload();
                        }
                        else {
                            M.toast({ html: '{Literal}There was a problem deleting this page{/Literal}' });
                        }
                    }
                });
            // }
        }
    },

    savePageName: function () {
        var that = this;
        var newPageName = this.$el.find('#pageName').val();
        var currentPage = this.$el.find('#page-selector option:selected').text();
        var sessionToken = this.getCookie();
        
        if (currentPage.toUpperCase() == "MAIN" || currentPage == "ראשי") {
            M.toast({ html: '{Literal}The room "main" cannot be changed{/Literal}' }); 
        }
        else {
            $.ajax({
                url: '/data/rename-page',
                data: {
                    oldPageName: currentPage,
                    newPageName: (newPageName),
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',
    
                success: function (data) {
                    for (var i = 0; i < that.pages.length; i++) {
                        if (that.pages[i] == currentPage) {
                            that.pages[i] = newPageName;
                        }
                    }

                    for (var i = 0; i < that.items.length; i++) {
                        if (that.items[i].page == currentPage) {
                            that.items[i].page = newPageName;
                        }
                    }
                    that.render();
                    M.toast({ html: '{Literal}Page name changed successfully{/Literal}' });
                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}There was a problem renaming this page{/Literal}' });
                    }
                }
            });
        }
    },

    deletePage: function () {
        var that = this;
        var sessionToken = this.getCookie();
        var currentPage = this.$el.find('#page-selector option:selected').text();
        var keySetName = this.$el.find('#key-set-selector option:selected').text();

        if (keySetName == "MAIN" || keySetName == "ראשי") {
            keySetName = "";
        }
        
        $.ajax({
            url: '/data/remove-menu-page',
            data: {
                page: currentPage,
                keySetName: keySetName,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                that.render();
                M.toast({ html: '{Literal}Page removed successfully{/Literal}' });

                for (i = 0; i < that.items.length; i++)
                {
                    if (that.items[i].page == currentPage)
                    {
                        that.items[i] = "";
                        //newDivId = "divTable" + i;
                        //$('#' + newDivId).remove();
                    }
                }

                
                for (i = 0; i < that.pages.length; i++)
                {
                    if (that.pages[i] == that.pages)
                    {
                        that.pages[i] = "";
                    }
                }
                //that.render();
            },

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

    addKeySet: function() {
        var that = this;
        var sessionToken = this.getCookie();
        var newKeySetName = this.$el.find('#newKeySetName').val();
        var foundName = false;

        for (var i = 0; i < this.keySet; i++) {
            if (newKeySetName == this.keySet[i].name) {
                foundName = true;
            }
        }

        if (newKeySetName == "" || newKeySetName.toUpperCase() === 'MAIN' || newKeySetName === 'ראשי') {
            M.toast({ html: '{Literal}Please enter a valid key set name{/Literal}' });
        }
        else if (!foundName) {
            that.keySet.unshift(newKeySetName);
            var updatedModal = {
                id: 0,
                name: 'New Button',
                row: 3,
                column: 1,
                width: 1,
                height: 1,
                imageName: 'posBtn01',
                type: 'I',
                text: 'New Button',
                cr: true,
                keysetName: newKeySetName,
                page: "Main",
                noRepeat: false,
                keyNumber: Math.floor(Math.random() * 100) + 1,
                noSync: false,
                isActive: true
            }

            $.ajax({
                url: '/data/add-pos-key',
                data: {
                    menuKey: JSON.stringify(updatedModal),
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',
    
                success: function (data) {
                    M.toast({ html: '{Literal}Key Set added successfully{/Literal}' });

                    
                    // $(widget).append(widgetContent);
                    // that.grid.addWidget($(widget), node.x, node.y, node.width, node.height);
                        

                    var pageSelector = that.$el.find('#page-selector');
                    $(pageSelector).html("");
                    option = $('<option>');
                    $(option).attr('selected', '');
                    $(option).val("MAIN");
                    $(option).html("MAIN");
                    $(pageSelector).append(option);

                    $(pageSelector).formSelect();


                    var keySetSelector = that.$el.find('#key-set-selector');
                    $(keySetSelector).html("");

                    for (var i = 0; i < that.keySet.length; i++) {
                        var keySet = that.keySet[i];

                        if (keySet == newKeySetName) {
                            option = $('<option>');
                            $(option).attr('selected', '');
                            $(option).val(keySet);
                            $(option).html(keySet);
                            $(keySetSelector).append(option);
                        }
                        else {
                            option = $('<option>');
                            $(option).val(keySet);
                            $(option).html(keySet);
                            $(keySetSelector).append(option);
                        }
                    }
               
                    $(keySetSelector).formSelect();

                },
    
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}There was a problem deleting this page{/Literal}' });
                    }
                }
            });
        }
        else {
            M.toast({ html: '{Literal}This Key Set has already been defined{/Literal}' });
        }
    },

    saveEditedKey: function() {
        var that = this;
        var currentKeySet = this.$el.find('#key-set-selector option:selected').text();
        var currentPage = this.$el.find('#page-selector option:selected').text();
        var changedText = "";

        if (currentKeySet == "MAIN" || currentKeySet == "ראשי") {
            currentKeySet = "";
        }
        if (this.chosenKey.page.toUpperCase() == 'TOP') {
            currentPage = this.chosenKey.page;
        }

        // this.chosenKey.imageName = document.querySelector('input[name="pageRadio"]:checked').dataset.imagename;
        if ($('#tareForm').is(":visible")) {
            var tareWeight = this.$el.find('#editTareWeight').val();
            var tareText = this.$el.find('#editTareText').val();
            changedText = tareText;


            this.chosenKey.imageName = 'posBtn08';
            
            var updatedModal = {
                id: this.chosenKey.id,
                name: tareText,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                width: this.chosenKey.width,
                height: this.chosenKey.height,
                imageName:  this.chosenKey.imageName,
                textColor: this.chosenKey.textColor,
                type: '#',
                text: tareWeight,
                cr: true,
                keysetName: currentKeySet,
                page: currentPage,
                noRepeat: false,
                keyNumber:  this.chosenKey.keyNumber,
                noSync: false,
                isActive: true
            }

            this.chosenKey = updatedModal;

            this.editPosKey();
            
        }
        else if ($('#keysetForm').is(":visible")) {
            var keySet = this.$el.find('#key-set-form-selector option:selected').text();
            var keySetVal = this.$el.find('#key-set-form-selector').val();
            var keySetText = this.$el.find('#editKeysetText').val();
            changedText = keySetText;
            this.chosenKey.imageName = 'posBtn08';


            var updatedModal = {
                id: this.chosenKey.id,
                name: keySetText,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                width: this.chosenKey.width,
                height: this.chosenKey.height,
                imageName:  this.chosenKey.imageName,
                textColor: this.chosenKey.textColor,
                type: 'k',
                text: keySetVal,
                cr: true,
                keysetName: currentKeySet,
                page: currentPage,
                noRepeat: false,
                keyNumber:  this.chosenKey.keyNumber,
                noSync: false,
                isActive: true
            }

            this.chosenKey = updatedModal;

            this.editPosKey();
        }
        else if ($('#percentForm').is(":visible")) {
            var percentButtonText = this.$el.find('#percentButtonText').val();
            var discountPercent = this.$el.find('#discountPercent').val();
            changedText = percentButtonText;

            var updatedModal = {
                id: this.chosenKey.id,
                name: percentButtonText,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                width: this.chosenKey.width,
                height: this.chosenKey.height,
                imageName:  this.chosenKey.imageName,
                textColor: this.chosenKey.textColor,
                type: 'S',
                text: discountPercent,
                cr: true,
                keysetName: currentKeySet,
                page: currentPage,
                noRepeat: false,
                keyNumber:  this.chosenKey.keyNumber,
                noSync: false,
                isActive: true
            }

            this.chosenKey = updatedModal;

            this.editPosKey();
        }
        else if ($('#saleDiscountForm').is(":visible")) {
            var saleDiscountText = this.$el.find('#saleDiscountText').val();
            var saleDiscount = this.$el.find('#saleDiscount').val();
            var type = document.getElementById('saleDiscountForm').dataset.type;
            changedText = saleDiscountText;

            if (saleDiscountText != '' && saleDiscount !=  '') {
    
                var updatedModal = {
                    id: this.chosenKey.id,
                    name: saleDiscountText,
                    row: this.chosenKey.row,
                    column: this.chosenKey.column,
                    width: this.chosenKey.width,
                    height: this.chosenKey.height,
                    imageName:  this.chosenKey.imageName,
                    textColor: this.chosenKey.textColor,
                    type: type,
                    text: saleDiscount,
                    cr: true,
                    keysetName: currentKeySet,
                    page: currentPage,
                    noRepeat: false,
                    keyNumber:  this.chosenKey.keyNumber,
                    noSync: false,
                    isActive: true
                }
    
                this.chosenKey = updatedModal;
    
                this.editPosKey();
            }
            else {
                M.toast({ html: '{Literal}Both Inputs Are Required{/Literal}' });
            }
        }
        
        else if ($('#itemDiscountForm').is(":visible")) {
            var itemDiscountText = this.$el.find('#itemDiscountText').val();
            var itemDiscount = this.$el.find('#itemDiscount').val();
            changedText = itemDiscountText;

            if (itemDiscountText != '' && itemDiscount !=  '') {
    
                var updatedModal = {
                    id: this.chosenKey.id,
                    name: itemDiscountText,
                    row: this.chosenKey.row,
                    column: this.chosenKey.column,
                    width: this.chosenKey.width,
                    height: this.chosenKey.height,
                    imageName:  this.chosenKey.imageName,
                    textColor: this.chosenKey.textColor,
                    type: this.chosenKey.type,
                    text: itemDiscount,
                    cr: true,
                    keysetName: currentKeySet,
                    page: currentPage,
                    noRepeat: false,
                    keyNumber:  this.chosenKey.keyNumber,
                    noSync: false,
                    isActive: true
                }
    
                this.chosenKey = updatedModal;
    
                this.editPosKey();
            }
            else {
                M.toast({ html: '{Literal}Both Inputs Are Required{/Literal}' });
            }
        }
        else if ($('#priceLevelForm').is(":visible")) {
            var priceLevel = this.$el.find('#price-level-selector option:selected').text();
            var priceLevelButtonText = this.$el.find('#priceLevelButtonText').val();
            changedText = priceLevelButtonText;

            var updatedModal = {
                id: this.chosenKey.id,
                name: priceLevelButtonText,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                width: this.chosenKey.width,
                height: this.chosenKey.height,
                imageName:  this.chosenKey.imageName,
                textColor: this.chosenKey.textColor,
                type: 'L',
                text: priceLevel,
                cr: this.chosenKey.cr,
                keysetName: currentKeySet,
                page: currentPage,
                noRepeat: this.chosenKey.noRepeat,
                keyNumber:  this.chosenKey.keyNumber,
                noSync: this.chosenKey.noSync,
                isActive: this.chosenKey.isActive
            }

            this.chosenKey = updatedModal;

            this.editPosKey();
        }
        else if ($('#labelForm').is(":visible")) {
            var labelButtonText = this.$el.find('#labelButtonText').val();
            changedText = labelButtonText;


            var updatedModal = {
                id: this.chosenKey.id,
                name: labelButtonText,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                width: this.chosenKey.width,
                height: this.chosenKey.height,
                imageName:  this.chosenKey.imageName,
                textColor: this.chosenKey.textColor,
                type: 'I',
                text: labelButtonText,
                cr: this.chosenKey.cr,
                keysetName: currentKeySet,
                page: currentPage,
                noRepeat: this.chosenKey.noRepeat,
                keyNumber:  this.chosenKey.keyNumber,
                noSync: this.chosenKey.noSync,
                isActive: this.chosenKey.isActive
            }

            this.chosenKey = updatedModal;

            this.editPosKey();
        }
        else if ($('#itemForm').is(":visible")) {
            var pageButtonText = this.$el.find('#itemButtonText').val();
            var cr = this.$el.find('.cr:checked').length > 0;
            var noRepeat = this.$el.find('.noRepeat:checked').length > 0;
            changedText = pageButtonText;


            var updatedModal = {
                id: this.chosenKey.id,
                name: pageButtonText,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                width: this.chosenKey.width,
                height: this.chosenKey.height,
                imageName:  this.chosenKey.imageName,
                textColor: this.chosenKey.textColor,
                type: 'I',
                text: this.chosenKey.text,
                cr: cr,
                keysetName: currentKeySet,
                page: currentPage,
                noRepeat: noRepeat,
                keyNumber:  this.chosenKey.keyNumber,
                noSync: this.chosenKey.noSync,
                isActive: this.chosenKey.isActive
            }

            this.chosenKey = updatedModal;

            this.editPosKey();
        }
        else if ($('#pageForm').is(":visible")) {
            var pageSelected = this.$el.find('#page-form-selector option:selected').text();
            var pageSelectedVal = this.$el.find('#page-form-selector').val();
            var pageButtonText = this.$el.find('#pageButtonText').val();
            changedText = pageButtonText;
            this.chosenKey.imageName = document.querySelector('input[name="pageRadio"]:checked').dataset.imagename;


            if (pageSelectedVal == "") {
                pageSelected = this.chosenKey.text;
            }

            var updatedModal = {
                id: this.chosenKey.id,
                name: pageButtonText,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                width: this.chosenKey.width,
                height: this.chosenKey.height,
                imageName:  this.chosenKey.imageName,
                textColor: this.chosenKey.textColor,
                type: 'P',
                text: pageSelected,
                cr: this.chosenKey.cr,
                keysetName: currentKeySet,
                page: this.chosenKey.page,
                noRepeat: this.chosenKey.noRepeat,
                keyNumber:  this.chosenKey.keyNumber,
                noSync: this.chosenKey.noSync,
                isActive: this.chosenKey.isActive
            }

            this.chosenKey = updatedModal;
            const thisPageKey = this.items.find( i => i.id == this.chosenKey.id );
            thisPageKey.imageName = this.chosenKey.imageName;
            // that.items.forEach( item => {
            //     if(item.type == 'Page' || item.type == 'P' || item.page != currentPage || item.keysetName != currentKeyset )
            //         return true;

            //     item.
            // });

            this.editPosKey();
        }

    },
    
    editPosKey: function () {
        var that = this;
        var sessionToken = this.getCookie();

        $.ajax({
            url: '/data/edit-pos-key',
            data: {
                menuKey: JSON.stringify(that.chosenKey),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            
            success: async function (data) {
                M.toast({ html: '{Literal}Menu Key added successfully{/Literal}' });
                for (var i = 0; i < that.items.length; i++) {
                    if (that.items[i].id == that.chosenKey.id) {
                        that.items[i] = that.chosenKey
                    }
                }

                // that.render();
                that.changePage();
            },

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

    saveMovedKey: function (saveKey) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/edit-pos-key',
            data: {
                menuKey: JSON.stringify(saveKey),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                for (var i = 0; i < that.items.length; i++) {
                    if (that.items[i].id == saveKey.id) {
                        that.items[i] = saveKey
                    }
                }

            },

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

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

        var updatedPageModels = [];
        
        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

        var currentKeySet = this.$el.find('#key-set-selector option:selected').text();
        if (currentKeySet.toUpperCase() == "MAIN" || currentKeySet == "ראשי") {
            currentKeySet = "";
        }

        var currentPage = this.$el.find('#page-selector option:selected').text();

        var thisPageMenuKeys = document.querySelectorAll('#menu-keys .menu-key-card .card-panel-entity');

        var row = 2;
        var col = 1;

        for (let i = 0; i < thisPageMenuKeys.length; i++) {
            const element = thisPageMenuKeys[i];
            const id = element.dataset.id;
            const item = this.items.find( item => item.id == id);
            if(item) {
                item.column = col;
                item.row = row;
                updatedPageModels.push(item);
                if(col / 7 >= 1){
                    row += item.height;
                    col = 1;
                }
                else
                    col += item.width;
            }
        }

        row = 1;
        col = 1;

        var thisPageMenuKeys = document.querySelectorAll('#page-keys .page-key-card .card-panel-entity');
        for (let i = 0; i < thisPageMenuKeys.length; i++) {
            const element = thisPageMenuKeys[i];
            const id = element.dataset.id;
            const item = this.items.find( item => item.id == id);
            if(item) {
                item.column = col;
                item.row = row;
                updatedPageModels.push(item);
                if(col / 7 >= 1){
                    row += item.height;
                    col = 1;
                }
                else
                    col += item.width;
            }
        }


        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

        var savedMenuKeys = {
            page: updatedPageModels
        }
        
        
        $.ajax({
            url: '/data/save-all-pos-keys',
            data: {
                savedMenuKeys: JSON.stringify(savedMenuKeys),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                M.toast({ html: '{Literal}Menu Page save successfully{/Literal}' });
            },

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

    closeNewModals: function () {
       $("#new-key-set-modal").hide();
       var itemFormModal = this.$el.find('#new-key-set-modal').modal();
       itemFormModal.modal('close');

       $("#new-page-form-modal").hide();
       var itemFormModal = this.$el.find('#new-page-form-modal').modal();
       itemFormModal.modal('close');
       
       $("#item-form-modal").hide();
       var itemFormModal = this.$el.find('#item-form-modal').modal();
       itemFormModal.modal('close');
       
       $("#page-form-modal").hide();
       var itemFormModal = this.$el.find('#page-form-modal').modal();
       itemFormModal.modal('close');

       $("#label-form-modal").hide();
       var itemFormModal = this.$el.find('#label-form-modal').modal();
       itemFormModal.modal('close');

       $("#price-level-form-modal").hide();
       var itemFormModal = this.$el.find('#price-level-form-modal').modal();
       itemFormModal.modal('close');

       $("#key-set-form-modal").hide();
       var itemFormModal = this.$el.find('#key-set-form-modal').modal();
       itemFormModal.modal('close');
       
       $("#tare-form-modal").hide();
       var itemFormModal = this.$el.find('#tare-form-modal').modal();
       itemFormModal.modal('close');
       
       $("#sale-reprice-form-modal").hide();
       var itemFormModal = this.$el.find('#sale-reprice-form-modal').modal();
       itemFormModal.modal('close');
       
       $("#item-discount-form-modal").hide();
       var itemFormModal = this.$el.find('#item-discount-form-modal').modal();
       itemFormModal.modal('close');

       $("#sale-discount-form-modal").hide();
       var itemFormModal = this.$el.find('#sale-discount-form-modal').modal();
       itemFormModal.modal('close');
       
       $("#new-page-by-item-type-form-modal").hide();
       var itemFormModal = this.$el.find('#new-page-by-item-type-form-modal').modal();
       itemFormModal.modal('close');
    },

    loadPageOnPageKeyClick: function(event) {
        const el = event.target.closest('.card-panel');
        const key = this.items.find(item => item.id == el?.dataset.id);
        if(key && key.type == 'P' || key.type == 'Page') {   
            let pageName = key.text;
            if(pageName == 'MAIN')
                pageName = '';
            if(key.text != this.currentPage) {
                if(!document.querySelector('#page-selector option[value="'+pageName+'"')) {
                     document.getElementById('page-selector').add(new Option(pageName, pageName));
                     this.pages.push(pageName);
                }
                
                document.getElementById('page-selector').value = pageName;
                
                this.changePage();
            }
        }
    },

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

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

    typeCategoryGroupSelect: function() {
        if(document.getElementById('typeRadioBtn').checked) {
            document.getElementById('itemType').style.display = 'block';
            document.getElementById('itemCategory').style.display = 'none';
        }
        if(document.getElementById('categoryRadioBtn').checked) {
            document.getElementById('itemType').style.display = 'none';
            document.getElementById('itemCategory').style.display = 'block';
        }
    }
});