//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',
    'modules/modal-assign-cover/modal-assign-cover',
    'js/multiselect/virtual-select.min',
    '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, AssignCoverModal) {

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

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

                s1Pos6Reached: true,
                s2Pos6Reached: true,
                s3Pos6Reached: true,
                s4Pos6Reached: true,

                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,

                draggedObject: null,
                allowedPositions: [],
                productDragModel: null,

                readOnlyPermissions: true,
                reassignPermissions: false,

            },
            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;
                    },
                },
                disabledAddPiece: {
                    deps: ['search'],
                    get: function (search) {
                        if (search === '' || search.length !== 7) 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
                                    var newRunoutTable = _.map(resp.Table9,
                                        function (obj) {
                                            return {
                                                Pos: obj.Pos === 5 ? 6 : obj.Pos
                                                , StrandId: obj.StrandId
                                                , Sequence: obj.Sequence
                                                , HeatName: obj.HeatName
                                                , ProductNumber: obj.ProductNumber
                                                , CurrentPos: obj.Pos
                                                , Color: obj.Color
                                            };
                                        }
                                    );
                                    that.set({ tablePositions: newRunoutTable });
                                    that.productsTablePosition.setDataColl(newRunoutTable, resp.Table1);
                                    //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;
            },
           
            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);
                    });
                    console.log("CAS.ChangeProductRunoutPosition", this.fixedParameters);
                    //return;
                    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-supervision';
            } catch (Error) { }
        }





        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-supervision',
            id: 'caster-supervision',
            title: 'Caster Supervision',
            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,
                    'click #addNewPiece': this.addNewPiece,
                    //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,
                    'click #ReassignProductBtn': this.ReassignProductBtn_click,
                    'click #CoversReportBtn': this.CoversReportBtn_click,
                };
            },

            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            subviews: null,
            viewParams: null,
            tooltip: null,
            tooltip1: null,
            watchdogLimit: 3,
            watchdogTimer: 0,
            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();

                var write = this.getPermissions();
                this.model.set({
                    readOnlyPermissions: !write
                })

                var reassignPermissions = this.getPermissionsReassignProducts();
                this.model.set({
                    reassignPermissions: reassignPermissions
                })

            },

            getPermissions: function () {
                var write = $.inArray('caster_torch_cooling_bed_readWrite', app.models.user.get('roles'));
                var ctx = {
                    write: write != -1 ? true : false,
                };
                return ctx.write;
            },
            getPermissionsReassignProducts: function () {
                var write = $.inArray('crp_w', app.models.user.get('roles'));
                var ctx = {
                    write: write != -1 ? true : false,
                };
                return ctx.write;
            },
            HeatsRealTimeBtn_click: function () {
                app.router.navigate('!/caster-heats-real-time/', { trigger: true });
            },
            CoversReportBtn_click: function () {
                app.router.navigate('!/covers-report/', { trigger: true });
            },
            ReassignProductBtn_click: function () {
                var that = this;
                //rowModel = this.model.get('rowModel'),
                that.reassignProduct();

            },
            reassignProduct: function () {
                var m = this.model.toJSON();
                var modal = new Screen.Views.ReassignProduct({
                    // data: model,
                    bus: this.bus,
                });
                modal.show();
            },
            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,
                                            sortable: false,
                                        },
                                        {
                                            name: 'Status',
                                            label: app.translate([that, app], 'Status'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'MeltOrder',
                                            label: app.translate([that, app], 'Melt Order'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'Grade',
                                            label: app.translate([that, app], 'Grade'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'S1Products',
                                            label: app.translate([that, app], 'S1'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'S2Products',
                                            label: app.translate([that, app], 'S2'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'S3Products',
                                            label: app.translate([that, app], 'S3'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'S4Products',
                                            label: app.translate([that, app], 'S4'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'ProductsWeight',
                                            label: app.translate([that, app], 'Sol. Weight'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'LiqWeight',
                                            label: app.translate([that, app], 'Liq. Weight'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'Hydrogen',
                                            label: app.translate([that, app], 'H'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'UnderCover',
                                            label: app.translate([that, app], 'Cover'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: 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 write = that.getPermissions();
                                            if (write) {
                                                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,
                                            sortable: false,
                                        },
                                        {
                                            name: 'TaggingStatusCode',
                                            label: app.translate([that, app], '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,
                                            sortable: false,
                                        },
                                        {
                                            name: 'Destination',
                                            label: app.translate([that, app], 'Dest'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: 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,
                                            sortable: false,
                                        },
                                        {
                                            name: 'CutTime',
                                            label: app.translate([that, app], 'Cut'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: 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,
                                            sortable: false,
                                        },

                                        {
                                            name: 'SentToL3',
                                            label: app.translate([that, app], 'L3'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: 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 write = that.getPermissions();
                                            if (write) {
                                                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');

                                var write = that.getPermissions();

                                if (write) {
                                    $(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') return false;
                                                        else return true;
                                                    },
                                                    disabled: function () {
                                                        var model = that.model.get('rowModel');
                                                        if (model.TaggingStatusCode === 'P') return true;
                                                        else return false;
                                                    }
                                                },
                                                "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: "Tail Crop",
                                                    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;
                                                    },
                                                },
                                                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;
                                                    },
                                                },
                                                "opt-assign-cover": {
                                                    name: "Assign Cover",
                                                    icon: "edit",
                                                    disabled: function (key, opt) {
                                                        var model = that.model.get('rowModel');
                                                        if (model && model.UnderCover) return true;
                                                        else return false;
                                                    },
                                                    visible: function () {
                                                        var model = that.model.get('rowModel');
                                                        if (model.TableType !== 'PROCESSES') return false;
                                                        else return true;
                                                    },
                                                },
                                                "opt-unassign-cover": {
                                                    name: "Unassign Cover",
                                                    icon: "edit",
                                                    disabled: function (key, opt) {
                                                        var model = that.model.get('rowModel');
                                                        if (model && model.UnderCover) 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;
                this.pauseRealTime = 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 = parseInt(splitSelectedDragId[0].split('str')[1]);
                var sequence = splitSelectedDragId[1].split('seq')[1];
                var heat = splitSelectedDragId[2].split('heat')[1];


                var allowedPositions = [];
                if (strandId === 1) {
                    allowedPositions = [
                        "#strand1pos2", "#strand1pos3", "#strand1pos4", "#strand1pos5", "#strand1pos6",
                        "#pos11", "#pos10", "#pos9", "#pos8"

                    ];
                }
                if (strandId === 2) {
                    allowedPositions = [
                        "#strand2pos2", "#strand2pos3", "#strand2pos4", "#strand2pos5", "#strand2pos6",
                        "#pos11", "#pos10", "#pos9", "#pos8"

                    ];
                }
                if (strandId === 3) {
                    allowedPositions = [
                        "#strand3pos2", "#strand3pos3", "#strand3pos4", "#strand3pos5", "#strand3pos6",
                        "#pos11", "#pos10", "#pos9", "#pos8"

                    ];
                }
                if (strandId === 4) {
                    allowedPositions = [
                        "#strand4pos2", "#strand4pos3", "#strand4pos4", "#strand4pos5", "#strand4pos6",
                        "#pos11", "#pos10", "#pos9", "#pos8"

                    ];
                }
                productDragModel = {
                    StrandId: strandId,
                    Sequence: sequence,
                    HeatName: heat,
                }
                _.each(this.model.productsTablePosition.models, function (model) {
                    obj = model.attributes;
                    if (obj.StrandId == strandId && obj.Sequence == sequence && obj.HeatName == heat) {
                        dragModel = model;
                    }
                });

                this.model.set({ allowedPositions: allowedPositions, productDragModel: productDragModel });
                _.each(allowedPositions, function (obj) {
                    $(obj).addClass('allowed-locations');
                });
            },
            dragenter: function (event) {
                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 strandNumber = null;
                var PositionNumber = null;
                var dropContainerId = "#" + $(event.currentTarget).context.id;

                var productDragModel = this.model.get('productDragModel');

                if (dropContainerId.includes('strand')) {
                    strandNumber = parseInt(dropContainerId[7]);
                }
                PositionNumber = parseInt($(event.currentTarget).context.id.split('pos')[1]);

                var parent = document.getElementById($(event.currentTarget).context.id);

                if (!parent.hasChildNodes() && this.model.get('allowedPositions').includes(dropContainerId)) {
                    event.target.appendChild(that.model.attributes.draggedObject);
                    this.model.changeProductRunoutPosition({
                        HeatName: productDragModel.HeatName
                        , Pos: PositionNumber
                        , Sequence: productDragModel.Sequence
                        , StrandId: strandNumber ? strandNumber : productDragModel.StrandId
                    });
                } else {
                    app.views.topMessages.showMessage('Runout position not allowed ', { stay: 3000, });
                }
            },
            dragend: function () {
                this.removeDragOverClass();
                this.removeAllowedLocationsClass();
                this.pauseTimer = false;
                this.pauseRealTime = false;

                this.model.set({
                    productDragModel: 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, });
                }
            },
            
            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;
                    var write = that.getPermissions();
                    _.each(that.model.productsTablePosition.toJSON(), function (obj) {
                        if (obj.Pos >= 2 && obj.Pos <= 6) {
                            dropContainerId = '#strand' + obj.StrandId + 'pos' + obj.Pos;
                        } else {
                            dropContainerId = '#pos' + obj.Pos;
                        }
                        draggableObjectId = '#str' + obj.StrandId + '-seq' + obj.Sequence + '-heat' + obj.HeatName;
                        that.append($(dropContainerId), $(draggableObjectId));
                        if (!write) {
                            that.$el.find(draggableObjectId).removeClass('draggable');
                        }
                    });
                    var pos6reached = _.where(that.model.productsTablePosition.toJSON(), { CurrentPos: 6 });
                    var element = null;
                    var s1pos6 = false;
                    var s2pos6 = false;
                    var s3pos6 = false;
                    var s4pos6 = false;
                    _.each(pos6reached, function (obj) {
                        if (obj.StrandId === 1) {
                            element = document.getElementById('s1-rectsvg');
                            element.classList.remove("hide");
                            s1pos6 = true;
                        }
                        if (obj.StrandId === 2) {
                            element = document.getElementById('s2-rectsvg');
                            element.classList.remove("hide");
                            s2pos6 = true;
                        }
                        if (obj.StrandId === 3) {
                            element = document.getElementById('s3-rectsvg');
                            element.classList.remove("hide");
                            s3pos6 = true;
                        }
                        if (obj.StrandId === 4) {
                            element = document.getElementById('s4-rectsvg');
                            element.classList.remove("hide");
                            s4pos6 = true;
                        }
                    });
                    if (!s1pos6) {
                        element = document.getElementById('s1-rectsvg');
                        element.classList.add("hide");
                    }
                    if (!s2pos6) {
                        element = document.getElementById('s2-rectsvg');
                        element.classList.add("hide");
                    }
                    if (!s3pos6) {
                        element = document.getElementById('s3-rectsvg');
                        element.classList.add("hide");
                    }
                    if (!s4pos6) {
                        element = document.getElementById('s4-rectsvg');
                        element.classList.add("hide");
                    }




                }
                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) {

                // Watchdog
                if (this.pauseTimer) {
                    this.watchdogTimer += 1;
                    console.log("watchdog increment:", this.watchdogTimer, "Of: ", this.watchdogLimit);
                }
                if (this.watchdogTimer >= this.watchdogLimit) {
                    console.log("reset watchdog");
                    this.pauseTimer = false;
                    this.pauseRealTime = false;
                    this.watchdogTimer = 0;
                }
                // Watchdog

                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) {
                //console.log("refresh");
                this.watchdogTimer = 0;
                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) {
                        $("#strand1bars").html('');
                        svg = d3.select("#strand1bars");
                        fixedLengthPX = $('#strand1bars')[0].getBoundingClientRect().width;
                    } else if (StrandId == 2) {
                        $("#strand2bars").html('');
                        svg = d3.select("#strand2bars");
                        fixedLengthPX = $('#strand2bars')[0].getBoundingClientRect().width;
                    } else if (StrandId == 3) {
                        $("#strand3bars").html('');
                        svg = d3.select("#strand3bars");
                        fixedLengthPX = $('#strand3bars')[0].getBoundingClientRect().width;
                    } else if (StrandId == 4) {
                        $("#strand4bars").html('');
                        svg = d3.select("#strand4bars");
                        fixedLengthPX = $('#strand4bars')[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 and HOT CHARGE 
            drawCoolingBedHeats: function () {
                var that = this;
                var model = this.model.toJSON();
                var coolingBed = model.coolingBed;
                var hotCharge = model.hotCharge;
                var currentColor = '#ccc';
                const coolingBedContainer = document.getElementById('cooling-bed');
                const hotChargeContainer = document.getElementById('hot-charge');





                $("#cooling-bed").html('');
                $("#hot-charge").html('');

                // COOLING BED
                var parentDiv = document.createElement('div');
                var childDiv = document.createElement('div');
                var h5 = document.createElement('h5');
                var id = '';

                _.each(coolingBed, function (obj) {
                    parentDiv = document.createElement('div');
                    childDiv = document.createElement('div');
                    h5 = document.createElement('h5');
                    //get id
                    id = 'str' + obj.StrandId + '-seq' + obj.Sequence + '-heat' + obj.HeatName;
                    //parent div
                    parentDiv.classList.add('draggable-object');
                    //parentDiv.classList.add('draggable', 'draggable-object');
                    parentDiv.setAttribute('id', id);

                    //child div
                    childDiv.classList.add('product-box');
                    //childDiv.setAttribute('draggable', 'true');
                    //h5
                    h5.classList.add('product-number');
                    h5.setAttribute('data-bind', 'text:ProductNumber');
                    h5.innerHTML = obj.ProductNumber;



                    //add background color
                    currentColor =
                        _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })
                            && _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })[0]
                            && _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })[0].Color
                            ? _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })[0].Color : '#ccc';

                    parentDiv.style.backgroundColor = currentColor;

                    //append elements
                    childDiv.appendChild(h5);
                    parentDiv.appendChild(childDiv);

                    coolingBedContainer.appendChild(parentDiv);
                });




                // HOT CHARGE

                _.each(hotCharge, function (obj) {
                    parentDiv = document.createElement('div');
                    childDiv = document.createElement('div');
                    h5 = document.createElement('h5');
                    //get id
                    id = 'str' + obj.StrandId + '-seq' + obj.Sequence + '-heat' + obj.HeatName;
                    //parent div

                    parentDiv.classList.add('draggable-object');
                    // parentDiv.classList.add('draggable', 'draggable-object');
                    parentDiv.setAttribute('id', id);
                    parentDiv.style.backgroundColor = 'yellow';

                    //child div
                    childDiv.classList.add('product-box');
                    //childDiv.setAttribute('draggable', 'true');
                    //h5
                    h5.classList.add('product-number');
                    h5.setAttribute('data-bind', 'text:ProductNumber');
                    h5.innerHTML = obj.ProductNumber;

                    //add background color
                    currentColor =
                        _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })
                            && _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })[0]
                            && _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })[0].Color
                            ? _.where(that.model.get('heatColors'), { HeatName: obj.HeatName })[0].Color : '#ccc';

                    parentDiv.style.backgroundColor = currentColor;


                    //append elements
                    childDiv.appendChild(h5);
                    parentDiv.appendChild(childDiv);

                    hotChargeContainer.appendChild(parentDiv);
                });



            },


            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------------------------------------//
            //-------- 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":
                        var modal = new Screen.Views.PrintTagConfirmationModal({
                            data: rowModel,
                            bus: this.bus
                        });
                        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;
                    case "opt-assign-cover":
                        var data = [];
                         data = {
                            HeatNumber: rowModel.HeatName,
                            action: 'A'
                        };
                        modal = new AssignCoverModal.Views.AssignCoverModal({
                            parent: this,
                            data: data,
                            rowModel: rowModel,
                            bus: that.bus,
                        });
                        modal.show();
                        that.model.fetch();
                        break;
                    case "opt-unassign-cover":
                        var that = this;
        
                            modal = new Modal.Views.Main({
                                focusOk: false,
                                focusSelector: '#btn-cancel',
                                title: 'Unassign Cover',
                                message: 'Are you sure you want to unassign cover ' + rowModel.UnderCover + ' from Heat ' + rowModel.HeatName + '?',
                                buttons_type: "CONTINUE-CANCEL",
                            });
                            this.listenToOnce(modal, "continue", function (modal) {
                                try {
                                    var updateModel = new AssignCoverModal.Models.AssignCoverModal();
                                    var params = {HeatNumber: rowModel.HeatName, CoverId: rowModel.UnderCover, action: 'U'}
                                    updateModel.updateCoverHeat(params);
                                    that.model.fetch();
                                }
                                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");

            },
            addNewPiece: function () {
                var that = this;
                this.addNewProduct({
                    CurrentHeatName: that.model.get('search'),
                });
            },

            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.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-supervision",
            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 invalid', { 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,
                sequenceId: 1,
                sequences: [
                    { label: '1', value: 1 }
                    , { label: '2', value: 2 }
                    , { label: '3', value: 3 }
                    , { label: '4', value: 4 }
                    , { label: '5', value: 5 }
                    , { label: '6', value: 6 }
                    , { label: '7', value: 7 }
                    , { label: '8', value: 8 }
                    , { label: '9', value: 9 }
                    , { label: '10', value: 10 }
                    , { label: '11', value: 11 }
                    , { label: '12', value: 12 }
                    , { label: '13', value: 13 }
                    , { label: '14', value: 14 }
                    , { label: '15', value: 15 }
                    , { label: '16', value: 16 }
                    , { label: '17', value: 17 }
                    , { label: '18', value: 18 }
                    , { label: '19', value: 19 }
                    , { label: '20', value: 20 }
                ],
                moldId: 1,
                molds: []

            },
        });
        Screen.Views.AddNewProduct = Backbone.Epoxy.View.extend({
            template: "caster-supervision",
            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.model.set({
                    heatNumber: data.CurrentHeatName
                })
                this.bus = options.bus;
                this.bindEvents();
                this.fetchMolds();

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

            },

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

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetMolds',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table && resp.Table.length > 0) {
                                    // Map mold list to expected structure: label, value
                                    var mappedMolds = resp.Table.map(function (mold) {
                                        return {
                                            label: mold.Abbrev + ' (' + mold.Size + ')',
                                            value: mold.MoldTypeId,
                                        };
                                    });

                                    // Set mapped molds into the model
                                    that.model.set({ molds: mappedMolds });

                                    // Set default moldId as the first mold's value
                                    that.model.set({ moldId: mappedMolds[0].value });
                                }
                                else {
                                    app.views.topMessages.showMessage('NO MOLDS FOUND', { stay: 3000 });
                                    console.error('CAS.GetMolds returned empty or invalid result.');
                                }
                            }
                            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;
            },
            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, },
                    { Name: '@sequenceId', Type: 'INT', Value: params.sequenceId, },
                    // { Name: '@moldId', Type: 'INT', Value: params.moldId, },
                ];
                _.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 ? resp.Table[0].ProductMsg : 'CALL TO DATABASE FAILED', { stay: 5000, });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 3000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 3000, });
                                        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,
                            sequenceId: model.sequenceId,
                            moldId: model.moldId,
                        })
                        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.renderMultipicker();
                    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-supervision",
            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 (model.pieceLength < 60) {
                        app.views.topMessages.showMessage('The Piece Length must be greater than 60 inches', { stay: 2000, });
                    }
                    else if (model.scrapLength > 60) {

                        app.views.topMessages.showMessage('The Scrap Length must be smaller than 60 inches', { stay: 2000, });
                    }
                    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-supervision",
            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);
            },
        });

        Screen.Models.ReassignProduct = Backbone.Epoxy.Model.extend({
            defaults: {
                heatDestination: null,
                heatSource: null,
            },
            initialize: function () {
                this.heatProducts = new Screen.Collections.ProductsColl();
            },
            fetchProducts: function () {
                var that = this;fapp.DatabaseNames.MES
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', that.get('heatSource'));
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetProductsByHeat',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    that.heatProducts.setDataColl(resp.Table);
                                    //that.trigger('catalogs-fetched');
                                }
                                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 (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            reassignProducts: function (params) {
                var that = this;
                qp = new Core.Database.QueryParameters();


                var layout = [];
                _.each(params.productsSelected, function (obj) {
                    layout.push(obj.toJSON());

                });
                qp.Add(
                    '@Layout',
                    'XML',
                    app.jsonArrayToXml(
                        layout,
                        [
                            'Id',

                        ]
                    )
                );

                var test = app.jsonArrayToXml(
                    layout,
                    [
                        'Id',

                    ]
                );

                qp.Add('@SourceHeatName', 'VARCHAR', that.get('heatSource'));
                qp.Add('@TargetHeatName', 'VARCHAR', that.get('heatDestination'));
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.ReassignProducts',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (!resp.Message)) {
                                    app.views.topMessages.showMessage('Moved Products from ' + that.get('heatSource') + ' to ' + that.get('heatDestination'), { 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;
            },
        });

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

        Screen.Views.ReassignProduct = Backbone.Epoxy.View.extend({
            template: "caster-supervision",
            id: "reassign-product",
            className: "modal modal-reassign-product hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptReassignBtn": this.acceptBtn_click,
                    "click #cancelReassignBtn": 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,
                    'click #backNavBtn': this.heatNavigationBtn_click,
                    'click #forwardNavBtn': this.heatNavigationBtn_click,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            data: [],
            lastHeatsColl: [],
            grid: [],
            productId: null,
            heats: [], // it has the list of heats with treatments --> ex: {value:'A15895-1',label:'A15895-1'} --> it replaces the old "heatNames" variable            
            heatDestination: null, // it has the selected heat with treatment --> ex: 'A15895-1' --> it replaces the old "heatName" variable
            heatSource: null,
            productsChecked: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.ReassignProduct();
                }
                var data = options.data;
                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.fetchCatalogs();
                        // that.renderMultipicker();
                        that.trigger("render");

                    }, true, customPath);

                }, customPath, "reassing_products_template");

            },

            fetchCatalogs: function () {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', that.model.get('heat'));
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetAutocompleteHeatsCaster1',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    if (resp.Table[0] && resp.Table[0].value) {
                                        splitHeat = resp.Table[0].value.split('-');
                                    }
                                    that.model.set({
                                        heats: _.map(resp.Table, function (obj) {
                                            return { label: obj.label, value: obj.value }
                                        }),
                                        //heatSource: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                        //heatDestination: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',

                                    });
                                    that.trigger('catalogs-fetched');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.model.set({
                                            hasData_process: false,
                                            isLoading_process: false,


                                        });
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.model.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            fetchNavigateHeat: function (params) {
                var qp = new Core.Database.QueryParameters();
                var that = this;
                qp.Add('@heatName', 'VARCHAR(10)', params.heatName);
                qp.Add('@treatment', 'SMALLINT', params.treatment);
                qp.Add('@direction', 'SMALLINT', params.direction);
                qp.Add('@Asset', 'CHAR(3)', 'CAS');
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetNavigatedHeat',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table && resp.Table[0] && resp.Table[0].HeatName && resp.Table[0].HeatName !== '') {
                                    that.set({
                                        heats: _.map(resp.Table, function (obj) {
                                            return { label: obj.HeatName, value: obj.HeatName }
                                        }),
                                        heatDestination: resp.Table[0] && resp.Table[0].HeatName ? resp.Table[0].HeatName : '',
                                        heatSource: resp.Table[0] && resp.Table[0].HeatName ? resp.Table[0].HeatName : '',
                                        heat: resp.Table[0] && resp.Table[0].HeatName ? resp.Table[0].HeatName : null,
                                        treatment: resp.Table[0] && resp.Table[0].Treatment ? resp.Table[0].Treatment : 1,

                                    });
                                    that.trigger('heat-name-changed');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            heatNavigationBtn_click: function (e) {
                const { id } = e.target;
                const params = this.model.toJSON();
                const splitHeat = params.heatAndTreatment.split('-');
                const direction = id === 'backNavBtn' ? -1 : 1;
                this.model.fetchNavigateHeat({
                    heatName: splitHeat[0],
                    treatment: splitHeat[1],
                    direction
                });

            },
            renderMultipickerDestination: function () {
                var that = this;
                var heatNamesPicker = new VirtualSelect.init({
                    ele: '#heat-destination-picker-multi-select',
                    options: that.model.get('heats'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select Heat',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearch,
                });
                //document.querySelector('#heat-destination-picker-multi-select').setValue(that.model.get('heatDestination'));
                document.querySelector('#heat-destination-picker-multi-select').addEventListener('change', function (e) {
                    $('.vscomp-search-clear').click();
                    if (this.value === that.model.get('heatDestination')) {
                        return 0;
                    }
                    else {
                        var newHeatName = this.value;
                        if (newHeatName && newHeatName != '') {
                            that.model.set({
                                heatDestination: newHeatName
                            });
                            that.refresh();
                            that.UpdateURL();
                        }
                    }
                });

            },
            renderMultipickerSource: function () {
                var that = this;
                var heatNamesPicker = new VirtualSelect.init({
                    ele: '#heat-source-picker-multi-select',
                    options: that.model.get('heats'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select Heat',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearch,
                });
                // document.querySelector('#heat-source-picker-multi-select').setValue(that.model.get('heatSource'));
                document.querySelector('#heat-source-picker-multi-select').addEventListener('change', function (e) {
                    $('.vscomp-search-clear').click();
                    if (this.value === that.model.get('heatSource')) {
                        return 0;
                    }
                    else {
                        var newHeatName = this.value;
                        if (newHeatName && newHeatName != '') {
                            that.model.set({
                                heatSource: newHeatName
                            });
                            that.refresh();
                            that.UpdateURL();
                        }
                    }
                });

            },

            onSampleSelectServerSearch: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                var splitSelectedValue = this.selectedValues && this.selectedValues[0] && this.selectedValues[0].length > 0 ? this.selectedValues[0] : null;
                if (splitSelectedValue) {
                    splitSelectedValue = splitSelectedValue.split('-');
                }
                qp.Add('@HeatName', 'VARCHAR(10)', searchValue);
                qp.Add('@SelectedHeatName', 'VARCHAR(10)', splitSelectedValue && splitSelectedValue[0] ? splitSelectedValue[0] : null);
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetAutocompleteHeatsCaster1',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                virtualSelect.setServerOptions(resp.Table);

                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            heatNameChanged: function () {
                const value = this.model.get('heatAndTreatment');
                const options = this.model.get('heats');
                document.querySelector('#heat-picker-multi-select').setOptions(options);
                document.querySelector('#heat-picker-multi-select').setValue(value);
                this.UpdateURL();
                this.refresh();

            },

            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.model, 'heat-name-changed', this.heatNameChanged);
                this.listenTo(this.model, 'change:heatSource', this.heatSourceChanged);
            },
            heatSourceChanged: function () {
                var that = this;
                this.productsChecked = [];
                this.buildSourceProductsGrid();
                console.log();
            },
            buildSourceProductsGrid: function () {
                var that = this;
                //var productsChecked = [];
                that.model.fetchProducts();

                console.log();

                var productsGrid = new Backgrid.Grid({
                    className: 'grid-styles table products-table',
                    columns: [
                        {
                            name: '',
                            label: '',
                            cell: Backgrid.Cell.extend({
                                className: 'checkbox-cell',
                                parentView: that,
                                events: {
                                    'change input[type="checkbox"]': 'onCheckboxChange'
                                },
                                render: function () {
                                    var checkbox = $('<input type="checkbox" />');
                                    this.$el.empty().append(checkbox);
                                    return this;
                                },
                                onCheckboxChange: function (e) {
                                    var checkbox = $(e.target);
                                    var rowChecked = checkbox.closest('tr');
                                    var model = this.model;

                                    //this.model.set('materialChecked', materialChecked);
                                    if (checkbox.is(':checked')) {
                                        rowChecked.addClass('highlight-product-reassign');
                                        if (!this.parentView.productsChecked.includes(model)) {
                                            this.parentView.productsChecked.push(model);
                                        }
                                    }
                                    else {
                                        rowChecked.removeClass('highlight-product-reassign');
                                        var index = this.parentView.productsChecked.indexOf(model);
                                        if (index !== -1) {
                                            this.parentView.productsChecked.splice(index, 1);
                                        }
                                    }
                                }
                            })
                        },
                        {
                            name: 'ProductName',
                            label: app.translate([that, app], 'Product Name'),
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell',
                            }),
                            editable: false,
                            sortable: false,
                        },
                        {
                            name: 'StrandId',
                            label: app.translate([that, app], 'Strand'),
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell',
                            }),
                            editable: false,
                            sortable: false,
                        },
                        {
                            name: 'Sequence',
                            label: app.translate([that, app], 'Sequence'),
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell',
                            }),
                            editable: false,
                            sortable: false,
                        },
                        {
                            name: 'Timestamp',
                            label: app.translate([that, app], 'Timestamp'),
                            cell: Backgrid.Extension.MomentCell.extend({
                                className: 'momment-cell align-center-cell timestamp',
                                modelFormat: 'x',
                                displayFormat: 'YYYY-MM-DD HH:mm:ss',
                            }),
                            editable: false,
                            sortable: false,
                        },
                        {
                            name: 'Weight',
                            label: app.translate([that, app], 'Weight'),
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell',
                            }),
                            editable: false,
                            sortable: false,
                        },
                        {
                            name: 'Length',
                            label: app.translate([that, app], 'Length'),
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell',
                            }),
                            editable: false,
                            sortable: false,
                        },

                    ],
                    collection: that.model.heatProducts,
                    mainView: that

                });
                that.$el.find('.source-products-container').empty().append(productsGrid.render().el);
            },
            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 {
                    var that = this;
                    if (that.productsChecked.length > 0 && that.model.get('heatDestination') != null && that.model.get('heatSource') != null) {

                        if (that.model.get('heatDestination') == that.model.get('heatSource')) {
                            app.views.topMessages.showMessage('Heat Destination and Source must be different', { stay: 5000, });
                        }
                        else {
                            this.model.reassignProducts({
                                productsSelected: that.productsChecked,
                                sourceHeatName: that.model.get('heatSource'),
                                targetHeatName: that.model.get('heatDestination')
                            })

                            this.close();
                        }
                    }

                    else {
                        app.views.topMessages.showMessage('Heat Destination and Source are Mandatory. Also at least one product must be selected', { stay: 5000, });
                    }

                }
                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();
                    this.renderMultipickerSource();
                    this.renderMultipickerDestination();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    //this.renderMultipicker();
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
        });
        //-------------------------------//
        //------ Print Tag Confirmation -------//
        //------------------------------//
        Screen.Models.PrintTagConfirmation = Backbone.Epoxy.Model.extend({
            defaults: {
                productNumber: null,
                printerId: 1,
                comments: '',
                rowModel: null,
                printers: [{ value: 1, label: 1 }, { value: 2, label: 2 }],
                reasonPhrases: null,
                employeeNumber: null,
                pieceLength: 0,
                reasonPhraseId: 1
                
            },
            initialize: function () {
                var reasonPhrases = this.fetchReasonPhrases();
                this.set('reasonPhrases', reasonPhrases);

            },
            fetchReasonPhrases: function () {
                var reasonPhrases = [];
                var qp = new Core.Database.QueryParameters();
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetTagPrintReasonPhrases',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if (resp.Table) {
                                    reasonPhrases = resp.Table.map(item => {
                                        return {
                                            value: item.ReasonPhraseId,
                                            label: item.Name
                                        };
                                    });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData: false,
                                            isLoading: false,

                                        });

                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData: false,
                                            isLoading: false,
                                        });
                                    }

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Async: false,
                        Secured: true,
                    },
                    app.ConnectionStrings.app
                );

                return reasonPhrases;
            }
        });

        Screen.Views.PrintTagConfirmationModal = Backbone.Epoxy.View.extend({
            template: "caster-supervision",
            id: "print-tag-confirmation",
            className: "modal modal-print-tag-confirmation hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptPrintBtn": this.acceptBtn_click,
                    "click #cancelPrintBtn": 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: null,
            lastHeatsColl: [],
            grid: [],
            productId: null,
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.PrintTagConfirmation();
                }
                var data = options.data;
                this.model.set({
                    productNumber: data.ProductNumber
                })
                this.model.set({
                    productId: data.Id
                })
                this.model.set({
                    pieceLength: 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, "print_confirmation_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);
            },

            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 {
                    var that = this;
                    var model = this.model.toJSON();
                    var warningMessage = document.getElementById('warning');
                    if (model.employeeNumber === null) {
                        warningMessage.style.display = 'inline';
                        e.preventDefault();
                    }
                    else {
                        warningMessage.style.display = 'none';
                        this.printTag({ productId: model.productId, printer: model.printerId, employee: model.employeeNumber, reasonPhraseId: model.reasonPhraseId, comments: model.comments, pieceLength: model.pieceLength })
                        this.close();
                    }


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

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

                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                    { Name: '@Printer', Type: 'INT', Value: params.printer, },
                    { Name: '@ReasonPhraseId', Type: 'INT', Value: params.reasonPhraseId, },
                    { Name: '@Comments', Type: 'VARCHAR', Value: params.comments, },
                    { Name: '@Employee', Type: 'VARCHAR', Value: params.employee, },
                    { 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.UpsertTaggingCommand',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('Tagging in process...', { 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;
            },

            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.renderMultipicker();
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
        });

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


    });