//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',
    
    'modules/modal2',
    'backgrid',
    'moment',
    'js/d3v4/d3.v4',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',

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

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
               
                hasData: false,
                isLoading: false,

                isLoading_products: true,

                SP_S1: 0,
                SP_S2: 0,
                SP_S3: 0,
                SP_S4: 0,

                Products_S1: 0,
                Products_S2: 0,
                Products_S3: 0,
                Products_S4: 0,

                Speed_S1: 0,
                Speed_S2: 0,
                Speed_S3: 0,
                Speed_S4: 0,

                TipML_S1: 0,
                TipML_S2: 0,
                TipML_S3: 0,
                TipML_S4: 0,

                MoldML_S1: 0,
                MoldML_S2: 0,
                MoldML_S3: 0,
                MoldML_S4: 0,

                HeatStartML_S1: 0,
                HeatStartML_S2: 0,
                HeatStartML_S3: 0,
                HeatStartML_S4: 0,

                RemainingSolid_S1:0,
                RemainingSolid_S2:0,
                RemainingSolid_S3:0,
                RemainingSolid_S4:0,
                
                
                RemainingLiquid_S1:0,
                RemainingLiquid_S2:0,
                RemainingLiquid_S3:0,
                RemainingLiquid_S4:0,

                Mesured_S1:0,
                Mesured_S2:0,
                Mesured_S3:0,
                Mesured_S4:0,

                
                TotalRemaining_S1:0,
                TotalRemaining_S2:0,
                TotalRemaining_S3:0,
                TotalRemaining_S4:0,

                heatColors: [],
                rectangleColors: ["#69b3a2", "#ff9728", "#479dc4", "#7767cb", "#67c2cb", "#69b3a2", "#ff9728", "#479dc4", "#7767cb", "#67c2cb"],
                TWIBlanket: null,
                rowModel:[],
                contextMenuOption: null,
                showNewProductGrid: false,
                grid: [],
                gridProducts: [],
                gridHeats: [],
                search: '',
                strands: [{ label: 'Strand 1', value: 1 }, { label: 'Strand 2', value: 2 }, { label: 'Strand 3', value: 3 }, { label: 'Strand 4', value: 4 }],
                strandId: '-',
                ladleId: null,
                ladleHeatName: null,
                length: null,
            },
            computeds: {
                realTime: {
                    deps: ['strandId', 'search'],
                    get: function (strand, search) {
                        if (strand === '-' && search === '') return true;
                        else return false;
                    },
                },
               disabledStrandPicker: {
                   deps: ['search'],
                   get: function (search) {
                        if (search === '') return true;
                        else return false;
                    },
                }
            },
            initialize: function () {
                this.itemsColl = new Screen.Collections.Items();
                this.productsColl = new Screen.Collections.ItemsProducts();
                this.newProductsColl = new Screen.Collections.ItemsProducts();
            },
            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                if (!params || !params.products) {

                    var colors = that.get('rectangleColors');
                    var heatColors = [];

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

                                    if ((resp) && (resp.Table)) {
                                        if (resp.Table1) {
                                            _.each(resp.Table1, function (heat, i) {
                                                heatColors.push({ HeatName: heat.HeatName, Color: colors[i] });
                                            });
                                            that.set({ heatColors: heatColors });
                                        }

                                        if (resp.Table4 && resp.Table && resp.Table2 && resp.Table3 && resp.Table7) that.itemsColl.setDataColl(resp.Table4, resp.Table, resp.Table2, resp.Table3, resp.Table7);
                                        if (resp.Table5) that.productsColl.setDataColl(resp.Table5);

                                        if (resp.Table6) {
                                            that.set('TWIBlanket', resp.Table6[0].TWIBlanket);
                                        }
                                        that.trigger('GetTorchDataWebReady');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            console.error(new Error(resp.Message).stack);
                                            //  app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                            that.trigger('GetTorchDataWebReady');
                                        }
                                        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;
                }
                else {
                    this.fixedParameters = [
                        { Name: '@HeatName', Type: 'VARCHAR', Value: that.get('search') === '' ? null : that.get('search'), },
                        { Name: '@StrandId', Type: 'INT', Value: that.get('strandId') === '-' ? null : that.get('strandId'), },
                    ];
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                  
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.GetTorchProductsDataWeb',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {

                                    if ((resp) && (resp.Table)) {
                                        that.productsColl.setDataColl(resp.Table);
                                        that.trigger('GetTorchDataWebReady');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            console.error(new Error(resp.Message).stack);
                                            //  app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                            that.trigger('GetTorchDataWebReady');
                                        }
                                        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;

                }
            },
            reassing: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@processId', Type: 'INT', Value: params.processId, },
                        { Name: '@heatId', Type: 'INT', Value: params.heatId, },
                    ];


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

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.ReassingCasterProcess',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Caster Process Reassigned', { stay: 5000, });
                                        that.trigger('reassigned');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            removeProduct: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                    this.fixedParameters = [
                        { Name: '@productId', Type: 'INT', Value: params.productId, },
                    ];


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

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.RemoveProduct',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                             
                                if ((resp) && (resp.Table)) {             
                                        app.views.topMessages.showMessage(resp.Table[0].ProductMsg, { stay: 5000, });
                                }
                                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;
            },
            addProductManually: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                    this.fixedParameters = [
                        { Name: '@heatName', Type: 'VARCHAR', Value: params.heatName, },
                        { Name: '@strandId', Type: 'INT', Value: params.strandId, },      
                        { Name: '@length', Type: 'FLOAT', Value: params.length, },
                    ];
                    
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.AddProductManually',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                             
                                if ((resp) && (resp.Table)) {             
                                        app.views.topMessages.showMessage(resp.Table[0].ProductMsg, { stay: 5000, });
                                }
                                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;
            },
            printTag: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                ];


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

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

                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('Tagging in process...', { stay: 5000, });
                                    that.trigger('triggerFetch');
                                    //app.views.topMessages.showMessage(resp.Table[0].ProductMsg, { stay: 5000, });
                                }
                                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;
            },           
            resendToL3: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                ];


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

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

                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('Resend Product to L3 in process...', { stay: 5000, });
                                    that.trigger('triggerFetch');
                                    //app.views.topMessages.showMessage(resp.Table[0].ProductMsg, { stay: 5000, });
                                }
                                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;
            },
            markAsScrap: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.MarkProductAsScrap',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    if (params.markAsScrap === true) app.views.topMessages.showMessage('Mark as Scrap in process...', { stay: 5000, });
                                    else if (params.markAsScrap === false) app.views.topMessages.showMessage('Unmark as Scrap in process...', { stay: 5000, });
                                    that.trigger('triggerFetch');
                                }
                                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;
            },
            manualLadleOpen: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.LAD.ForceOpenLadleEvent',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Manual Ladle Open Command Sent', { stay: 5000, });
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            getHeatManualLadleOpen: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.LAD.GetHeatAtCas1ArmPosition',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && resp.Table) {
                                        that.set({
                                            ladleId: (resp.Table[0] && resp.Table[0].LadleId) ? resp.Table[0].LadleId : null,
                                            ladleHeatName: (resp.Table[0] && resp.Table[0].HeatNumber) ? resp.Table[0].HeatNumber : null
                                        });
                                        that.trigger('ladleOpenParameters');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
        });

        Screen.generateID = function (viewParams) {
            try {
                //if the viewparams change the view id, then evaluate the viewparams here
                //and return the appropiate id.refreshbtn
                return 'caster-torch';
            } catch (Error) { }
        }


        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-torch',
            id: 'caster-torch',
            title: 'Caster Torch',
            events: function () {
                return {        
                    'click #TWIBtn': this.TWIBtn_click,
                    'click #saveBtn' : this.saveBtn_click,
                    'click #hideNewProductGridBtn': this.hideNewProductGridBtn_click,
                    'click #LadleOpenBtn': this.ladleOpenBtn_click,
                    'keypress #search': this.search_keypress,
                    'click #backToRealTime': this.backToRealTime_click,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            subviews: null,
            viewParams: null,
            tooltip: null,
            tooltip1: null,
            pauseTimer: false,
            pauseRealTime: false,
            strands:[],
            sequences: [],

            currentModal: null,

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

                var that = this;
                this.templates = {
                    splitProduct: null,
                };

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

                this.grids = {};
                this.bindingSources = {};

                this.subviews = {};
            
                this.autoRefresh = {
                    enabled: null
                    , toid: null
                    , every: 5 * 1000 
                };
                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);

                this.strands =  [['1', 1],['2', 2],['3', 3],['4', 4]];                
                this.sequences = [['1',1],['2',2],['3',3],['4',4],['5',5],['6',6],['7',7],['8',8],['9',9],['10',10]];
                this.bindEvents();
            },
            backToRealTime_click: function () {
                this.model.set({
                    strandId: '-',
                    search: '',
                });
                this.model.fetch({ products: false });

            },
            ladleOpenBtn_click: function () {
                this.model.getHeatManualLadleOpen();               
            },
            ladleOpenParameters_ready: function () {
                var that = this;
                if (this.model.get('ladleId') != null && this.model.get('ladleHeatName') != null) {

                    modal = new Modal.Views.Main({
                        focusOk: false,
                        focusSelector: '#btn-cancel',
                        title: 'Manual Ladle Open',
                        message: 'Are you sure you want to open Ladle ' + this.model.get('ladleId') + ' with Heat ' + this.model.get('ladleHeatName')  +'?',
                        buttons_type: "CONTINUE-CANCEL",
                    });
                    this.listenToOnce(modal, "continue", function (modal) {
                        try {
                            that.model.manualLadleOpen()
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    });
                    modal.show();
                } else {

                    app.views.topMessages.showMessage('No Heat at Caster 1 Inboard Position', { stay: 5000, });
                }
            },
            saveBtn_click: function(){
                var newProductModel = this.model.newProductsColl.models[0].toJSON();
                
                this.model.addProductManually({
                    heatName    : newProductModel.HeatName,
                    strandId  : newProductModel.StrandId,
                    length    : newProductModel.Length,                   
                });
                
                this.model.newProductsColl.reset();
                
                this.model.set({showNewProductGrid: false});
            },
            hideNewProductGridBtn_click: function(){
                this.model.set({showNewProductGrid: false});
            },
            TWIBtn_click: function(){
                var TWIBlanket = this.model.get('TWIBlanket')
                if (TWIBlanket)  Backbone.history.navigate('!/twi-management/' +TWIBlanket, { trigger: true });
                else Backbone.history.navigate('!/twi-management/', { trigger: true });
            },
            onModalAcceptBtn: function (processId, heatId) {
                this.model.reassing({
                    processId: processId,
                    heatId: heatId,
                })
            },
            bindEvents: function () {
                this.listenTo(this.model.itemsColl, 'fetch', this.processes_ready);
                this.listenTo(this.model, 'GetTorchDataWebReady', this.GetTorchDataWebReady_ready);
                this.listenTo(this.model, 'ladleOpenParameters', this.ladleOpenParameters_ready);
                this.listenTo(this.model.productsColl, 'change', this.productsColl_change);
                this.listenTo(this.model.productsColl, 'product-updated', this.product_updated);
                this.listenTo(this.model, 'change:strandId', this.getProductsGrid);
                this.listenTo(this.model, 'change:search', this.getProductsGrid);
                this.listenTo(this.model.productsColl,"backgrid:editing",this.backgrid_editing);                
                this.listenTo(this, "editing", this.backgrid_editing_pause_timer);

            },        
            getProductsGrid: function () {
                this.model.set({
                    isLoading_products:true,
                })
                this.refresh();
            },
            backgrid_editing: function(){  
                this.pauseTimer = true;
                this.trigger('editing');
            },
            backgrid_editing_pause_timer:function(){
                this.pauseTimer = true;
            },
            product_updated: function(){
                this.pauseTimer = false;
            },
            productsColl_change: function (m, b, c) {
            var fromFetch = (b && b.from == 'fetch') ? true : false;            
            if (!fromFetch) {
                
                m.collection.upsertItem({
                    Id: m.get('Id'),
                    Length: m.get('Length') ,
                    
                })
            }
        },
            GetTorchDataWebReady_ready: function () {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({ isLoading_products: false });
                        that.pauseTimer = false;
                    },
                    100
                );
            },             

            //Auto refresh
            _refresh: function (opt) {
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }
                if (!this.pauseTimer) this.refresh();

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

                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        this.autoRefresh.every
                    );
                }
            },
            startAutoRefresh: function () {
                try {
                    if (this.autoRefresh.enabled !== true) {
                        var that = this;

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

                        this.autoRefresh.enabled = true;

                        //use a timeout to execute the first refresh to return the handle to the start function caller.
                        //So when the caller finish it will do the first refresh.
                        this.autoRefresh.toid = setTimeout(
                            function () { that._refresh(); },
                            1
                        );
                    }
                } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },
            stopAutoRefresh: function () {
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }
                this.autoRefresh.enabled = false;
            },

            refresh: function (viewParams) {
                if (this.currentModal) {
                    this.currentModal.hide();
                    this.currentModal = null;
                }

                if (!this.pauseRealTime) {
                    this.pauseTimer = true;
                    if (this.model.get('search') === '' && this.model.get('strandId') === '-') {
                        this.model.fetch({ products: false });
                    } else if (this.model.get('search') === '' && this.model.get('strandId') != '-') {
                        this.model.set({
                            strandId: '-',
                            search: '',
                        });
                        this.model.fetch({ products: true });
                    }
                    else {
                        this.model.fetch({ products: true });
                    }
                }
            },           
            drawRectangles: function (productsData,StrandId) {
                var that = this;
                var svg = null;

                var MaxMeniscoML = 1800; // Lenght in ML
             
                var y = 10; //Rectangle y Px position

             

                var fixedLengthPX = 800; // Lenght in PX


                //Already Exists tooltip
                var tooltip1 = document.getElementsByClassName('tooltip1');

                if (!tooltip1 || tooltip1.length == 0) {
                    // Define the div for the tooltip
                    var div = d3.select("body").append("div")
                        .attr("class", "tooltip1")
                        .style("opacity", 0);

                    that.tooltip1 = div;
                }



                if (StrandId == 1) {
                    $("#graph1").html('');
                    svg = d3.select("#graph1");
                    fixedLengthPX = $('#graph1')[0].getBoundingClientRect().width;
                } else if (StrandId == 2) {
                    $("#graph2").html('');
                    svg = d3.select("#graph2");
                    fixedLengthPX = $('#graph2')[0].getBoundingClientRect().width;
                } else if (StrandId == 3) {
                    $("#graph3").html('');
                    svg = d3.select("#graph3");
                    fixedLengthPX = $('#graph3')[0].getBoundingClientRect().width;
                } else if (StrandId == 4) {
                    $("#graph4").html('');
                    svg = d3.select("#graph4");
                    fixedLengthPX = $('#graph4')[0].getBoundingClientRect().width;
                }

                var products = _.where(productsData, { StrandId: StrandId });

                if (products && products[0] && products[0].LineML) {

                    var lineML = products[0].LineML;
                    var linePx = lineML * fixedLengthPX / MaxMeniscoML;

                    var xPx = 0;
                    var widthPx = 0;

                    _.each(products, function (prod) {

                        xPx = fixedLengthPX - prod.MLE * linePx / lineML;
                        widthPx = (prod.MLE - prod.MLS) * linePx / lineML;

                        var color = _.where(that.model.get('heatColors'), { HeatName: prod.Heat });
                        var xText = xPx + widthPx / 2
                        var BL_Between = prod.BL_Between ? prod.BL_Between : ' - ';

                        svg.append("rect")
                            .attr("x", xPx)
                            .attr("y", y)
                            .attr("width", widthPx)
                            .attr("height", 30)
                            .attr("stroke", "black")
                            .attr("fill", color[0] && color[0].Color ? color[0].Color : "#67c2cb" )
                            .attr("opacity", prod.Unfinished == 1 ? 0.5 : 1)
                            .attr("cursor","pointer")

                            .on('mouseover', function () {
                                d3.select(this)
                                    .transition()
                                    .duration(500)
                                    .attr('stroke', 'red')
                                    .attr('stroke-width', 2)

                                if (!that.tooltip1) {
                                    // Define the div for the tooltip
                                    var div = d3.select("body").append("div")
                                        .attr("class", "tooltip1")
                                        .style("opacity", 0);
                                    that.tooltip1 = div;
                                }


                                that.tooltip1.transition()
                                    .duration(200)
                                    .style("opacity", 1);
                                that.tooltip1.html(
                                    "Heat: " + prod.Heat + "<br/>"
                                    + " Sequence: " + prod.ProductNumber + "<br/>"
                                    + " Transition ML :" + BL_Between + "<br/>"
                                )
                                    .style("left", (d3.event.pageX) + "px")
                                    .style("top", (d3.event.pageY - 28) + "px");	
                            })
                            .on('mouseout', function () {
                                d3.select(this)
                                    .transition()
                                    .duration(500)
                                    .attr('stroke', 'black')
                                    .attr('stroke-width', 1)
                                that.tooltip1.transition()
                                    .duration(500)
                                    .style("opacity", 0);
                            })
                            //.append("svg:title")
                            //.text(function (d) { return "Heat: " + prod.Heat + " Product Number: " + prod.ProductNumber })

                        svg.append('text').text(prod.ProductNumber)
                            .attr('x', xText)
                            .attr('y', y*3)
                            .attr('fill', 'black')

                   
                    });
                    //-- Boundary Lines
                    var BL1 = products[0].BL1;
                    var BL2 = products[0].BL2;
                
                    var boundLengthPx = 0;
                    if ( BL1 && BL2 && BL1 == BL2) {

                    
                        boundLengthPx = BL1 * linePx / lineML;

                        svg.append("line")
                            .attr("x1", fixedLengthPX - boundLengthPx)
                            .attr("x2", fixedLengthPX - boundLengthPx)
                            .attr("y1", y - 7)
                            .attr("y2", y + 37)
                            .attr("stroke", "red")
                            .attr("stroke-dasharray", 2)
                    } else if (BL1 && BL2 && BL1 != BL2){
                        boundLengthPx = BL1 * linePx / lineML;

                        svg.append("line")
                            .attr("x1", fixedLengthPX - boundLengthPx)
                            .attr("x2", fixedLengthPX - boundLengthPx)
                            .attr("y1", y - 7)
                            .attr("y2", y + 37)
                            .attr("stroke", "red")
                            .attr("stroke-dasharray", 2)


                        boundLengthPx = BL2 * linePx / lineML;

                        svg.append("line")
                            .attr("x1", fixedLengthPX - boundLengthPx)
                            .attr("x2", fixedLengthPX - boundLengthPx)
                            .attr("y1", y - 7)
                            .attr("y2", y + 37)
                            .attr("stroke", "black")
                            .attr("stroke-dasharray", 2)
                    }

                }
            },
            drawReadyRectangles: function (productsData, StrandId) {
                var that = this;
                var svg = null;

                var fixedLengthPX = 800; // Lenght in PX
                var y = 10; //Rectangle y Px position

                var products = _.where(productsData, { StrandId: StrandId });
                var xPx = 0;
                var widthPx = 0;

                //Already Exists tooltip
                var tooltip = document.getElementsByClassName('tooltip');
               
                if (!tooltip || tooltip.length == 0) {
                    // Define the div for the tooltip
                    var div = d3.select("body").append("div")
                        .attr("class", "tooltip")
                        .style("opacity", 0);
                    that.tooltip =div;
                }
                

                if (StrandId == 1) {
                    $("#graph1_p").html('');
                    svg = d3.select("#graph1_p");
                    fixedLengthPX = $('#graph1_p')[0].getBoundingClientRect().width;

                } else if (StrandId == 2) {
                    $("#graph2_p").html('');
                    svg = d3.select("#graph2_p");
                    fixedLengthPX = $('#graph2_p')[0].getBoundingClientRect().width;

                } else if (StrandId == 3) {
                    $("#graph3_p").html('');
                    svg = d3.select("#graph3_p");
                    fixedLengthPX = $('#graph3_p')[0].getBoundingClientRect().width;

                } else if (StrandId == 4) {
                    $("#graph4_p").html('');
                    svg = d3.select("#graph4_p");
                    fixedLengthPX = $('#graph4_p')[0].getBoundingClientRect().width;

                }
                var prodLengthPx = 40,
                    xPx = 0;

                var maxProducts = products.length;
                if (maxProducts > 6) {
                    prodLengthPx = fixedLengthPX / maxProducts;
                }
                _.each(products, function (prod) {

                    widthPx = xPx + prodLengthPx;

                    var xText = xPx + prodLengthPx / 2;

                    var color = _.where(that.model.get('heatColors'), { HeatName: prod.HeatName });

                    var CutComplete = new moment(prod.CutComplete).format('YYYY-MM-DD HH:mm:ss');
                    CutComplete = new moment(CutComplete, 'YYYY-MM-DD HH:mm:ss').format('MM/DD HH:mm');



                    svg.append("rect")
                        .attr("x", xPx)
                        .attr("y", y)
                        .attr("width", prodLengthPx)
                        .attr("height", 30)
                        .attr("stroke", "black")
                        .attr("fill", color[0] && color[0].Color ? color[0].Color : "#67c2cb" )
                        .attr("cursor", "pointer")
                        .on('mouseover', function (d) {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'red')
                                .attr('stroke-width', 2)

                            if (!that.tooltip) {
                                // Define the div for the tooltip
                                var div = d3.select("body").append("div")
                                    .attr("class", "tooltip")
                                    .style("opacity", 0);
                                that.tooltip = div;
                            }

                            that.tooltip.transition()
                                .duration(0)
                                .style("opacity", 1);
                            that.tooltip.html(
                                        "Heat: " + prod.HeatName + "<br/>" 
                                    + " Sequence: " + prod.Sequence + "<br/>"
                                    + " Start ML: " + prod.MLS.toFixed(2) + "<br/>"
                                    + " End ML: " + prod.MLE.toFixed(2) + "<br/>" 
                                    + " Cut Time: " + CutComplete + "<br/>" 
                                )
                                .style("left", (d3.event.pageX) + "px")
                                .style("top", (d3.event.pageY - 28) + "px");	
                            
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'black')
                                .attr('stroke-width', 1)
                            that.tooltip.transition()
                                .duration(0)
                                .style("opacity", 0);

                   
                        })
                        //.append("svg:title")                        
                        //.text(function (d) {
                        //    return "Heat: " + prod.HeatName + " Product Number: " + prod.Sequence
                        //})
                       


                    svg.append('text').text(prod.Sequence)
                        .attr('x', xText - 5.0)
                        .attr('y', y * 3)
                        .attr('fill', 'black')


                    xPx = widthPx;


                });

            },
            processes_ready: function (data, realTimeData, productsData, productsReadyData, lastProcesses) {
                try {
                    var that = this;
                    var newHeat = false;
                    setTimeout(
                        function () {
                            var params = that.model.itemsColl.toJSON();


                            
                            that.model.set({
                                hasData: (that.model.itemsColl.length > 0),
                                isLoading: false,
                            });
                            var realTimeData_S1 = _.where(realTimeData, { StrandId: 1 });
                            var realTimeData_S2 = _.where(realTimeData, { StrandId: 2 });
                            var realTimeData_S3 = _.where(realTimeData, { StrandId: 3 });
                            var realTimeData_S4 = _.where(realTimeData, { StrandId: 4 });

                            that.model.set({

                                Products_S1: realTimeData_S1[0].Products.toFixed(2),
                                Products_S2: realTimeData_S2[0].Products.toFixed(2),
                                Products_S3: realTimeData_S3[0].Products.toFixed(2),
                                Products_S4: realTimeData_S4[0].Products.toFixed(2),

                                SP_S1: realTimeData_S1[0].PresetML ? realTimeData_S1[0].PresetML.toFixed(2) : 0,
                                SP_S2: realTimeData_S2[0].PresetML ? realTimeData_S2[0].PresetML.toFixed(2) : 0,
                                SP_S3: realTimeData_S3[0].PresetML ? realTimeData_S3[0].PresetML.toFixed(2) : 0,
                                SP_S4: realTimeData_S4[0].PresetML ? realTimeData_S4[0].PresetML.toFixed(2) : 0,


                                Speed_S1: realTimeData_S1[0].Speed ? realTimeData_S1[0].Speed.toFixed(2) : 0,
                                Speed_S2: realTimeData_S2[0].Speed ? realTimeData_S2[0].Speed.toFixed(2) : 0,
                                Speed_S3: realTimeData_S3[0].Speed ? realTimeData_S3[0].Speed.toFixed(2) : 0,
                                Speed_S4: realTimeData_S4[0].Speed ? realTimeData_S4[0].Speed.toFixed(2) : 0,
                                
                                
                                RemainingSolid_S1:realTimeData_S1[0].RemainingSolid ? realTimeData_S1[0].RemainingSolid.toFixed(2) : 0,
                                RemainingSolid_S2:realTimeData_S2[0].RemainingSolid ? realTimeData_S2[0].RemainingSolid.toFixed(2) : 0,
                                RemainingSolid_S3:realTimeData_S3[0].RemainingSolid ? realTimeData_S3[0].RemainingSolid.toFixed(2) : 0,
                                RemainingSolid_S4:realTimeData_S4[0].RemainingSolid ? realTimeData_S4[0].RemainingSolid.toFixed(2) : 0,

                                
                                RemainingLiquid_S1:realTimeData_S1[0].RemainingLiquid ? realTimeData_S1[0].RemainingLiquid.toFixed(2) : 0,
                                RemainingLiquid_S2:realTimeData_S2[0].RemainingLiquid ? realTimeData_S2[0].RemainingLiquid.toFixed(2) : 0,
                                RemainingLiquid_S3:realTimeData_S3[0].RemainingLiquid ? realTimeData_S3[0].RemainingLiquid.toFixed(2) : 0,
                                RemainingLiquid_S4:realTimeData_S4[0].RemainingLiquid ? realTimeData_S4[0].RemainingLiquid.toFixed(2) : 0,

                                
                                Mesured_S1:realTimeData_S1[0].Mesured ? realTimeData_S1[0].Mesured.toFixed(2) : 0,
                                Mesured_S2:realTimeData_S2[0].Mesured ? realTimeData_S2[0].Mesured.toFixed(2) : 0,
                                Mesured_S3:realTimeData_S3[0].Mesured ? realTimeData_S3[0].Mesured.toFixed(2) : 0,
                                Mesured_S4:realTimeData_S4[0].Mesured ? realTimeData_S4[0].Mesured.toFixed(2) : 0,

                                TotalRemaining_S1:realTimeData_S1[0].TotalRemaining ? realTimeData_S1[0].TotalRemaining.toFixed(2) : 0,
                                TotalRemaining_S2:realTimeData_S2[0].TotalRemaining ? realTimeData_S2[0].TotalRemaining.toFixed(2) : 0,
                                TotalRemaining_S3:realTimeData_S3[0].TotalRemaining ? realTimeData_S3[0].TotalRemaining.toFixed(2) : 0,
                                TotalRemaining_S4:realTimeData_S4[0].TotalRemaining ? realTimeData_S4[0].TotalRemaining.toFixed(2) : 0,
                            })
                            that.drawRectangles(productsData, 1);
                            that.drawRectangles(productsData, 2);
                            that.drawRectangles(productsData, 3);
                            that.drawRectangles(productsData, 4);

                            that.drawReadyRectangles(productsReadyData, 1);
                            that.drawReadyRectangles(productsReadyData, 2);
                            that.drawReadyRectangles(productsReadyData, 3);
                            that.drawReadyRectangles(productsReadyData, 4);

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



            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) {
                                that.options.i18n[that.template] = i18nJED;
                                that.$el.html(tmp());
                                that.applyBindings();

                                //that.templates.splitProduct = Handlebars.compile(that.$el.find('#split_product_template').html());

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

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



                                var gridNewProduct = new Backgrid.Grid({
                                    className: 'backgrid table table-hover',
                                    columns: [
                                        {
                                            name: 'HeatName',
                                            label: app.translate([that, app], 'Heat Name'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'StrandId',
                                            label: app.translate([that, app], 'Strand'),
                                            cell: Backgrid.SelectCell.extend({
                                                optionValues: function () {
                                                    return that.strands;
                                                },
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: true,
                                        },
                                        {
                                            name: 'Length',
                                            label: app.translate([that, app], 'Length'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: true,
                                        },
                                    ],
                                    collection: that.model.newProductsColl,

                                });
                                that.$el.find('.new-products-grid-container').append(gridNewProduct.render().el);

                                var gridHeats = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    columns: [
                                        {
                                            name: 'HeatName',
                                            label: app.translate([that, app], 'Heat'),
                                            cell: Backgrid.StringCell.extend({
                                                className: function () {
                                                    var heatName = this.model.toJSON().HeatName;
                                                    var colors = _.where(that.model.get('heatColors'), { HeatName: heatName });
                                                    var color = colors[0] && colors[0].Color ? colors[0].Color : null
                                                    var classes = 'string-cell align-center-cell heat-row';

                                                    if (color == '#69b3a2')
                                                        classes = 'string-cell align-center-cell heat-row color0';
                                                    else if (color == '#ff9728')
                                                        classes = 'string-cell align-center-cell heat-row color1';
                                                    else if (color == '#479dc4')
                                                        classes = 'string-cell align-center-cell heat-row color2';
                                                    else if (color == '#7767cb')
                                                        classes = 'string-cell align-center-cell heat-row color3';
                                                    else if (color == '#67c2cb')
                                                        classes = 'string-cell align-center-cell heat-row color4';
                                                    return classes;
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Status',
                                            label: app.translate([that, app], 'Status'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'MeltOrder',
                                            label: app.translate([that, app], 'Melt Order'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Grade',
                                            label: app.translate([that, app], 'Grade'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'S1Products',
                                            label: app.translate([that, app], 'S1'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'S2Products',
                                            label: app.translate([that, app], 'S2'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'S3Products',
                                            label: app.translate([that, app], 'S3'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'S4Products',
                                            label: app.translate([that, app], 'S4'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'ProductsWeight',
                                            label: app.translate([that, app], 'Solid Weight'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'LiqWeight',
                                            label: app.translate([that, app], 'Liq Weight'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                    ],
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        },
                                        events: {
                                            contextmenu: 'onRightClick',
                                        },
                                        onRightClick: function (e) {
                                            e.preventDefault();
                                            var model = this.model.toJSON();

                                            var rowsView = that.model.get('gridHeats').body.rows;
                                            var newIndex = _.indexOf(rowsView, this);
                                            this.$el.addClass("onRightClickSelectedRow");

                                            that.model.set({
                                                rowModel: model,
                                                index: newIndex,
                                            });
                                        },

                                    }),                                   
                                    collection: that.model.itemsColl,

                                });
                                that.$el.find('.processes-grid-container').append(gridHeats.render().el);

                                var gridProducts = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    columns: [
                                        {
                                            name: 'ProductNumber',
                                            label: app.translate([that, app], 'Product'),
                                            cell: Backgrid.StringCell.extend({
                                                className: function () {
                                                    var heatName = this.model.toJSON().HeatName;
                                                    
                                                    var currHeatName = this.model.toJSON().CurrentHeatName;

                                                    var manuallyCreated = this.model.toJSON().ManuallyCreated;

                                                    if (manuallyCreated){                                                    
                                                        var colors = _.where(that.model.get('heatColors'), { HeatName: currHeatName });
                                                        var color = colors[0] && colors[0].Color ? colors[0].Color : null
                                                  
                                                    } else {
                                                         var colors = _.where(that.model.get('heatColors'), { HeatName: heatName });
                                                         var color = colors[0] && colors[0].Color ? colors[0].Color : null
                                                  
                                                    }
                                                     var classes = 'string-cell align-center-cell heat-row';

                                                    if (color == '#69b3a2')
                                                        classes = 'string-cell align-center-cell heat-row color0';
                                                    else if (color == '#ff9728')
                                                        classes = 'string-cell align-center-cell heat-row color1';
                                                    else if (color == '#479dc4')
                                                        classes = 'string-cell align-center-cell heat-row color2';
                                                    else if (color == '#7767cb')
                                                        classes = 'string-cell align-center-cell heat-row color3';
                                                    else if (color == '#67c2cb')
                                                        classes = 'string-cell align-center-cell heat-row color4';
                                                    return classes;
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'TaggingStatusCode',
                                            label: app.translate([that, app], 'Tagging Status'),
                                            cell: Backgrid.StringCell.extend({
                                                className: function () {
                                                    var model = this.model.toJSON();
                                                    if (model.TaggingStatusCode === 'S') return 'string-cell align-center-cell tagSent'; 
                                                    if (model.TaggingStatusCode === 'C') return 'string-cell align-center-cell tagCompleted'; 
                                                    if (model.TaggingStatusCode === 'F') return 'string-cell align-center-cell tagFailed'; 
                                                    else return 'string-cell align-center-cell';
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Destination',
                                            label: app.translate([that, app], 'Destination'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Quality',
                                            label: app.translate([that, app], 'Quality'),
                                            cell: Backgrid.StringCell.extend({
                                                className: function () {
                                                    var model = this.model.toJSON();
                                                    if (model.Quality === 'SC') return 'string-cell align-center-cell badQuality';
                                                    else return 'string-cell align-center-cell';
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'CutTime',
                                            label: app.translate([that, app], 'Cut Time'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Length',
                                            label: app.translate([that, app], 'Length'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'SentToL3',
                                            label: app.translate([that, app], 'Sent To L3'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                    ],
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        },
                                        events: {
                                            contextmenu: 'onRightClick',
                                        },
                                        onRightClick: function (e) {
                                            e.preventDefault();
                                            var model = this.model.toJSON();

                                            var rowsView = that.model.get('gridProducts').body.rows;
                                            var newIndex = _.indexOf(rowsView, this);
                                            this.$el.addClass("onRightClickSelectedRow");



                                            that.model.set({ 
                                                rowModel: model,
                                                index: newIndex,
                                            });
                                        },

                                    }),
                                    collection: that.model.productsColl,

                                });                                
                                that.model.set({ gridHeats: gridHeats, gridProducts: gridProducts});
                                that.$el.find('.products-grid-container').append(gridProducts.render().el);

                                $.contextMenu( 'destroy' );
                                $(function (obj) {
                                    $.contextMenu({
                                        selector: '.production-table',
                                        callback: function(key, options) {
                                            that.model.set({contextMenuOption:key});                        
                                            that.contextMenuOptionPressed();
                                        },
                                        items: {
                                            "opt-add-new-piece": {
                                                name: "Add New Piece",
                                                icon: "fa-archive",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-remove-piece": {
                                                name: "Remove Piece",
                                                icon: "fa-close",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },

                                            separator1: {
                                                "type": "cm_separator",
                                            },
                                            "opt-print-tag": {
                                                name: "Print Tag",
                                                icon: "fa-tag",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES' || model.TaggingStatusCode !== 'U') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-re-print-tag": {
                                                name: "Unprint Tag",
                                                icon: "fa-tag",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES' || model.TaggingStatusCode === 'U') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-resend-to-l3": {
                                                name: "Resend to L3", icon: "fa-share-square",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-unmark-as-scrap": {
                                                name: "Unmark as Scrap",
                                                icon: "fa-check-square",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES' || model.Quality !== 'SC') return false;
                                                    else return true;
                                                },
                                            },

                                            "opt-mark-as-scrap": {
                                                name: "Mark as Scrap",
                                                icon: "fa-check-square",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES' || model.Quality === 'SC') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-split-product": {
                                                name: "Split Piece",
                                                icon: "edit",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-assign-heat": {
                                                name: "Assign Heat",
                                                icon: "edit",
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model && model.HeatName && model.HeatName.includes('UNK')) return false;
                                                    else return true;                                                      
                                                }
                                            },
                                            
                                                        
                                        },
                                        events: {
                                            hide: function (options) {
                                                that.pauseRealTime = false;
                                                that.removeHighlightRow();
                                            },
                                            show: function () {
                                                that.pauseRealTime = true;
                                            }
                                        }
                                    }); 
                                });                           


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

                                that.startAutoRefresh();

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

            contextMenuOptionPressed: function(){
                var that = this;
                    rowModel = this.model.get('rowModel'),
                    contextMenuOption = this.model.get('contextMenuOption');
            
                switch (contextMenuOption) {
                    case "opt-add-new-piece":
                        that.model.set({showNewProductGrid: true});
                        
                        that.model.newProductsColl.unshift({
                            id: -1,
                            isNew: true,
                            HeatName: rowModel.CurrentHeatName,
                            //CurrentHeatName: rowModel.CurrentHeatName,
                        });
                        break;   
                    case "opt-remove-piece":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "delete_item_modal_confirm_title"),
                            message: app.translate([this, app], "delete_item_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                           
                                that.model.removeProduct({
                                    productId: rowModel.Id
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();

                        break;
                    case "opt-print-tag":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "print_item_modal_confirm_title"),
                            message: app.translate([this, app], "print_item_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {

                                that.model.printTag({
                                    productId: rowModel.Id
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();


                        break;
                    case "opt-re-print-tag":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "re_print_item_modal_confirm_title"),
                            message: app.translate([this, app], "re_print_item_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {

                                that.model.printTag({
                                    productId: rowModel.Id
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        break;
                    case "opt-resend-to-l3":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "resend_item_modal_confirm_title"),
                            message: app.translate([this, app], "resend_item_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {

                                that.model.resendToL3({
                                    productId: rowModel.Id
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();


                        break;
                    case "opt-assign-heat":
                        if (rowModel.TableType === "PRODUCTS")
                            this.openEditionModal(rowModel, false, rowModel.ProcessId);
                        else if (rowModel.TableType === "PROCESSES")
                            this.openEditionModal(rowModel, false, rowModel.Id);

                        break;
                    case "opt-mark-as-scrap":
                        that.model.markAsScrap({
                            productId: rowModel.Id
                            , markAsScrap: true,
                        });
                        break;
                    case "opt-unmark-as-scrap":
                        that.model.markAsScrap({
                            productId: rowModel.Id
                            ,markAsScrap: false,
                        });
                        break;
                    case "opt-split-product":
                        that.splitProduct(rowModel);
                        break;
                }
            },
            removeHighlightRow: function () {
                var previousIndex = this.model.get('index');
                var rowsView = this.model.get('gridProducts').body.rows;
                var rowsViewHeats = this.model.get('gridHeats').body.rows;
               

                if (rowsView && rowsView[previousIndex] && rowsView[previousIndex].$el)
                    rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");

                if (rowsViewHeats && rowsViewHeats[previousIndex] && rowsViewHeats[previousIndex].$el)
                    rowsViewHeats[previousIndex].$el.removeClass("onRightClickSelectedRow");
                
               // this.model.set({showNewProductGrid: false});
            },


            openEditionModal: function (model, unassign, processId) {
                var modal = new Screen.Views.AssignModal({
                    processId: processId,
                    row: model,
                    bus: this.bus,
                    unassign: unassign,
                });
                modal.show();
            },

      
            //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;
                //If currentModal exists, hide it and erase it.
                if (this.currentModal) {
                    this.currentModal.hide();
                    this.currentModal = null;
                }
                this.stopAutoRefresh();
                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) { }
            },


            splitProduct: function (model) {
                var modal = new Screen.Views.SplitProduct({
                    data: model,
                });
                modal.show();
            },
        });
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        Screen.Collections.ItemsProducts = Backbone.Collection.extend({
            isFetching: false,
            currentPage: 1,
            pageSize: 100,

            fixedParameters: [],
            setDataColl: function (data) {
                var newColl,
                    that = this;
                that.set(data).trigger('fetch', data);
            },

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

                this.fixedParameters = [
                    { Name: '@Id', Type: 'INT', Value: params.Id, },
                    { Name: '@Length', Type: 'FLOAT', Value: params.Length, },
                ];

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

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

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

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

            fixedParameters: [],
            setDataColl: function (data, realTimeData, productsData, productsReadyData, lastProcesses) {
                var newColl,
                    that = this;
                that.set(data).trigger('fetch', data, realTimeData, productsData, productsReadyData, lastProcesses);
            },


        });

        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /****** ASSIGN UNK HEATS ********/

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

        Screen.Collections.LastHeats = Backbone.Collection.extend({
            fetch: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();

                qp.Add('@processId', 'INT', params.processId);

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

                                if ((resp) && (resp.Table)) {
                                    newColl = resp.Table;
                                    that.set(newColl);
                                    that.trigger('fetch', that, newColl);

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

        });

        Screen.Models.AssignModal = Backbone.Epoxy.Model.extend({
            defaults: {
                errorMsg: '',
                processing: true,
                title: '',
                hasData: false,
                isLoading: true,
                index: null,

                selectedHeatId: null,
                currentProcessId: null,
                show_unassign_btn: false,
            },
        });
        Screen.Models.SplitProduct = Backbone.Epoxy.Model.extend({
            defaults: {
                productNumber: '',
                pieceLength: '',
                scrapLength: '',
            },
        });


        Screen.Views.SplitProduct = Backbone.Epoxy.View.extend({
            template: "caster-torch",
            id: "split-heats",
            className: "modal modal-split-heat hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            data: [],
            lastHeatsColl: [],
            grid: [],
            productId: null,
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.SplitProduct();
                }
                var data = options.data;
                this.productId = data.Id;
                this.model.set({
                    productNumber: data.ProductNumber + ' / ' + data.Length,
                })

                this.bindEvents();

                return this;
            },

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

                this.$el.modal('hide');
            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/custom-screens/' + this.template + '/';
                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        that.i18n[that.template] = i18nJED;
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        that.isRendered = true;
                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "split_product_template");

            },



            show: function () {
                if (!this.isRendered) {
                    this.render();
                }
                else {
                    this.$el.modal({
                        keyboard: true,
                        backdrop: 'both',
                    });
                }

                return this;
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
            },

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

                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },
            splitProduct: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@productId'    , Type: 'INT', Value: params.productId, },
                        { Name: '@pieceLength', Type: 'FLOAT', Value: params.pieceLength, },
                        { Name: '@scrapLength', Type: 'FLOAT', Value: params.scrapLength, },
                    ];

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

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.SplitProduct',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Piece Splited', { stay: 5000, });
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            acceptBtn_click: function (e) {
                try {
                    var that = this;
                    var model = this.model.toJSON();

                    if (isNaN(model.pieceLength) || model.pieceLength === '' || model.pieceLength === null) {
                        app.views.topMessages.showMessage('The Piece Length is Not a Number', { stay: 2000, });
                    }else
                    if (isNaN(model.scrapLength) || model.scrapLength === '' || model.scrapLength === null) {

                        app.views.topMessages.showMessage('The Scrap Length is Not a Number', { stay: 2000, });
                    }


                    if (isNaN(model.pieceLength) || model.pieceLength === '' || model.pieceLength === null || isNaN(model.scrapLength) || model.scrapLength === '' || model.scrapLength === null) {


                    } else {
                        this.splitProduct({
                            productId: that.productId,
                            pieceLength: model.pieceLength,
                            scrapLength: model.scrapLength,

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

            unassignBtn_click: function () {
                try {
                    //this.bus.trigger("modalUnassignBtn", this.model.get('currentProcessId'));

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

            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_hidden: function (e) {
                try {
                    this.visible = false;

                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
        });

        Screen.Views.AssignModal = Backbone.Epoxy.View.extend({
            template: "caster-torch",
            id: "assign-heats",
            className: "modal modal-assign-heats hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "click #unassignBtn": this.unassignBtn_click,
                    "submit form": this.form_submit,
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            row: [],
            lastHeatsColl: [],
            grid: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.AssignModal();
                }
                //this.row = options.row.toJSON();
                this.row = options.row;
                this.model.set({
                    currentProcessId: this.processId,
                    show_unassign_btn: false,
                    title: " Assign Caster Process " + this.row.HeatName
                });

                this.lastHeatsColl = new Screen.Collections.LastHeats();

                this.lastHeatsColl.fetch({
                    processId: this.processId
                });

                this.bus = options.bus;

                this.bindEvents();

                return this;
            },

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

                this.$el.modal('hide');
            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/custom-screens/' + this.template + '/';
                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        that.i18n[that.template] = i18nJED;
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        var columns = [
                            {
                                name: 'HeatName',
                                label: 'Heat',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },
                            {
                                name: 'EndTap',
                                label: 'End Tap',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },
                            {
                                name: 'GradeName',
                                label: 'Grade',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },


                        ];
                        var grid = new Backgrid.Grid({
                            className: 'backgrid table table-hover table-condensed',
                            collection: that.lastHeatsColl,
                            columns: columns,
                            row: Backgrid.Row.extend({
                                initialize: function (options) {
                                    Backgrid.Row.prototype.initialize.apply(this, arguments);

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

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

                                        if (!this.$el.hasClass("selectedItem")) {
                                            this.$el.addClass("selectedItem");
                                            that.model.set({ selectedHeatId: this.model.get('HeatId') });
                                        }
                                        var rowsView = that.grid.body.rows;
                                        var newIndex = _.indexOf(rowsView, this);

                                        if (previousIndex != null && previousIndex != newIndex) rowsView[previousIndex].$el.removeClass("selectedItem");

                                        that.model.set({
                                            index: newIndex,
                                        });

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

                        that.grid = grid;
                        that.$el.find('.last-heats-grid-container').append(grid.render().el);

                        that.isRendered = true;



                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "assign_heats_torch_modal");

            },



            show: function () {
                if (!this.isRendered) {
                    this.render();
                }
                else {
                    this.$el.modal({
                        keyboard: true,
                        backdrop: 'both',
                    });
                }

                return this;
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
                this.listenTo(this.lastHeatsColl, 'fetch', this.lastHeats_ready);


            },

            lastHeats_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData: (that.lastHeatsColl.length > 0),
                                processing: false,
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');

                        this.remove();
                        this.unbind();

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

            acceptBtn_click: function (e) {
                try {
                    this.bus.trigger("modalAcceptBtn", this.model.get('currentProcessId'), this.model.get('selectedHeatId'));

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

            unassignBtn_click: function () {
                try {
                    this.bus.trigger("modalUnassignBtn", this.model.get('currentProcessId'));

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

            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_hidden: function (e) {
                try {
                    this.visible = false;

                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

        });

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