//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',
    'modules/ladle-info-widget/ladle-info-widget',
    'modules/modal-trigger-acceptance-caster-lmf/modal-trigger-acceptance-caster-lmf',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',

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

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

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

                hasData: false,
                isLoading: false,

                isLoading_products: true,
                //(0 = OFF, 1 = DB INSERT, 2 = CAST, 3 = TAILOUT)

                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,


                Measured_S1: 0,
                Measured_S2: 0,
                Measured_S3: 0,
                Measured_S4: 0,
                CasterMode_S1: null,
                CasterMode_S2: null,
                CasterMode_S3: null,
                CasterMode_S4: null,

                MaterialRemaining_Top_S1: '',
                MaterialRemaining_Middle_S1: '',
                MaterialRemaining_Bottom_S1: '',

                MaterialRemaining_Top_S2: '',
                MaterialRemaining_Middle_S2: '',
                MaterialRemaining_Bottom_S2: '',

                MaterialRemaining_Top_S3: '',
                MaterialRemaining_Middle_S3: '',
                MaterialRemaining_Bottom_S3: '',

                MaterialRemaining_Top_S4: '',
                MaterialRemaining_Middle_S4: '',
                MaterialRemaining_Bottom_S4: '',

                heatColors: [],
                HydrogenHeatName: '',
                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,
                coolingBed: [],
                tablePositions: [],
                hotCharge: [],
                tundishes: [],
                tundish1Number: '-',
                tundish2Number: '-',

                tundish1Circle: 0,
                tundish2Circle: 0,


                LeftValue_1: '',
                Title_1: '',
                TopValue_1: '',
                MiddleValue_1: '',
                MiddleLeftValue_1: '',
                MiddleRightValue_1: '',
                BottomLeftValue_1: '',
                BottomMiddleValue_1: '',
                BottomRightValue_1: '',
                LadleOpen: false,

                LeftValue_2: '',
                Title_2: '',
                TopValue_2: '',
                MiddleValue_2: '',
                MiddleLeftValue_2: '',
                MiddleRightValue_2: '',
                BottomLeftValue_2: '',
                BottomMiddleValue_2: '',
                BottomRightValue_2: '',


                LeftValue_3: '',
                Title_3: '',
                TopValue_3: '',
                MiddleValue_3: '',
                MiddleLeftValue_3: '',
                MiddleRightValue_3: '',
                BottomLeftValue_3: '',
                BottomMiddleValue_3: '',
                BottomRightValue_3: '',

                LeftValue_4: '',
                Title_4: '',
                TopLeftValue_4: '',
                TopRightValue_4: '',
                BottomLeftValue2_4: '',
                BottomRightValue2_4: '',
                SingleLeftValue: false,

                dragModel: null,
                draggedObject: null,
                allowedPositions: [],

            },
            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;
                    },
                },
                Name_S1: {
                    deps: ['CasterMode_S1'],
                    get: function (casterMode) {
                        if (casterMode === 0) {             // OFF
                            $("#Name_S1").css("background-color", "#CCC");
                            $("#Name_S1").css("color", "#505050");
                            return 'S1 OFF';
                        }
                        if (casterMode === 1) {              // DB INSERT
                            $("#Name_S1").css("background-color", "#FF9728");
                            $("#Name_S1").css("color", "#505050");
                            return 'S1 INS';
                        }
                        if (casterMode === 2) {             // CAST
                            $("#Name_S1").css("background-color", "#ff4028");
                            $("#Name_S1").css("color", "white");
                            return 'S1 CAST';
                        }
                        if (casterMode === 3) {             // TAILOUT
                            $("#Name_S1").css("background-color", "#4358ed");
                            $("#Name_S1").css("color", "white");
                            return 'S1 TAIL';
                        }
                        else {
                            $("#Name_S1").css("background-color", "#eee");
                            $("#Name_S1").css("color", "#505050");
                            return 'S1'
                        };
                    },
                },
                Name_S2: {
                    deps: ['CasterMode_S2'],
                    get: function (casterMode) {
                        if (casterMode === 0) {             // OFF
                            $("#Name_S2").css("background-color", "#CCC");
                            $("#Name_S2").css("color", "#505050");
                            return 'S2 OFF';
                        }
                        if (casterMode === 1) {              // DB INSERT
                            $("#Name_S2").css("background-color", "#FF9728");
                            $("#Name_S2").css("color", "#505050");
                            return 'S2 INS';
                        }
                        if (casterMode === 2) {             // CAST
                            $("#Name_S2").css("background-color", "#ff4028");
                            $("#Name_S2").css("color", "white");
                            return 'S2 CAST';
                        }
                        if (casterMode === 3) {             // TAILOUT
                            $("#Name_S2").css("background-color", "#4358ed");
                            $("#Name_S2").css("color", "white");
                            return 'S2 TAIL';
                        }
                        else {
                            $("#Name_S2").css("background-color", "#eee");
                            $("#Name_S2").css("color", "#505050");
                            return 'S2'
                        };
                    },
                },
                Name_S3: {
                    deps: ['CasterMode_S3'],
                    get: function (casterMode) {
                        if (casterMode === 0) {             // OFF
                            $("#Name_S3").css("background-color", "#CCC");
                            $("#Name_S3").css("color", "#505050");
                            return 'S3 OFF';
                        }
                        if (casterMode === 1) {              // DB INSERT
                            $("#Name_S3").css("background-color", "#FF9728");
                            $("#Name_S3").css("color", "#505050");
                            return 'S3 INS';
                        }
                        if (casterMode === 2) {             // CAST
                            $("#Name_S3").css("background-color", "#ff4028");
                            $("#Name_S3").css("color", "white");
                            return 'S3 CAST';
                        }
                        if (casterMode === 3) {             // TAILOUT
                            $("#Name_S3").css("background-color", "#4358ed");
                            $("#Name_S3").css("color", "white");
                            return 'S3 TAIL';
                        }
                        else {
                            $("#Name_S3").css("background-color", "#eee");
                            $("#Name_S3").css("color", "#505050");
                            return 'S3'
                        };
                    },
                },
                Name_S4: {
                    deps: ['CasterMode_S4'],
                    get: function (casterMode) {
                        if (casterMode === 0) {             // OFF
                            $("#Name_S4").css("background-color", "#CCC");
                            $("#Name_S4").css("color", "#505050");
                            return 'S4 OFF';
                        }
                        if (casterMode === 1) {              // DB INSERT
                            $("#Name_S4").css("background-color", "#FF9728");
                            $("#Name_S4").css("color", "#505050");
                            return 'S4 INS';
                        }
                        if (casterMode === 2) {             // CAST
                            $("#Name_S4").css("background-color", "#ff4028");
                            $("#Name_S4").css("color", "white");
                            return 'S4 CAST';
                        }
                        if (casterMode === 3) {             // TAILOUT
                            $("#Name_S4").css("background-color", "#4358ed");
                            $("#Name_S4").css("color", "white");
                            return 'S4 TAIL';
                        }
                        else {
                            $("#Name_S4").css("background-color", "#eee");
                            $("#Name_S4").css("color", "#505050");
                            return 'S4'
                        };
                    },
                },

            },
            initialize: function () {
                this.itemsColl = new Screen.Collections.Items();
                this.productsColl = new Screen.Collections.ItemsProducts();
                this.newProductsColl = new Screen.Collections.ItemsProducts();
                this.positions = new Screen.Collections.Positions();
                this.productsTablePosition = new Screen.Collections.ProductsTablePosition();
            },
            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                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.GetCasterSupervisionWeb',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    //Get Heats By Color
                                    that.set({ heatColors: resp.Table1 });

                                    // Top Table (Last 4 Heats) + Bottom chart-table (Strands data + dynamic products list Heat + Boundaries)
                                    // - Table4  --> Top Table with the last 4 heats in the caster
                                    // - Table   --> Bottom right table: Strand data --> example: Speed, Reamaining, caster mode
                                    // - Table2  --> Real time data: list of products for the dynamic bottom chart
                                    // - Table13 --> Heat Boundary for the dynamic bottom chart
                                    if (resp.Table4 && resp.Table && resp.Table2 && resp.Table13) {
                                        that.itemsColl.setDataColl(resp.Table4, resp.Table, resp.Table2, resp.Table13);
                                    }

                                    //right table
                                    if (resp.Table5) that.productsColl.setDataColl(resp.Table5);

                                    //TWI
                                    if (resp.Table6) that.set('TWIBlanket', resp.Table6[0].TWIBlanket);

                                    //Cooling bed
                                    if (resp.Table8) that.set({ coolingBed: resp.Table8 });

                                    // Hot charge
                                    that.set({ hotCharge: resp.Table10 });

                                    //Runout table
                                    that.set({ tablePositions: resp.Table9 });
                                    that.productsTablePosition.setDataColl(resp.Table9, resp.Table1);

                                    // Tundish lists
                                    _.each(resp.Table11, function (obj) {
                                        that.set({ tundish1Circle: obj.TundishCar1 });
                                        that.set({ tundish2Circle: obj.TundishCar2 });
                                    });

                                    that.positions.setDataColl(resp.Table12);

                                    // Hydrogen Redirect
                                    if (resp.Table14) {
                                        that.set({
                                            HydrogenHeatName: resp.Table14 && resp.Table14[0] && resp.Table14[0].HeatName ? resp.Table14[0].HeatName : ''
                                        })
                                    };

                                    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;
            },
            changeDeliveredDestination: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@productId', Type: 'INT', Value: params.productId, },
                        { Name: '@destination', Type: 'CHAR', Value: params.destination, },
                    ];

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

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.ChangeDeliveredDestination',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Destination changed ', { stay: 5000, });
                                        that.trigger('triggerFetch');
                                    }
                                    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); }
            },
            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.AssignCasterProcessInPLC',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Heat Assigned', { 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.Message)) {
                                    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;
            },
            changeProductQuality: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                    { Name: '@qualityCode', Type: 'INT', Value: parseInt(params.qualityCode), },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.ChangeProductQuality',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && !(resp.Message)) {
                                    app.views.topMessages.showMessage('Product Quality Change in Progress...', { 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); }
            },
            updateTundishCar: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                this.fixedParameters = [
                    { Name: '@Id', Type: 'INT', Value: isNaN(params.Id) || params.Id === '' ? null : parseInt(params.Id), },
                    { Name: '@TundishId', Type: 'INT', Value: isNaN(params.TundishId) || params.TundishId === '' ? null : params.TundishId, },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.UpdateTundishCar',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    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;
            },
            getTundishCars: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                var tundishes = [];
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.getTundishCars',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    if (resp.Table) {
                                        _.each(resp.Table, function (obj) {
                                            tundishes.push({ label: obj.Name, value: obj.Id });
                                        });
                                        that.set({ tundishes: tundishes });
                                    }
                                    _.each(resp.Table1, function (obj) {
                                        if (obj && obj.TundishCar1) {
                                            that.set({ tundish1Number: obj.TundishCar1 });
                                        }
                                        if (obj && obj.TundishCar2) {
                                            that.set({ tundish2Number: obj.TundishCar2 });
                                        }
                                    });
                                    that.trigger('tundishCars');
                                }
                                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;
            },
            changeProductRunoutPosition: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    var sequence = null;

                    if (params.Sequence[0] == 0) {
                        sequence = parseInt(params.Sequence.split('0')[1]);
                    } else {
                        sequence = parsetInt(params.Sequence);
                    }
                    this.fixedParameters = [
                        { Name: '@HeatNumber', Type: 'VARCHAR', Value: params.HeatName, },
                        { Name: '@StrandId', Type: 'INT', Value: parseInt(params.StrandId), },
                        { Name: '@PositionId', Type: 'INT', Value: parseInt(params.Pos), },
                        { Name: '@Sequence', Type: 'INT', Value: sequence, },

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

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.ChangeProductRunoutPosition',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Product Runout Position changed ', { stay: 5000, });
                                        //that.trigger('triggerFetch');
                                    }
                                    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-cooling-bed-cooling-bed';
            } catch (Error) { }
        }





        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-torch-cooling-bed',
            id: 'caster-torch-cooling-bed',
            title: 'Caster Torch',
            events: function () {
                return {

                    'click #HeatsRealTimeBtn': this.HeatsRealTimeBtn_click,
                    'click #TWIBtn': this.TWIBtn_click,
                    'click #HydrogenBtn': this.HydrogenBtn_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,
                    //Handle drag
                    'mousedown .draggable': 'detectdrag',
                    'mouseup .draggable': 'mouseupdrag',
                    'dragstart .draggable': 'dragstart',
                    'dragend .draggable': 'dragend',
                    // Handle drop
                    'dragenter .dropable': 'dragenter',
                    'dragleave .dropable': 'dragleave',
                    'drop .dropable': 'drop',
                    'dragover .dropable': function (ev) {
                        ev.preventDefault();
                    },
                    'click .dropable': this.draggable_click,
                    'click #in-transit-position': this.acceptHeatInTransit,
                    'click #out-position': this.acceptHeatOutboard,
                    'click #in-position': this.acceptHeatInboard,
                };
            },

            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            subviews: null,
            viewParams: null,
            tooltip: null,
            tooltip1: null,
            pauseTimer: false,
            pauseRealTime: false,
            strands: [],
            sequences: [],
            editProductModal: [],
            currentModal: null,
            timeCounter: 0,
            positionsView: null,
            productsPositionView: null,
            acceptHeatModal: 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 = {
                };

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

                this.grids = {};
                this.bindingSources = {
                    positions: that.model.positions,
                    productsTablePosition: that.model.productsTablePosition,
                };

                this.subviews = {};

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

                };
                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);
                this.bus.on("modalAcceptTrigger", this.onModalAcceptTrigger, 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();
            },
            HeatsRealTimeBtn_click: function () {
                app.router.navigate('!/caster-heats-real-time/', { trigger: true });
            },
            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.positionsView = LadleInfoWidget.Views.LadleInfoWidget.extend({});

                                that.productsPositionView = Screen.Views.ProductPosition.extend({
                                    template: Handlebars.compile(that.$el.find('#ProductsViewPositionTemplate').html()),
                                });

                                that.applyBindings();


                                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 color1';
                                                    else if (color == '#ff9728') classes = 'string-cell align-center-cell heat-row color2';
                                                    else if (color == '#479dc4') classes = 'string-cell align-center-cell heat-row color3';
                                                    else if (color == '#d3e71a') classes = 'string-cell align-center-cell heat-row color4';
                                                    else if (color == '#67c2cb') classes = 'string-cell align-center-cell heat-row color5';
                                                    else if (color == '#edec35') classes = 'string-cell align-center-cell heat-row color6';
                                                    else if (color == '#69f59c') classes = 'string-cell align-center-cell heat-row color7';
                                                    else if (color == '#87c2cb') classes = 'string-cell align-center-cell heat-row color8';
                                                    else if (color == '#ed8c35') classes = 'string-cell align-center-cell heat-row color9';
                                                    else if (color == '#69859c') classes = 'string-cell align-center-cell heat-row color10';
                                                    else classes = 'string-cell align-center-cell color0';
                                                    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], 'Sol. 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,
                                        },
                                        {
                                            name: 'Hydrogen',
                                            label: app.translate([that, app], 'Hydrogen'),
                                            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 color1';
                                                    else if (color == '#ff9728') classes = 'string-cell align-center-cell heat-row color2';
                                                    else if (color == '#479dc4') classes = 'string-cell align-center-cell heat-row color3';
                                                    else if (color == '#d3e71a') classes = 'string-cell align-center-cell heat-row color4';
                                                    else if (color == '#67c2cb') classes = 'string-cell align-center-cell heat-row color5';
                                                    else if (color == '#edec35') classes = 'string-cell align-center-cell heat-row color6';
                                                    else if (color == '#69f59c') classes = 'string-cell align-center-cell heat-row color7';
                                                    else if (color == '#87c2cb') classes = 'string-cell align-center-cell heat-row color8';
                                                    else if (color == '#ed8c35') classes = 'string-cell align-center-cell heat-row color9';
                                                    else if (color == '#69859c') classes = 'string-cell align-center-cell heat-row color10';
                                                    else classes = 'string-cell align-center-cell color0';

                                                    return classes;
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'TaggingStatusCode',
                                            label: app.translate([that, app], 'Tag 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], 'Dest'),
                                            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.isCrop === 1) {
                                                        if (model.Quality === 'T') return 'string-cell align-center-cell isCropQuality';
                                                        if (model.Quality === 'H') return 'string-cell align-center-cell isCropQuality';
                                                        else return 'string-cell align-center-cell';

                                                    } else {

                                                        if (model.Quality === 'S') return 'string-cell align-center-cell badQuality';
                                                        if (model.Quality === 'H') return 'string-cell align-center-cell';
                                                        else return 'string-cell align-center-cell';
                                                    } 
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'CutTime',
                                            label: app.translate([that, app], 'Cut'),
                                            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: function () {
                                                    var model = this.model.toJSON();
                                                    if (model.isTail == 1) return 'string-cell align-center-cell isTail';
                                                    else return 'string-cell align-center-cell';
                                                },
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'SentToL3',
                                            label: app.translate([that, app], 'L3 Sent'),
                                            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 Piece",
                                                icon: "fa-archive",
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-edit-length-piece": {
                                                name: "Change Length",
                                                icon: "edit",
                                                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-send-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;
                                                },
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return true;
                                                    else if (model && model.SentToL3 === 'No') return true;
                                                    else return false;
                                                }
                                            },
                                          
                                            "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",
                                                visible: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType !== 'PROCESSES') return false;
                                                    else return true;
                                                },
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType !== 'PROCESSES') return true;
                                                    else if (model && model.HeatName && model.HeatName.includes('UNK')) return false;
                                                    else return true;
                                                }
                                            },
                                            separator2: {
                                                "type": "cm_separator",
                                            },
                                            "opt-set-quality-prime": {
                                                name: "Set Quality to Prime",
                                                icon: "fa-check-square",
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.QualityCode == '1') return true;
                                                    else return false;
                                                },                   
                                                visible: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-set-quality-hold": {
                                                name: "Set Quality to Hold",
                                                icon: "fa-check-square",
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.QualityCode == '2') return true;
                                                    else return false;
                                                },
                                                visible: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-set-quality-scrap": {
                                                name: "Set Quality to Scrap",
                                                icon: "fa-check-square",
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model.QualityCode == '3') return true;
                                                    else return false;
                                                },
                                                visible: function (key, opt) {
                                                    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;
                                            //    },
                                            //},

                                            separator3: {
                                                "type": "cm_separator",
                                            },
                                            "opt-send-ct": {
                                                name: "Send to CT",
                                                icon: "edit",
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model && model.Id) return false;
                                                    else return true;
                                                },
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-send-hc": {
                                                name: "Send to HT",
                                                icon: "edit",
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model && model.Id) return false;
                                                    else return true;
                                                },
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType === 'PROCESSES') return false;
                                                    else return true;
                                                },
                                            },
                                            "opt-redirect-hydorgen": {
                                                name: "Hydrogen",
                                                icon: "edit",
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model && model.Id) return false;
                                                    else return true;
                                                },
                                                visible: function () {
                                                    var model = that.model.get('rowModel');
                                                    if (model.TableType !== 'PROCESSES') 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
                );
            },
            //Drag and drop functions
            detectdrag: function (event) {
                var that = this;

                //Pause Timer
                this.pauseTimer = true;

                //Get Dragged HTML Object 
                if (event.target.parentNode.parentNode.classList[0] === "dropable") { //make sure that we are not dragging the dropable container too
                    this.model.set({ draggedObject: event.target.parentNode });
                } else {
                    this.model.set({ draggedObject: event.target.parentNode.parentNode });
                }

                // Get Dragged Element ID to find the DragModel using the Sequence, Strand and Heat
                var dragItem = $(event.currentTarget);
                var splitSelectedDragId = dragItem.context.id.split('-');
                var strandId = splitSelectedDragId[0].split('str')[1];
                var sequence = splitSelectedDragId[1].split('seq')[1];
                var heat = splitSelectedDragId[2].split('heat')[1];
                var dragModel = null;

                var notAllowedPositions = [];

                _.each(this.model.productsTablePosition.models, function (model) {
                    obj = model.attributes;
                    if (obj.StrandId == strandId && obj.Sequence == sequence && obj.HeatName == heat) {
                        dragModel = model;
                    }
                    if (obj.StrandId == strandId) {
                        notAllowedPositions.push(obj.Pos);
                    }
                });
                var allowedPositions = [];

                var positionIsNotAllowed = false;
                for (var i = 2; i <= 6; i++) {
                    _.each(notAllowedPositions, function (pos) {
                        if (i == pos) {
                            positionIsNotAllowed = true;
                        }
                    })
                    if (positionIsNotAllowed === false) allowedPositions.push("#strand" + strandId + 'pos' + i);
                    positionIsNotAllowed = false;
                }

                var notRepeatedPositions = [...new Set(allowedPositions)];
                this.model.set({ dragModel: dragModel, allowedPositions: notRepeatedPositions });

                //display allowed locations
                _.each(notRepeatedPositions, function (obj) {
                    $(obj).addClass('allowed-locations');
                });
            },
            dragenter: function (event) {

                //var dropContainer = $(event.currentTarget);
                this.dragEnterContainer = $(event.currentTarget);

                var dropContainerId = "#" + $(event.currentTarget).context.id;
                if (this.model.get('allowedPositions').includes(dropContainerId)) {
                    this.dragEnterContainer.addClass('drag-over-drop-container');

                }

                event.preventDefault();
            },
            dragleave: function (event) {
                this.removeDragOverClass();
            },
            drop: function (event) {
                var that = this;
                var dropContainerId = "#" + $(event.currentTarget).context.id;
                if (this.model.get('allowedPositions').includes(dropContainerId)) {
                    event.target.appendChild(that.model.attributes.draggedObject);

                    // UPDATE MODEL OF COLLECTION IN JAVASCRIPT
                    // 1 - Find Index of Model
                    var index = that.model.productsTablePosition.models.indexOf(that.model.attributes.dragModel);
                    // 2 - Get Model from Collection
                    var model = that.model.productsTablePosition.models[index];
                    // 3 - Set New Position
                    that.model.attributes.dragModel.Pos = parseInt($(event.currentTarget).context.id.split('pos')[1]);
                    // 4 - Update collection
                    model.set(that.model.attributes.dragModel);

                    var updatedModel = that.model.attributes.dragModel.attributes;
                    // SEND DATA TO DATABASE
                    this.model.changeProductRunoutPosition({
                        HeatName: updatedModel.HeatName
                        , Pos: updatedModel.Pos
                        , Sequence: updatedModel.Sequence
                        , StrandId: updatedModel.StrandId
                    });
                } else {
                    app.views.topMessages.showMessage('Runout position not allowed ', { stay: 3000, });
                }


            },
            dragend: function () {
                this.removeDragOverClass();
                this.removeAllowedLocationsClass();
                this.pauseTimer = false;
                this.model.set({
                    dragModel: null,
                    draggedObject: null,
                    allowedPositions: [],
                })

            },
            mouseupdrag: function () {
                this.removeAllowedLocationsClass();
                this.removeDragOverClass();
            },
            removeDragOverClass: function () {
                this.$el.find('.drag-over-drop-container').removeClass('drag-over-drop-container');
            },
            removeAllowedLocationsClass: function () {
                this.$el.find('.allowed-locations').removeClass('allowed-locations');
            },



            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 });
            },
            HydrogenBtn_click: function () {
                var heatNameOpen = this.model.get('HydrogenHeatName');
                app.router.navigate('!/hydrogen-samples/' + heatNameOpen, { trigger: true });
            },
            onModalAcceptBtn: function (processId, heatId) {
                this.model.reassing({
                    processId: processId,
                    heatId: heatId,
                })
            },
            bindEvents: function () {

                this.listenTo(this.model.positions, 'fetch', this.positions_fetched);
                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);
                this.listenTo(this.model, 'tundishCars', this.tundishCars_updated);
                this.listenTo(this.model, 'change:tundish1Number', this.tundish1Number_changed);
                this.listenTo(this.model, 'change:tundish2Number', this.tundish2Number_changed);
                this.listenTo(this.model, 'change:tundish1Circle', this.tundish1Circle_changed);
                this.listenTo(this.model, 'change:tundish2Circle', this.tundish2Circle_changed);

                this.listenTo(this.model.productsTablePosition, 'fetch', this.productsTablePosition_fetched);

            },
            productsTablePosition_fetched: function (topRunoutTablePositions) {
                try {
                    var that = this;

                    $("#strand1pos2").html('');
                    $("#strand1pos3").html('');
                    $("#strand1pos4").html('');
                    $("#strand1pos5").html('');
                    $("#strand1pos6").html('');

                    $("#strand2pos2").html('');
                    $("#strand2pos3").html('');
                    $("#strand2pos4").html('');
                    $("#strand2pos5").html('');
                    $("#strand2pos6").html('');


                    $("#strand3pos2").html('');
                    $("#strand3pos3").html('');
                    $("#strand3pos4").html('');
                    $("#strand3pos5").html('');
                    $("#strand3pos6").html('');


                    $("#strand4pos2").html('');
                    $("#strand4pos3").html('');
                    $("#strand4pos4").html('');
                    $("#strand4pos5").html('');
                    $("#strand4pos6").html('');


                    $("#pos8").html('');
                    $("#pos9").html('');
                    $("#pos10").html('');
                    $("#pos11").html('');
                    var dropContainerId = null;
                    var draggableObjectId = null;
                    _.each(that.model.productsTablePosition.toJSON(), function (obj) {
                        if (obj.Pos >= 2 && obj.Pos <= 6) {
                            dropContainerId = '#strand' + obj.StrandId + 'pos' + obj.Pos;
                            draggableObjectId = '#str' + obj.StrandId + '-seq' + obj.Sequence + '-heat' + obj.HeatName;

                            that.append($(dropContainerId), $(draggableObjectId));
                        }
                    });

                    _.each(that.model.productsTablePosition.toJSON(), function (obj) {
                        if (obj.Pos >= 8 && obj.Pos <= 11) {
                            dropContainerId = '#pos' + obj.Pos;
                            draggableObjectId = '#str' + obj.StrandId + '-seq' + obj.Sequence + '-heat' + obj.HeatName;
                            that.append($(dropContainerId), $(draggableObjectId));
                            that.$el.find(draggableObjectId).removeClass('draggable');

                            that.$el.find(draggableObjectId)[0].children[0].setAttribute("draggable", false)
                            that.$el.find(draggableObjectId)[0].children[0].style.cursor = "auto";
                        }
                    });


                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            positions_fetched: function () {
                try {
                    var that = this;
                    var elementId;
                    var positions = that.model.positions.toJSON();
                    var inboundValues = _.where(positions, { ScreenPositionId: "#INBOUND" })[0];
                    var outboundValues = _.where(positions, { ScreenPositionId: "#OUTBOUND" })[0];
                    var itValues = _.where(positions, { ScreenPositionId: "#IT" })[0];
                    var tundishValues = _.where(positions, { ScreenPositionId: "#TUNDISH" })[0];

                    var colors = null;
                    var color = null;
                    var currentHeat = null;


                    this.model.set({
                        LeftValue_1: inboundValues && inboundValues.LeftValue ? inboundValues.LeftValue : ''
                        , TopValue_1: inboundValues && inboundValues.TopValue ? inboundValues.TopValue : ''
                        , Title_1: inboundValues && inboundValues.Title ? inboundValues.Title : ''
                        , MiddleValue_1: inboundValues && inboundValues.MiddleValue ? inboundValues.MiddleValue : ''
                        , MiddleLeftValue_1: inboundValues && inboundValues.MiddleLeftValue ? inboundValues.MiddleLeftValue : ''
                        , MiddleRightValue_1: inboundValues && inboundValues.MiddleRightValue ? inboundValues.MiddleRightValue : ''
                        , BottomLeftValue_1: inboundValues && inboundValues.BottomLeftValue ? inboundValues.BottomLeftValue : ''
                        , BottomMiddleValue_1: inboundValues && inboundValues.BottomMiddleValue ? inboundValues.BottomMiddleValue : ''
                        , BottomRightValue_1: inboundValues && inboundValues.BottomRightValue ? inboundValues.BottomRightValue : ''
                        , LadleOpen: inboundValues && inboundValues.LadleOpen ? inboundValues.LadleOpen : ''
                    });


                    // Set Background Colors by Heat
                    currentHeat = that.model.get('TopValue_1').replace(/ /g, ''); //REMOVE ALL BLANK SPACES FROM THE HEAT NAME
                    colors = _.where(that.model.get('heatColors'), { HeatName: currentHeat });
                    color = colors[0] && colors[0].Color ? colors[0].Color : null;
                    if (color) $(".inboard-heat").css("background-color", color);
                    else $(".inboard-heat").css("background-color", '#FFFFFF');

                    this.model.set({
                        LeftValue_2: outboundValues && outboundValues.LeftValue ? outboundValues.LeftValue : ''
                        , Title_2: outboundValues && outboundValues.Title ? outboundValues.Title : ''
                        , TopValue_2: outboundValues && outboundValues.TopValue ? outboundValues.TopValue : ''
                        , MiddleValue_2: outboundValues && outboundValues.MiddleValue ? outboundValues.MiddleValue : ''
                        , MiddleLeftValue_2: outboundValues && outboundValues.MiddleLeftValue ? outboundValues.MiddleLeftValue : ''
                        , MiddleRightValue_2: outboundValues && outboundValues.MiddleRightValue ? outboundValues.MiddleRightValue : ''
                        , BottomLeftValue_2: outboundValues && outboundValues.BottomLeftValue ? outboundValues.BottomLeftValue : ''
                        , BottomMiddleValue_2: outboundValues && outboundValues.BottomMiddleValue ? outboundValues.BottomMiddleValue : ''
                        , BottomRightValue_2: outboundValues && outboundValues.BottomRightValue ? outboundValues.BottomRightValue : ''
                    });

                    // Set Background Colors by Heat
                    currentHeat = that.model.get('TopValue_2').replace(/ /g, ''); //REMOVE ALL BLANK SPACES FROM THE HEAT NAME
                    colors = _.where(that.model.get('heatColors'), { HeatName: currentHeat });
                    color = colors[0] && colors[0].Color ? colors[0].Color : null;
                    if (color) $(".outboard-heat").css("background-color", color);
                    else $(".outboard-heat").css("background-color", '#FFFFFF');

                    this.model.set({
                        LeftValue_3: itValues && itValues.LeftValue ? itValues.LeftValue : ''
                        , Title_3: itValues && itValues.Title ? itValues.Title : ''
                        , TopValue_3: itValues && itValues.TopValue ? itValues.TopValue : ''
                        , MiddleValue_3: itValues && itValues.MiddleValue ? itValues.MiddleValue : ''
                        , MiddleLeftValue_3: itValues && itValues.MiddleLeftValue ? itValues.MiddleLeftValue : ''
                        , MiddleRightValue_3: itValues && itValues.MiddleRightValue ? itValues.MiddleRightValue : ''
                        , BottomLeftValue_3: itValues && itValues.BottomLeftValue ? itValues.BottomLeftValue : ''
                        , BottomMiddleValue_3: itValues && itValues.BottomMiddleValue ? itValues.BottomMiddleValue : ''
                        , BottomRightValue_3: itValues && itValues.BottomRightValue ? itValues.BottomRightValue : ''
                    })
                    // Set Background Colors by Heat
                    currentHeat = that.model.get('TopValue_3').replace(/ /g, ''); //REMOVE ALL BLANK SPACES FROM THE HEAT NAME
                    colors = _.where(that.model.get('heatColors'), { HeatName: currentHeat });
                    color = colors[0] && colors[0].Color ? colors[0].Color : null;
                    if (color) $(".intransit-heat").css("background-color", color);
                    else $(".intransit-heat").css("background-color", '#FFFFFF');


                    this.model.set({
                        Title_4: tundishValues && tundishValues.Title ? tundishValues.Title : '',
                        LeftValue_4: tundishValues && tundishValues.LeftValue ? tundishValues.LeftValue : '', //Temperature
                        TopLeftValue_4: tundishValues && tundishValues.TopLeftValue ? tundishValues.TopLeftValue : '', //Heat
                        TopRightValue_4: tundishValues && tundishValues.TopRightValue ? tundishValues.TopRightValue : '', // Weight
                        BottomLeftValue2_4: tundishValues && tundishValues.BottomLeftValue2 ? tundishValues.BottomLeftValue2 : '',   //Heat 
                        BottomRightValue2_4: tundishValues && tundishValues.BottomRightValue2 ? tundishValues.BottomRightValue2 : '', // Weight
                    });
                    var model = this.model.toJSON();
                    if (model.TopLeftValue_4 === model.BottomLeftValue2_4 || model.TopLeftValue_4 === '' || model.BottomLeftValue2_4 === '') {

                        this.model.set({
                            SingleLeftValue: true,
                        })
                        if (model.TopLeftValue === '' && model.BottomLeftValue2_4 === '') {
                            this.model.set({
                                BottomLeftValue2_4: '',
                            })
                        } else {
                            this.model.set({
                                BottomLeftValue2_4: model.BottomLeftValue2_4 ? model.BottomLeftValue2_4 : model.TopLeftValue_4,
                                BottomRightValue2_4: (model.BottomRightValue2_4 || model.TopRightValue) ?
                                    (model.BottomRightValue2_4 ? model.BottomRightValue2_4 : model.TopRightValue) : '',
                            })
                        }

                        // Set Background Colors by Heat
                        currentHeat = that.model.get('BottomLeftValue2_4').replace(/ /g, ''); //REMOVE ALL BLANK SPACES FROM THE HEAT NAME
                        colors = _.where(that.model.get('heatColors'), { HeatName: currentHeat });
                        color = colors[0] && colors[0].Color ? colors[0].Color : null;
                        if (color) $(".tundish-heat-bottom").css("background-color", color);
                        else $(".tundish-heat-bottom").css("background-color", '#FFFFFF');

                    } else {
                        this.model.set({
                            SingleLeftValue: false,
                        });

                        // Set Background Colors by Heat
                        currentHeat = that.model.get('BottomLeftValue2_4').replace(/ /g, ''); //REMOVE ALL BLANK SPACES FROM THE HEAT NAME
                        colors = _.where(that.model.get('heatColors'), { HeatName: currentHeat });
                        color = colors[0] && colors[0].Color ? colors[0].Color : null;
                        if (color) $(".tundish-heat-bottom-2").css("background-color", color);
                        else $(".tundish-heat-bottom-2").css("background-color", '#FFFFFF');

                        currentHeat = that.model.get('TopLeftValue_4').replace(/ /g, ''); //REMOVE ALL BLANK SPACES FROM THE HEAT NAME
                        colors = _.where(that.model.get('heatColors'), { HeatName: currentHeat });
                        color = colors[0] && colors[0].Color ? colors[0].Color : null;
                        if (color) $(".tundish-heat-top").css("background-color", color);
                        else $(".tundish-heat-top").css("background-color", '#FFFFFF');
                    }
                    //   $(".blink-bg").removeClass('blink-bg');

                    if (inboundValues && inboundValues.AcceptHeat) {
                        $('#in-position').addClass('blink-bg');
                    } else {
                        $("#in-position").removeClass('blink-bg');
                    }
                    if (outboundValues && outboundValues.AcceptHeat) {
                        $('#out-position').addClass('blink-bg');
                    } else {
                        $("#out-position").removeClass('blink-bg');
                    }
                    if (itValues && itValues.AcceptHeat) {
                        $('#in-transit-position').addClass('blink-bg');
                    } else {
                        $("#in-transit-position").removeClass('blink-bg');
                    }





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

            acceptHeatInTransit: function () {
                var positions = this.model.positions.toJSON();
                var values = _.where(positions, { ScreenPositionId: "#IT" })[0];
                if ($('#in-transit-position').hasClass('blink-bg')) {
                    this.acceptHeat(values);
                }
            },
            acceptHeatOutboard: function () {
                var positions = this.model.positions.toJSON();
                var values = _.where(positions, { ScreenPositionId: "#OUTBOUND" })[0];             
                if ($('#out-position').hasClass('blink-bg')) {
                    this.acceptHeat(values);
                }
            },
            acceptHeatInboard: function () {
                var positions = this.model.positions.toJSON();
                var values = _.where(positions, { ScreenPositionId: "#INBOUND" })[0];
                if ($('#in-position').hasClass('blink-bg')) {
                    this.acceptHeat(values);
                }
            },

            acceptHeat: function (values) {
                var data = []
                    that = this;
                data = {
                     GradeName:       values.GradeName          
                    ,HeatNumber:      values.HeatNumber      
                    ,LadleID:         values.LadleID          
                    ,MaterialSize:    values.MaterialSize      
                    ,MeltOrderNumber: values.MeltOrderNumber    
                    ,SteelWeight:     values.SteelWeight       
                };
                /* roleName = values.Title;*/
                roleName = 'CASTER';

                if (that.acceptHeatModal == null && $('.modal.in').length == 0) {
                    that.acceptHeatModal = new ModalTriggerAcceptance.Views.ModalTriggerAcceptance({
                        parent: this,
                        data: data,
                        roleName: roleName,
                        bus: null,
                    });

                    this.listenTo(that.acceptHeatModal, 'close', function () {
                        try {
                            that.acceptHeatModal = null;

                            this.pauseTimer = false;
                            that.refresh();
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });
                    try {
                        if ($('.modal.in').length == 0) { //Check again if there is another modal of any kind displayed to prevent issues.
                            this.pauseTimer = true;
                            that.acceptHeatModal.show();
                        }
                        else {
                            that.acceptHeatModal.close();
                            that.acceptHeatModal = null;

                            this.pauseTimer = false;
                            that.refresh();
                        }
                    }
                    catch (e) {
                        if (that.acceptHeatModal != null) {
                            that.acceptHeatModal.close();
                            that.acceptHeatModal = null;

                            this.pauseTimer = false;
                            that.refresh();
                        }
                        app.views.topMessages.showMessage(app.translate([that, app], 'MODAL_DISPLAY_ERROR'), { stay: 5 * 1000, });
                        console.error((e.stack) ? e.stack : new Error(e).stack);
                    }


                }
            },
            tundish1Circle_changed: function () {
                if (this.model.get('tundish1Circle') === 1) {
                    $(".tunidsh1Circle").css("background-color", "green");
                } else {
                    $(".tunidsh1Circle").css("background-color", "lightgray");
                }
            },
            tundish2Circle_changed: function () {
                if (this.model.get('tundish2Circle') === 1) {
                    $(".tunidsh2Circle").css("background-color", "green");
                } else {
                    $(".tunidsh2Circle").css("background-color", "lightgray");
                }
            },

            tundishCars_updated: function () {
                this.listenTo(this.model, 'change:tundish1Number', this.tundish1Number_changed);
                this.listenTo(this.model, 'change:tundish2Number', this.tundish2Number_changed);
            },
            tundish1Number_changed: function (obj) {
                var that = this;
                var tundish1Number = that.model.get('tundish1Number') === '-' ? null : that.model.get('tundish1Number');
                this.model.updateTundishCar({
                    Id: 1,
                    TundishId: tundish1Number
                });
            },
            tundish2Number_changed: function () {
                var that = this;
                var tundish2Number = that.model.get('tundish2Number') === '-' ? null : that.model.get('tundish2Number');
                this.model.updateTundishCar({
                    Id: 2,
                    TundishId: tundish2Number
                });
            },
            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.timeCounter === 0) {
                    this.stopListening(this.model, 'change:tundish1Number', this.tundish1Number_changed);
                    this.stopListening(this.model, 'change:tundish2Number', this.tundish2Number_changed);
                    this.model.getTundishCars();
                }
                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 });
                    }

                    this.timeCounter += 1;
                    if (this.timeCounter > 0) {
                        this.timeCounter = 0;
                    }


                }
            },
            onModalAcceptTrigger: function (obj) {
                this.model.fetch({ products: true });
            },




            //-------------------------------------------------------//
            //-------- BOTTOM DYNAMIC CHART AND STRANDS TABLE -------//
            //-------------------------------------------------------//
            processes_ready: function (strandData, productsData, boundaryData) {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData: (that.model.itemsColl.length > 0),
                                isLoading: false,
                            });
                            // Set Data to the bottom-right table --> Caster Mode, Remainig, Speed, etc..
                            that.setBottomTableData(strandData);

                            // Create dynamic products + create boundary limits
                            that.drawDynamicProducts(productsData, boundaryData);

                            // Create cooling bed and hot charge products
                            that.drawCoolingBedHeats();
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            // --- BOTTOM DYNAMIC CHART-TABLE
            drawDynamicProducts: function (productsData, boundaryData) {
                var that = this;
                var strands = [1, 2, 3, 4];
                var y = 10; //Rectangle y pixels position
                var fixedLengthPX = 800; // Length in PX
                var TotalLength = 1700; // Length in Inches: 977" + 4" + 570
                var svg = null;
                var products = [];
                var boundary = [];

                var lineML = 0;
                var linePx = 0;
                var xPx = 0;
                var widthPx = 0;
                var xText = '';

                var BoundaryWidthPx = 0;
                var RelativeStartLengthPx = 0;
                var GradeMixingEndPx = 0;
                var GradeMixingStartPx = 0;

                _.each(strands, function (StrandId) {

                    // remove previous chart + get div dimension by strand
                    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;
                    }

                    products = _.where(productsData, { StrandId: StrandId });
                    boundary = _.where(boundaryData, { strandId: StrandId });

                    if (products && products[0] && products[0].LineML) {
                        lineML = products[0].LineML;
                        linePx = lineML * fixedLengthPX / TotalLength;
                        xPx = 0;
                        widthPx = 0;
                        xText = '';
                        // Draw products
                        _.each(products, function (prod) {
                            xPx = fixedLengthPX - prod.MLE * linePx / lineML;
                            widthPx = (prod.MLE - prod.MLS) * linePx / lineML;
                            xText = xPx + widthPx / 2;

                            if (prod && prod.CutInProgress) {
                                svg.append("rect")
                                    .attr("x", widthPx + xPx - 6)
                                    .attr("y", 0)
                                    .attr("width", 12)
                                    .attr("height", 10)
                                    .attr("stroke", "black")
                                    .attr("fill", "red");
                            };
                            svg.append("rect")
                                .attr("x", xPx)
                                .attr("y", y)
                                .attr("width", widthPx)
                                .attr("height", 30)
                                .attr("stroke", "black")
                                .attr("fill", prod.Color)
                                .attr("cursor", "pointer")
                            svg.append('text').text(prod.ProductNumber)
                                .attr('x', xText)
                                .attr('y', y * 3)
                                .attr('fill', 'black')
                        });

                        // Draw dashed lines --> Home position
                        _.each(products, function (prod) {
                            if (prod && prod.Counter && prod.Counter === 1 && prod.TorchMLE) {
                                svg.append('line')
                                    .attr("stroke", "black")
                                    .style("stroke-dasharray", ("3, 3"))
                                    .attr("x1", fixedLengthPX - prod.TorchMLE * linePx / lineML)
                                    .attr("x2", fixedLengthPX - prod.TorchMLE * linePx / lineML)
                                    .attr("y1", 0)
                                    .attr("y2", 50);
                            }
                        });

                        //-- Draw boundary boxes
                        BoundaryWidthPx = 0;
                        RelativeStartLengthPx = 0;
                        GradeMixingEndPx = 0;
                        GradeMixingStartPx = 0;
                        _.each(boundary, function (bound) {
                            if (bound.RelativeStartLength < products[0].LineML) {
                                RelativeStartLengthPx = bound.RelativeStartLength * linePx / lineML;

                                GradeMixingEndPx = bound.GradeMixingEnd * linePx / lineML;
                                GradeMixingStartPx = bound.GradeMixingStart * linePx / lineML;

                                BoundaryWidthPx = GradeMixingEndPx - GradeMixingStartPx;

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

                                svg.append("rect")
                                    .attr("x", fixedLengthPX - GradeMixingEndPx)
                                    .attr("y", y - 7)
                                    .attr("width", BoundaryWidthPx)
                                    .attr("height", 44)
                                    .attr("stroke", "red")
                                    .attr("fill", "none")
                            }
                        })
                    }
                });



            },
            setBottomTableData: function (strandData) {
                var that = this;
                var strandData_S1 = _.where(strandData, { StrandId: 1 });
                var strandData_S2 = _.where(strandData, { StrandId: 2 });
                var strandData_S3 = _.where(strandData, { StrandId: 3 });
                var strandData_S4 = _.where(strandData, { StrandId: 4 });

                var mr_S1 = strandData_S1[0] && strandData_S1[0].MaterialRemainingInfo && strandData_S1[0].MaterialRemainingInfo.includes(',') ? strandData_S1[0].MaterialRemainingInfo.split(',') : ''
                var mr_S2 = strandData_S2[0] && strandData_S2[0].MaterialRemainingInfo && strandData_S2[0].MaterialRemainingInfo.includes(',') ? strandData_S2[0].MaterialRemainingInfo.split(',') : ''
                var mr_S3 = strandData_S3[0] && strandData_S3[0].MaterialRemainingInfo && strandData_S3[0].MaterialRemainingInfo.includes(',') ? strandData_S3[0].MaterialRemainingInfo.split(',') : ''
                var mr_S4 = strandData_S4[0] && strandData_S4[0].MaterialRemainingInfo && strandData_S4[0].MaterialRemainingInfo.includes(',') ? strandData_S4[0].MaterialRemainingInfo.split(',') : ''

                that.model.set({
                    MaterialRemaining_Top_S1: mr_S1 && mr_S1[0] ? mr_S1[0] : '',
                    MaterialRemaining_Middle_S1: mr_S1 && mr_S1[1] ? mr_S1[1] : '',
                    MaterialRemaining_Bottom_S1: mr_S1 && mr_S1[2] ? mr_S1[2] : '',

                    MaterialRemaining_Top_S2: mr_S2 && mr_S2[0] ? mr_S2[0] : '',
                    MaterialRemaining_Middle_S2: mr_S2 && mr_S2[1] ? mr_S2[1] : '',
                    MaterialRemaining_Bottom_S2: mr_S2 && mr_S2[2] ? mr_S2[2] : '',

                    MaterialRemaining_Top_S3: mr_S3 && mr_S3[0] ? mr_S3[0] : '',
                    MaterialRemaining_Middle_S3: mr_S3 && mr_S3[1] ? mr_S3[1] : '',
                    MaterialRemaining_Bottom_S3: mr_S3 && mr_S3[2] ? mr_S3[2] : '',


                    MaterialRemaining_Top_S4: mr_S4 && mr_S4[0] ? mr_S4[0] : '',
                    MaterialRemaining_Middle_S4: mr_S4 && mr_S4[1] ? mr_S4[1] : '',
                    MaterialRemaining_Bottom_S4: mr_S4 && mr_S4[2] ? mr_S4[2] : '',

                    CasterMode_S1: strandData_S1[0].CasterMode,
                    CasterMode_S2: strandData_S2[0].CasterMode,
                    CasterMode_S3: strandData_S3[0].CasterMode,
                    CasterMode_S4: strandData_S4[0].CasterMode,

                    Products_S1: strandData_S1[0].Products.toFixed(2),
                    Products_S2: strandData_S2[0].Products.toFixed(2),
                    Products_S3: strandData_S3[0].Products.toFixed(2),
                    Products_S4: strandData_S4[0].Products.toFixed(2),

                    SP_S1: strandData_S1[0].PresetML ? strandData_S1[0].PresetML.toFixed(2) : 0,
                    SP_S2: strandData_S2[0].PresetML ? strandData_S2[0].PresetML.toFixed(2) : 0,
                    SP_S3: strandData_S3[0].PresetML ? strandData_S3[0].PresetML.toFixed(2) : 0,
                    SP_S4: strandData_S4[0].PresetML ? strandData_S4[0].PresetML.toFixed(2) : 0,


                    Speed_S1: strandData_S1[0].Speed ? strandData_S1[0].Speed.toFixed(2) : 0,
                    Speed_S2: strandData_S2[0].Speed ? strandData_S2[0].Speed.toFixed(2) : 0,
                    Speed_S3: strandData_S3[0].Speed ? strandData_S3[0].Speed.toFixed(2) : 0,
                    Speed_S4: strandData_S4[0].Speed ? strandData_S4[0].Speed.toFixed(2) : 0,


                    MaterialRemaining_S1: strandData_S1[0].MaterialRemainingInfo ? strandData_S1[0].MaterialRemainingInfo : 0,
                    MaterialRemaining_S2: strandData_S2[0].MaterialRemainingInfo ? strandData_S2[0].MaterialRemainingInfo : 0,
                    MaterialRemaining_S3: strandData_S3[0].MaterialRemainingInfo ? strandData_S3[0].MaterialRemainingInfo : 0,
                    MaterialRemaining_S4: strandData_S4[0].MaterialRemainingInfo ? strandData_S4[0].MaterialRemainingInfo : 0,


                    Measured_S1: strandData_S1[0].Measured ? strandData_S1[0].Measured.toFixed(2) : 0,
                    Measured_S2: strandData_S2[0].Measured ? strandData_S2[0].Measured.toFixed(2) : 0,
                    Measured_S3: strandData_S3[0].Measured ? strandData_S3[0].Measured.toFixed(2) : 0,
                    Measured_S4: strandData_S4[0].Measured ? strandData_S4[0].Measured.toFixed(2) : 0,
                })
            },

            // --- COOLING BED
            drawCoolingBedHeats: function () {
                var svg = null;
                var trId = '';
                var colors = null;
                var color = null;
                var that = this;
                var model = this.model.toJSON();
                var coolingBed = model.coolingBed;

                var hotCharge = model.hotCharge;
                var maxRows = 37;
                var minRows = 20;
                for (var i = minRows; i <= maxRows; i++) {
                    trId = '#graph' + i + '_p';
                    $(trId).html('');
                    svg = d3.select(trId);
                    if (coolingBed.length > 0) {
                        colors = _.where(that.model.get('heatColors'), { HeatName: coolingBed[i - 20] && coolingBed[i - 20].HeatName ? coolingBed[i - 20].HeatName : null });
                        color = colors[0] && colors[0].Color ? colors[0].Color : '#eeeeee';

                        svg.append("rect").attr("x", 0).attr("y", 0).attr("width", 140).attr("height", 20).attr("stroke", "gray").attr("fill", color);

                        if (coolingBed[i - 20] && coolingBed[i - 20].ProductNumber) {
                            svg.append("text").attr("x", 25).attr("y", 14).text(coolingBed[i - 20].ProductNumber).attr('font-size', '15px').attr('fill', '#505050').attr('font-weight', 'bold');
                        }
                    }
                    if (i >= 20 && i < 26 && hotCharge.length > 0) {
                        colors = _.where(that.model.get('heatColors'), { HeatName: hotCharge[i - 20] && hotCharge[i - 20].HeatName ? hotCharge[i - 20].HeatName : null });
                        color = colors[0] && colors[0].Color ? colors[0].Color : '#eeeeee';

                        svg.append("rect").attr("x", 150).attr("y", 0).attr("width", 140).attr("height", 20).attr("stroke", "gray").attr("fill", color);
                        if (hotCharge[i - 20] && hotCharge[i - 20].ProductNumber) {
                            svg.append("text").attr("x", 175).attr("y", 14).text(hotCharge[i - 20].ProductNumber).attr('font-size', '15px').attr('fill', '#505050').attr('font-weight', 'bold');
                        }
                    }
                }


            },            


            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------- CONTEXT MENU OPTIONS -------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            contextMenuOptionPressed: function () {
                var that = this;
                rowModel = this.model.get('rowModel'),
                    contextMenuOption = this.model.get('contextMenuOption');
                var message = '';
                switch (contextMenuOption) {
                    case "opt-redirect-hydorgen":
                        app.router.navigate('!/hydrogen-samples/' + rowModel.HeatName, { trigger: true });
                        break;
                    case "opt-add-new-piece":
                        that.addNewProduct(rowModel);
                        break;
                    case "opt-remove-piece":
                        message = 'The product ' + rowModel.ProductNumber + ' will be removed. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "delete_item_modal_confirm_title"),
                            message: 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":
                        message = 'The tag ' + rowModel.ProductNumber + ' will be printed. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "print_item_modal_confirm_title"),
                            message: 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":
                        message = 'The tag ' + rowModel.ProductNumber + ' will be reprinted. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "re_print_item_modal_confirm_title"),
                            message: 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-send-to-l3":
                        message = 'The product ' + rowModel.ProductNumber + ' will be sent to L3. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "resend_item_modal_confirm_title"),
                            message: 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-set-quality-prime":
                        that.model.changeProductQuality({
                            productId: rowModel.Id,
                            qualityCode: 1,
                        });
                        break;
                    case "opt-set-quality-hold":
                        that.model.changeProductQuality({
                            productId: rowModel.Id,
                            qualityCode: 2,
                        });
                        break;
                    case "opt-set-quality-scrap":
                        that.model.changeProductQuality({
                            productId: rowModel.Id,
                            qualityCode: 3,
                        });
                        break;
                    case "opt-split-product":
                        that.splitProduct(rowModel);
                        break;
                    case "opt-edit-length-piece":
                        that.editProductLength(rowModel);
                        break;
                    case "opt-send-ct":
                        message = 'The product ' + rowModel.ProductNumber + ' will be sent to Cooling Bed. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: 'Send To Cooling Table Confirmation',
                            message: message,
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {

                                that.model.changeDeliveredDestination({
                                    productId: rowModel.Id,
                                    destination: 'CT'
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        break;
                    case "opt-send-hc":
                        message = 'The product ' + rowModel.ProductNumber + ' will be sent to Hot Charge. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: 'Send To Hot Charge Confirmation',
                            message: message,
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {

                                that.model.changeDeliveredDestination({
                                    productId: rowModel.Id,
                                    destination: 'HC'
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        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");

            },


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

            splitProduct: function (model) {
                var modal = new Screen.Views.SplitProduct({
                    data: model,
                    bus: this.bus,
                });
                modal.show();
            },
            addNewProduct: function (model) {
                var modal = new Screen.Views.AddNewProduct({
                    data: model,
                    bus: this.bus,
                });
                modal.show();
            },
            editProductLength: function (model) {

                var modal = new Screen.Views.EditProductLength({
                    data: model,
                    bus: this.bus,
                });
                this.editProductModal = modal;
                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) { }
            },



        });



        /*-------------------------------------------------------- */
        /*-------------------------------------------------------- */
        /*-------------------------------------------------------- */
        /*-------------PRODUCTS POSITON DRAG AND DROP------------- */
        /*-------------------------------------------------------- */
        /*-------------------------------------------------------- */
        /*-------------------------------------------------------- */

        Screen.Views.ProductPosition = Backbone.Epoxy.View.extend({
            tagName: 'div',
            className: 'draggable draggable-object',

            initialize: function (attr) {
                this.model = attr.model;
                var params = this.model.toJSON();
                var id = 'str' + params.StrandId + '-seq' + params.Sequence + '-heat' + params.HeatName;
                this.model.set({
                    largePosition: params.Pos == 6 ? true : false,
                })
                $(this.el).css("background-color", params.Color);
                $(this.el).attr("id", id);

                this.render();
            },

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

        });




        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        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, strandData, productsData, boundaryData) {
                var newColl,
                    that = this;
                that.set(data).trigger('fetch', strandData, productsData, boundaryData);
            },


        });

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

        });



        //-------------------------------//
        //------ Split Product -------//
        //------------------------------//
        Screen.Models.EditProductLength = Backbone.Epoxy.Model.extend({
            defaults: {
                productNumber: '',
                pieceLength: '',
                scrapLength: '',
            },
        });
        Screen.Views.EditProductLength = Backbone.Epoxy.View.extend({
            template: "caster-torch-cooling-bed",
            id: "edit-product-length",
            className: "modal modal-edit-product-length 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.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();

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


                    }, true, customPath);

                }, customPath, "edit_product_length_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 () {
            },
            editProductLength: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@productId', Type: 'INT', Value: params.productId, },
                        { Name: '@length', Type: 'FLOAT', Value: params.pieceLength, },
                    ];

                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.UpdateProductLength',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        that.bus.trigger("modalAcceptTrigger");
                                        app.views.topMessages.showMessage('Product length update in process...', { stay: 3000, });
                                    }
                                    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 (model.pieceLength <= 0) {
                        app.views.topMessages.showMessage('The Piece Length is invalid', { stay: 2000, });
                    } else {
                        this.editProductLength({
                            productId: that.productId,
                            pieceLength: model.pieceLength

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

        //-------------------------------//
        //------ Add New Product -------//
        //------------------------------//
        Screen.Models.AddNewProduct = Backbone.Epoxy.Model.extend({
            defaults: {
                heatNumber: '',
                pieceLength: '',
                scrapLength: '',
                strands: [{ label: 'Strand 1', value: 1 }, { label: 'Strand 2', value: 2 }, { label: 'Strand 3', value: 3 }, { label: 'Strand 4', value: 4 }],
                strandId: 1,

            },
        });
        Screen.Views.AddNewProduct = Backbone.Epoxy.View.extend({
            template: "caster-torch-cooling-bed",
            id: "add-new-product",
            className: "modal modal-add-new-product 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.AddNewProduct();
                }
                var data = options.data;
                this.productId = data.Id;
                this.model.set({
                    heatNumber: data.CurrentHeatName
                })
                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();



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


                    }, true, customPath);

                }, customPath, "add_new_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 () {
            },
            addNewProduct: 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)) {
                                    that.bus.trigger("modalAcceptTrigger");
                                    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;
            },
            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 (model.pieceLength <= 0) {
                        app.views.topMessages.showMessage('The Piece Length is invalid', { stay: 2000, });
                    } else {
                        this.addNewProduct({
                            heatName: model.heatNumber,
                            strandId: model.strandId,
                            length: model.pieceLength,
                        })
                        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); }
            },
        });



        //-------------------------------//
        //------ Split Product -------//
        //------------------------------//
        Screen.Models.SplitProduct = Backbone.Epoxy.Model.extend({
            defaults: {
                productNumber: '',
                pieceLength: '',
                scrapLength: '',
            },
        });
        Screen.Views.SplitProduct = Backbone.Epoxy.View.extend({
            template: "caster-torch-cooling-bed",
            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.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();

                        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) {
                                        that.bus.trigger("modalAcceptTrigger");
                                        app.views.topMessages.showMessage('Split Piece', { 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); }
            },
        });


        //---------------------//
        //------ Assign -------//
        //---------------------//
        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.Views.AssignModal = Backbone.Epoxy.View.extend({
            template: "caster-torch-cooling-bed",
            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,
                            },

                            {
                                name: 'MaterialSize',
                                label: 'Mold Size',
                                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'));

                    app.views.topMessages.showMessage('Method disabled. To unassign a Heat go to Caster Production screen ', { stay: 5000, });
                    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); }
            },

        });

        ////////////////////////////////////////////////
        ////////////                        ////////////
        ////////////                        ////////////
        //////////// LADLE POSITION WIDGET  ////////////
        ////////////                        ////////////
        ////////////                        ////////////
        ////////////////////////////////////////////////
        Screen.Collections.Positions = Backbone.Collection.extend({
            setDataColl: function (data) {
                this.set(data).trigger('fetch', this, data);
            },
        });

        Screen.Collections.ProductsTablePosition = Backbone.Collection.extend({
            setDataColl: function (data, colors) {
                var validPositions = [];
                var topRunoutTablePositions = [];
                var color = '#eee';

                _.each(data, function (obj) {
                    color = _.where(colors, { HeatName: obj.HeatName }) && _.where(colors, { HeatName: obj.HeatName })[0] && _.where(colors, { HeatName: obj.HeatName })[0].Color ? _.where(colors, { HeatName: obj.HeatName })[0].Color : '#eee'
                    obj.Color = color
                    if (obj.Pos >= 2 && obj.Pos <= 6) {
                        validPositions.push(obj);
                    }
                    else {
                        topRunoutTablePositions.push(obj);
                    }
                });
                var pos8 = _.where(topRunoutTablePositions, { Pos: 8 });
                var pos9 = _.where(topRunoutTablePositions, { Pos: 9 });
                var pos10 = _.where(topRunoutTablePositions, { Pos: 10 });
                var pos11 = _.where(topRunoutTablePositions, { Pos: 11 });

                // Filter the 8 to 11 positions
                var filteredRunoutTable = [];
                if (pos8.length > 0) {
                    filteredRunoutTable.push(pos8[0]);
                }
                if (pos9.length > 0) {
                    filteredRunoutTable.push(pos9[0]);
                }
                if (pos10.length > 0) {
                    filteredRunoutTable.push(pos10[0]);
                }
                if (pos11.length > 0) {
                    filteredRunoutTable.push(pos11[0]);
                }

                // Final Data
                var finalData = [];
                _.each(validPositions, function (obj) {
                    finalData.push(obj);
                })
                _.each(filteredRunoutTable, function (obj) {
                    finalData.push(obj);
                })

                this.set(finalData).trigger('fetch', filteredRunoutTable);
            },
        });




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