//SCREEN-BOILERPLATE

//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
  // Application variable, always include it to have access to app methods.
  'app',

  //templates-loader: this loads templates async.
  'js/templates-loader',
  'backgrid',
  'moment',
    'modules/modal2',

   // 'js/autocomplete/autocomplete',
  'backgrid/moment-cell',
  'js/jquery.clearsearch/jquery.clearsearch',
  'js/jstree/jstree',
    'backgrid/infinator',

    'js/autocomplete/backbone.autocomplete',
    
    'js/multiselect/virtual-select.min',
],
    function (app, T, Backgrid, moment, Modal) {
    var Screen = { Models: {}, Views: {}, Collections: {},

        SEARCH_MODE : 1, SHIFT_NAVIGATION_MODE: 2,
        MODAL_PICKER: 4, MODAL_DATA_ENTRY: 5,

    };

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {

            crews: [],
            logEntryTypes: [],
            statusCodes: [],
            shifts: [],
            users: [],

            typesSelected: [],
            statusSelected: [],

            start: new moment().subtract(5, 'days').format('MM/DD/YYYY'),
            end: new moment().format('MM/DD/YYYY'),
            crewId: '-',
            logEntryTypeId: '-',
            statusCodeId: '-',
            shiftId: '-',
            searchText: '',
            author: '',
            id: '-',
            selectedDate: new moment().format('MM/DD/YYYY HH:mm:ss'),
            selectedShift: 'D',
            userId: '-',

            itemId: '',
            itemTitle: '',
            itemMeltOrder:'',
            itemDate: new moment().format('YYYY-MM-DD'),
            itemShift: '',
            itemCrew: '',
            itemAuthor: '',
            itemDescription: '',
            itemLogEntryType: '',
            itemTime: '', 
            itemProductionDate: new moment().format('YYYY-MM-DD'),
            showShiftPickers: '',
            showDataEntryMode: '',
            currentMode: Screen.SEARCH_MODE,
            assetId: null,
            itemStatusCodeId: 2,
            equipmentTable: [],
            modalSelected: Screen.MODAL_PICKER,
        
            index: null,
            hasData: false,
            isLoading: 0,
            grid: null,
            lockTitle: true,


            itemAssetId: '',
            equipmentPickerName: '',
            equipmentDataEntryName: '',
            equipmentCodeId: null,
            equipmentCodeName: '',
            casterProcessId: '-',

        },
        initialize: function () {
            this.fetchPickers({ async: false });
        },
        changeSelectedItem: function (item) {
            if (item) {
                this.set({
                    itemTitle: item.get('title'),
                    itemMeltOrder: item.get('meltOrder'),
                    itemId: item.get('id'),
                    itemCrew: item.get('crew'),
                    itemShift: item.get('shift'),
                    itemAuthor: item.get('author'),
                    itemDate: new moment(item.get('time'), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD'),
                    itemDescription: item.get('description'),
                    itemLogEntryType: item.get('logEntryType'),
                    equipmentDataEntryName: item.get('assetName'),
                    itemStatusCodeId: item.get('statusCodeId'),
                    itemAssetId: item.get('assetId'),
                    itemTime: new moment(item.get('time'), 'YYYY-MM-DD HH:mm:ss').format('HH:mm:ss'),
                    itemProductionDate: new moment(item.get('productionDate')).format('YYYY-MM-DD'),
                });
            }
            else {
                this.set(this.defaults);
            }
        },

        fetchPickers: function (options) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                opt = _.extend({ async: true, }, options);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LogBook.GetLogBookCatalogs',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                _.each(resp.Table, function (obj) {
                                    var tableKey = 'Table' + obj.Index;
                                   
                                    if (resp.Table7) {
                                        newItems = [];
                                        _.each(resp.Table7, function (obj) {
                                            newItems.push({
                                                id: obj.AssetId,
                                                equipmentId: obj.ParentAssetId,
                                                name: obj.AssetName,
                                            });
                                            that.set('equipmentTable', newItems);
                                        });
                                    };
                                    if (resp.Table8) {
                                        that.set('statusCodes', _.map(resp.Table8, function (obj) {
                                            return {
                                                value: obj.StatusCodeId,
                                                label: obj.StatusCodeName,
                                            };
                                        }));
                                    };
                                    switch (obj.Name) {
                                       case 'CREWS':
                                            that.set('crews', _.map(resp[tableKey], function (obj) {
                                                return {
                                                    value: obj.Crew,
                                                    label: obj.Crew,
                                                };
                                            }));
                                            break;
                                        case 'SHIFTS':
                                            that.set('shifts', _.map(resp[tableKey], function (obj) {
                                                return {
                                                    value: obj.Shift,
                                                    label: obj.Shift,
                                                };
                                            }));
                                            break;

                                        case 'LOGENTRYTYPES':
                                            that.set('logEntryTypes', _.map(resp[tableKey], function (obj) {
                                                return {
                                                    value: obj.LogEntryTypeId,
                                                    label: obj.LogEntryTypeName,
                                                };
                                            }));
                                            break;
                                        //case 'EQUIPMENTS':
                                        //    newItems = [];
                                        //    _.each(resp[tableKey], function (obj) {
                                        //            newItems.push({
                                        //                id: obj.Id,
                                        //                equipmentId: obj.EquipmentId,
                                        //                name: obj.EquipmentName,
                                        //        });
                                        //        that.set('equipmentTable', newItems);
                                        //    });
                                        //break;
                                        case 'USERS':
                                            that.set('users', _.map(resp[tableKey], function (obj) {
                                                return {
                                                    name: obj.Author,
                                                };
                                            }));
                                        break;
                                      
                                    }
                                });
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(new Error(resp.Message).stack);
                                else
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: opt.async,
                },
                app.ConnectionStrings.app
            );

            return this;
        },


    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.refreshbtn
            return 'casting-log-book';
        } catch (Error) { }
    }
    Screen.Models.Users = Backbone.Model.extend({
        label: function () {
            return this.get("name");
        }
    });

    Screen.Collections.Users = Backbone.Collection.extend({
            model: Screen.Models.Users,
    });

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'casting-log-book'
        , id: 'casting-log-book'
        , title: 'Casting Log Book'

        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a _refresh method to reset the view without erasing the DOM.
        , isCacheable: false
        , events: function () {
            return {
                'click #addItemBtn': this.addItemBtn_click,
                'click #deleteItemBtn': this.deleteItemBtn_click,
                'click #refreshBtn': this.refreshBtn_click,
                'click #saveItemBtn': this.saveItemBtn_click,
                'click #forwardNavBtn': this.forwardNavBtn_click,
                'click #backNavBtn': this.backNavBtn_click,
                'click #shiftViewBtn': this.shiftViewBtn_click,
                'click #searchViewBtn': this.searchViewBtn_click,
                'click #excelBtn': this.excelBtn_click,
                'click #equipmentPicker': this.equipmentPicker_click,
                'click #equipmentEntry': this.equipmentEntry_click,
                'keypress #searchTbx': this.searchTbx_keypress,
                'click #showSearchItemsBtn': this.showSearchItemsBtn_click,
                'click #printBtn': this.printBtn_click,
            };
        }
        , bindings: 'data-bind'
        , setIdNull: false
        , itemsColl: null
        , searchTbx: null
        , initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };
           
            this.model = new Screen.Models.Main();
            this.itemsColl = new Screen.Collections.Items();
            this.itemsCollPrint = new Screen.Collections.ItemsPrint();
            this.bindEvents();

      
        }
        , printBtn_click: function () {
            window.print();
            return false;
        }

        , equipmentPicker_click: function () {
            this.model.set('modalSelected', Screen.MODAL_PICKER);
            this.showEquipmentModal();
        }
        , equipmentEntry_click: function () {
            this.model.set('modalSelected', Screen.MODAL_DATA_ENTRY);
            this.showEquipmentModal();
        }

        , showEquipmentModal: function () {
            this.EquipmentModal = new Screen.Views.EquipmentModal({
                parent: this,
            });
            this.EquipmentModal.setEquipmentCodes();
            this.EquipmentModal.show();
        }

        , render: function (container, viewParams) {
            var that = this;
            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;
            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/custom-screens/' + this.template + '/';

            T.render.call(
                this,
                this.template,
                function (tmp) {

                    //getInternationalizationData
                    if (!that.options.i18n) that.options.i18n = {};
                    
                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.options.i18n[that.template] = i18nJED;
                            that.$el.html(tmp());
                            that.applyBindings();
                            that.append(thatContainer, that.$el);

                            var Users = new Screen.Collections.Users()
                            _.each(that.model.get('users'), function (obj) {
                                Users.add(obj);
                            });
                            new AutoCompleteView({
                                input: $("#search"),
                                minKeywordLength: 1,
                                model: Users,
                            }).render();

                            var gridPrint = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'Datetime',
                                        label: app.translate(that, 'item_datetime_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell crew-column',
                                        }),
                                    },
                                    {
                                        name: 'CrewID',
                                        label: app.translate(that, 'item_crew_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell crew-column',
                                        }),

                                    },
                                    {
                                        name: 'Title',
                                        label: app.translate(that, 'item_title_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell title-column',
                                        }),
                                    },
                                    {
                                        name: 'Description',
                                        label: app.translate(that, 'item_description_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell desc-column',
                                        }),
                                    },
                                    {
                                        name: 'TypeName',
                                        label: 'Type',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },

                                    {
                                        name: 'StatusCodeName',
                                        label: 'Status',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },

                                ],

                                collection: that.itemsCollPrint,
                            });

                            that.$el.find('.items-grid-container-print').append(gridPrint.render().el);


                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'time',
                                        label: app.translate(that, 'item_datetime_col_label'),
                                        editable: false,
                                        cell: Backgrid.Extension.MomentCell.extend({
                                            className: 'string-cell align-center-cell time-column',
                                            modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                            displayFormat: app.translate([that, app], 'YYYY-MM-DD HH:mm'),
                                        }),
                                    },
                                    {
                                        name: 'meltOrder',
                                        label: 'Melt Order',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'crew',
                                        label: app.translate(that, 'item_crew_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell crew-column',
                                        }),

                                    },
                                    {
                                        name: 'title',
                                        label: app.translate(that, 'item_title_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell title-column',
                                        }),
                                    },
                                    {
                                        name: 'desc',
                                        label: app.translate(that, 'item_description_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell desc-column',
                                        }),
                                    },
                                    {
                                        name: 'logEntryTypeName',
                                        label: 'Type',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },

                                    {
                                        name: 'statusCodeName',
                                        label: 'Status',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    
                                ],

                                row: Backgrid.Row.extend({
                                    initialize: function (options) {
                                        Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        var status = this.model.toJSON().statusCodeName;

                                        if (status === "Done") this.$el.addClass('color-six');


                                        
                                    },
                                    events: {
                                        click: 'click',
                                    },

                                    click: function (e) {
                                        try {
                                            var previousIndex = that.model.get('index');

                                            if (!this.$el.hasClass("selectedItem")) {
                                                that.model.changeSelectedItem(this.model);
                                                this.$el.addClass("selectedItem");
                                            }

                                            var rowsView = that.model.get('grid').body.rows;
                                            var newIndex = _.indexOf(rowsView, this);
                                            if (previousIndex != null && previousIndex != newIndex) rowsView[previousIndex].$el.removeClass("selectedItem");

                                            that.model.set({
                                                index: newIndex,
                                                showDataEntryMode: '1',

                                            });

                                            that.UpdateURL();
                                        }
                                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                    },
                                }),

                                collection: that.itemsColl,


                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);
                                        this.listenTo(this.collection, 'backgrid:sort', function (obj) {
                                            that.model.set({
                                                index: null,
                                                showDataEntryMode: '',
                                            });
                                        });
                                    },

                                }),
                            });

                            that.model.set({ grid: grid });
                            that.$el.find('.items-grid-container').append(grid.render().el);

                            that.$el.find('.input-date').datepicker();

                            that.$el.find('#timepicker1').timepicker({
                                showMeridian: false,
                                secondStep: 1,
                                minuteStep: 1,
                                showSeconds: true,
                            });
                            that.multiselect_type_picker();
                            that.multiselect_status_picker();
                            if (viewParams.start) {
                                viewParams.start = new moment(viewParams.start, 'YYYYMMDD').format('MM/DD/YYYY');
                            }
                            if (viewParams.end) {
                                viewParams.end = new moment(viewParams.end, 'YYYYMMDD').format('MM/DD/YYYY');
                            }

                            if (viewParams.id && !isNaN(viewParams.id)) {
                                viewParams.itemId = viewParams.id;
                            }

                            if (viewParams.casterProcessId && !isNaN(viewParams.casterProcessId)) {
                                viewParams.casterProcessId = viewParams.casterProcessId;
                            }
                            // set view parameters as model parameters
                            that.model.set(viewParams);
                            that.getCurrentMode();

                            // refresh collection
                            that.refresh(); 
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        }, 

        multiselect_type_picker() {
            var that = this;
            var typePicker = new VirtualSelect.init({
                ele: '#types-picker-multi-select',
                options: that.model.get('logEntryTypes'),
                multiple: true,
                search: true,
                placeholder: 'Select Type',
                showSelectedOptionsFirst: true,
            });
            document.querySelector('#types-picker-multi-select').addEventListener('change', function () {
                var typesSelected = [];
                if (this.value) {
                    _.each(this.value, function (obj) {
                     
                        typesSelected.push({ value: obj });
                    });
                }
                that.model.set({
                    typesSelected: typesSelected
                })

            });
        },

        multiselect_status_picker() {
            var that = this;
            var statusPicker = new VirtualSelect.init({
                ele: '#status-picker-multi-select',
                options: that.model.get('statusCodes'),
                multiple: true,
                search: true,
                placeholder: 'Select Status',
                showSelectedOptionsFirst: true,
            });
            document.querySelector('#status-picker-multi-select').addEventListener('change', function () {
               
                var statusSelected = [];
                if (this.value) {
                    _.each(this.value, function (obj) {

                        statusSelected.push({ value: obj });
                    });
                }
                that.model.set({
                    statusSelected: statusSelected
                })
            });
        },


        getCurrentMode() {
            var params = this.model.toJSON();
            if (params.mode == Screen.SHIFT_NAVIGATION_MODE)
                this.model.set('currentMode', Screen.SHIFT_NAVIGATION_MODE);
            else if (params.mode == Screen.SEARCH_MODE)
                this.model.set('currentMode', Screen.SEARCH_MODE);
            else 
                this.model.set('currentMode', Screen.SEARCH_MODE);
        },

        refresh: function () {
            try {
                this.itemsColl.reset();
                this.model.set({
                    index: null,
                    isLoading: true,
                    hasData: false,
                });
                // reload collection 
                this.itemsColl.fetch({
                    itemId: this.model.get('itemId'),
                    start: this.model.get('start'),
                    end: this.model.get('end'),
                    crewId: this.model.get('crewId'),
                    shiftId: this.model.get('shiftId'),
                    searchText: this.model.get('searchText'),
                    logEntryTypeId: this.model.get('logEntryTypeId'),
                    statusCodeId: this.model.get('statusCodeId'),
                    assetId: this.model.get('equipmentCodeId'),
                    author: this.model.get('author'),
                    refresh: true,
                    casterProcessId: this.model.get('casterProcessId'),
                    typesSelected: this.model.get('typesSelected'),
                    statusSelected:this.model.get('statusSelected'),
                });
                this.itemsCollPrint.fetch();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }

        , append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.options.state == app.view_states.loading
                || this.options.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.options.state = app.view_states.shown;
                container.append(el);

                this.options.onappend(this);
            }

            if (this.options.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        }
        , bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(event_equipment, 'new_equipmentId', this.trigger_equipment);
            this.listenTo(this.itemsColl, 'fetch', this.itemsColl_fetch),
                _.bindAll(this, 'on_keypress'),
                $(document).bind('keydown', this.on_keypress);
            this.listenTo(this.model, 'change:currentMode', this.setPickersParams);
            this.listenTo(this.model, 'change:itemDate change:itemTime', this.itemDatetime_change);
            this.listenTo(this.model, 'change:index', this.index_changed);

        }

        , index_changed: function () {
            rowsView = this.model.get('grid').body.rows;
            if (this.model.get('index')) {
                row = rowsView[this.model.get('index')].model.toJSON();
                if (row.autoGenerated == 1) document.getElementById("input-title").disabled = true;
                else document.getElementById("input-title").disabled = false;
            } else document.getElementById("input-title").disabled = false;
            
        }
        , itemDatetime_change: function () {
            var params = this.itemsColl.model.prototype.getDefaultItem({
                Datetime: this.model.get('itemDate') + ' ' + this.model.get('itemTime'),
            });
            this.model.set({
                itemShift: params.itemShift,
                itemCrew: params.itemCrew,
                itemProductionDate: params.itemProductionDateDef,
            });
        }

        , setPickersParams: function () {
            var params = this.model.toJSON();
            switch (this.model.get('currentMode')) {
                case Screen.SEARCH_MODE:
                    this.model.set({
                        showDataEntryMode: '',
                        showShiftPickers: '',
                        mode: '0',
                        shiftId: '-',
                        start: new moment(this.model.get('selectedDate'), 'MM-DD-YYYY').format('MM/DD/YYYY'),
                        end: new moment(this.model.get('selectedDate'), 'MM-DD-YYYY').format('MM/DD/YYYY'),
                    });
                    break;
                case Screen.SHIFT_NAVIGATION_MODE:
                        var blank = this.itemsColl.model.prototype.getDefault();
                        if (params.shiftId != 'N' && params.shiftId != 'D') {
                            this.model.set({
                                shiftId: blank.itemShift,
                                selectedShift: blank.itemShift,
                            });
                        } else {
                            this.model.set({
                                shiftId: params.shiftId,
                                selectedShift: params.shiftId,
                            });
                        } 
                        this.model.set({
                            showDataEntryMode: '',
                            showShiftPickers: '1',
                            mode: '1',  
                            selectedDate: new moment(this.model.get('start'), 'MM/DD/YYYY').format('MM-DD-YYYY'),
                            start: new moment(this.model.get('start'), 'MM/DD/YYYY').format('MM-DD-YYYY'),
                            end: new moment(this.model.get('start'), 'MM/DD/YYYY').format('MM-DD-YYYY'),
                            equipmentCodeId: null,
                            crewId: '-',
                            logEntryTypeId: '-',
                            statusCodeId: '-',
                            searchText: '',
                            author: '',
                        });
                    
                    break;

                    this.UpdateURL();
                    this.refresh();
            }   
        }

        , trigger_equipment: function (attrs) {
            var that = this;

            var assetId = attrs.equipmentCodeId;
            var assets = attrs.equipmentCodes;
            var assetSelected = _.where(assets, { id: assetId });
            var assetName = (assetSelected[0] && assetSelected[0].equipmentName) ? assetSelected[0].equipmentName : null;

            this.model.set({ assetId: assetId });

            if (this.model.get('modalSelected') == Screen.MODAL_PICKER) {
                that.model.set('equipmentPickerName', assetName);
                that.model.set('equipmentCodeId', attrs.equipmentCodeId);
                if (attrs.equipmentCodeId == null) {
                    that.model.set('equipmentPickerName', null);
                    //app.views.topMessages.showMessage('Equipment not assigned', { stay: 5000, });
                }
                    
            }
            if (this.model.get('modalSelected') == Screen.MODAL_DATA_ENTRY) {
                that.model.set('equipmentDataEntryName', assetName);
                this.model.set('itemAssetId', attrs.equipmentCodeId);
                if (attrs.equipmentCodeId == null) {
                    that.model.set('equipmentDataEntryName', null);
                   // app.views.topMessages.showMessage('Equipment not assigned', { stay: 5000, });
                }
            }
        }
        
        , excelBtn_click: function (e) {
            try {
                var qp = new Core.Database.QueryParameters(),
                    attrs = this.model.toJSON(),
                    params;

                params = [
                    { Name: '@Start', Type: 'DATE', Value: attrs.start, },
                    { Name: '@End', Type: 'DATE', Value: attrs.end, },
                    { Name: '@TimeZoneCode', Type: 'CHAR(10)', Value: 'EDTIND' },
                    { Name: '@LogBookTypeCode', Type: 'CHAR(1)', Value: 'C' },
                ];
                _.each(params, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

                var cellsData = [
                    { Column: 'A', Value: 'Date' },   
                    { Column: 'B', Value: 'Shift' },
                    { Column: 'C', Value: 'Crew' },
                    { Column: 'D', Value: 'Title' },
                    { Column: 'E', Value: 'Author' },
                    { Column: 'F', Value: 'Description' },
                    { Column: 'G', Value: 'LogEntryType' },
                    { Column: 'H', Value: 'Equipment' },
                    { Column: 'I', Value: 'Status' },

                ];

                var SQLCellsData = [
                    { ExcelColumnName: 'A', SQLDataColumnName: 'ProductionDate', DataType: 'String'},
                    { ExcelColumnName: 'B', SQLDataColumnName: 'ShiftID', DataType: 'String' },
                    { ExcelColumnName: 'C', SQLDataColumnName: 'CrewID', DataType: 'String' },
                    { ExcelColumnName: 'D', SQLDataColumnName: 'Title', DataType: 'String' },
                    { ExcelColumnName: 'E', SQLDataColumnName: 'Author', DataType: 'String' },
                    { ExcelColumnName: 'F', SQLDataColumnName: 'Description', DataType: 'String' },
                    { ExcelColumnName: 'G', SQLDataColumnName: 'TypeName', DataType: 'String' },
                    { ExcelColumnName: 'H', SQLDataColumnName: 'AssetName', DataType: 'String' },
                    { ExcelColumnName: 'I', SQLDataColumnName: 'StatusCodeName', DataType: 'String' },
                ];


                Core.Export.Excel({
                    Data: [
                        {
                            SheetName: 'Data',
                            RowsData: [{
                                CellsData: cellsData
                            }],
                            StartRowIndex: 1,
                        },
                        {
                            SheetName: 'Data',
                            RowsData: [],
                            StartRowIndex: 2,
                            DataSourceName: 'data',
                            DataSourceTableIndex: 0,
                            SQLCellsData: SQLCellsData
                        }
                    ],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'Casting Log Book',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.LogBook.GetLogBook',
                                QueryParameters: qp,
                            },
                        },
                    ]},
                    function (resp) {
                        try {
                            if ((resp) && (resp.Success == true) && (resp.Data)) {
                                location.href = app.foldersRoot + '/excel/' + resp.Data;
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error('Server response not valid.');
                            }
                        }
                        catch (Error) { console.error(Error); }
                    },
                    function (resp) {
                        console.error(resp);
                    }
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }


        , itemsColl_fetch: function (coll, resp) {
            try {
                var that = this;
                // reload data entry
                var selectedItemId = this.model.get('itemId');
                if (selectedItemId) {
                    var item = this.itemsColl.select(function (model) { return model.get('id') == selectedItemId })
                    if (item && item[0]) this.model.changeSelectedItem(item[0]);
                }
                
                setTimeout(
                    function () {
                        that.model.set({
                            hasData: (that.itemsColl.length > 0),
                            isLoading: false,
                        });
                    },
                    100
                );

                if (that.itemsColl.length > 0)
                    that.scrollToBottomTrigger(that.itemsColl);
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }

        ,scrollToBottomTrigger: function (collection) {
            let listContainer = document.getElementById(collection.getGridId());
            listContainer.addEventListener('scroll', function (e) {
                if (listContainer.scrollTop >= (listContainer.scrollHeight - listContainer.offsetHeight))
                    collection.getNextPage();
            });
        }

        , deleteItemBtn_click: function (model) {
            try {
                var that = this;
                var modal = new Modal.Views.Main({
                    focusOk: false,
                    focusSelector: '#deleteItemBtn',
                    title: app.translate([that, app], "delete_item_confirm_title"),
                    message: app.translate([that, app], "delete_item_confirm_message"),
                    buttons_type: "CONTINUE-CANCEL",
                });
                this.listenToOnce(modal, "continue", function (modal) {
                    this.itemsColl.deleteItem({
                        itemId: this.model.get('itemId'),
                    });
                    this.model.set(this.itemsColl.model.prototype.getDefault());
                    this.model.set('showDataEntryMode', '');
                    this.UpdateURL();
                    this.refresh();
                });
                modal.show();

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        

        , addItemBtn_click: function (model) {
            this.model.set(this.itemsColl.model.prototype.getDefault());
            this.model.set('showDataEntryMode', '1');
        }
        , saveItemBtn_click: function (model) {
            const currentAssetId = this.model.get('assetId');
            if (!currentAssetId) {
                app.views.topMessages.showMessage('Equipment field is mandatory', { stay: 5000, });
                return;
            }

            this.itemsColl.upsertItem(this.model);
            this.model.set(this.itemsColl.model.prototype.getDefault());
            this.model.set('showDataEntryMode', ''); 
            this.UpdateURL();
            this.refresh();
        }
        , UpdateURL: function () {
            try {
                var params = this.model.toJSON();
                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                start: new moment(params.start, "MM/DD/YYYY").format("YYYYMMDD"),
                                end: new moment(params.end, "MM/DD/YYYY").format("YYYYMMDD"),
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        , refreshBtn_click: function (model) {
            this.model.set('showDataEntryMode', '');
            this.model.set('itemId', null);
            this.model.set('casterProcessId', '-');
            this.UpdateURL();
            this.refresh();
        }

        , UpdateNav(nav) {
            var params = this.model.toJSON();
            if (nav && this.model.get('selectedShift') == 'N')
                this.model.set('selectedDate', new moment(params.selectedDate, 'MM/DD/YYYY').add(1, 'day').format('MM-DD-YYYY'));

            if (!nav && this.model.get('selectedShift') == 'D')
                this.model.set('selectedDate', new moment(params.selectedDate, 'MM/DD/YYYY').subtract(1, 'day').format('MM-DD-YYYY'));


            if (this.model.get('selectedShift') == 'N') this.model.set('selectedShift', 'D');
            else
                if (this.model.get('selectedShift') == 'D') this.model.set('selectedShift', 'N');

            this.model.set('showDataEntryMode', '');
            this.model.set('itemId', null);

            var params = this.model.toJSON();
            this.model.set('start', new moment(params.selectedDate, 'MM-DD-YYYY').format('MM/DD/YYYY'));
            this.model.set('end', new moment(params.selectedDate, 'MM-DD-YYYY').format('MM/DD/YYYY'));
            this.model.set('shiftId', this.model.get('selectedShift'));

            this.UpdateURL();
            this.refresh();
        },

        forwardNavBtn_click: function () {
            this.UpdateNav(true);
        },
        backNavBtn_click: function () {
            this.UpdateNav(false);
        },

        shiftViewBtn_click: function () {
            this.model.set('currentMode', Screen.SHIFT_NAVIGATION_MODE)
            this.UpdateURL();
            this.refresh();
        },
        
        searchViewBtn_click: function () {
            this.model.set('currentMode', Screen.SEARCH_MODE);
            this.refresh();
        },


        hasScrollBar: function () {
            var element = document.getElementById("grid-logBook");
            if (element) {
                var scrollBarHeight = element.scrollHeight;

                if (parseFloat(scrollBarHeight) > window.innerHeight) {
                    return true;
                }
                else
                    return false;
            }
            
        },

        insideInputOrTextarea: function () {
            var comments = document.getElementById('entry-textarea'),
                title = document.getElementById('input-title'),
                author = document.getElementById('input-author');
            return (document.activeElement === comments || document.activeElement === title || document.activeElement === author);
        },

        on_keypress: function (e) {
            var that = this,
                rowsView = that.model.get('grid') && that.model.get('grid').body && that.model.get('grid').body.rows ? that.model.get('grid').body.rows : null,
                previousIndex = that.model.get('index');

            if (!this.insideInputOrTextarea()) {
                if (this.hasScrollBar()) {
                    var hel = document.getElementsByClassName("selectedItem"),
                        gridHeight = document.getElementsByClassName("items-grid-container"),
                        element = document.getElementById("grid-logBook"),
                        scrollTop = element.scrollTop,
                        constLevelSup = parseInt(window.innerHeight * 0.27),
                        constLevelInf = constLevelSup + constLevelSup,
                        diff = 0;
                    if (hel[0]) diff = hel[0].offsetTop - scrollTop + parseInt(constLevelSup);
                    if ([38, 40].indexOf(e.keyCode) > -1) {
                        if (window.event.code == 'ArrowDown') {
                            if ((parseFloat(diff) < parseFloat(gridHeight[0].offsetHeight)) && (diff - parseInt(constLevelSup) > 0)) {
                                e.preventDefault();
                            }
                        }
                        if (window.event.code == 'ArrowUp') {
                            if ((diff - parseInt(constLevelInf)) > 0) {
                                e.preventDefault();
                            }
                        }
                    }
                }

                if (window.event.code == 'ArrowUp' && previousIndex != 0) {
                    rowsView[previousIndex].$el.removeClass("selectedItem");
                    rowsView[previousIndex - 1].$el.addClass("selectedItem");
                    that.model.set({
                        index: previousIndex - 1,
                    });
                    that.model.changeSelectedItem(rowsView[previousIndex - 1].model);
                }

                if (window.event.code == 'ArrowDown' && (previousIndex != (rowsView.length - 1))) {
                    rowsView[previousIndex].$el.removeClass("selectedItem");
                    rowsView[previousIndex + 1].$el.addClass("selectedItem");
                    that.model.set({
                        index: previousIndex + 1,
                    });
                    that.model.changeSelectedItem(rowsView[previousIndex + 1].model);

                }
                
            }

        },
        bindViewScopedEvents: function () {
            var that = this;
        },
        unbindViewScopedEvents: function () {

        },
        close: function () {
            this.options.state = app.view_states.closed;

            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        show: function () {
            this.options.state = app.view_states.shown;

            this.bindEvents();
            this.$el.show();
        },
        hide: function () {
            this.options.state = app.view_states.hidden;

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        preRender: function () {
            app.models.subnavbar.set('subnavbar', false);
        },
        reRender: function (viewParams) {
            try {
                this.refresh();
            } catch (Error) { }
        },


    });

        
    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        defaults: {
            id: null,
            author: null,
            productionDate: new moment().format('YYYY-MM-DD'),
            shift: null,
            crew: null,
            title: null,
            description: null,
            logEntryType: null,
            logEntryTypeName: null,
            equipmentCodeName: null,
            equipmentId: null,
            time: null,
            assetId: null,
            assetName: null,
            statusCodeId: 2,
            statusCodeName: null,
            datetime: null,
            meltOrder: '',
        },

        parse: function (obj) {
            var result = {
                id: obj.ID,
                author: obj.Author,
                productionDate: new moment(obj.ProductionDate),
                shift: obj.ShiftID,
                crew: obj.CrewID,
                title: obj.Title,
                desc: obj.Description ? String(obj.Description).substring(0, 100) : '',
                description: obj.Description,
                logEntryType: obj.LogEntryTypeID,
                logEntryTypeName: obj.TypeName,
                equipmentCodeName: obj.EquipmentName,
                equipment: obj.EquipmentId,
                time: obj.Time ? new moment(obj.Time).format('YYYY-MM-DD HH:mm:ss') : new moment(obj.ProductionDate).format('YYYY-MM-DD') + ' ' + '00:00:00',
                autoGenerated: obj.AutoGenerated,
                assetId: obj.AssetId,
                assetName: obj.AssetName,
                statusCodeId: obj.StatusCodeId,
                statusCodeName: obj.StatusCodeName,
                datetime: obj.Datetime ? obj.Datetime : '',
                meltOrder: obj.MeltOrder ? obj.MeltOrder : '',
            };
            return result;
        }

        , getDefaultItem: function (params) {
            try {
                var that = this;
                var qp = new QueryParameters();
                var result = {};
                var item = [];
                item = [
                    { name: 'Datetime', type: 'DATETIME', value: params.Datetime },
                    { name: '@TimeZoneCode', type: 'CHAR', value: app.models.user.get('timezoneCode') },
                ];

                for (var q in item) {
                    qp.Add(item[q].name, item[q].type, item[q].value);

                }
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LogBook.GetDefaultLogEntry',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table && resp.Table[0]) {
                                    obj = resp.Table[0];
                                    result = {
                                        itemCrew: obj.CrewID,
                                        itemShift: obj.ShiftID == '1' ? 'D' : 'N',
                                        itemProductionDateDef: new moment(obj.ProductionDate).format('MM/DD/YYYY'),
                                    }
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                    }
                                    else
                                        console.error("Server response not valid.");
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: false
                    },
                    app.ConnectionStrings.app
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            return result;
        }
        
        , getDefault: function () {
            try {
                var that = this;
                var qp = new QueryParameters();
                var result = {};
                var item = [
                    { name: '@TimeZoneCode', type: 'CHAR', value: app.models.user.get('timezoneCode') },
                ];

                for (var q in item) {
                    qp.Add(item[q].name, item[q].type, item[q].value);

                }
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LogBook.GetDefaultLogEntry',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table && resp.Table[0]) {
                                    obj = resp.Table[0];
                                    result = {
                                        itemCrew: obj.CrewID,
                                        itemDate: new moment().format('YYYY-MM-DD'),
                                        itemShift: obj.ShiftID == '1' ? 'D' : 'N',
                                        itemTitle: '',
                                        itemMeltOrder: '',
                                        itemAuthor: obj.CurrentUser,
                                        itemDescription: '',
                                        itemId: 'new',
                                        itemLogEntryType: obj.LogEntryTypeID,
                                        itemAssetId: null,
                                        itemTime: new moment().format('HH:mm:ss'),
                                        equipmentDataEntryName: '',
                                        itemStatusCodeId: obj.StatusCodeId,
                                    }
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                    }
                                    else
                                        console.error("Server response not valid.");
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: false
                    },
                    app.ConnectionStrings.app
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            return result;
        }
    });


    Screen.Collections.ItemsPrint = Backbone.Collection.extend({

        fetch: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LogBook.GetCasterLogBookPrint',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && (resp.Table)) {
                                var newColl = resp.Table;
                                that.set(newColl);
                                that.trigger('fetch', that, newColl);
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    console.error(new Error(resp.Message).stack);
                                    app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                }
                                else {
                                    app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                }
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: true,
                },
                app.ConnectionStrings.app
            );
            return this;
        },

    });

    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.Item,

        isFetching: false,
        currentPage: 1,
        pageSize: 100,


        fixedParameters: [],

        getGridId: function () {
            return 'grid-logBook';
        },

        fetch: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                options = params ? _.clone(params) : {};
            if (params.casterProcessId && params.casterProcessId != '-') {
                this.fixedParameters = [
                    { Name: '@CasterProcessId', Type: 'INT', Value: params.casterProcessId, }
                ];

                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

            } else {
                if (options.refresh) {
                    this.resetPagination(true);
                    if ($.isNumeric(params.itemId)) {
                        this.fixedParameters = [
                            { Name: '@Id', Type: 'INT', Value: params.itemId, }
                        ]
                    }
                    else {
                        this.fixedParameters = [
                            { Name: '@Start', Type: 'DATETIME', Value: params.start, },
                            { Name: '@End', Type: 'DATETIME', Value: params.end, },
                            { Name: '@CrewId', Type: 'CHAR', Value: params.crewId != '-' ? params.crewId : null, },
                            { Name: '@ShiftId', Type: 'CHAR', Value: params.shiftId != '-' ? params.shiftId : null, },
                          //  { Name: '@LogEntryTypeID', Type: 'INT', Value: params.logEntryTypeId != '-' ? params.logEntryTypeId : null, },

                           // { Name: '@StatusCodeId', Type: 'INT', Value: params.statusCodeId != '-' ? params.statusCodeId : null, },
                            { Name: '@AssetId', Type: 'INT', Value: params.assetId, },
                            { Name: '@SearchText', Type: 'VARCHAR', Value: params.searchText != '' ? params.searchText : null, },
                            { Name: '@Author', Type: 'VARCHAR', Value: params.author != '' ? params.author : null, },
                            { Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
                            { Name: '@LogBookTypeCode', Type: 'CHAR(1)', Value: 'C' },
                        ];

                        //layout data xml parameter
                        qp.Add(
                            'LayoutTypes',
                            'XML',
                            app.jsonArrayToXml(
                                params.typesSelected,
                                [
                                    'value',
                                ]
                            )
                        );
                        qp.Add(
                            'LayoutStatus',
                            'XML',
                            app.jsonArrayToXml(
                                params.statusSelected,
                                [
                                    'value',
                                ]
                            )
                        );
                    }
                }
                this.isFetching = true;

                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

                if (!options.refresh) {
                    qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize + 1);
                    qp.Add('@rowsToFetch', 'INT', this.pageSize - 1);
                } else {
                    qp.Add('@fromRow', 'INT', 0);
                    qp.Add('@toRow', 'INT', this.currentPage * this.pageSize);
                    qp.Add('@rowsToFetch', 'INT', this.pageSize);
                }

            }

          
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LogBook.GetLogBook',
                 qp,
                 {
                     onSuccess: function (resp) {
                         try {

                             if ((resp) && (resp.Table)) {
                                 var newColl = _.map(resp.Table, that.model.prototype.parse);
                                 var method = (options.refresh) ? 'set' : 'add';

                                 that[method](newColl);
                                 that.trigger('fetch', that, newColl);
                                 if (newColl.length == 0 && method == 'add')
                                     that.currentPage--;


                                 that.isFetching = false;


                             }
                             else {
                                 if ((resp) && (resp.Message)) {
                                     console.error(new Error(resp.Message).stack);
                                     app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                 }
                                 else {
                                     app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                     console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                 }
                             }
                         }
                         catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                     },
                     onFailure: function (resp) {
                         console.error(resp);
                     },
                     Secured: true,
                     Async: true,
                 },
                 app.ConnectionStrings.app
            );
            return this;
        },
        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },
        deleteItem: function (params) {
            try {
                var that = this;
                var qp = new QueryParameters();
                qp.Add('@Id', 'INT', params.itemId);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LogBook.DeleteLogEntry',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp) {
                                    app.views.topMessages.showMessage('Log entry deleted', { stay: 5000, });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                    }
                                    else
                                        console.error("Server response not valid.");
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: false,
                    },
                        app.ConnectionStrings.app
                    );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

        upsertItem: function (model) {
            try {
               

                item = [
                    { name: '@Title', type: 'VARCHAR', value: model.get('itemTitle') },
                    { name: '@Description', type: 'VARCHAR', value: model.get('itemDescription') },
                    { name: '@LogEntryTypeId', type: 'INT', value: model.get('itemLogEntryType') },
                    { name: '@AssetId', type: 'INT', value: model.get('assetId') },

                    { name: '@StatusCodeId', type: 'INT', value: model.get('itemStatusCodeId') },

                    { name: '@Datetime', type: 'DATETIME', value: model.get('itemDate') + ' ' + model.get('itemTime') },
                    { name: '@TimeZoneCode', type: 'CHAR(10)', value: app.models.user.get('timezoneCode') },
                    { name: '@LogBookTypeCode', type: 'CHAR(1)', value: 'C' },

                ];

                if ($.isNumeric(model.get('itemId'))) {
                    item.push({ name: '@Id', type: 'INT', value: model.get('itemId') });
                };

                if (model.get('itemId') == 'new') {
                    item.push({ name: '@NewEntry', type: 'BIT', value: 1 });
                }

                var that = this;
                var qp = new QueryParameters();

                for (var q in item) {
                    qp.Add(item[q].name, item[q].type, item[q].value);

                }
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LogBook.UpsertLogEntry',
                       qp,
                       {
                           onSuccess: function (resp) {
                               try {
                                   if ((resp) && (resp.Table)) {
                                       if ((resp.Table[0]) && (resp.Table[0].ID)) {
                                           model.set('itemId', resp.Table[0].ID);
                                       } else {
                                           model.set('itemId', null);
                                       }
                                       app.views.topMessages.showMessage('Log entry saved', { stay: 5000, });
                                   }
                                   else {
                                       if ((resp) && (resp.Message)) {
                                           app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                           console.error(resp.Message);
                                       }
                                       else {
                                           app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                           console.error("Server response not valid.");
                                       }
                                   }
                               }
                               catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                           },
                           onFailure: function (resp) {
                               console.error(resp);
                           },
                           Secured: true,
                           Async: false,
                       },
                       app.ConnectionStrings.app
                   );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }

    });

    Screen.Models.EquipmentModal = Backbone.Epoxy.Model.extend({
        defaults: {
            equipmentCodeId: null,
            equipmentCodes: [],

            errorMsg: '',
            processing: false,

            curEquipmentCodeId: null,

        },

        fetchEquipmentCodes: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LogBook.GetLogBookCatalogs',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                _.each(resp.Table, function (obj) { 
                                    var tableKey = 'Table' + obj.Index;

                                    if (resp.Table7) {
                                        newItems = [];
                                        _.each(resp.Table7, function (obj) {
                                            newItems.push({
                                                id: obj.AssetId,
                                                parentId: obj.ParentAssetId,
                                                typeName: obj.AssetName,
                                                equipmentName: obj.AssetName,
                                                equipmentId: obj.AssetId,
                                            });
                                            that.set('equipmentCodes', newItems);
                                        });
                                    }

                                    //switch (obj.Name) {
                                    //    case 'EQUIPMENTS':
                                    //        newItems = [];
                                    //        _.each(resp[tableKey], function (obj) {
                                    //            newItems.push({
                                    //                id:obj.Id,
                                    //                parentId:obj.ParentId,
                                    //                typeName:obj.TypeName,
                                    //                equipmentName: obj.EquipmentName,
                                    //                equipmentId: obj.EquipmentId,
                                    //            })
                                    //        });
                                    //        that.set('equipmentCodes', newItems);
                                    //    break;
                                        
                                    //}
                                })
                            }     
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        reset: function () {
            this.set(this.defaults);
        },
    });

    var event_equipment = _({}).extend(Backbone.Events);


    Screen.Views.EquipmentModal = Backbone.Epoxy.View.extend({
        template: 'log-book',
        id: 'log-book',
        className: "modal modal-delays hide fade",
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        bindings: "data-bind",
        isCacheable: false,
        events: function () {
            return {
                "click #acceptBtn": this.acceptBtn_click,
                "click #cancelBtn": this.cancelBtn_click,
                "submit form": this.form_submit,
                "keypress": this.modal_keypress,
                "show.bs.modal": this.modal_show,
                "shown.bs.modal": this.modal_shown,
                "hidden.bs.modal": this.modal_hidden,
            };
        },

        container: null,
        content: null,
        disposed: false,
        isRendered: false,
        parent: null,
        preventDispose: false,
        visible: false,

        equipmentCodesTree: null,
        equipmentCodesTreeItemsColl: null,
        

        initialize: function (options) {
            _.extend(this, options);
            if (!this.model)
                this.model = new Screen.Models.EquipmentModal();

            var parentModel = options.parent.model.toJSON();
            if (parentModel.modalSelected == Screen.MODAL_PICKER) {
                this.model.set('curEquipmentCodeId', parentModel.equipmentCodeId);
            } else if (parentModel.modalSelected == Screen.MODAL_DATA_ENTRY) {
                this.model.set('curEquipmentCodeId', parentModel.itemAssetId);
            }

          
            this.bindEvents();
            return this;
        },

        hide: function (preventDispose) {
            this.preventDispose = (preventDispose);

            this.$el.modal('hide');
        },

        render: function (container) {
            if (container)
                this.container = container;

            var that = this;
            var customPath = '/app/custom-screens/log-book/';

            T.render.call(
                this,
                this.template,
                function (tmp) {
                    //getInternationalizationData
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.i18n[that.template] = i18nJED;
                            //loading the view and appeding it to the views's $el.
                            that.$el.html(tmp(that.model.toJSON()));
                            that.applyBindings();
                           
                            $.jstree.defaults.core.themes.variant = 'large';
                            that.$el.find('.equipment-codes-tree').jstree({
                                core: {
                                    check_callback: true,
                                    data: function (obj, cb) {
                                        var modelAttrs = that.model.toJSON();
                                        var data = modelAttrs.equipmentCodes;
                                        var curEquipmentCodeId = that.model.get('curEquipmentCodeId');
                                    
                                        var items = [{
                                            id: -100,
                                            equipmentId: null,
                                            parent: '#',
                                            type: 'code',
                                            text: 'All',
                                            state: {
                                                disabled: false,
                                                opened: true,
                                            },
                                        }];

                                        _.each(data, function (itemData) {
                                            items.push({
                                                id: itemData.id,
                                                equipmentId: itemData.equipmentId,
                                                parent: (itemData.parentId != null) ? itemData.parentId : -100,
                                                state: {
                                                    disabled: (modelAttrs.processing),
                                                    selected: curEquipmentCodeId ? (itemData.equipmentId == curEquipmentCodeId) : false,
                                                },
                                                type: 'code',
                                                /*text: (itemData.equipmentName != null) ? (itemData.typeName + ' - ' + itemData.equipmentName) : itemData.typeName,*/
                                                text: itemData.equipmentName,
                                            });
                                        });

                                       

                                        cb.call(this, items);
                                    },
                                },
                                types: {
                                    '#': {
                                        valid_children: ['root'],
                                        max_children: 1,
                                    },
                                    'root': {
                                        icon: 'fa fa-ellipsis-h',
                                        valid_children: ['code'],
                                    },
                                    'code': {
                                        'icon': 'fa fa-circle-thin',
                                        valid_children: ['code'],
                                        max_depth: 1,
                                    },
                                },
                                plugins: [
                                    'wholerow',
                                    'types',
                                ],
                            });
                            that.equipmentCodesTree = that.$el.find('.equipment-codes-tree').jstree(true);

                            that.$el.find('.equipment-codes-tree').bind({
                                'select_node.jstree': _.bind(that.equipmentCodesTree_selectNode, that),
                            });
                            
                            that.isRendered = true;

                            that.trigger("render");
                        },
                        true,
                        customPath
                    );


                }, customPath, "equipment_declare_modal");
        },
        reset: function () {
            this.model.reset();
        },
        setData: function (attrs) {
            this.model.set(attrs);
        },
        setEquipmentCodes: function () {
            this.model.fetchEquipmentCodes();
        },
        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            //this.model.set({
            //    errorMsg: "",
            //    processing: true,
            //});
           
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                if (this.model.get('manual') == false) {
                    this.$el.modal({
                        keyboard: false,
                        backdrop: 'static',
                    });
                }
                else {
                    this.$el.modal({
                        keyboard: true,
                        backdrop: 'both',
                    });
                }
            }

            return this;
        },

        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenToOnce(this, "render", this.view_render)
                .listenTo(this.model, "change:equipmentCodeId", this.model_change_equipmentCodeId)
                .listenTo(this.model, "change:equipmentCodes", this.model_change_equipmentCodes);
        },
        close: function () {

            if (this.disposed == false) {
                if (this.visible == true) {
                    this.hide();
                }
                else {
                    this.trigger('close');

                    //Do not close the modal like we do with others to prevent a rerender every time that is displayed.
                    this.remove();
                    this.unbind();

                    this.disposed = true;
                }
            }
        },
        preRender: function () {
            app.models.subnavbar.set("dateControl", false);
        },
        reRender: function () {
        },

        acceptBtn_click: function (e) {
            try {
                var attrs = this.model.toJSON();
                event_equipment.trigger('new_equipmentId', attrs);
                this.close();

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        equipmentCodesTree_selectNode: function (e, obj) {
            try {
                //this.model.set('equipmentCodeId', obj.node.id);
                this.model.set('equipmentCodeId', obj.node.original.equipmentId);
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        form_submit: function (e) {
            try {
                e.preventDefault();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_keypress: function (e) {
            try {
                var attrs = this.model.toJSON();

                if (((e.which == 13) && (e.shiftKey == false))
                    && (attrs.processing == false)) {
                    this.save();
                    e.preventDefault();
                }
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_hidden: function (e) {
            try {
                this.visible = false;

                if (!this.preventDispose)
                    this.close();
                else
                    this.preventDispose = false;
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_show: function (e) {
            try {
                this.visible = true;
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_shown: function (e) {
            try {
                this.$el.find(".autofocus").focus();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        model_change_equipmentCodeId: function (model) {
            try {
                if (this.isRendered == true) {
                    this.equipmentCodesTree.deselect_all();
                    this.equipmentCodesTree.select_node(this.model.get('equipmentCodeId'));
                }
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        model_change_equipmentCodes: function (model) {
            try {
                if (this.isRendered == true) {
                    this.equipmentCodesTree.refresh();
                }
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        view_render: function () {
            try {
                this.show();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    // Required, return the module for AMD compliance.
    return Screen;

});