var ChoiceKeysView = Backbone.View.extend({
    breadcrumb: {},
    gridSizeRows: 11,
    gridSizeCols: 7,
    occupiedCells: {},
    prefilledUnoccupiedCells: false,
    chosenKey: {},
    chosenKeyId: '',
    currentKeySet: '',
    itemsStyleMapping: {},
    itemMapping: {},
    addedKey: {},

    pages: [],
    keySet: [],

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

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

        'click #itemCard' : 'showItems',
        'click #labelCard' : 'showLabelPage',

        'change #page-selector' : 'changePage',
        'change #individual-page-selector': 'changeIndividualPage',

        'click #editPageName': 'openEditNameModal',
        'click #addKeySetButton': 'openAddKeySetModal',
        'click .save-menu-page-button' : 'saveNewMenuPage',
        'click #addPageButton' : 'addNewPage',
        'click .save-new-page-button' : 'saveNewPage',
        '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 .save-label-button' : 'choosePageLabel',
        'click .save-item-button' : 'chooseItemCard',

        'click .cancel-items-button' : 'closeNewModals',
        'click .cancel-label-button' : 'closeNewModals',
    },

    dataChangedAndNotSaved: false,

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.breadcrumb = options.breadcrumb;
        this.posKeyFormTemplate = options.posKeyFormTemplate;
        this.model = options.model;
    },

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

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

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

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

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

        if (target.classList.length < 3){
            that.formModal = that.$el.find('#pos-key-form-modal').modal();
            that.formModal.modal('open');
            $('#item-form-modal').hide();
            $('#label-form-modal').hide();

            var itemSearch = document.getElementById('itemSearch');
            itemSearch.value = "";
            var itemText = document.getElementById('itemText');
            itemText.value = "";
            var label = document.getElementById('label');
            label.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);
        }
    },

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

    showMenu: function (e) {
        var element = $(e.currentTarget);
        var parent = $(element).parent();
        var id = $(parent).attr('data-id');
        var name = $(parent).attr('data-name');
        this.chosenKeyId = id;
        var floatingMenu = this.$el.find('.floating-menu');
        
        $(floatingMenu).hide();
        $(floatingMenu).css('top', e.originalEvent.pageY - 75 + 'px');
        $(floatingMenu).css('left', e.originalEvent.pageX + 'px');
        $(floatingMenu).fadeIn('fast');
        $(floatingMenu).find('.edited-button-name').html(name);
        
    },

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

    //https://github.com/gridstack/gridstack.js/tree/develop/doc
    render: function () {
        this.gridInit = true;
        
        var that = this;
        $('select').formSelect();
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-choice-keys',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.items = data;
                that.pages = [];
                for (var i = 0; i < Object.keys(that.items).length; i++) {
                    that.pages.push(that.items[i].choiceGroup);
                }

                $(document).ready(function () {
                    that.$el.html(that.template({
                        items: that.items,
                        keySet: [],
                        pages: that.pages
                    }));
                    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();
                        }
                    });

                    var options = {
                        width: 8,
                        height: 12,
                        cellHeight: 49,
                        verticalMargin: 1,
                        alwaysShowResizeHandle: true,
                        disableOneColumnMode: true,
                        removable: false,
                        locked: true,
                    };
                    $('.grid-stack').gridstack(options);
                    $('.grid-stack').on('dragstart', function(event, ui) {
                        var grid = this;
                        var element = event.target;
                        element.dataset.changed = true;
                        that.$el.find('.floating-menu').hide();
                    });

                    that.grid = that.$el.find('.grid-stack').data('gridstack');

                    if (Object.keys(that.items).length == 0) {
                        that.formModal = that.$el.find('#pos-key-form-modal').modal();
                        that.formModal.modal('open');
                        $('#item-form-modal').hide();
                        $('#label-form-modal').hide();
            
                        var itemSearch = document.getElementById('itemSearch');
                        itemSearch.value = "";
                        var itemText = document.getElementById('itemText');
                        itemText.value = "";
                        var label = document.getElementById('label');
                        label.value = "";

                        var newPageModal = that.$el.find('#new-page-form-modal').modal();
                        newPageModal.modal('open');
                    }
                    else {
                        for (var i = 0; i < Object.keys(that.items).length; i++) {
                            if (i == 0 && that.items[i].pageArray[0] != null) {
                                for (var j = 0; j < that.items[i].pageArray[0].length; j++) {
                                    var item =  that.items[i].pageArray[0][j];
                                    var maxAllowed = item.maxAllowed;
                                    var minRequired = item.minRequired;

                                    var node = {
                                        x: item.column - 1,
                                        y: item.row - 1,
                                        width: item.wide,
                                        height: item.high,
                                    };
                                    

                                    var widget = $('<div>');
                                    var widgetContent = $('<div class="grid-stack-item-content valign-wrapper" id="' + item.id +'">');
                                    
                                        
                                    $(widgetContent).css('display', 'flex');
                                    $(widgetContent).css('justify-content', 'center');
                                    $(widgetContent).css('border', '1px solid #555');
                                    $(widgetContent).css('font-size', '0.8rem');
                                    
                                    if (item.imageName == "posBtn01") {
                                        $(widgetContent).css('background-color', '#E2E3E2');
                                    }
                                    else if (item.imageName == "posBtn02") {
                                        $(widgetContent).css('background-color', '#4ABD98');
                                    }
                                    else if (item.imageName == "posBtn03") {
                                        $(widgetContent).css('background-color', '#A4D391');
                                    }
                                    else if (item.imageName == "posBtn04") {
                                        $(widgetContent).css('background-color', '#F6F3B0');
                                    }
                                    else if (item.imageName == "posBtn05") {
                                        $(widgetContent).css('background-color', '#F1AFAF');
                                    }
                                    else if (item.imageName == "posBtn06") {
                                        $(widgetContent).css('background-color', '#DEBEDB');
                                    }
                                    else if (item.imageName == "posBtn07") {
                                        $(widgetContent).css('background-color', '#B4B3DF');
                                    }
                                    else if (item.imageName == "posBtn08") {
                                        $(widgetContent).css('background-color', '#97CAEB');
                                    }
                                    else if (item.imageName == "posBtn09") {
                                        $(widgetContent).css('background-color', '#252525');
                                        $(widgetContent).css('color', '#ffffff');
                                    }
                                    else {
                                        $(widgetContent).css('background-color', '#ffffff');
                                    }
        
                                    $(widgetContent).html(item.text);
                                    
                                    $(widget).attr("data-gs-locked", "yes");
                                    //$(widget).attr("data-gs-max-width", 2);
                                    $(widget).attr("data-gs-max-height", 11);
                                    $(widget).attr("data-id", item.id);
                                    $(widget).attr("data-name", item.text);
                                    $(widget).append(widgetContent);
                                    if (node.x >= 6 && node.width > 1) {
                                        if (node.x > 6) {
        
                                        }
                                        else {
                                            that.grid.addWidget($(widget), node.x, node.y, node.width, node.height);
                                        }
                                    }
                                    else {
                                        that.grid.addWidget($(widget), node.x, node.y, node.width, node.height); 
                                    }
                                    
                                }
                                
                                $('#maxAllowed').val(maxAllowed);
                                $('#minRequired').val(minRequired);
                            }
                        };
                    }
                    
                        that.gridInit = false;
        
                    $('select').formSelect();
                    that.editModal = that.$el.find('#pos-key-edit-modal').modal();
                    that.deleteModal = that.$el.find('#pos-key-delete-modal').modal();
                });
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Occured a problem while rendering this page{/Literal}' });
                }
            }
        });
        
        App.breadCrumbToolTip = "Create, manage, and edit your Choice Group keys"
        App.setBreadcrumbs(this.breadcrumb);
        return this;
    },

    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,
            lmit: 20,
            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].itemCode + ' / ' + results[i].itemDescription] = null;
                    that.itemMapping[results[i].itemCode + ' / ' + results[i].itemDescription] = 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];
                let description = Object.entries(that.itemMapping)[i][0];
                description = description.replace(itemId.value + ' / ', '');
                itemDesc.value = description;
            }
        }
    },

    /*-----------------------------------------------------------------------------------------------------------------------------------------*/
    changeIndividualPage: function() {
        var that = this;
        var choiceGroup = this.$el.find('#page-selector option:selected').text(); 
        var page = this.$el.find('#individual-page-selector option:selected').text(); 

        var options = {
            width: 7,
            height: 11,
            cellHeight: 49,
            verticalMargin: 1,
            alwaysShowResizeHandle: true,
            disableOneColumnMode: true,
            removable: false,
            locked: true,
        };
        $('.grid-stack').gridstack(options);
        $('.grid-stack').on('dragstart', function(event, ui) {
            var grid = this;
            var element = event.target;
            element.dataset.changed = true;
            that.$el.find('.floating-menu').hide();
        });


        grid = $('.grid-stack').data('gridstack');
        grid.removeAll();
        var maxAllowed = 0;
        var minRequired = 0;

        for (var t = 0; t <  Object.keys(that.items).length; t++) {
            if (that.items[t].choiceGroup == choiceGroup) {
                for (var j = 0; j < that.items[t].pageArray.length; j++) {
                    if (j == (page - 1) && that.items[t].pageArray[j] != null) {
                        for (var i = 0; i < that.items[t].pageArray[j].length; i++) {
                            var item = that.items[t].pageArray[j][i];
                            var node = {
                                x: item.column - 1,
                                y: item.row - 1,
                                width: item.wide,
                                height: item.high,
                            };
                                    
                            var widget = $('<div>');
                            var widgetContent = $('<div class="grid-stack-item-content valign-wrapper" id="' + item.id +'">');
        
                            $(widgetContent).css('display', 'flex');
                            $(widgetContent).css('justify-content', 'center');
                            $(widgetContent).css('border', '1px solid #555');
                            $(widgetContent).css('font-size', '0.8rem');
                            
                            if (item.imageName == "posBtn01") {
                                $(widgetContent).css('background-color', '#E2E3E2');
                            }
                            else if (item.imageName == "posBtn02") {
                                $(widgetContent).css('background-color', '#4ABD98');
                            }
                            else if (item.imageName == "posBtn03") {
                                $(widgetContent).css('background-color', '#A4D391');
                            }
                            else if (item.imageName == "posBtn04") {
                                $(widgetContent).css('background-color', '#F6F3B0');
                            }
                            else if (item.imageName == "posBtn05") {
                                $(widgetContent).css('background-color', '#F1AFAF');
                            }
                            else if (item.imageName == "posBtn06") {
                                $(widgetContent).css('background-color', '#DEBEDB');
                            }
                            else if (item.imageName == "posBtn07") {
                                $(widgetContent).css('background-color', '#B4B3DF');
                            }
                            else if (item.imageName == "posBtn08") {
                                $(widgetContent).css('background-color', '#97CAEB');
                            }
                            else if (item.imageName == "posBtn09") {
                                $(widgetContent).css('background-color', '#252525');
                                $(widgetContent).css('color', '#ffffff');
                            }
                            else {
                                $(widgetContent).css('background-color', '#ffffff');
                            }
        
                            $(widgetContent).html(item.text);
                            
                            $(widget).attr("data-gs-locked", "yes");
                            //$(widget).attr("data-gs-max-width", 2);
                            $(widget).attr("data-gs-max-height", 11);
                            $(widget).attr("data-id", item.id);
                            $(widget).attr("data-name", item.text);
                            $(widget).append(widgetContent);
                            if (node.x >= 6 && node.width > 1) {
                                if (node.x > 6) {

                                }
                                else {
                                    that.grid.addWidget($(widget), node.x, node.y, node.width, node.height);
                                }
                            }
                            else {
                                that.grid.addWidget($(widget), node.x, node.y, node.width, node.height); 
                            }
                        }
                        minRequired = item.minRequired;
                        maxAllowed = item.maxAllowed;
                        break;
                    }
                }
                break;
            }
        }

        $('#maxAllowed').val(maxAllowed);
        $('#minRequired').val(minRequired);
    },

    changePage: function () {
        var that = this;
        var choiceGroup = this.$el.find('#page-selector option:selected').text(); 
        var page = this.$el.find('#individual-page-selector option:selected').text(); 


        var options = {
            width: 7,
            height: 11,
            cellHeight: 49,
            verticalMargin: 1,
            alwaysShowResizeHandle: true,
            disableOneColumnMode: true,
            removable: false,
            locked: true,
        };
        $('.grid-stack').gridstack(options);
        $('.grid-stack').on('dragstart', function(event, ui) {
            var grid = this;
            var element = event.target;
            element.dataset.changed = true;
            that.$el.find('.floating-menu').hide();
        });


        grid = $('.grid-stack').data('gridstack');
        grid.removeAll();
        var maxAllowed = 0;
        var minRequired = 0;

        for (var t = 0; t <  Object.keys(that.items).length; t++) {
            if (that.items[t].choiceGroup == choiceGroup) {
                for (var j = 0; j < that.items[t].pageArray.length; j++) {
                    if (j == (page - 1) && that.items[t].pageArray[j] != null) {
                        for (var i = 0; i < that.items[t].pageArray[j].length; i++) {
                            var item = that.items[t].pageArray[j][i];
                            var node = {
                                x: item.column - 1,
                                y: item.row - 1,
                                width: item.wide,
                                height: item.high,
                            };
                        
                            var widget = $('<div>');
                            var widgetContent = $('<div class="grid-stack-item-content valign-wrapper" id="' + item.id +'">');

                            $(widgetContent).css('display', 'flex');
                            $(widgetContent).css('justify-content', 'center');
                            $(widgetContent).css('border', '1px solid #555');
                            $(widgetContent).css('font-size', '0.8rem');
                            
                            if (item.imageName == "posBtn01") {
                                $(widgetContent).css('background-color', '#E2E3E2');
                            }
                            else if (item.imageName == "posBtn02") {
                                $(widgetContent).css('background-color', '#4ABD98');
                            }
                            else if (item.imageName == "posBtn03") {
                                $(widgetContent).css('background-color', '#A4D391');
                            }
                            else if (item.imageName == "posBtn04") {
                                $(widgetContent).css('background-color', '#F6F3B0');
                            }
                            else if (item.imageName == "posBtn05") {
                                $(widgetContent).css('background-color', '#F1AFAF');
                            }
                            else if (item.imageName == "posBtn06") {
                                $(widgetContent).css('background-color', '#DEBEDB');
                            }
                            else if (item.imageName == "posBtn07") {
                                $(widgetContent).css('background-color', '#B4B3DF');
                            }
                            else if (item.imageName == "posBtn08") {
                                $(widgetContent).css('background-color', '#97CAEB');
                            }
                            else if (item.imageName == "posBtn09") {
                                $(widgetContent).css('background-color', '#252525');
                                $(widgetContent).css('color', '#ffffff');
                            }
                            else {
                                $(widgetContent).css('background-color', '#ffffff');
                            }

                            $(widgetContent).html(item.text);
                            
                            $(widget).attr("data-gs-locked", "yes");
                            //$(widget).attr("data-gs-max-width", 2);
                           $(widget).attr("data-gs-max-height", 11);
                            $(widget).attr("data-id", item.id);
                            $(widget).attr("data-name", item.text);
                            $(widget).append(widgetContent);
                            if (node.x >= 6 && node.width > 1) {
                                if (node.x > 6) {

                                }
                                else {
                                    that.grid.addWidget($(widget), node.x, node.y, node.width, node.height);
                                }
                            }
                            else {
                                that.grid.addWidget($(widget), node.x, node.y, node.width, node.height); 
                            }
                        }
                        minRequired = item.minRequired;
                        maxAllowed = item.maxAllowed;
                        break;
                    }
                };
                break;
            }
        }

        
        $('#maxAllowed').val(maxAllowed);
        $('#minRequired').val(minRequired);
    },
    
    chooseItemCard: function (e) {
        var itemSearch = this.$el.find('#itemSearch').val();
        var itemText = this.$el.find('#itemText').val();
        var minRequired = this.$el.find('#minRequired').val();
        var maxAllowed = this.$el.find('#maxAllowed').val();

        if (itemSearch != null && itemSearch != '' && itemText != '' && itemText != null) { 
            var grid = $('.grid-stack').data('gridstack');
            var widget = $('<div>');
            var widgetContent = $('<div>');
            $(widgetContent)
                .addClass("grid-stack-item-content")
                .addClass('valign-wrapper');
            $(widgetContent).css('display', 'flex');
            $(widgetContent).css('justify-content', 'center');
            $(widgetContent).css('border', '1px solid #555');
            $(widgetContent).css('font-size', '0.8rem');
            $(widgetContent).css('color', 'black');
            $(widgetContent).css('background-color', 'rgb(226,227,226)');

            $(widgetContent).html(itemText);
            $(widget).attr("data-gs-locked", true);
            //$(widget).attr("data-gs-max-width", 2);
            $(widget).attr("data-gs-max-height", 11);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", itemText);
            $(widget).append(widgetContent);
            if (App.serverInfo.isFoodService) {
                grid.addWidget($(widget), 1, 1, 1, 1, true);
            }
            else {
                grid.addWidget($(widget), 1, 1, 2, 1, true);
            }
            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].dataset.name == itemText) {
                   
                        var updatedModel = {
                            id: 0,
                            noRepeat: true,
                            text: itemText,
                            display: itemSearch,
                            order: 0,
                            itemCode: itemSearch,
                            cr: true,
                            lastChoice: true,
                            row: grid.grid.nodes[i].y + 1,
                            column: grid.grid.nodes[i].x + 1,
                            wide: 1,
                            high: 1,
                            imageName: "posBtn01",
                            noSync: false,
                            minRequired: minRequired,
                            maxAllowed: maxAllowed
                        }
                   
                    this.addNewPosKey(updatedModel)
        
                    $('#pos-key-form-modal').modal().modal('close');
                }
            }
        }
        else {
            M.toast({ html: '{Literal}A button name and item are required{/Literal}' });
        }
    },

    choosePageLabel: function () {
        var that = this;
        var label = this.$el.find('#label').val();
        var minRequired = this.$el.find('#minRequired').val();
        var maxAllowed = this.$el.find('#maxAllowed').val();

        if (label != null && label != '' && label != undefined) { 
            $('#pos-key-form-modal').modal().modal('close');
            var grid = $('.grid-stack').data('gridstack');
            var widget = $('<div>');
            var widgetContent = $('<div>');
            $(widgetContent)
                .addClass("grid-stack-item-content")
                .addClass("gray")
                .addClass('valign-wrapper');
            $(widgetContent).css('display', 'flex');
            $(widgetContent).css('justify-content', 'center');
            $(widgetContent).css('border', '1px solid #555');
            $(widgetContent).css('font-size', '0.8rem');
            $(widgetContent).css('color', 'black');
            $(widgetContent).css('background-color', 'rgb(226,227,226)');

            $(widgetContent).html(label);
            $(widget).attr("data-gs-locked", true);
            //$(widget).attr("data-gs-max-width", 2);
            $(widget).attr("data-gs-max-height", 11);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", label);
            $(widget).append(widgetContent);
            if (App.serverInfo.isFoodService) {
                grid.addWidget($(widget), 1, 1, 1, 1, true);
            }
            else {
                grid.addWidget($(widget), 1, 1, 2, 1, true);
            }

            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].dataset.name == label) {
                    
                    var updatedModel = {
                        id: 0,
                        noRepeat: true,
                        text: label,
                        display: label,
                        order: 0,
                        itemCode: "",
                        cr: true,
                        lastChoice: true,
                        row: grid.grid.nodes[i].y - 1,
                        column: grid.grid.nodes[i].x + 1,
                        wide: 1,
                        high: 1,
                        imageName: "posBtn01",
                        noSync: false,
                        minRequired: minRequired,
                        maxAllowed: maxAllowed
                    }
                    if (this.grid.grid.nodes[i].y <= 1) {
                        updatedModel.row = grid.grid.nodes[i].y + 1;
                    }
                    this.addNewPosKey(updatedModel)
                    break;
                }
            }
        }
        else {
            M.toast({ html: '{Literal}Please enter text name{/Literal}' });
        }
    },

    addNewPosKey: function (updatedModel) {
        var that = this;
        var sessionToken = this.getCookie();
        var choiceGroup = this.$el.find('#page-selector option:selected').text();
        var page = this.$el.find('#individual-page-selector option:selected').text();
        var savePage = this.$el.find('#page-selector option:selected').text(); 
        var saveIndividualPage = this.$el.find('#individual-page-selector option:selected').text();
        var minRequired = this.$el.find('#minRequired').val();
        var maxAllowed = this.$el.find('#maxAllowed').val();

        $.ajax({
            url: '/data/add-choice-key',
            data: {
                choiceKey: JSON.stringify(updatedModel),
                choiceGroup: choiceGroup,
                page: page,
                token: sessionToken,
                minRequired: minRequired,
                maxAllowed: maxAllowed
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                var grid = $('.grid-stack').data('gridstack');

                for (var i = 0; i < grid.grid.nodes.length; i++)
                {
                    if (grid.grid.nodes[i].el[0].innerText == updatedModel.text) {
                           
                        $(grid.grid.nodes[i].el[0]).attr('data-id', '' + data.id)
                        $(grid.grid.nodes[i].el[0]).attr('id', '' + data.id)
                        grid.grid.nodes[i].id = data.id;
                    }
                }
                that.grid = grid;
                updatedModel.id = data.id;

                for (var i = 0; i < Object.keys(that.items).length; i++) {
                    if (that.items[i].choiceGroup == savePage) {
                        for (var j = 0; j < that.items[i].pageArray.length; j++) {
                            if (j == saveIndividualPage - 1 ) {
                                that.items[i].pageArray[j].push(updatedModel);
                                break;
                            }
                        }
                        break;
                    } 
                }
                that.addedKey = updatedModel;
                M.toast({ html: '{Literal}Choice Key added 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 Choixw Key{/Literal}.' });
                }
            }
        });
        
    },

    deleteKey: function (e) {
        var that = this;
        var page = this.$el.find('#page-selector option:selected').text(); 
        var individualPage = this.$el.find('#individual-page-selector option:selected').text();
        var sessionToken = this.getCookie();

        for (var i = 0; i < Object.keys(that.items).length; i++) {
            if (that.items[i].choiceGroup == page) {
                for (var j = 0; j < that.items[i].pageArray.length; j++) {
                    if (j == individualPage - 1 ) {
                        for (var t = 0; t < that.items[i].pageArray[j].length; t++) {
                            if (that.items[i].pageArray[j][t].id == this.chosenKeyId) {
                                this.chosenKey = that.items[i].pageArray[j][t];
                                that.items[i].pageArray[j].splice(t,1);
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            } 
        }

        var grid = that.grid;
        for (var i = 0; i < that.grid.grid.nodes.length; i ++) {
            var chosenId = $(grid.grid.nodes[i].el[0]).attr('data-id');
            if (chosenId == 0) {
                chosenId = grid.grid.nodes[i].el[0].id;
            }
            if (that.chosenKey.id == chosenId) {
                el = $(grid.grid.nodes[i].el)
                grid.removeWidget(el);
                break;
            }
        }
        
        $.ajax({
            url: '/data/remove-choice-key',
            data: {
                buttonId: (that.chosenKeyId),
                choiceGroup: page,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {

                M.toast({ html: '{Literal}Choice Key removed 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 deleting this Choice 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 Choice Group is already defined{/Literal}' });
            }
            else {
                that.pages.push(menuPage);  
                this.render();
            }
        }
        else {
            M.toast({ html: '{Literal}Please enter a valid Choice Group 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');
    },

    saveNewPage: function () {
        var that = this;
        var sessionToken = this.getCookie();
        var newPageName = this.$el.find('#newPageName').val();
        var minRequired = this.$el.find('#minRequired').val();
        var maxAllowed = this.$el.find('#maxAllowed').val();

        if (newPageName == "") {
            M.toast({ html: '{Literal}A Choice Group 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 Choice Group Name Is Already Defined{/Literal}' });
            }
            else {
                this.pages.unshift(newPageName);

                var updatedModal = {
                    id: 0,
                    noRepeat: true,
                    text: "New Button",
                    display: 'New Button',
                    order: 0,
                    itemCode: "",
                    cr: true,
                    lastChoice: true,
                    row: 3,
                    column: 1,
                    wide: 1,
                    high: 1,
                    imageName: "posBtn01",
                    noSync: false,
                }

                $.ajax({
                    url: '/data/add-choice-key',
                    data: {
                        choiceKey: JSON.stringify(updatedModal),
                        choiceGroup: newPageName,
                        page: 1, //TODO
                        token: sessionToken,
                        minRequired: minRequired,
                        maxAllowed: maxAllowed
                    },
                    dataType: 'json',
                    type: 'POST',
        
                    success: function (data) {
                        M.toast({ html: '{Literal}Page 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 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();
        
        $.ajax({
            url: '/data/rename-choice-group',
            data: {
                oldChoiceGroup: currentPage,
                newChoiceGroup: (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 <  Object.keys(that.items).length; i++) {
                    if (that.items[i].choiceGroup == currentPage) {
                        that.items[i].choiceGroup = newPageName;
                    }
                }
                that.render();
                M.toast({ html: '{Literal}Choice Group 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 Choice Group{/Literal}' });
                }
            }
        });
    },

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

        if ($('#labelForm').is(":visible")) {
            var labelButtonText = this.$el.find('#labelButtonText').val();
            if (labelButtonText.indexOf(',') > 0) {
                labelButtonText = labelButtonText.replace(',', "&com;");
            }
            var pizzaType = document.getElementById('pizzaType').value;
            if(pizzaType != '') {
                labelButtonText = pizzaType + labelButtonText + pizzaType;
            }

            var labelBlue = this.$el.find('#labelBlue:checked').length > 0;
            var labelGray = this.$el.find('#labelGray:checked').length > 0;
            var labelGreen = this.$el.find('#labelGreen:checked').length > 0;
            var labelOrange = this.$el.find('#labelOrange:checked').length > 0;
            var labelPink = this.$el.find('#labelPink:checked').length > 0;
            var labelPurple = this.$el.find('#labelPurple:checked').length > 0;
            var labelRed = this.$el.find('#labelRed:checked').length > 0;
            var labelTeal = this.$el.find('#labelTeal:checked').length > 0;
            var labelYellow = this.$el.find('#labelYellow:checked').length > 0;

            var cr = this.$el.find('.crLabel:checked').length > 0;
            var noRepeat = this.$el.find('.noRepeatLabel:checked').length > 0;
            var lastChoice = this.$el.find('.lastChoiceLabel:checked').length > 0;

            var minRequired = this.$el.find('#minRequired').val();
            var maxAllowed = this.$el.find('#maxAllowed').val();

            if (labelBlue) {
                this.chosenKey.imageName = 'posBtn08';
            }
            else if (labelGray) {
                this.chosenKey.imageName = 'posBtn01';
            }
            else if (labelGreen) {
                this.chosenKey.imageName = 'posBtn03';
            }
            else if (labelOrange) {
                this.chosenKey.imageName = 'posBtn09';
                this.chosenKey.textColor = "White";
            }
            else if (labelPink) {
                this.chosenKey.imageName = 'posBtn06';
            }
            else if (labelPurple) {
                this.chosenKey.imageName = 'posBtn07';
            }
            else if (labelRed) {
                this.chosenKey.imageName = 'posBtn05';
            }
            else if (labelTeal) {
                this.chosenKey.imageName = 'posBtn02';
            }
            else if (labelYellow) {
                this.chosenKey.imageName = 'posBtn04';
            }

            var updatedModal = {
                id: this.chosenKey.id,
                noRepeat: noRepeat,
                text: labelButtonText,
                display: labelButtonText,
                order: this.chosenKey.order,
                itemCode: "",
                cr: cr,
                lastChoice: lastChoice,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                wide: this.chosenKey.wide,
                high: this.chosenKey.high,
                imageName: this.chosenKey.imageName,
                noSync: this.chosenKey.noSync,
                maxAllowed: maxAllowed,
                minRequired: minRequired
            }

            this.chosenKey = updatedModal;

            await this.editPosKey();
        }
        else if ($('#itemForm').is(":visible")) {
            var labelButtonText = this.$el.find('#itemButtonText').val();
            if (labelButtonText.indexOf(',') > 0) {
                labelButtonText = labelButtonText.replace(',', "&com;");
            }
            var cr = this.$el.find('.cr:checked').length > 0;
            var noRepeat = this.$el.find('.noRepeat:checked').length > 0;
            var lastChoice = this.$el.find('.lastChoice:checked').length > 0;

            var itemBlue = this.$el.find('#itemBlue:checked').length > 0;
            var itemGray = this.$el.find('#itemGray:checked').length > 0;
            var itemGreen = this.$el.find('#itemGreen:checked').length > 0;
            var itemOrange = this.$el.find('#itemOrange:checked').length > 0;
            var itemPink = this.$el.find('#itemPink:checked').length > 0;
            var itemPurple = this.$el.find('#itemPurple:checked').length > 0;
            var itemRed = this.$el.find('#itemRed:checked').length > 0;
            var itemTeal = this.$el.find('#itemTeal:checked').length > 0;
            var itemYellow = this.$el.find('#itemYellow:checked').length > 0;

            if (itemBlue) {
                this.chosenKey.imageName = 'posBtn08';
            }
            else if (itemGray) {
                this.chosenKey.imageName = 'posBtn01';
            }
            else if (itemGreen) {
                this.chosenKey.imageName = 'posBtn03';
            }
            else if (itemOrange) {
                this.chosenKey.imageName = 'posBtn09';
                this.chosenKey.textColor = "White";
            }
            else if (itemPink) {
                this.chosenKey.imageName = 'posBtn06';
            }
            else if (itemPurple) {
                this.chosenKey.imageName = 'posBtn07';
            }
            else if (itemRed) {
                this.chosenKey.imageName = 'posBtn05';
            }
            else if (itemTeal) {
                this.chosenKey.imageName = 'posBtn02';
            }
            else if (itemYellow) {
                this.chosenKey.imageName = 'posBtn04';
            }

            var updatedModal = {
                id: this.chosenKey.id,
                noRepeat: noRepeat,
                text: labelButtonText,
                display: this.chosenKey.display,
                order: this.chosenKey.order,
                itemCode: this.chosenKey.itemCode,
                cr: cr,
                lastChoice: lastChoice,
                row: this.chosenKey.row,
                column: this.chosenKey.column,
                wide: this.chosenKey.wide,
                high: this.chosenKey.high,
                imageName: this.chosenKey.imageName,
                noSync: this.chosenKey.noSync,
                maxAllowed: maxAllowed,
                minRequired: minRequired
            }

            this.chosenKey = updatedModal;

            await this.editPosKey();
        }

        var grid = that.grid;
        for (var i = 0; i < that.grid.grid.nodes.length; i ++) {
            var chosenId = $(grid.grid.nodes[i].el[0]).attr('data-id');
            if (chosenId == 0) {
                chosenId = grid.grid.nodes[i].id;
            }
            
            if (that.chosenKey.id == chosenId) {
                if (that.chosenKey.id == that.addedKey.id) {
                    var chosenWidget = $('#'+ that.chosenKey.id)[0].children[0]; 
                }
                else {
                    var chosenWidget = $('#'+ that.chosenKey.id)[0];       
                }

                if (labelButtonText.indexOf('&com;') > 0) {
                    labelButtonText = labelButtonText.replace('&com;', ",");
                }
                
                $(chosenWidget).text(labelButtonText)

                if (that.chosenKey.imageName == "posBtn01") {
                    $(chosenWidget).css({
                        'background-color': '#E2E3E2 !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn02") {
                    $(chosenWidget).css({
                        'background-color': '#4ABD98 !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn03") {
                    $(chosenWidget).css({
                        'background-color': '#A4D391 !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn04") {
                    $(chosenWidget).css({
                        'background-color': '#F6F3B0 !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn05") {
                    $(chosenWidget).css({
                        'background-color': '#F1AFAF !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn06") {
                    $(chosenWidget).css({
                        'background-color': '#DEBEDB !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn07") {
                    $(chosenWidget).css({
                        'background-color': '#B4B3DF !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn08") {
                    $(chosenWidget).css({
                        'background-color': '#97CAEB !important'
                    });
                }
                else if (that.chosenKey.imageName == "posBtn09") {
                    $(chosenWidget).css({
                        'background-color': '#252525 !important',
                        'color': '#ffffff'
                    });
                }
                else {
                    $(chosenWidget).css({
                        'background-color': '#ffffff !important'
                    });
                }
                
            }
        }
    },
    
    editPosKey: function () {
        var that = this;
        var sessionToken = this.getCookie();
        var choiceGroup = this.$el.find('#page-selector option:selected').text();
        var page = this.$el.find('#individual-page-selector option:selected').text();
        var individualPage = this.$el.find('#individual-page-selector option:selected').text();
        var minRequired = this.$el.find('#minRequired').val();
        var maxAllowed = this.$el.find('#maxAllowed').val();

        $.ajax({
            url: '/data/add-choice-key',
            data: {
                choiceKey: JSON.stringify(that.chosenKey),
                choiceGroup: choiceGroup,
                page: page,
                token: sessionToken,
                minRequired: minRequired,
                maxAllowed: maxAllowed
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                M.toast({ html: '{Literal}Choice Key added successfully{/Literal}' });
                
                if (that.chosenKey.text.indexOf('&com;') > 0) {
                    that.chosenKey.text = that.chosenKey.text.replace('&com;', ",");
                }
                console.log(that.chosenKey);
                for (var i = 0; i < Object.keys(that.items).length; i++) {
                    if (that.items[i].choiceGroup == choiceGroup) {
                        for (var j = 0; j < that.items[i].pageArray.length; j++) {
                            if (j == individualPage - 1 ) {
                                for (var t = 0; t < that.items[i].pageArray[j].length; t++) {
                                    if (that.items[i].pageArray[j][t].id == that.chosenKeyId) {
                                        that.items[i].pageArray[j][t] = that.chosenKey;
                                        
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                        break;
                    } 
                }


                for (var i = 0; i <  Object.keys(that.items).length; i++) {
                    if (choiceGroup == that.items[i].choiceGroup) {
                        for (var j = 0; j < that.items[i].choiceKeys.length; j++) {
                            if (that.items[i].choiceKeys[j].id == that.chosenKey.id) {
                                that.items[i].choiceKeys[j] = that.chosenKey
                                break;
                            }
                        }
                        break;
                    }
                    
                }

            },

            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 Choice Key{/Literal}.' });
                }
            }
        });
    },

    saveKeys: function () {
        var that = this;
        var sessionToken = this.getCookie();
        grid = this.grid;
        var minRequired = this.$el.find('#minRequired').val();
        var maxAllowed = this.$el.find('#maxAllowed').val();
        var updatedPageModels = {};
        
        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

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

        for (var i = 0; i < this.grid.grid.nodes.length; i++) {
            for (var j = 0; j < Object.size(this.items); j++) {
                var chosenId = $(grid.grid.nodes[i].el[0]).attr('data-id');
                if (chosenId == 0) {
                    chosenId = grid.grid.nodes[i].id;
                }
                if (this.items[j].choiceGroup == choiceGroup) {
                    for (var t = 0; t < this.items[j].pageArray.length; t++) {
                        if (t == (page - 1)) {
                            for (var m = 0; m < that.items[j].pageArray[t].length; m++) {
                                if (chosenId == this.items[j].pageArray[t][m].id) {
                                    if($(grid.grid.nodes[i].el[0]).attr('data-changed') == 'true') {

                                        this.items[j].pageArray[t][m].column = this.grid.grid.nodes[i].x + 1;
                                        this.items[j].pageArray[t][m].row = this.grid.grid.nodes[i].y + 1;
                                        
                                        this.items[j].pageArray[t][m].high = this.grid.grid.nodes[i].height;
                                        this.items[j].pageArray[t][m].wide = this.grid.grid.nodes[i].width;
                                        updatedPageModels[Object.size(updatedPageModels)] =  this.items[j].pageArray[t][m];
                                    }
                                }
                            }
                        }
                    }
                    break;
                }
            }
        }

        var keysSent = 0;

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };
        var len = Object.size(updatedPageModels);
        for (var t = 0; t < len; t++) {
            var choiceKey = JSON.stringify(updatedPageModels[t]);
            choiceKey = JSON.parse(choiceKey);
            choiceKey.item = {};

            $.ajax({
                url: '/data/add-choice-key',
                data: {
                    choiceKey: JSON.stringify(choiceKey),
                    choiceGroup: choiceGroup,
                    page: page, //TODO
                    token: sessionToken,
                    minRequired: minRequired,
                    maxAllowed: maxAllowed
                },
                dataType: 'json',
                type: 'POST',
                
                success: function (data) {
                    keysSent++;

                    if (keysSent == Object.size(updatedPageModels) - 1 || Object.size(updatedPageModels) == 1) {
                        M.toast({ html: '{Literal}Menu Page save successfully{/Literal}' });

                        var changedEl = document.querySelectorAll('.grid-stack-item.ui-draggable[data-changed="true"');
                        changedEl.forEach(element => {
                            element.dataset.changed = false;
                        });
                    }
                },

                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}.' });
                        var changedEl = document.querySelectorAll('.grid-stack-item.ui-draggable[data-changed="true"');
                        changedEl.forEach(element => {
                            element.dataset.changed = false;
                        });
                    }
                }
            });
        }
    },

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


    openEditModal: function (e) {
        var that = this;
        var page = this.$el.find('#page-selector option:selected').text(); 
        var individualPage = this.$el.find('#individual-page-selector option:selected').text(); 
        var element = $(e.currentTarget);
        var parent = $(element).parent();
        //var chosenId = $(parent).attr('data-id');
        //var chosenId = $.attr('data-id');(grid.grid.nodes[i].el[0])

        for (var i = 0; i < Object.keys(that.items).length; i++) {
            if (that.items[i].choiceGroup == page) {
                for (var j = 0; j < that.items[i].pageArray.length; j++) {
                    if (j == individualPage - 1 ) {
                        for (var t = 0; t < that.items[i].pageArray[j].length; t++) {
                            if (that.items[i].pageArray[j][t].id == this.chosenKeyId) {
                                this.chosenKey = that.items[i].pageArray[j][t];
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            } 
        }

        $('#itemForm').hide();
        $('#labelForm').hide();
        if (this.chosenKey.itemCode != "") {
            var itemVal = document.getElementById('itemButtonText');
            itemVal.value = this.chosenKey.text;

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

            $('.cr').prop('checked', this.chosenKey.cr);
            $('.noRepeat').prop('checked', this.chosenKey.noRepeat);
            $('.lastChoice').prop('checked', this.chosenKey.lastChoice);
          

            if (this.chosenKey.imageName == "posBtn01") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', true);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn02") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', true);
                $('#itemYellow').prop('checked', false);

            }
            else if (this.chosenKey.imageName == "posBtn03") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', true);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn04") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', true);
            }
            else if (this.chosenKey.imageName == "posBtn05") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', true);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn06") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', true);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn07") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', true);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn08") {
                $('#itemBlue').prop('checked', true);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', false);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn09") {
                $('#itemBlue').prop('checked', false);
                $('#itemGray').prop('checked', false);
                $('#itemGreen').prop('checked', false);
                $('#itemOrange').prop('checked', true);
                $('#itemPink').prop('checked', false);
                $('#itemPurple').prop('checked', false);
                $('#itemRed').prop('checked', false);
                $('#itemTeal').prop('checked', false);
                $('#itemYellow').prop('checked', false);
            }

            this.editModal.modal('open');
            $('#itemForm').show();
        }
        else {
            var itemVal = document.getElementById('labelButtonText');
            var pizzaType = this.getPizzaType(this.chosenKey.text);
            var pizzaTypeSelect = document.getElementById('pizzaType');
            pizzaTypeSelect.value = pizzaType;
            
            itemVal.value = this.chosenKey.text.replaceAll(pizzaType, '');

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

            $('.crLabel').prop('checked', this.chosenKey.cr);
            $('.noRepeatLabel').prop('checked', this.chosenKey.noRepeat);
            $('.lastChoiceLabel').prop('checked', this.chosenKey.lastChoice);
      

            if (this.chosenKey.imageName == "posBtn01") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', true);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn02") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', true);
                $('#labelYellow').prop('checked', false);

            }
            else if (this.chosenKey.imageName == "posBtn03") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', true);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn04") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', true);
            }
            else if (this.chosenKey.imageName == "posBtn05") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', true);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn06") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', true);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn07") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', true);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn08") {
                $('#labelBlue').prop('checked', true);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', false);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', false);
            }
            else if (this.chosenKey.imageName == "posBtn09") {
                $('#labelBlue').prop('checked', false);
                $('#labelGray').prop('checked', false);
                $('#labelGreen').prop('checked', false);
                $('#labelOrange').prop('checked', true);
                $('#labelPink').prop('checked', false);
                $('#labelPurple').prop('checked', false);
                $('#labelRed').prop('checked', false);
                $('#labelTeal').prop('checked', false);
                $('#labelYellow').prop('checked', false);
            }

            this.editModal.modal('open');
            $('#labelForm').show();
            $('select').formSelect();
        }
    },

    getPizzaType: function(value) {
        var pizzaType = '';
        if(value.startsWith('#3R#') && value.endsWith('#3R#'))
            pizzaType = '#3R#';
        else if(value.startsWith('#3S#') && value.endsWith('#3S#'))
            pizzaType = '#3S#';
        else if(value.startsWith('#') && value.endsWith('#'))
            pizzaType= '#';

        return pizzaType
    }
});