//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/infinator',
    'backgrid/moment-cell',
    'backgrid/duration-cell',
    'backgrid/grouped-columns',

    "js/jquery.floatThead/jquery.floatThead",
    'js/jquery.contextMenu/jquery.contextMenu',
],
    function (app, T, Backgrid, moment,Modal) {

        var Screen = { Models: {}, Views: {}, Collections: {} }

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                start: new moment().subtract(2, 'days').format('YYYY-MM-DD'),
                end: new moment().format('YYYY-MM-DD'),

                tankCode: null,
                tanks: [{ label: '1', value: 1 }, { label: '2', value: 2 }],

                crewId: null,
                crews: [{ label: 'A', value: 'A' }, { label: 'B', value: 'B' }, { label: 'C', value: 'C' }, { label: 'D', value: 'D' }],

                shiftId: null,
                shifts: [{ label: 'D', value: 1 }, { label: 'N', value: '2' }],

                hasData: false,
                isLoading: false,

                rowModel: [],
                contextMenuOption:1,
                
                index: null,
                grid: [],
                hasPermission: false,
                hideShowHandAdditionToggle: false,
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },

        });


        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'vtd-production',
            id: 'vtd-production',
            title: 'VTD Production',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    "click .btn-export-to-excel": this.exportToExcel,
                    'click #closeHandAdditionModal': this.refreshBtn_click,
                    "click .handAddToggle" : this.hideShowHandAddition,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            itemsColl: null,
            subviews: null,
            viewParams: null,

            initialize: function () {
                this.options.state = app.view_states.loading;
                this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

                var that = this;

                if (!this.model)
                    this.model = new Screen.Models.Main();

                this.grids = {};

                this.itemsColl = new Screen.Collections.Items();


                this.bindingSources = {};

                this.subviews = {};
                this.autoRefresh = {
                    enabled: null
                    , toid: null
                    , every: 5 * 1000
                };


                this.bindEvents();
                this.getPermissions();
            },
            getPermissions: function () {
                var write = $.inArray('vtdp_w', app.models.user.get('roles'));
                var ctx = {
                    readWrite: (write != -1) ? true : false,
                };
                this.model.set('hasPermission', ctx.readWrite);
            },
            bindEvents: function () {
                this.listenTo(this.itemsColl, 'fetch', this.processes_ready);
                this.listenTo(this.itemsColl, 'backgrid:rowclick', this.backgrid_rowclick);

            },
            backgrid_rowclick: function (model) {
                try {
                    app.router.navigate(
                        app.router.resolveURL(
                            'vtd-heat-report',
                            {
                                heatName: model.get('HeatName'),
                                treatmentNumber: model.get('Treatment'),
                            },
                            false
                        ),
                        { trigger: true, }
                    );
                }
                catch (Error) { console.error(Error.stack); }
            },
            _refresh: function (opt) {
                this.itemsColl.reset();

                this.model.set({
                    hasData: false,
                    isLoading: true,
                });

                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }

                this.refreshProcesses(opt);

                if (this.autoRefresh.enabled == true) {
                    var that = this;

                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        this.autoRefresh.every
                    );
                }
            },
            refresh: function (viewParams) {

                var fixedParams = _.extend({}, Screen.Models.Main.prototype.defaults, viewParams);

                if (viewParams.start)
                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.tankCode)
                    fixedParams.tankCode = (viewParams.tankCode != '-' && viewParams.tankCode != null) ? parseInt(viewParams.tankCode, 10) : null;
                if (viewParams.crewId)
                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                if (viewParams.shiftId)
                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;

                this.model.set(fixedParams);

                this._refresh({
                    reset: true,
                    params: _.extend(
                        {},
                        fixedParams,
                        {}
                    ),
                });
            },
       

            render: function (container, viewParams) {
                var that = this;

                this.viewParams = viewParams;

                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) {
                        if (!that.options.i18n) that.options.i18n = {};

                        app.getI18NJed(
                            that,
                            that.template,
                            function (i18nJED) {
                                //storing internationalization data
                                that.options.i18n[that.template] = i18nJED;

                                //loading the view and appeding it to the views's $el.
                                that.$el.html(tmp());

                                that.applyBindings();

                                that.$('.handAddToggle').prop('checked', that.model.get("hideShowHandAdditionToggle"));
                                //that.$el.find(".handAddToggle")[0].checked = that.model.get("hideShowHandAdditionToggle");

                                //start: the view was already loaded an is on a div element, but not appended to the main container
                                //here you can perform anything you want DOM related, by getting the dom element via that.$el.find('#id')
                                //or this.$('#id')


                                var header = Backgrid.Extension.GroupedHeader.extend({
                                    columnLayout:
                                        [{
                                            name: 'Wire Additions', children:
                                                [
                                                    { name: 'Aluminum' },
                                                    { name: 'CaSi' },
                                                    { name: 'FeB' },
                                                    { name: 'FeTi' },
                                                    { name: 'Sulphur' },

                                                ]
                                        },
                                        {
                                            name: 'Hand Additions', children:
                                                [
                                                    { name: 'MAluminum' },
                                                    { name: 'MCaSi' },
                                                    { name: 'MFeB' },
                                                    { name: 'MFeTi' },
                                                    { name: 'MSulphur' },

                                                ]
                                        },
                                       
                                        ],
                                    initialize: function (options) {
                                        Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        //this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },
                                    render: function () {
                                        var that = this;
                                        Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                        return this;
                                    },
                                });

                                var columns = [
                                    {
                                        name: 'HeatName',
                                        label: app.translate([that, app], 'Heat'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell start-row',
                                        }),                                    
                                    },  
                                    {
                                        name: 'ShiftName',
                                        label: app.translate([that, app], 'Shift'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    }, 
                                    {
                                        name: 'CrewId',
                                        label: app.translate([that, app], 'Crew'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },                                  
                                    {
                                        name: 'TankCode',
                                        label: app.translate([that, app], 'Tank'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'LadleId',
                                        label: app.translate([that, app], 'Ladle'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'StartLocal',
                                        label: app.translate([that, app], 'Start'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell start-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'EndLocal',
                                        label: app.translate([that, app], 'End'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell start-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'TotalTime',
                                        label: app.translate([that, app], 'Total Time'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell start-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Treatment',
                                        label: app.translate([that, app], 'Treatment'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MinimumTorr',
                                        label: app.translate([that, app], 'Min Torr'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MinTorrTime',
                                        label: app.translate([that, app], 'Min Torr Time'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'VacTime',
                                        label: app.translate([that, app], 'Vaccum Time'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MeltOrder',
                                        label: app.translate([that, app], 'Melt Order'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },    
                                    {
                                        name: 'GradeName',
                                        label: app.translate([that, app], 'Grade'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },   
                                    {
                                        name: 'Temperature',
                                        label: app.translate([that, app], 'Temp.'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Aluminum',
                                        label: app.translate([that, app], 'Al'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    }, 
                                    {
                                        name: 'CaSi',
                                        label: app.translate([that, app], 'CaSi'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    }, 

                                    {
                                        name: 'FeB',
                                        label: app.translate([that, app], 'FeB'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    }, 
                                    {
                                        name: 'FeTi',
                                        label: app.translate([that, app], 'FeTi'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    }, 
                                    {
                                        name: 'Sulphur',
                                        label: app.translate([that, app], 'Sulfur'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MAluminum',
                                        label: app.translate([that, app], 'Al'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MCaSi',
                                        label: app.translate([that, app], 'CaSi'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    },

                                    {
                                        name: 'MFeB',
                                        label: app.translate([that, app], 'FeB'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MFeTi',
                                        label: app.translate([that, app], 'FeTi'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    }, 
                                    {
                                        name: 'MSulphur',
                                        label: app.translate([that, app], 'Sulfur'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell materials-row',
                                        }),
                                        editable: false,
                                    }, 
                                    {
                                        name: 'isFoamed',
                                        label: app.translate([that, app], 'Heat Foamed'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Cell.extend({
                                            events: {
                                                click: 'click',
                                            },
                                            template: function () {
                                                
                                                if (that.model.get('hasPermission')) {
                                                    return _.template("<input class='grid-checkbox checkbox big-checkbox' tabindex='-1' type='checkbox'/>"); 
                                                }
                                                else {
                                                    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("isFoamed")) this.$el.find(".grid-checkbox").attr("checked", "checked");
                                                this.delegateEvents();
                                                return this;
                                            },
                                            click: function (e) {
                                                var that = this;
                                                if (e.target.getAttribute('type') == 'checkbox') {

                                                    var actionOnCheck = (e.target.checked) ? 'Check' : 'Uncheck';
                                                    modal = new Modal.Views.Main({
                                                        focusOk: false,
                                                        focusSelector: '#btn-cancel',
                                                        title: 'Profiles Screen Role',
                                                        message: 'Are you sure you want to ' + actionOnCheck +' Foamed for Heat: ' + that.model.get('HeatName') + '?',
                                                        buttons_type: "CONTINUE-CANCEL",
                                                    });
                                                    this.listenToOnce(modal, "continue", function (modal) {
                                                        try {
                                                            var params = { option: 'F', processId: this.model.get('Id'), enabled: e.target.checked }
                                                            this.model.collection.updateFoamedStirredWell(params);
                                                        }
                                                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                                    });

                                                    this.listenToOnce(modal, "cancel", function (modal) {
                                                        try {
                                                            if (e.target.checked) {
                                                                this.$el.find(".grid-checkbox")[0].checked = false
                                                            }
                                                            else {
                                                                this.$el.find(".grid-checkbox")[0].checked = true
                                                            }
                                                        }
                                                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                                    });
                                                    modal.show();
                                                   
                                                    
                                                }
                                            },  
                                            className: "string-cell align-center-cell col-class",
                                        }),
                                    },
                                    {
                                        name: 'isStirredWell',
                                        label: app.translate([that, app], 'Ladle Stirred Well'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Cell.extend({
                                            events: {
                                                click: 'click',
                                            },
                                            template: function () {

                                                if (that.model.get('hasPermission')) {
                                                    return _.template("<input class='grid-checkbox checkbox big-checkbox' tabindex='-1' type='checkbox'/>");
                                                }
                                                else {
                                                    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("isStirredWell")) this.$el.find(".grid-checkbox").attr("checked", "checked");
                                                this.delegateEvents();
                                                return this;
                                            },
                                            click: function (e) {
                                                if (e.target.getAttribute('type') == 'checkbox') {

                                                    var actionOnCheck = (e.target.checked) ? 'Check' : 'Uncheck';
                                                    modal = new Modal.Views.Main({
                                                        focusOk: false,
                                                        focusSelector: '#btn-cancel',
                                                        title: 'Profiles Screen Role',
                                                        message: 'Are you sure you want to ' + actionOnCheck + ' Stirred for Heat: ' + that.model.get('HeatName') + '?',
                                                        buttons_type: "CONTINUE-CANCEL",
                                                    });
                                                    this.listenToOnce(modal, "continue", function (modal) {
                                                        try {
                                                            var params = { option: 'S', processId: this.model.get('Id'), enabled: e.target.checked }
                                                            this.model.collection.updateFoamedStirredWell(params);
                                                        }
                                                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                                    });

                                                    this.listenToOnce(modal, "cancel", function (modal) {
                                                        try {
                                                            if (e.target.checked) {
                                                                this.$el.find(".grid-checkbox")[0].checked = false
                                                            }
                                                            else {
                                                                this.$el.find(".grid-checkbox")[0].checked = true
                                                            }
                                                        }
                                                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                                    });
                                                    modal.show();

                                                }
                                            },
                                            className: "string-cell align-center-cell col-class",
                                        }),
                                    },
                                    {
                                        name: 'Hand Additions',
                                        cell: Backgrid.Cell.extend({
                                            className: "button-cell align-center-cell materials-row",
                                            events: {
                                                'click button': 'onButtonClick'
                                            },
                                            render: function () {
                                                this.$el.empty();
                                                var button = $('<button>').html('<i class="fa fa-pencil-square-o" aria-hidden="true"></i>');
                                                button.addClass('handAdditionBtn');
                                                this.$el.append(button);
                                                this.delegateEvents();
                                                return this;
                                            },
                                            onButtonClick: function (e) {
                                                e.preventDefault();
                                                if (e.target.nodeName == 'I') {
                                                    
                                                   
                                                    this.showModal();
                                                }
                                            },
                                            showModal: function () {
                                                var that = this;
                                                var params = { ProcessId: this.model.get('Id') }
                                                var handAdditionAndMat = this.getHandAdditions(params);
                                                var handAdditions = handAdditionAndMat.handAdditions;
                                                var materials = handAdditionAndMat.materials;

                                                var CustomRow = Backgrid.Row.extend({
                                                    render: function () {
                                                        Backgrid.Row.prototype.render.apply(this, arguments);

                                                        // Add a placeholder for the save button
                                                        this.$el.append('<td class="save-button-cell align-center-cell renderable"><button class="save-action-button"  style="visibility:hidden;"><i class="fa fa-check-square" aria-hidden="true"></i></button></td>');
                                                        return this;
                                                    }
                                                });

                                                var DeleteCell = Backgrid.Cell.extend({
                                                    className: 'delete-cell align-center-cell',
                                                    events: {
                                                        'click .delete-button': 'deleteRow'
                                                    },
                                                    render: function () {
                                                        this.$el.html('<button class="delete-button"><i class="fa fa-minus-circle" aria-hidden="true"></i></button>');
                                                        return this;
                                                    },
                                                    deleteRow: function (e) {

                                                        var rowElement = $(e.currentTarget).closest('tr');
                                                        var row = gridAlloys.body.rows.find(function (row) {
                                                            return row.el === rowElement[0];
                                                        });

                                                        e.preventDefault();
                                                        $('#handAdditions').addClass('blur');
                                                        modal = new Modal.Views.Main({
                                                            focusOk: false,
                                                            focusSelector: '#btn-cancel',
                                                            title: 'Remove Addition',
                                                            message: 'Are you sure you want to delete the Addition?',
                                                            buttons_type: "CONTINUE-CANCEL",
                                                        });
                                                        that.listenToOnce(modal, "continue", function (modal) {
                                                            try {
                                                                var params = { HandAdditionId: row.model.get('Id') }
                                                                var removed = that.removeHandAddition(params);
                                                                // Remove the model from the collection. If was removed OK from the DB
                                                                if (removed) {
                                                                    row.model.collection.remove(row.model);
                                                                    app.views.topMessages.showMessage('Addition Removed', { stay: 5000, });
                                                                }
                                                               else {
                                                                    app.views.topMessages.showMessage('Error Removing Addition', { stay: 5000, });
                                                                }
                                                                $('#handAdditions').removeClass('blur');
                                                            }
                                                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                                        });

                                                        that.listenToOnce(modal, "cancel", function (modal) {
                                                            try {
                                                                $('#handAdditions').removeClass('blur');
                                                            }
                                                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                                        });
                                                        modal.show();
                                                        
                                                    }
                                                });

                                                var MaterialSelectCell = Backgrid.SelectCell.extend({
                                                    className: 'select-cell align-center-cell',
                                                   
                                                    initialize: function (options) {
                                                        Backgrid.SelectCell.prototype.initialize.apply(this, arguments);

                                                        // Map material names to IDs
                                                        this.optionValues = materials.map(function (material) {
                                                            return [material.get('Name'), material.get('Id')];
                                                        });

                                                        // Set the initial value
                                                        this.listenTo(this.model, 'change:Material', this.render);
                                                    },

                                                    render: function () {
                                                        // Get the material name from the model
                                                        var materialName = this.model.get('Material');


                                                        // I do this because in the plant they called Sulfur and we have it Sulphur. 
                                                        if (materialName == 'Sulphur') {
                                                            materialName = 'Sulfur';
                                                        }

                                                        // Find the corresponding material ID
                                                        var material = materials.find(function (m) {
                                                            return m.get('Name') === materialName;
                                                        });

                                                        if (material) {
                                                            // Set the value to the material ID
                                                            this.$el.html('<select>' + this.optionValues.map(function (option) {
                                                                return '<option value="' + option[1] + '"' + (option[1] === material.get('Id') ? ' selected' : '') + '>' + option[0] + '</option>';
                                                            }).join('') + '</select>');
                                                        }
                                                        this.$el.find('select').on('change', this.updateModel.bind(this));
                                                        return this;
                                                    },

                                                    updateModel: function (e) {
                                                        var selectedId = this.$el.find('select').val();
                                                        var selectedMaterial = materials.find(function (material) {
                                                            return material.get('Id') == selectedId;
                                                        });

                                                        if (selectedMaterial) {
                                                            // Update the model with the new Material Name and Id
                                                            this.model.set({
                                                                'Material': selectedMaterial.get('Name'),
                                                                'MaterialId': selectedId
                                                            });
                                                        }
                                                    }
                                                });

                                                var TimestampCell = Backgrid.Cell.extend({
                                                    className: 'timestamp-cell align-center-cell',
                                                    editor: Backgrid.InputCellEditor.extend({
                                                        events: {
                                                            'blur': 'save',
                                                            'keydown': function (e) {
                                                                if (e.which === 13) { // Enter key
                                                                    this.save();
                                                                }
                                                            }
                                                        },
                                                        render: function () {
                                                            Backgrid.InputCellEditor.prototype.render.apply(this, arguments);
                                                            var flatpickrInstance = flatpickr(this.el, {
                                                                enableTime: true,
                                                                dateFormat: 'Y-m-d H:i',
                                                                onChange: (selectedDates, dateStr) => {
                                                                    this.model.set(this.column.get('name'), dateStr);
                                                                }
                                                            });
                                                            return this;
                                                        },
                                                        save: function (e) {
                                                            if (this.$el.val()) {
                                                                this.model.set(this.column.get('name'), this.$el.val());
                                                            }
                                                            this.trigger('done');
                                                        }
                                                    })
                                                });




                                                    var gridAlloys = new Backgrid.Grid({
                                                        className: 'backgrid table table-hover table-condensed production-table',
                                                        columns: [
                                                            {
                                                                name: 'Material',
                                                                label:  'Material',
                                                                cell: MaterialSelectCell ,
                                                                editable: false,
                                                                sortable: false,
                                                            },
                                                            {
                                                                name: 'WeightValue',
                                                                label:  'Weight',
                                                                cell: Backgrid.NumberCell.extend({
                                                                    className: 'number-cell align-center-cell',
                                                                }),
                                                                editable: true,
                                                                sortable: false,
                                                            },
                                                            {
                                                                name: 'WeightSetpoint',
                                                                label:'Weight SP',
                                                                cell: Backgrid.StringCell.extend({
                                                                    className: 'string-cell align-center-cell',
                                                                }),
                                                                editable: true,
                                                                sortable: false,
                                                            },
                                                            //{
                                                            //    name: 'BinNumber',
                                                            //    label: 'Bin',
                                                            //    cell: Backgrid.StringCell.extend({
                                                            //        className: 'string-cell align-center-cell',
                                                            //    }),
                                                            //    editable: true,
                                                            //    sortable: false,
                                                            //},
                                                            //{
                                                            //    name: 'SourceCode',
                                                            //    label: 'Source',
                                                            //    cell: Backgrid.StringCell.extend({
                                                            //        className: 'string-cell align-center-cell',
                                                            //    }),
                                                            //    editable: false,
                                                            //    sortable: false,
                                                            //},
                                                            {
                                                                name: 'Delete',
                                                                label: '',
                                                                cell: DeleteCell,
                                                                editable: false,
                                                                sortable: false,
                                                            }
                                                        ],
                                                        collection: handAdditions,
                                                        row: CustomRow
                                                    });

                                                $(".hand-additions-items-grid-container").empty().append(gridAlloys.render().el);


                                                gridAlloys.body.$el.on('click', '.save-action-button', function (e) {
                                                    e.preventDefault();

                                                    var rowElement = $(e.currentTarget).closest('tr');
                                                    var row = gridAlloys.body.rows.find(function (row) {
                                                        return row.el === rowElement[0];
                                                    });

                                                    // check if its an ADD or UPDATE via the NewAddition value from the new model
                                                    if (row.model.get('NewAddition')) {

                                                        // Reset previous highlighting
                                                        row.$('.highlight-missing-value').removeClass('highlight-missing-value');

                                                        var missingValue = false;

                                                        // Check for missing values and highlight cells
                                                        var requiredFields = ['Material', 'WeightValue', 'WeightSetpoint', 'SourceCode'];
                                                        requiredFields.forEach(function (field) {
                                                            if (!row.model.get(field)) {
                                                                missingValue = true;
                                                            }
                                                        });

                                                        if (missingValue) {
                                                            app.views.topMessages.showMessage('Please fill in all required fields', { stay: 5000, });
                                                            return;
                                                        }





                                                        var params = { ProcessId: that.model.get('Id'), MaterialId: materials.filter(x => x.get('Name') == row.model.get('Material'))[0].get('Id'), Weight: row.model.get('WeightValue'), WeightSP: row.model.get('WeightSetpoint'), Comments: '' }
                                                        var inserted = that.insertHandAddition(params);
                                                        if (inserted) {
                                                            row.$('.save-action-button').css('visibility', 'hidden');
                                                            app.views.topMessages.showMessage('New Addition Created', { stay: 5000, });
                                                            that.model.trigger('addition-inserted');
                                                        }
                                                        else {
                                                            app.views.topMessages.showMessage('Error Creating new Addition', { stay: 5000, });
                                                        }
                                                    }
                                                    else {
                                                        var params = { AdditionId: row.model.get('Id'), MaterialId: materials.filter(x => x.get('Name') == row.model.get('Material'))[0].get('Id'), Weight: row.model.get('WeightValue'), WeightSP: row.model.get('WeightSetpoint'), Comments: ' ' };
                                                        var updated = that.updateHandAddition(params);


                                                        if (updated) {
                                                            row.$('.save-action-button').css('visibility', 'hidden');
                                                            app.views.topMessages.showMessage('Addition Updated', { stay: 5000, });
                                                        }
                                                        else {
                                                            app.views.topMessages.showMessage('Error Updating Addition', { stay: 5000, });
                                                        }

                                                    }
                                                  
                                                });


                                                $('#addHandAdditionBtn').on('click', function (e) {
                                                    e.preventDefault();

                                                    // Create a new model instance with default values
                                                    var newHandAddition = new Backbone.Model({
                                                        Timestamp: '', 
                                                        //Need to add a value to render the Select
                                                        Material: "CaSi    ",
                                                        WeightValue: null,
                                                        WeightSetpoint: null,
                                                        SourceCode: 'W',
                                                        NewAddition: true
                                                    });
                                                    handAdditions.add(newHandAddition);
                                                   //gridAlloys.render().el;
                                                });

                                                handAdditions.on('change', function (model) {
                                                    // Find the row for the changed model
                                                    var row = gridAlloys.body.rows.find(function (row) {
                                                        return row.model === model;
                                                    });

                                                    if (row) {
                                                        row.$('.save-action-button').css('visibility', 'visible');
                                                        //row.$el.addClass('highlight-modified-row');
                                                    }


                                                });

                                                    // Show the modal
                                                $('#handAdditions').modal('show');
                                                    
                                            },
                                            getHandAdditions: function (params) {
                                                var that = this,
                                                    qp = new Core.Database.QueryParameters();

                                                var handAdditions = new Screen.Collections.ItemsCollection();
                                                var materials = new Screen.Collections.ItemsCollection();

                                                this.fixedParameters = [
                                                    { Name: '@processId', Type: 'INT', Value: params.ProcessId, },
                                                ];
                                                _.each(this.fixedParameters, function (qpParams) {
                                                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                                                });

                                                Core.Json.CallProcedure(
                                                    app.DatabaseNames.MES + '.VTD.GetHandAdditionsByProcessId',
                                                    qp,
                                                    {
                                                        onSuccess: function (resp) {
                                                            try {
                                                                if (resp) {


                                                                    if (resp.Table) {
                                                                        
                                                                        handAdditions.setDataColl(resp.Table);
                                                                        materials.setDataColl(resp.Table1);
                                                                    } 

                                                                    that.trigger('fetch', resp);
                                                                }
                                                                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: false,
                                                    },
                                                    app.ConnectionStrings.app
                                                );

                                                return { handAdditions: handAdditions, materials: materials };
                                            },
                                            removeHandAddition: function (params) {
                                                var that = this,
                                                    qp = new Core.Database.QueryParameters();

                                                var removed = false;
                                                this.fixedParameters = [
                                                    { Name: '@id', Type: 'INT', Value: params.HandAdditionId, },
                                                    { Name: '@comment', Type: 'VARCHAR', Value: ' ', },
                                                ];
                                                _.each(this.fixedParameters, function (qpParams) {
                                                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                                                });

                                                Core.Json.CallProcedure(
                                                    app.DatabaseNames.MES + '.VTD.RemoveAdditionManually',
                                                    qp,
                                                    {
                                                        onSuccess: function (resp) {
                                                            try {
                                                                if (resp) {


                                                                    if (resp.Table) {
                                                                        removed = true;
                                                                    }

                                                                }
                                                                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: false,
                                                    },
                                                    app.ConnectionStrings.app
                                                );

                                                return removed;
                                            },
                                            updateHandAddition: function (params) {
                                                var that = this,
                                                    qp = new Core.Database.QueryParameters();

                                                var updated = false;
                                                this.fixedParameters = [
                                                    { Name: '@id', Type: 'INT', Value: params.AdditionId, },
                                                    { Name: '@materialId', Type: 'INT', Value: params.MaterialId, },
                                                    { Name: '@weight', Type: 'FLOAT', Value: params.Weight, },
                                                    { Name: '@weightSP', Type: 'FLOAT', Value: params.WeightSP, },
                                                    { Name: '@comment', Type: 'VARCHAR', Value: ' ', },
                                                ];
                                                _.each(this.fixedParameters, function (qpParams) {
                                                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                                                });

                                                Core.Json.CallProcedure(
                                                    app.DatabaseNames.MES + '.VTD.UpdateAdditionManually',
                                                    qp,
                                                    {
                                                        onSuccess: function (resp) {
                                                            try {
                                                                if (resp) {


                                                                    if (resp.Table) {
                                                                        updated = true;
                                                                    }

                                                                }
                                                                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: false,
                                                    },
                                                    app.ConnectionStrings.app
                                                );

                                                return updated;
                                            },
                                            insertHandAddition: function (params) {
                                                var that = this,
                                                    qp = new Core.Database.QueryParameters();

                                                var updated = false;
                                                this.fixedParameters = [
                                                    { Name: '@processId', Type: 'INT', Value: params.ProcessId, },
                                                    { Name: '@materialId', Type: 'INT', Value: params.MaterialId, },
                                                    { Name: '@weight', Type: 'FLOAT', Value: params.Weight, },
                                                    { Name: '@weightSP', Type: 'FLOAT', Value: params.WeightSP, },
                                                    { Name: '@comment', Type: 'VARCHAR', Value: ' ', },
                                                    { Name: '@dumpStart', Type: 'VARCHAR', Value: params.Timestamp, },
                                                ];
                                                _.each(this.fixedParameters, function (qpParams) {
                                                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                                                });

                                                Core.Json.CallProcedure(
                                                    app.DatabaseNames.MES + '.VTD.InsertAdditionManually',
                                                    qp,
                                                    {
                                                        onSuccess: function (resp) {
                                                            try {
                                                                if (resp) {


                                                                    if (resp.Table) {
                                                                        updated = true;
                                                                    }

                                                                }
                                                                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: false,
                                                    },
                                                    app.ConnectionStrings.app
                                                );

                                                return updated;
                                            },
                                        }),
                                        editable: false,
                                    }, 
                                ]


                                // Hide Columns based on Toggle
                                if (!that.model.get('hideShowHandAdditionToggle')) {
                                    // Define the columns to hide
                                    var columnsToHide = ['MAluminum', 'MCaSi', 'MFeB', 'MFeTi', 'MSulphur'];
                                    columns = columns.filter(x => !columnsToHide.includes(x.name))
                                }

                                that.$el.find('.input-date').datepicker();
                                var grid = that.grids.production = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    columns: columns,
                                    header: header,
                                    collection: that.itemsColl,
                                    row: Backgrid.Row.extend({
                                        events: function () {
                                            return {
                                                'click': this.click,
                                            };
                                        },
                                        click: function (e) {
                                            if (!(e.target.getAttribute('Type') == 'checkbox') && !(e.target.nodeName == 'I')) { 
                                                try {
                                                    this.model.trigger('backgrid:rowclick', this.model);
                                                }
                                                catch (Error) { console.error(Error.stack); }
                                            }
                                        }
                                    }),
                                    //row: Backgrid.Row.extend({
                                    //    initialize: function (options) {
                                    //        Backgrid.Row.prototype.initialize.apply(this, arguments);

                                    //    },
                                    //    events: {
                                    //       // contextmenu: 'onRightClick',
                                    //        click: 'click',
                                    //    },
                                    //    //onRightClick: function (e) {
                                            
                                    //    //    e.preventDefault();
                                    //    //    var model = this.model.toJSON();
                                            
                                    //    //    var rowsView = that.model.get('grid').body.rows;
                                    //    //    var newIndex = _.indexOf(rowsView, this);
                                    //    //    this.$el.addClass("onRightClickSelectedRow");

                                    //    //    that.model.set({ 
                                    //    //        rowModel: model,
                                    //    //        showAssignOption: model.HeatId === null ? true : false,
                                    //    //        index: newIndex,
                                    //    //    });
                                    //    //},
                                    //    click: function (e) {

                                    //        if (!e.target.getAttribute('Type') == 'checkbox') {
                                    //            try {
                                    //                this.model.trigger('backgrid:rowclick', this.model);
                                    //            }
                                    //            catch (Error) { console.error(Error.stack); }
                                    //        }
                                    //        else {
                                    //            console.log();
                                    //        }
                                    //    },                                    

                                    //}),
                                    footer: Backgrid.Extension.Infinator.extend({
                                        scrollToTop: false,
                                    }),

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

                                //appending view to the main container
                                that.append(thatContainer, that.$el);

                                
                                //$.contextMenu( 'destroy' );


                                //$(function() {
                                //    $.contextMenu({
                                //        selector: '#vtd-production .string-cell', 
                                //        callback: function(key, options) {
                                //            if (key === 'heat')  that.model.set({contextMenuOption:1});      
                                //            that.contextMenuOptionPressed();
                                //        },
                                //        items: {
                                //            "heat": {name: "Go To Heat Report", icon: "fa-bar-chart"},                                         
                                                        
                                //        },
                                //        events: {
                                //            hide : function(options){
                                //                that.removeHighlightRow();
                                //            },
                                //        }
                                //    }); 
                                //});


                                //Set model with view params here to prevent changes on the model when the view bindings are applied.
                                var fixedParams = _.extend({}, viewParams);

                                if (fixedParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (viewParams.tankCode)
                                    fixedParams.tankCode = (viewParams.tankCode != '-' && viewParams.tankCode != null) ? parseInt(viewParams.tankCode, 10) : null;
                                if (viewParams.crewId)
                                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                                if (viewParams.shiftId)
                                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;

                                that.model.set(fixedParams);

                                //Call first refresh.
                                var params = that.model.toJSON();

                                

                               
                                that._refresh({
                                    reset: true,
                                    params: _.extend(
                                        {},
                                        params,
                                        {
                                        }
                                    ),
                                });


                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            hideShowHandAddition: function (e) {
                var that = this;
                if (!e.target.checked) {
                    that.model.set('hideShowHandAdditionToggle', false);
                }
                else {
                    that.model.set('hideShowHandAdditionToggle', true);
                }
                this.render(null, this.viewParams);
            },
            removeHighlightRow: function(){
                var previousIndex = this.model.get('index');
                var rowsView = this.model.get('grid').body.rows;
                rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");
            },

            contextMenuOptionPressed: function(){                
                var that = this;
                var model = this.model.get('rowModel');
                var contextMenuOption = this.model.get('contextMenuOption');               
                if (contextMenuOption === 1) {
                    app.router.navigate(
                        app.router.resolveURL(
                            'vtd-heat-report',
                            {
                                heatName: model.HeatName,
                            },
                            false
                        ),
                        { trigger: true, }
                    );
                }
            },
            processes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            if (that.itemsColl.length > 0) that.show_backgrid();
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            show_backgrid: function () {
                var container = this.$el.find(".processes-grid-container");
                container.empty();

                container.append(this.grids.production.render().el);

                var table = container.find(".production-table")
                table.floatThead({
                    scrollingTop: function () {
                        try {
                            return $(".fixed-subnavbar").height() + ($("header").height() / 2);
                        } catch (error) { return 111; }
                    },
                    zIndex: 500,
                    useAbsolutePositioning: false,
                });

            },

            refreshProcesses: function (options) {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {}, });

                if ((opt.refresh == true) || (opt.reset == true))
                    this.model.set('isLoading', true);


                this.itemsColl.fetch({
                    start: attrs.start,
                    end: attrs.end,
                    crewId: (attrs.crewId == "") ? null : attrs.crewId,
                    shiftId: (attrs.shiftId == "") ? null : attrs.shiftId,
                    refresh: true,
                    tankCode: attrs.tankCode ? attrs.tankCode : null,
                });
            },
          

            exportToExcel: function () {
                var that = this,
                    params = this.model.toJSON();

                var params = [
                    { Name: '@start', Type: 'DATETIME', Value: params.start, },
                    { Name: '@end', Type: 'DATETIME', Value: params.end, },
                    { Name: '@crewId', Type: 'CHAR', Value: (params.crewId != '' && params.crewId != '-') ? params.crewId : null, },
                    { Name: '@shiftId', Type: 'INT', Value: (params.shiftId != '' && params.shiftId != '-') ? params.shiftId : null, },
                    { Name: '@tankCode', Type: 'INT', Value: (params.tankCode != '' && params.tankCode != '-') ? params.tankCode : null, },
                    { Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
                ];
                var QP = new QueryParameters();

                _.each(params, function (qpParams) {
                    QP.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });


                var data = {
                    Data: [],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'VTD-Production',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.VTD.GetProcesses',
                                QueryParameters: QP,
                            },
                        },
                    ]
                };

                /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'Heat' },
                                { Column: 'B', Value: 'Shift' },
                                { Column: 'C', Value: 'Crew' },
                                { Column: 'D', Value: 'Tank' },
                                { Column: 'E', Value: 'Ladle' },
                                { Column: 'F', Value: 'Start' },
                                { Column: 'G', Value: 'End' },
                                { Column: 'H', Value: 'Total Time' },
                                { Column: 'I', Value: 'Treatment' },
                                { Column: 'J', Value: 'Minimum Torr' },
                                { Column: 'K', Value: 'Minimum Torr Time' },
                                { Column: 'L', Value: 'Wire Additions' },
                                { Column: 'M', Value: 'Vaccum Time' },
                                { Column: 'N', Value: 'Melt Order' },
                                { Column: 'O', Value: 'Grade' },
                                { Column: 'P', Value: 'Temperature' },
                                { Column: 'Q', Value: 'Wired-Al' },
                                { Column: 'R', Value: 'Wired-CaSi' },
                                { Column: 'S', Value: 'Wired-FeB' },
                                { Column: 'T', Value: 'Wired-FeTi' },
                                { Column: 'U', Value: 'Wired-Sulfur' },
                                { Column: 'V', Value: 'Manual-Al' },
                                { Column: 'W', Value: 'Manual-CaSi' },
                                { Column: 'X', Value: 'Manual-FeB' },
                                { Column: 'Y', Value: 'Manual-FeTi' },
                                { Column: 'Z', Value: 'Manual-Sulfur' },
                                { Column: 'AA', Value: 'Heat Foamed' },
                                { Column: 'AB', Value: 'Ladle Stirred Well' },

                            ],
                    }],
                    StartRowIndex: 1,
                });

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'HeatName', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'ShiftName', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'CrewId', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'TankCode', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'LadleId', DataType: 'String' },
                            { ExcelColumnName: 'F', SQLDataColumnName: 'StartLocal', DataType: 'String' },
                            { ExcelColumnName: 'G', SQLDataColumnName: 'EndLocal', DataType: 'String' },
                            { ExcelColumnName: 'H', SQLDataColumnName: 'TotalTime', DataType: 'String' },
                            { ExcelColumnName: 'I', SQLDataColumnName: 'Treatment', DataType: 'String' },
                            { ExcelColumnName: 'J', SQLDataColumnName: 'MinimumTorr', DataType: 'String' },
                            { ExcelColumnName: 'K', SQLDataColumnName: 'MinTorrTime', DataType: 'String' },
                            { ExcelColumnName: 'L', SQLDataColumnName: 'WireAdditions', DataType: 'String' },
                            { ExcelColumnName: 'M', SQLDataColumnName: 'VacTime', DataType: 'String' },
                            { ExcelColumnName: 'N', SQLDataColumnName: 'MeltOrder', DataType: 'String' },
                            { ExcelColumnName: 'O', SQLDataColumnName: 'GradeName', DataType: 'String' },
                            { ExcelColumnName: 'P', SQLDataColumnName: 'Temperature', DataType: 'String' },
                            { ExcelColumnName: 'Q', SQLDataColumnName: 'Aluminum', DataType: 'String' },
                            { ExcelColumnName: 'R', SQLDataColumnName: 'CaSi', DataType: 'String' },
                            { ExcelColumnName: 'S', SQLDataColumnName: 'FeB', DataType: 'String' },
                            { ExcelColumnName: 'T', SQLDataColumnName: 'FeTi', DataType: 'String' },
                            { ExcelColumnName: 'U', SQLDataColumnName: 'Sulphur', DataType: 'String' },
                            { ExcelColumnName: 'V', SQLDataColumnName: 'MAluminum', DataType: 'String' },
                            { ExcelColumnName: 'W', SQLDataColumnName: 'MCaSi', DataType: 'String' },
                            { ExcelColumnName: 'X', SQLDataColumnName: 'MFeB', DataType: 'String' },
                            { ExcelColumnName: 'Y', SQLDataColumnName: 'MFeTi', DataType: 'String' },
                            { ExcelColumnName: 'Z', SQLDataColumnName: 'MSulphur', DataType: 'String' },
                            { ExcelColumnName: 'AA', SQLDataColumnName: 'isFoamed', DataType: 'String' },
                            { ExcelColumnName: 'AB', SQLDataColumnName: 'isStirredWell', DataType: 'String' },
                           
                        ],
                });

                Core.Export.Excel(
                    data,
                    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); }
                        that.model.setExportButtonExporting(false);
                    },
                    function (resp) {
                        that.model.refreshProcesses();
                        that.model.setExportButtonExporting(false);
                        console.error(resp);
                    }
                );
            },
            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    tankCode: (params.tankCode == null || params.tankCode == "") ? '-' : params.tankCode,
                                    crewId: (params.crewId == null || params.crewId == "") ? '-' : params.crewId,
                                    shiftId: (params.shiftId == null || params.shiftId == "") ? '-' : params.shiftId,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

                    this._refresh({
                        reset: true,
                        params: _.extend(
                            {},
                            params,
                            {}
                        ),
                    });

                    window.scrollTo(0, 0);
                }
                catch (Error) { console.error(Error.stack); }
            },

            //Common functions
            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;
                }
            },
            bindViewScopedEvents: function () {
                var that = this;
            },
            unbindViewScopedEvents: function () {

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

                this.closeSubviews();
                this.remove();
                this.unbindViewScopedEvents();
                this.unbind();
            },
            closeSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.close();
                });
            },
            show: function () {
                this.options.state = app.view_states.shown;

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

                this.hideSubviews();

                this.$el.hide();
                this.unbind();
                this.stopListening();
            },
            hideSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.hide();
                });
            },
            preRender: function () {
                app.models.subnavbar.set("subnavbar", false);
            },
            reRender: function (viewParams) {
                try {
                    this.refresh(viewParams);
                } catch (Error) { }
            },
        });

        Screen.Collections.Items = Backbone.Collection.extend({
            isFetching: false,
            currentPage: 1,
            pageSize: 100,

            fixedParameters: [],

            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};
                if (options.refresh) {
                    this.resetPagination(true);
                    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: 'INT', Value: params.shiftId != '-' ? params.shiftId : null, },
                        { Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
                        { Name: '@TankCode', Type: 'INT', Value: params.tankCode, },
                        
                    ];
                }
                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 + '.VTD.GetProcesses',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    //var newColl = _.map(resp.Table, that.model.prototype.parse);
                                    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;
            },

            updateFoamedStirredWell: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                this.fixedParameters = [
                    { Name: '@Option', Type: 'CHAR', Value: params.option, },
                    { Name: '@ProcessId', Type: 'INT', Value: params.processId, },
                    { Name: '@Enabled', Type: 'BIT', Value: params.enabled },

                ];

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

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

                                if ((resp)) {
                                    
                                   
                                }
                                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);
                }
            },

        });

        Screen.Collections.ItemsCollection = Backbone.Collection.extend({
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = data;
                that.set(newColl).trigger('fetch', that, data);
            },
        });


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