var PosKeyMobileFormView = Backbone.View.extend({
    itemsStyleMapping: {},
    itemMapping: {},
    itemMapping2: [],
    prefillState: false,
    itemsAutocomplete: {},
    events: {
        'click .select-item': 'selectItem',
        'click .cancel-items-button' : 'closeItemModal',
        'click #pagesCards' : 'choosePageCard',
        'click #keysetCards' : 'chooseKeysetCards',
        'keyup #itemSearch': 'searchItemBySearchTerm',
        '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',
    },

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.model = options.model;
        this.pages = options.pages;
        this.keyset = options.keyset;
        this.target = options.target;
        this.keys = options.keys;
        if (options.currentKeySet == "MAIN" || options.currentKeySet == "ראשי" ) {
            this.currentKeySet = "";
        }
        else {
            this.currentKeySet = options.currentKeySet;
        }
        this.currentPage = options.currentPage;
    },

    render: function () {
        var that = this;
        this.$el.detach();
        this.$el.html(this.options.template);
        $(document).ready(function() {
            $('.tooltipped').tooltip();
            $('select').formSelect();
            that.initItems(); 
        });
        $(document).on('keydown', 'input, select', function(e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
              ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select,button,select').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    form.submit();
                }
                return false;
            }
        });
        return this;
    },

    closeItemModal: function () {
        $('#pos-key-form-modal').modal().modal('close');
    },
    
    initItems:  function () {
        var fullItems = this.getItemsFull();
    },

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


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

    renderItems: function (data) {
        var that = this;
        var itemCollection = {};
        for (var i = 0; i < data.length; i++) {
            var currentItem = data[i];
            currentItem.cardStyleClass = that.itemsStyleMapping[data[i].name];
            itemCollection[i] = (currentItem);
        }
        this.editableItemCollection = itemCollection;
        this.itemFullCollection = itemCollection;
        this.$el.html(this.template({
            items: that.itemFullCollection,
            pages: that.pages,
            keyset: that.keyset,
        })); 
        $('select').formSelect();
        var elems = document.querySelector('#itemSearch');
        this.itemsAutocomplete = M.Autocomplete.init(elems, {
            minLength: 1,
            limit: 20,
            sortFunction: function (a, b, inputString) {
                return a.indexOf(inputString) - b.indexOf(inputString);
            },
        });
    },

    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] = null;
                }
                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 (e) {
        var itemSearch = this.$el.find('#itemSearch').val();

        var grid = $('.grid-stack').data('gridstack');
        var widget = $('<div>');
        var widgetContent = $('<div>');
        $(widgetContent)
            .addClass("grid-stack-item-content")
            .addClass("purple lighten-4")
            .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).html(itemSearch);
        $(widget).attr("data-gs-locked", true);
        $(widget).attr("data-gs-max-width", 4);
        $(widget).attr("data-gs-max-height", 4);
        $(widget).attr("data-id", 0);
        $(widget).attr("data-name", itemSearch);
        $(widget).append(widgetContent);
        grid.addWidget($(widget), 1, 1, 1, 1, true);
        $('#pos-key-form-modal').modal().modal('close');
    },

    choosePriceLevel: function (e) {
        var priceLevelText = this.$el.find('#priceLevelText').val();
        var priceLevel = this.$el.find('#price-level-dropdown').val();
        
        if (priceLevelText != null && priceLevelText != '' && priceLevelText != undefined) { 
            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(priceLevelText);
            $(widget).attr("data-gs-locked", true);
            $(widget).attr("data-gs-max-width", 4);
            $(widget).attr("data-gs-max-height", 4);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", priceLevelText);
            $(widget).append(widgetContent);
            grid.addWidget($(widget), 1, 1, 1, 1, true);

            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].innerText == priceLevelText) {
                    var updatedModel = {
                        id: 0,
                        name: priceLevelText,
                        row: grid.grid.nodes[i].y - 1,
                        column: grid.grid.nodes[i].x + 1,
                        width: 1,
                        height: 1,
                        imageName: 'posBtn01',
                        type: 'L',
                        text: priceLevel,
                        cr: false,
                        keysetName: this.currentKeySet,
                        page: this.currentPage,
                        noRepeat: false,
                        keyNumber: Math.floor(Math.random() * 100) + 1,
                        noSync: false,
                        isActive: true
                    }
        
                    this.addNewPosKey(updatedModel)
        
                    $('#pos-key-form-modal').modal().modal('close');
                }
            }
        }
        else {
            M.toast({ html: '{Literal}Please enter label name{/Literal}' });
        }
    },

    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 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", 4);
            $(widget).attr("data-gs-max-height", 4);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", itemText);
            $(widget).append(widgetContent);
            grid.addWidget($(widget), 1, 1, 1, 1, true);

            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].innerText == itemText) {
                    var updatedModel = {
                        id: 0,
                        name: itemText,
                        row: grid.grid.nodes[i].y - 1,
                        column: grid.grid.nodes[i].x + 1,
                        width: 1,
                        height: 1,
                        imageName: 'posBtn01',
                        type: 'I',
                        text: itemSearch,
                        cr: false,
                        keysetName: this.currentKeySet,
                        page: this.currentPage,
                        noRepeat: false,
                        keyNumber: Math.floor(Math.random() * 100) + 1,
                        noSync: false,
                        isActive: true
                    }
        
                    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 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(itemId);
        $(widget).attr("data-gs-locked", true);
        $(widget).attr("data-gs-max-width", 4);
        $(widget).attr("data-gs-max-height", 4);
        $(widget).attr("data-id", 0);
        $(widget).attr("data-name", itemId);
        $(widget).append(widgetContent);
        grid.addWidget($(widget), 1, 1, 1, 1, true);

        for (var i = 0; i < grid.grid.nodes.length; i++)
        {   
            if (grid.grid.nodes[i].el[0].innerText == itemId) {
                var updatedModel = {
                    id: 0,
                    name: itemId,
                    row: grid.grid.nodes[i].y - 1,
                    column: grid.grid.nodes[i].x + 1,
                    width: 1,
                    height: 1,
                    imageName: 'posBtn01',
                    type: 'P',
                    text: itemId,
                    cr: false,
                    keysetName: this.currentKeySet,
                    page: this.currentPage,
                    noRepeat: false,
                    keyNumber: Math.floor(Math.random() * 100) + 1,
                    noSync: false,
                    isActive: true
                }
                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) { 
            $('#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", 4);
            $(widget).attr("data-gs-max-height", 4);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", label);
            $(widget).append(widgetContent);
            grid.addWidget($(widget), 1, 1, 1, 1, true);

            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].innerText == label) {
                    
                    var updatedModel = {
                        id: 0,
                        name: label,
                        row: grid.grid.nodes[i].y - 1,
                        column: grid.grid.nodes[i].x + 1,
                        width: 1,
                        height: 1,
                        imageName: 'posBtn01',
                        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
                    }
                    console.log(updatedModel);
                    this.addNewPosKey(updatedModel)
                    break;
                }
            }
        }
        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 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(tareText);
            $(widget).attr("data-gs-locked", true);
            $(widget).attr("data-gs-max-width", 4);
            $(widget).attr("data-gs-max-height", 4);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", tareText);
            $(widget).append(widgetContent);
            grid.addWidget($(widget), 1, 1, 1, 1, true);
            
            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].innerText == tareText) {
                    var updatedModel = {
                        id: 0,
                        name: tareText,
                        row: grid.grid.nodes[i].y - 1,
                        column: grid.grid.nodes[i].x + 1,
                        width: 1,
                        height: 1,
                        imageName: 'posBtn01',
                        type: '#',
                        text: tareWeight,
                        cr: false,
                        keysetName: this.currentKeySet,
                        page: this.currentPage,
                        noRepeat: false,
                        keyNumber: Math.floor(Math.random() * 100) + 1,
                        noSync: false,
                        isActive: true
                    }
                    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}' });
        }
    },

    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 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(saleRepriceText);
            $(widget).attr("data-gs-locked", true);
            $(widget).attr("data-gs-max-width", 4);
            $(widget).attr("data-gs-max-height", 4);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", saleRepriceText);
            $(widget).append(widgetContent);
            grid.addWidget($(widget), 1, 1, 1, 1, true);

            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].innerText == saleRepriceText) {
                    var updatedModel = {
                        id: 0,
                        name: saleRepriceText,
                        row: grid.grid.nodes[i].y - 1,
                        column: grid.grid.nodes[i].x + 1,
                        width: 1,
                        height: 1,
                        imageName: 'posBtn01',
                        type: 'S',
                        text: saleRepricePercent,
                        cr: false,
                        keysetName: this.currentKeySet,
                        page: this.currentPage,
                        noRepeat: false,
                        keyNumber: Math.floor(Math.random() * 100) + 1,
                        noSync: false,
                        isActive: true
                    }
        
                    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}' });
        }
    },

    selectItem: function (e) {   
        var that = this;
        var element = $(e.currentTarget);
        var salesId = $(element).attr('data-id');
        $('#item-form-modal').modal().modal('open');
    },

    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 == "ראשי") {
                keySet = '';
            }
            
            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(keySetText);
            $(widget).attr("data-gs-locked", true);
            $(widget).attr("data-gs-max-width", 4);
            $(widget).attr("data-gs-max-height", 4);
            $(widget).attr("data-id", 0);
            $(widget).attr("data-name", keySetText);
            $(widget).append(widgetContent);
            grid.addWidget($(widget), 1, 1, 1, 1, true);

            for (var i = 0; i < grid.grid.nodes.length; i++)
            {   
                if (grid.grid.nodes[i].el[0].innerText == keySetText) {
                    var updatedModel = {
                        id: 0,
                        name: keySetText,
                        row: grid.grid.nodes[i].y - 1,
                        column: grid.grid.nodes[i].x + 1,
                        width: 1,
                        height: 1,
                        imageName: 'posBtn01',
                        type: 'k',
                        text: keySet,
                        cr: false,
                        keysetName: this.currentKeySet,
                        page: this.currentPage,
                        noRepeat: false,
                        keyNumber: Math.floor(Math.random() * 100) + 1,
                        noSync: false,
                        isActive: true
                    }
        
                    $('#pos-key-form-modal').modal().modal('close');
                    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) {
                that.keys.add(updatedModel);

                M.toast({ html: '{Literal}Menu 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 Menu Key{/Literal}.' });
                }
            }
        });
    }
});
