//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',

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

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

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

                showDataEntryMode: '',
                searchText: '',
                index: null,
                hasData: false,
                isLoading: 0,
                grid: null,

                itemMO: '',
                itemName: '',
                itemGrade: '',
                itemDocument: '',
                itemArchived: false,
                itemProcess: 1,
                itemAuthor: '',

                archived: false,

                grades: [],
                gradeId: '-',
                processes: [],
                processId: 1,
                processId_test: 1,


                newFileName: null,
                inputFileName: null,

                fileName: null,
                fileDB64: null,

                downloadBtnPressed: false,

                itemStartDate: new moment().format('MM/DD/YYYY'),
                itemEndDate: new moment().format('MM/DD/YYYY'),

                hasPermission: false,

                newFilesBuffer: [],
                deleteFilesBuffer: [],



                hasData_files: false,
                isLoading_files: true,
                file_selected: false,

                selected_processes: [],
                selected_grades: [],
                selected_form_grades: [],
                selected_form_processes: [],
                selected_form_sizes: [],
                selected_sizes: [],
                gradeGroups: [],
                formGrades: [],
                sizes: [],
            },
            initialize: function () {
                this.fetchPickers({ async: false });
                this.fetchGrades({ async: false, gradeGroupIds: [] });
                this.fetchFormGrades({ async: false, gradeGroupIds: [] });
            },
            changeSelectedItem: function (item) {

                if (item) {
                    //Update the Form Pickers 
                    if (item.get('ProcessIds')) document.querySelector('#processes-form-multi-select').setValue(item.get('ProcessIds').split(','));
                    else document.querySelector('#processes-form-multi-select').setValue('');

                    if (item.get('SizeIds')) document.querySelector('#sizes-form-multi-select').setValue(item.get('SizeIds').split(','));
                    else document.querySelector('#sizes-form-multi-select').setValue('');

                    if (item.get('GradeIds')) document.querySelector('#grades-form-multi-select').setValue(item.get('GradeIds').split(','));
                    else document.querySelector('#grades-form-multi-select').setValue('');

                    this.set({
                        itemId: item.get('Id'),
                        itemMO: item.get('MeltOrder'),
                        itemGrade: item.get('GradeId'),
                        itemProcess: item.get('ProcessId'),
                        itemAuthor: item.get('Author'),
                        itemName: item.get('Name'),
                        itemArchived: item.get('Archived'),
                        itemEndDate: item.get('EndDate') ? new moment(item.get('EndDate')).format('MM/DD/YYYY') : new moment().format('MM/DD/YYYY'),
                    });
                }
                else {
                    //this.set(this.defaults);

                    //Update the Form Pickers 

                    document.querySelector('#processes-form-multi-select').setValue('');
                    document.querySelector('#sizes-form-multi-select').setValue('');
                    document.querySelector('#grades-form-multi-select').setValue('');

                    this.set({
                        itemId: null,
                        itemMO: '',
                        itemAuthor: '',
                        itemName: '',
                        itemEndDate: new moment().format('MM/DD/YYYY'),
                    });

                }
            },

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

                //layout data xml parameter
                qp.Add(
                    'LayoutGradeGroups',
                    'XML',
                    app.jsonArrayToXml(
                        options.gradeGroupIds,
                        [
                            'value',
                        ]
                    )
                );

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.TWI.GetGradesByGradeGroup',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    that.set('formGrades', _.map(resp.Table, function (obj) {
                                        return {
                                            value: obj.Id,
                                            label: obj.Name,
                                            description: obj.GradeGroupDescription,
                                        };
                                    }));

                                    that.trigger('fetch-form-grades');

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

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

                //layout data xml parameter
                qp.Add(
                    'LayoutGradeGroups',
                    'XML',
                    app.jsonArrayToXml(
                        options.gradeGroupIds,
                        [
                            'value',
                        ]
                    )
                );

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.TWI.GetGradesByGradeGroup',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    that.set('grades', _.map(resp.Table, function (obj) {
                                        return {
                                            value: obj.Id,
                                            label: obj.Name,
                                            description: obj.GradeGroupDescription,
                                        };
                                    }));

                                    that.trigger('fetch-grades');

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

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

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.TWI.GetCatalogs',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    that.set('processes', _.map(resp.Table, function (obj) {
                                        return {
                                            value: obj.Id,
                                            label: obj.Name,
                                        };
                                    }));
                                    that.set('gradeGroups', _.map(resp.Table1, function (obj) {
                                        return {
                                            value: obj.Id,
                                            label: obj.Name,
                                        };
                                    }));
                                    that.set('sizes', _.map(resp.Table2, function (obj) {
                                        return {
                                            value: obj.Id,
                                            label: obj.Name,
                                        };
                                    }));

                                }
                                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 'twi-management';
            } catch (Error) { }
        }

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'twi-management'
            , id: 'twi-management'
            , title: 'TWI Management'

            //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,

                    'keypress #searchTbx': this.searchTbx_keypress,
                    'change #FileBtn': _.bind(this.FileBtn_change, this),
                    'keydown #search': this.search_keydown,
                    'change #picker-checkbox': this.checkbox_change,


                };
            }
            , 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.fileitemsColl = new Screen.Collections.FileItems();
                this.bindEvents();

                this.getPermissions();

            }

            , getPermissions: function () {
                var read = $.inArray('twi_r', app.models.user.get('roles'));
                var write = $.inArray('twi_w', app.models.user.get('roles'));
                var ctx = {
                    readWrite: (read != -1 && write != -1) ? true : false,
                };
                this.model.set('hasPermission', ctx.readWrite);
            }

            , removeHighlightRow: function () {
                var previousIndex = this.model.get('index');
                var rowsView = this.model.get('grid').body.rows;
                rowsView[previousIndex].$el.removeClass("selectedItem");

            }
            , addItemBtn_click: function (model) {
                this.model.set(this.itemsColl.model.prototype.getDefault());
                this.model.changeSelectedItem(null);
                this.model.set({
                    itemId: null,
                    showDataEntryMode: '1',
                    hasData_files: false,
                    isLoading_files: false,
                });

                this.removeHighlightRow();
            }


            , checkbox_change: function () {
                this.refresh(null);
            }

            , search_keydown: function (e) {
                if (e.which == 13) {
                    $("#search").blur();
                    this.refresh(null);
                }
            }


            , form_grades_fetch: function () {
                var that = this;
                document.querySelector('#grades-form-multi-select').setOptions(that.model.get('formGrades'));
            }
            , grades_fetch: function () {
                var that = this;
                document.querySelector('#grades-picker-multi-select').setOptions(that.model.get('grades'));
            }


            , multiselect_picker_grades_gradeGroups: function () {
                var that = this;
                //-----------------------------------
                //-------- GRADE GROUPS PICKER ------
                //-----------------------------------
                var GradeGroupsPickerVirtualSelect = new VirtualSelect.init({
                    ele: '#grade-groups-picker-multi-select',
                    options: that.model.get('gradeGroups'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    showSelectedOptionsFirst: true,
                });
                document.querySelector('#grade-groups-picker-multi-select').addEventListener('change', function () {
                    var gradeGroupId = parseInt(this.value[0]);
                    var gradeGroupIds = [];
                    if (this.value) {
                        _.each(this.value, function (obj) {
                            gradeGroupIds.push({ value: obj });
                        });
                    }
                    that.model.fetchGrades({ async: false, gradeGroupIds: gradeGroupIds });

                });

                //-----------------------------
                //-------- GRADES PICKER ------
                //-----------------------------
                var GradesPickerVirtualSelect = new VirtualSelect.init({
                    ele: '#grades-picker-multi-select',
                    options: that.model.get('grades'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    hasOptionDescription: true,
                    showSelectedOptionsFirst: true,
                });
                document.querySelector('#grades-picker-multi-select').addEventListener('change', function () {
                    var grades = [];
                    that.model.set({ selected_grades: [] });
                    _.each(this.value, function (obj) {
                        grades.push({ value: obj });
                    });
                    that.model.set({ selected_grades: grades });
                    that.refresh(null);
                });

            }

            , multiselect_form_grades_gradeGroups: function () {
                var that = this;
                //---------------------------------
                //-------- GRADE GROUPS FORM ------
                //---------------------------------
                var GradeGroupsFormVirtualSelect = new VirtualSelect.init({
                    ele: '#grade-groups-form-multi-select',
                    options: that.model.get('gradeGroups'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    showSelectedOptionsFirst: true,
                });
                document.querySelector('#grade-groups-form-multi-select').addEventListener('change', function () {
                    var gradeGroupId = parseInt(this.value[0]);
                    var gradeGroupIds = [];
                    if (this.value) {
                        _.each(this.value, function (obj) {
                            gradeGroupIds.push({ value: obj });
                        });
                    }
                    that.model.fetchFormGrades({ async: false, gradeGroupIds: gradeGroupIds });
                });

                //---------------------------
                //-------- GRADES FORM ------
                //---------------------------
                var GradesFormVirtualSelect = new VirtualSelect.init({
                    ele: '#grades-form-multi-select',
                    options: that.model.get('formGrades'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    hasOptionDescription: true,
                    showSelectedOptionsFirst: true,
                });
                document.querySelector('#grades-form-multi-select').addEventListener('change', function () {

                    var grades = [];

                    that.model.set({ selected_form_grades: [] });
                    _.each(this.value, function (obj) {
                        grades.push({ value: obj });
                    });

                    that.model.set({ selected_form_grades: grades });
                });
            }



            , multiselect_picker_processes: function () {
                var that = this;
                //--------------------------------
                //-------- PROCESSES PICKER ------
                //--------------------------------
                var ProcessesPickerVirtualSelect = new VirtualSelect.init({
                    ele: '#processes-picker-multi-select',
                    options: that.model.get('processes'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    showSelectedOptionsFirst: true,
                });
                document.querySelector('#processes-picker-multi-select').addEventListener('change', function () {
                    var processes = [];

                    that.model.set({ selected_processes: [] });
                    _.each(this.value, function (obj) {
                        processes.push({ value: obj });
                    });

                    that.model.set({ selected_processes: processes });
                    that.refresh(null);
                });
            }


            , multiselect_form_processes: function () {
                var that = this;
                //--------------------------------
                //-------- PROCESSES FORM ------
                //--------------------------------
                var ProcessesFormVirtualSelect = new VirtualSelect.init({
                    ele: '#processes-form-multi-select',
                    options: that.model.get('processes'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    showSelectedOptionsFirst: true,
                });


                document.querySelector('#processes-form-multi-select').addEventListener('change', function () {
                    var processes = [];

                    that.model.set({ selected_form_processes: [] });
                    _.each(this.value, function (obj) {
                        processes.push({ value: obj });
                    });

                    that.model.set({ selected_form_processes: processes });
                });

            }


            , multiselect_picker_sizes: function () {
                var that = this;
                //--------------------------------
                //-------- SIZES PICKER ----------
                //--------------------------------
                var SizesPickerVirtualSelect = new VirtualSelect.init({
                    ele: '#sizes-picker-multi-select',
                    options: that.model.get('sizes'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    showSelectedOptionsFirst: true,
                });
                document.querySelector('#sizes-picker-multi-select').addEventListener('change', function () {
                    var sizes = [];
                    that.model.set({ selected_sizes: [] });
                    _.each(this.value, function (obj) {
                        sizes.push({ value: obj });
                    });
                    that.model.set({ selected_sizes: sizes });
                    that.refresh(null);
                });
            }


            , multiselect_form_sizes: function () {
                var that = this;
                //--------------------------------
                //-------- SIZES FORM ------
                //--------------------------------
                var SizesFormVirtualSelect = new VirtualSelect.init({
                    ele: '#sizes-form-multi-select',
                    options: that.model.get('sizes'),
                    multiple: true,
                    search: true,
                    placeholder: 'Select options here',
                    showSelectedOptionsFirst: true,
                });


                document.querySelector('#sizes-form-multi-select').addEventListener('change', function () {
                    var sizes = [];

                    that.model.set({ selected_form_sizes: [] });
                    _.each(this.value, function (obj) {
                        sizes.push({ value: obj });
                    });

                    that.model.set({ selected_form_sizes: sizes });
                });
            }



            , multiselectPickersConfiguration: function () {
                this.multiselect_picker_grades_gradeGroups();
                this.multiselect_form_grades_gradeGroups();
                this.multiselect_picker_processes();
                this.multiselect_form_processes();
                this.multiselect_picker_sizes();
                this.multiselect_form_sizes();


            }

            , bindEvents: function () {
                this.listenTo(this.model, 'change:gradeId change:processId', this.refresh);
                this.listenTo(this.itemsColl, 'fileDownloaded', this.fileDownload_ready);
                this.listenTo(this.fileitemsColl, 'fetch', this.fileitemsColl_fetch);
                this.listenTo(this.model, 'fetch-grades', this.grades_fetch);
                this.listenTo(this.model, 'fetch-form-grades', this.form_grades_fetch);
                this.listenTo(this.itemsColl, 'fetch', this.itemsColl_fetch),
                    _.bindAll(this, 'on_keypress'),
                    $(document).bind('keydown', this.on_keypress);
                this.listenTo(this.model, 'change:itemId', this.index_change);

            }

            , fileitemsColl_fetch: function () {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_files: (that.fileitemsColl.length > 0),
                            isLoading_files: false,
                        });
                    },
                    100
                );
            }
            , index_change: function () {
                var index = this.model.get('index');
                var itemId = this.model.get('itemId');
                this.fileitemsColl.reset();
                this.model.set({
                    hasData_files: false,
                    isLoading_files: true,
                });
                if (itemId)
                    this.fileitemsColl.fetch({
                        itemId: itemId
                    });
            }

            , refresh_files: function () {
                var itemId = this.model.get('itemId');
                this.fileitemsColl.reset();
                this.model.set({
                    hasData_files: false,
                    isLoading_files: true,
                });
                if (itemId)
                    this.fileitemsColl.fetch({
                        itemId: itemId
                    });
            }

            , saveFile: function () {
                var fileName = this.model.get('fileName');
                var fileDB64 = this.model.get('fileDB64');
                var newFilesBuffer = this.model.get('newFilesBuffer');

                newFilesBuffer.push({
                    fileName: fileName,
                    fileDB64: fileDB64,
                });

                this.model.set({
                    newFilesBuffer: newFilesBuffer,
                    inputFileName: '',
                    file_selected: false,
                });
                this.fileitemsColl.addModel({ Id: null, fileName: fileName });
            }

            , FileBtn_change: function (e) {

                var that = this;
                var input = this.$el.find('#FileBtn');

                var filename = input.val();
                var file = input[0].files[0];
                //Setup file reader
                var reader = new FileReader();

                // Read file into memory as UTF-16
                reader.readAsDataURL(file);
                // Handle progress, success, and errors
                reader.onload = function (evt) {
                    //Separate the headers from the data
                    var fileString = evt.target.result;
                    var data = fileString.split(',');

                    that.model.set({
                        fileName: filename.substr(12),
                        fileDB64: data[1],
                        inputFileName: filename.substr(12),
                        hasData_files: true,
                    });
                    that.saveFile();
                };
                reader.onerror = function errorHandler(evt) {
                    if (evt.target.error.name == "NotReadableError") {
                        app.views.topMessages.showMessage(app.translate([that, app], 'could_not_read_file'), { stay: 5 * 1000, });
                    }
                };
            }

            , setLoadingRowDownload: function (btnDownload, loadingRow) {
                this.model.set({
                    btnDownload: btnDownload,
                    loadingRow: loadingRow,
                })
                btnDownload.addClass("hide");
                loadingRow.removeClass("hide");
            }
            , fileDownload_ready: function (fileInfo) {
                if (fileInfo && fileInfo.FileName) window.open('http://L2S-MLT-MES/Export/TWIFiles/' + fileInfo.FileName)
                var btnDownload = this.model.get('btnDownload');
                var loadingRow = this.model.get('loadingRow');
                btnDownload.removeClass("hide");
                loadingRow.addClass("hide");

                this.model.set({
                    btnDownload: null,
                    loadingRow: null,
                })
            }


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

                                that.multiselectPickersConfiguration();



                                var ActionsCellDownload = Backgrid.Cell.extend({
                                    template: _.template(that.$el.find("#actions_cell_template").html()),
                                    className: "actions-cell align-center-cell",
                                    initialize: function () {
                                        Backgrid.Cell.prototype.initialize.apply(this, arguments);
                                    },
                                    events: {
                                        "click .btn-cell-action": "cellActionClick"
                                    },
                                    cellActionClick: function (e) {
                                        var target = $(e.target);
                                        var actionData = target.closest("[data-cell-action]").data("cell-action");
                                        if (actionData) {
                                            if (actionData == 'DOWNLOAD') {
                                                var btnDownload = this.$el.find(".btn-download");
                                                var loadingRow = this.$el.find(".loading-row");
                                                that.model.set({
                                                    downloadBtnPressed: true,
                                                });
                                                that.setLoadingRowDownload(btnDownload, loadingRow);
                                            }
                                            that.actionOnRow(this.model, actionData);

                                        }
                                    },
                                    render: function () {
                                        this.$el.html(this.template());

                                        this.$el.find("[data-toggle='tooltip']").tooltip();

                                        this.setRedirectMode();
                                        this.delegateEvents();
                                        return this;
                                    },
                                    setRedirectMode: function (val) {
                                        var btnDownload = this.$el.find(".btn-download");
                                        if (this.model.get('Id')) btnDownload.removeClass("hide");
                                    },
                                });

                                var ActionsCellRemove = Backgrid.Cell.extend({
                                    template: _.template(that.$el.find("#actions_cell_remove_template").html()),
                                    className: "actions-cell align-center-cell",
                                    initialize: function () {
                                        Backgrid.Cell.prototype.initialize.apply(this, arguments);
                                    },
                                    events: {
                                        "click .btn-cell-action": "cellActionClick"
                                    },
                                    cellActionClick: function (e) {
                                        var target = $(e.target);
                                        var deleteFilesBuffer = that.model.get('deleteFilesBuffer');
                                        that.fileitemsColl.removeModel({ model: this.model });
                                        if (this.model.get('Id')) {
                                            deleteFilesBuffer.push({ FileId: this.model.get('Id') })
                                            that.model.set({ deleteFilesBuffer: deleteFilesBuffer });
                                        } else {
                                            var index = 0;
                                            var fileNameToRemove = this.model.get('fileName');
                                            var newFilesBuffer = that.model.get('newFilesBuffer');

                                            _.each(that.model.get('newFilesBuffer'), function (obj, i) {
                                                if (obj.fileName === fileNameToRemove) index = i;
                                            });
                                            newFilesBuffer.splice(index, 1);
                                            that.model.set({ newFilesBuffer: newFilesBuffer });

                                        }
                                    },
                                    render: function () {
                                        this.$el.html(this.template());

                                        this.$el.find("[data-toggle='tooltip']").tooltip();
                                        this.delegateEvents();
                                        return this;
                                    },
                                });

                                // Files Grid
                                var gridFiles = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'DocumentName',
                                            label: app.translate(that, 'item_document_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell DocumentName',
                                            }),
                                        },
                                        {
                                            name: "actionsDownloadform",
                                            label: "",
                                            editable: false,
                                            sortable: false,
                                            cell: ActionsCellDownload
                                        },
                                        {
                                            name: "actionsRemoveform",
                                            label: "",
                                            editable: false,
                                            sortable: false,
                                            cell: ActionsCellRemove
                                        },
                                    ],


                                    collection: that.fileitemsColl,
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                            if (!this.model.get('Id')) this.$el.addClass("newFileClass");
                                        },

                                    }),


                                });


                                that.$el.find('.items-files-grid-container').append(gridFiles.render().el);







                                var grid = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'Name',
                                            label: app.translate(that, 'item_name_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'EndDateSring',
                                            label: app.translate(that, 'item_expiration_date_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),

                                        },
                                        {
                                            name: 'ProcessNames',
                                            label: app.translate(that, 'item_process_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'GradeNames',
                                            label: app.translate(that, 'item_grade_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'SizeNames',
                                            label: app.translate(that, 'item_size_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'MeltOrder',
                                            label: app.translate(that, 'item_melt_order_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'Author',
                                            label: app.translate(that, 'item_author_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'Archived',
                                            label: app.translate(that, 'item_archived_col_label'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.Cell.extend({
                                                template: function () {
                                                    return _.template("<input class='grid-checkbox checkbox big-checkbox' tabindex='-1' type='checkbox' disabled/>");
                                                },
                                                initialize: function () {
                                                    Backgrid.Cell.prototype.initialize.apply(this, arguments);
                                                },
                                                render: function () {
                                                    this.$el.html(this.template());
                                                    if (this.model.get("Archived")) this.$el.find(".grid-checkbox").attr("checked", "checked");

                                                    this.delegateEvents();
                                                    return this;
                                                },
                                                className: "string-cell align-center-cell col-class",
                                            }),
                                        },
                                    ],

                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        },
                                        events: {
                                            click: 'click',
                                        },

                                        click: function (e) {
                                            try {
                                                if (that.model.get('downloadBtnPressed') == false) {


                                                    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();

                                                } else {
                                                    that.model.set('downloadBtnPressed', false);
                                                }
                                            }
                                            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();

                                // set view parameters as model parameters
                                var Ids = [];
                                if (viewParams.Ids) {
                                    var array = viewParams.Ids.split(',');
                                    _.each(array, function (obj) {
                                        Ids.push({ Id: obj });
                                    });
                                }
                                // refresh collection
                                that.refresh(Ids);
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            actionOnRow: function (model, action) {
                switch (action.toUpperCase()) {
                    case "DOWNLOAD":
                        this.itemsColl.downloadItem({
                            itemId: model.get('Id'),
                        });
                        break;
                }
            },

            refresh: function (Ids) {
                try {
                    this.itemsColl.reset();
                    this.model.set({
                        index: null,
                        isLoading: true,
                        hasData: false,
                        newFilesBuffer: [],
                        deleteFilesBuffer: [],
                        showDataEntryMode: '',
                    });
                    // reload collection 
                    this.itemsColl.fetch({
                        archived: this.model.get('archived'),
                        searchText: this.model.get('searchText'),
                        gradeId: this.model.get('gradeId'),
                        processId: this.model.get('processId'),
                        processes: this.model.get('selected_processes'),
                        grades: this.model.get('selected_grades'),
                        sizes: this.model.get('selected_sizes'),
                        Ids: Ids ? Ids : [],
                        refresh: true,
                    });
                    this.UpdateURL();
                }
                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;
                }
            }

            , 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(null);
                    });
                    modal.show();

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


            , saveItemBtn_click: function (model) {
                this.itemsColl.upsertItem(this.model);
                this.model.set(this.itemsColl.model.prototype.getDefault());
                this.model.set('showDataEntryMode', '');
                this.UpdateURL();
                this.refresh(null);
            }
            , UpdateURL: function () {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    Ids: '',
                                }
                            ),
                            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.UpdateURL();
                this.refresh(null);
            },




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

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

            },

            insideInputOrTextarea: function () {
                var name = document.getElementById('input-name'),
                    meltorder = document.getElementById('input-meltorder');
                return (document.activeElement === name || document.activeElement === meltorder);
            },


            on_keypress: function (e) {
                var that = this,
                    rowsView = that.model.get('grid').body.rows,
                    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-twi-management"),
                            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(null);
                } catch (Error) { }
            },


        });


        Screen.Models.Item = Backbone.Epoxy.Model.extend({
            getDefault: function () {
                var result = {};
                result = {
                    itemId: null,
                    itemMO: '',
                    itemGrade: null,
                    itemName: '',
                    itemArchived: false,
                    itemProcess: 1,
                    inputFileName: '',
                }

                return result;
            }
        });

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

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


            fixedParameters: [],

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

            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};

                var IdsObject = params.Ids

                if (IdsObject) {
                    if (!params.Ids.length) IdsObject = [];
                }

                if (options.refresh) {
                    this.resetPagination(true);



                    if ($.isNumeric(params.itemId)) {
                        this.fixedParameters = [
                            { Name: '@Id', Type: 'INT', Value: params.itemId, }
                        ]
                    }
                    else {
                        this.fixedParameters = [
                            { Name: '@Search', Type: 'VARCHAR', Value: params.searchText != '' ? params.searchText : null, },
                            { Name: '@Archived', Type: 'BIT', Value: params.archived, },
                            { Name: '@GradeId', Type: 'INT', Value: params.gradeId === '-' ? null : parseInt(params.gradeId) },
                            { Name: '@ProcessId', Type: 'INT', Value: params.processId === '1' ? null : parseInt(params.processId) },
                        ];
                        //layout data xml parameter
                        var processes = [];
                        var allProcessesSelected = document.querySelector('#processes-picker-multi-select').isAllSelected();
                        if (!allProcessesSelected) processes = params.processes;

                        qp.Add(
                            'LayoutProcesses',
                            'XML',
                            app.jsonArrayToXml(
                                processes,
                                [
                                    'value',
                                ]
                            )
                        );
                        //layout data xml parameter
                        var grades = [];
                        var allGradesSelected = document.querySelector('#grades-picker-multi-select').isAllSelected();
                        if (!allGradesSelected) grades = params.grades;
                        qp.Add(
                            'LayoutGrades',
                            'XML',
                            app.jsonArrayToXml(
                                grades,
                                [
                                    'value',
                                ]
                            )
                        );
                        //layout data xml parameter
                        var sizes = [];
                        var allSizesSelected = document.querySelector('#sizes-picker-multi-select').isAllSelected();
                        if (!allSizesSelected) sizes = params.sizes;
                        qp.Add(
                            'LayoutSizes',
                            'XML',
                            app.jsonArrayToXml(
                                sizes,
                                [
                                    'value',
                                ]
                            )
                        );
                        //layout data xml parameter
                        qp.Add(
                            'LayoutIds',
                            'XML',
                            app.jsonArrayToXml(
                                IdsObject,
                                [
                                    'Id',
                                ]
                            )
                        );



                    }
                }
                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 + '.TWI.GetEntries',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    var newColl = resp.Table;
                                    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);
                }
            },
            downloadItem: function (params) {
                try {
                    var that = this;
                    var qp = new QueryParameters();
                    qp.Add('@Id', 'INT', parseInt(params.itemId));
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.TWI.DownloadFileByPath',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp) {
                                        that.trigger('fileDownloaded', resp.Table[0]);
                                        //app.views.topMessages.showMessage('File Downloaded', { stay: 5000, });
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                            that.trigger('fileDownloaded', null);
                                        }
                                        else {
                                            that.trigger('fileDownloaded', null);
                                            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); }
            },


            deleteItem: function (params) {
                try {
                    var that = this;
                    var qp = new QueryParameters();
                    qp.Add('@Id', 'INT', params.itemId);

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.TWI.DeleteEntry',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp) {
                                        app.views.topMessages.showMessage('Item 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 {
                    var that = this;
                    var qp = new QueryParameters();
                    var str = model.get('fileName');
                    var fileName = null;

                    if (str) {
                        fileName = str.replace(/\s/g, '');
                    }
                    item = [
                        { name: '@Id', type: 'VARCHAR', value: model.get('itemId') },
                        { name: '@Name', type: 'VARCHAR', value: model.get('itemName') },
                        { name: '@MeltOrder', type: 'VARCHAR', value: model.get('itemMO') },
                        { name: '@Archived', type: 'BIT', value: model.get('itemArchived') },
                        { name: '@EndDate', type: 'DATE', value: new moment(model.get('itemEndDate'), 'MM/DD/YYYY').format('YYYY-MM-DD') },

                    ];

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

                    }

                    qp.Add(
                        'LayoutProcesses',
                        'XML',
                        app.jsonArrayToXml(
                            model.get('selected_form_processes'),
                            [
                                'value',
                            ]
                        )
                    );

                    qp.Add(
                        'LayoutSizes',
                        'XML',
                        app.jsonArrayToXml(
                            model.get('selected_form_sizes'),
                            [
                                'value',
                            ]
                        )
                    );

                    qp.Add(
                        'LayoutGrades',
                        'XML',
                        app.jsonArrayToXml(
                            model.get('selected_form_grades'),
                            [
                                'value',
                            ]
                        )
                    );

                    qp.Add(
                        'LayoutNewFiles',
                        'XML',
                        app.jsonArrayToXml(
                            model.get('newFilesBuffer'),
                            [
                                'fileDB64',
                                'fileName'
                            ]
                        )
                    );
                    qp.Add(
                        'LayoutDeleteFiles',
                        'XML',
                        app.jsonArrayToXml(
                            model.get('deleteFilesBuffer'),
                            [
                                'FileId',
                            ]
                        )
                    );

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.TWI.UpsertEntry',
                        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('Item 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.");
                                        }
                                    }
                                    // that.trigger('entry-upserted');
                                }
                                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.Collections.FileItems = Backbone.Collection.extend({
            isFetching: false,
            currentPage: 1,
            pageSize: 100,


            fixedParameters: [],

            addModel: function (params) {
                var DocumentName = new moment().format('YYYYMMDDHHmmss') + params.fileName
                this.unshift({ Id: null, fileName: params.fileName, DocumentName: DocumentName });
            },
            removeModel: function (params) {
                this.remove(params.model);
            },

            fetch: function (params) {
                var that = this,
                    fixedParameters = [],
                    qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};
                this.fixedParameters = [
                    { Name: '@EntryId', Type: 'VARCHAR', Value: params.itemId, },

                ];

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


                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.TWI.GetFiles',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    var newColl = resp.Table;

                                    //var method = (options.refresh) ? 'set' : 'add';
                                    method = 'set';

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

        });

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

    });