//SCREEN-BOILERPLATE
//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
  // Application variable, always include it to have access to app methods.
  'app',

  //templates-loader: this loads templates async.
  'js/templates-loader',
  'backgrid',
  'moment',
  "modules/modal2",
  'modules/modal-trigger-acceptance-caster-lmf/modal-trigger-acceptance-caster-lmf',
  'modules/modal-change-melt-order/modal-change-melt-order',
  'components/modal-covers/modal-assign-cover',
  'backgrid/moment-cell',
  'js/jquery.contextMenu/jquery.contextMenu',
],
    function (app, T, Backgrid, moment, Modal, ModalTriggerAcceptance, ModalChangeMeltOrder, AssignCoverModal) {

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

    
    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            hasData_positions: false,
            isLoading_positions: true,

            hasData_attributes: false,
            isLoading_attributes: true,

            hasData_visualAttributes: false,
            isLoading_visualAttributes: true,

            appendGrid: true,

            LMF1_LadlePositionID: 10,
            LMF2_LadlePositionID: 20,

            //Casters
            showCaster1Positions:[],
            showCaster2Positions: [],

            show_cas1_pos1: true,
            show_cas1_pos2: true,
            show_cas1_pos3: true,
            show_cas1_pos4: true,


            show_cas2_pos1: true,
            show_cas2_pos2: true,
            show_cas2_pos3: true,
            show_cas2_pos4: true,

            cas1_pos1_label: '-',
            cas1_pos2_label: '-',
            cas1_pos3_label: '-',
            cas1_pos4_label: '-',


            cas2_pos1_label: '-',
            cas2_pos2_label: '-',
            cas2_pos3_label: '-',
            cas2_pos4_label: '-',


            rowModel: null,
            runOptionTrigger: false,
            inSource: true,
            TWIBlanket : null,
            rowModel: [],
            contextMenuOption: 1,

            index: null,
            grid: [],
            topGrid: [],


            readOnlyPermissions: true,
            dragModel: [],
            cas2Positions: null,
            cas1Positions: null,

            remainingHeatsCaster1: 0,
            remainingHeatsCaster2: 0,
            allowRefreshRemainingHeats: true,
            allowUpdateRemainingHeats: false,

            unjustifiedDelaysCas1 : 0,
            unjustifiedDelaysCas2 : 0,
        },
        computeds: {
            hasData: {
                deps: ['hasData_positions'],
                get: function (positions) {
                    return positions;
                },
            },
            isLoading: {
                deps: ['isLoading_positions'],
                get: function (positions) {
                    return positions;
                },
            },
            LMF1_WithoutCar: {
                deps: ['LMF1_LadlePositionID'],
                get: function (pos) {
                    return pos == 10;
                },
            },
            LMF1_Car1: {
                deps: ['LMF1_LadlePositionID'],
                get: function (pos) {
                    return pos == 16;
                },
            },
            LMF1_Car2: {
                deps: ['LMF1_LadlePositionID'],
                get: function (pos) {
                    return pos == 17;
                },
            },
            LMF2_WithoutCar: {
                deps: ['LMF2_LadlePositionID'],
                get: function (pos) {
                    return pos == 20;
                },
            },
            LMF2_Car3: {
                deps: ['LMF2_LadlePositionID'],
                get: function (pos) {
                    return pos == 28;
                },
            },
            LMF2_Car4: {
                deps: ['LMF2_LadlePositionID'],
                get: function (pos) {
                    return pos == 29;
                },
            },
            hasUnjustifiedDelaysCas1: {
            deps: ['unjustifiedDelaysCas1'],
            get: function (value) {
                value = parseInt(value, 10) || 0;
                return value > 0;
            },
            },
            hasUnjustifiedDelaysCas2: {
            deps: ['unjustifiedDelaysCas2'],
            get: function (value) {
                value = parseInt(value, 10) || 0;
                return value > 0;
            },
            },
            showUnjustifiedDelaysContainer: {
            deps: ['hasUnjustifiedDelaysCas1', 'hasUnjustifiedDelaysCas2'],
            get: function (cas1, cas2) {
                return cas1 || cas2; 
            },
            },


        },
        initialize: function () {
            this.positions = new Screen.Collections.Positions();
            this.positionsGrid = new Screen.Collections.Positions();
            this.gridCollection = new Screen.Collections.Grid();
            this.topGridCollection = new Screen.Collections.TopGrid();
            this.attributesCollection = new Screen.Collections.Attributes();
            this.visualAttributes = new Screen.Collections.VisualAttributes();
            this.dataFirstTable = null;

        },

        enableOrDisableLadlePosition(params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@Enable', 'BIT', params.enable);
            qp.Add('@LadlePositionId', 'INT', params.ladlePositionID);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.EnableOrDisableLadlePosition',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && !(resp.Message)) {
                                that.trigger('refreshStatus');
                                //if (params.ladlePositionID === 53) that.trigger('open-pourback-modal');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.trigger('refreshStatus');
                                }
                                else {
                                    console.error('Server response not valid.');
                                    app.views.topMessages.showMessage('Server response not valid.', { stay: 5000, });
                                    that.trigger('refreshStatus');

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

        },
        fetch: function (params) {
            var that = this;

            var cas1pos1 = null;
            var cas1pos2 = null;
            var cas1pos3 = null;
            var cas1pos4 = null;

            var cas2pos1 = null;
            var cas2pos2 = null;
            var cas2pos3 = null;
            var cas2pos4 = null;

            var qp = new Core.Database.QueryParameters();

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.GetMeltshopOverviewWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp && resp.Table) {
                                if (resp.Table && resp.Table1) {
                                    //---- CASTER 1 -----//
                                    if (resp.Table4) {
                                        that.set({ showCaster1Positions: resp.Table4 });
                                        cas1pos1 = _.findWhere(resp.Table4, { ScreenPosition: 1 });
                                        cas1pos2 = _.findWhere(resp.Table4, { ScreenPosition: 2 });
                                        cas1pos3 = _.findWhere(resp.Table4, { ScreenPosition: 3 });
                                        cas1pos4 = _.findWhere(resp.Table4, { ScreenPosition: 4 });

                                        that.set({
                                            cas1Positions: {
                                                 cas1pos1  : cas1pos1 ? { ...cas1pos1, screenID: 'pos1cas1' } : null 
                                                ,cas1pos2  : cas1pos2 ? { ...cas1pos2, screenID: 'pos2cas1' } : null
                                                ,cas1pos3  : cas1pos3 ? { ...cas1pos3, screenID: 'pos3cas1' } : null
                                                ,cas1pos4  : cas1pos4 ? { ...cas1pos4, screenID: 'pos4cas1' } : null
                                            }
                                        })

                                        if (cas1pos1) that.set({ show_cas1_pos1: true, cas1_pos1_label: cas1pos1.Name, });
                                        else that.set({ show_cas1_pos1: false, cas1_pos1_label: '-', });

                                        if (cas1pos2) that.set({ show_cas1_pos2: true, cas1_pos2_label: cas1pos2.Name, });
                                        else that.set({ show_cas1_pos2: false, cas1_pos2_label: '-', });

                                        if (cas1pos3) that.set({ show_cas1_pos3: true, cas1_pos3_label: cas1pos3.Name, });
                                        else that.set({ show_cas1_pos3: false, cas1_pos3_label: '-', });

                                        if (cas1pos4) that.set({ show_cas1_pos4: true, cas1_pos4_label: cas1pos4.Name, });
                                        else that.set({ show_cas1_pos4: false, cas1_pos4_label: '-', });
                                    }

                                    //---- CASTER 2 -----//
                                    if (resp.Table5) {
                                        that.set({ showCaster2Positions: resp.Table5 });

                                        cas2pos1 = _.findWhere(resp.Table5, { ScreenPosition: 1 });
                                        cas2pos2 = _.findWhere(resp.Table5, { ScreenPosition: 2 });
                                        cas2pos3 = _.findWhere(resp.Table5, { ScreenPosition: 3 });
                                        cas2pos4 = _.findWhere(resp.Table5, { ScreenPosition: 4 });
                                       
                                        that.set({
                                            cas2Positions: {
                                                  cas2pos1: cas2pos1 ? { ...cas2pos1, screenID: 'pos1cas2' } : null
                                                , cas2pos2: cas2pos2 ? { ...cas2pos2, screenID: 'pos2cas2' } : null
                                                , cas2pos3: cas2pos3 ? { ...cas2pos3, screenID: 'pos3cas2' } : null
                                                , cas2pos4: cas2pos4 ? { ...cas2pos4, screenID: 'pos4cas2' } : null
                                            }
                                        })
                                        if (cas2pos1) that.set({ show_cas2_pos1: true, cas2_pos1_label: cas2pos1.Name, });
                                        else that.set({ show_cas2_pos1: false, cas2_pos1_label: '-', });

                                        if (cas2pos2) that.set({ show_cas2_pos2: true, cas2_pos2_label: cas2pos2.Name, });
                                        else that.set({ show_cas2_pos2: false, cas2_pos2_label: '-', });

                                        if (cas2pos3) that.set({ show_cas2_pos3: true, cas2_pos3_label: cas2pos3.Name, });
                                        else that.set({ show_cas2_pos3: false, cas2_pos3_label: '-', });

                                        if (cas2pos4) that.set({ show_cas2_pos4: true, cas2_pos4_label: cas2pos4.Name, });
                                        else that.set({ show_cas2_pos4: false, cas2_pos4_label: '-', });
                                    }


                                    that.gridCollection.setDataColl(resp.Table);
                                    if (resp.Table8) that.topGridCollection.setDataColl(resp.Table8);
                                    that.positions.setDataColl(resp.Table);
                                    that.positionsGrid.setDataColl(resp.Table, true);

                                    that.attributesCollection.setDataColl(resp.Table1);
                                    that.visualAttributes.setDataColl(resp.Table3);
                                    if (that.get('appendGrid')) {
                                        that.trigger('buildGrid', resp.Table, resp.Table8 ? resp.Table8 : null);
                                    }
                                    if (resp.Table6) {
                                        if (resp.Table6[0] && resp.Table6[0].ActiveL1 && resp.Table6[0].ActiveL1 == 1)
                                            app.views.topMessages.showMessage("Ladle Tracking Controlled by Level 1", { stay: 4000, });
                                    }

                                    if (resp.Table7) {
                                        that.set('TWIBlanket', resp.Table7[0].TWIBlanket);
                                    }
                                    if (resp.Table9) {

                                        const cas1 = _.findWhere(resp.Table9, { CasterCode: 1 });
                                        const cas2 = _.findWhere(resp.Table9, { CasterCode: 2 });
                                    
                                        if (that.get('allowRefreshRemainingHeats'))
                                            that.set({
                                                remainingHeatsCaster1: cas1.RemainingHeats,
                                                remainingHeatsCaster2: cas2.RemainingHeats,
                                            })
                                    }
                                    var unjustifiedCas1 = 0;
                                    if (resp.Table10) {
                                        unjustifiedCas1 = resp.Table10[0].UnjustifiedDelays;
                                    }
                                    unjustifiedCas1 = parseInt(unjustifiedCas1 || 0, 10) || 0;
                                    that.set('unjustifiedDelaysCas1', unjustifiedCas1);

                                    var unjustifiedCas2 = 0;
                                    if (resp.Table10) {
                                        unjustifiedCas2 = resp.Table11[0].UnjustifiedDelays;
                                    }
                                    unjustifiedCas2 = parseInt(unjustifiedCas2 || 0, 10) || 0;
                                    that.set('unjustifiedDelaysCas2', unjustifiedCas2);

                                    var leftEl = document.getElementById('mustUnderCoverLeft');
                                    var rightEl = document.getElementById('mustUnderCoverRight');
                                    if (leftEl && rightEl) {
                                        var list = resp.Table12 || [];
                                        if (list.length === 0 && resp.Table7 && Array.isArray(resp.Table7) && resp.Table7[0] && 'HeatName' in resp.Table7[0] && 'UnderCover' in resp.Table7[0]) {
                                            list = resp.Table7;
                                        }
                                        var cell = (leftEl.closest && leftEl.closest('.must-under-cover-cell')) || (document.getElementById('mustUnderCoverBox') && document.getElementById('mustUnderCoverBox').parentElement);
                                        if (cell) {
                                            cell.style.display = list.length > 0 ? '' : 'none';
                                        }
                                        if (list.length > 0) {
                                        var notUnderCover = _.where(list, { UnderCover: 0 });
                                        var underCover = _.where(list, { UnderCover: 1 });
                                        var heatNameLeft = function (name) { return (name || '').replace(/"/g, '&quot;'); };
                                        leftEl.innerHTML = notUnderCover.map(function (item) {
                                            var val = item.HydrogenValue != null ? Number(item.HydrogenValue).toFixed(2) : '—';
                                            var name = item.HeatName || '';
                                            return '<span class="must-under-cover-heat must-under-cover-not-covered must-under-cover-draggable" draggable="true" data-heat-name="' + heatNameLeft(name) + '" data-toggle="tooltip" title="Hydrogen: ' + val + '">' + name + '</span>';
                                        }).join('');
                                        var heatNameRight = function (name) { return (name || '').replace(/"/g, '&quot;'); };
                                        function formatTimeUnderCover(seconds) {
                                            if (seconds == null || typeof seconds !== 'number') return '—';
                                            var h = Math.floor(seconds / 3600);
                                            var m = Math.floor((seconds % 3600) / 60);
                                            var s = seconds % 60;
                                            return h + 'h ' + m + 'm ' + s + 's';
                                        }
                                        function formatRemaining(seconds) {
                                            if (seconds == null || typeof seconds !== 'number' || seconds <= 0) return '—';
                                            var h = Math.floor(seconds / 3600);
                                            var m = Math.floor((seconds % 3600) / 60);
                                            return h + 'h ' + m + 'm';
                                        }
                                        rightEl.innerHTML = underCover.map(function (item) {
                                            var val = item.HydrogenValue != null ? Number(item.HydrogenValue).toFixed(2) : '—';
                                            var name = item.HeatName || '';
                                            var coverLabel = (item.CoverId != null && item.CoverId !== '') ? item.CoverId : '—';
                                            var timeStr = formatTimeUnderCover(item.TimeUnderCoverSeconds);
                                            var tip = 'Hydrogen: ' + val + '<br/>Cover: ' + coverLabel + '<br/>Under Cover: ' + timeStr;
                                            if (item.OutOfCoverAlertHours != null) {
                                                if (item.OutOfCoverAlertActive === 1) {
                                                    tip += '<br/>Alert: Active (threshold: ' + item.OutOfCoverAlertHours + 'h)';
                                                } else {
                                                    var remainingSeconds = (item.OutOfCoverAlertHours * 3600) - (item.TimeUnderCoverSeconds || 0);
                                                    tip += '<br/>Alert: In ' + formatRemaining(remainingSeconds) + ' (threshold: ' + item.OutOfCoverAlertHours + 'h)';
                                                }
                                            }
                                            var alertClass = (item.OutOfCoverAlertActive === 1) ? ' must-under-cover-covered-alert' : '';
                                            var coverId = (item.CoverId != null && item.CoverId !== '') ? String(item.CoverId) : '';
                                            var alertHours = item.OutOfCoverAlertHours != null ? item.OutOfCoverAlertHours : '';
                                            var editAlertTitle = 'Edit Out of Cover Alert';
                                            var bellHtml = (item.OutOfCoverAlertHours != null) ? ' <i class="fa fa-bell must-under-cover-edit-alert" title="' + editAlertTitle.replace(/"/g, '&quot;') + '"></i>' : '';
                                            return '<span class="must-under-cover-heat must-under-cover-covered must-under-cover-goto-report' + alertClass + '" data-heat-name="' + heatNameRight(name) + '" data-cover-id="' + heatNameRight(coverId) + '" data-out-of-cover-alert-hours="' + heatNameRight(String(alertHours)) + '" data-toggle="tooltip" data-html="true" title="' + tip.replace(/"/g, '&quot;') + '"><span class="must-under-cover-heat-name">' + name + '</span>' + bellHtml + '</span>';
                                        }).join('');
                                        var tooltipOpts = { template: '<div class="tooltip tooltip-must-under-cover" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' };
                                        $(leftEl).find('[data-toggle="tooltip"]').tooltip(tooltipOpts);
                                        $(rightEl).find('[data-toggle="tooltip"]').tooltip(tooltipOpts);
                                        }
                                    }
                                }
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData_positions: false,
                                        isLoading_positions: false,

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

                            }


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

            return this;

        },

        updateRemainingHeats: function (newValue, caster) {

            if (!this.get('allowUpdateRemainingHeats')) return;

            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@CasterCode', 'INT', caster);
            qp.Add('@RemainingHeats', 'INT', newValue);

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

                            if ((resp) && !(resp.Message)) {
                                //that.trigger('refreshStatus');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    //that.trigger('refreshStatus');
                                }
                                else {
                                    console.error('Server response not valid.');
                                    app.views.topMessages.showMessage('Server response not valid.', { stay: 5000, });
                                    //that.trigger('refreshStatus');

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


        },
        update: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@LadleId', 'INT', params.ladleID);
            qp.Add('@LadlePositionId', 'INT', params.ladlePositionID); 

            qp.Add('@GodMode', 'BIT', false);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.ChangeLadlePositionWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && !(resp.Message)) {
                                that.trigger('refreshStatus');
                               // if (params.ladlePositionID === 53) that.trigger('open-pourback-modal');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.trigger('refreshStatus');
                                }
                                else {
                                    console.error('Server response not valid.');
                                    app.views.topMessages.showMessage('Server response not valid.', { stay: 5000, });
                                    that.trigger('refreshStatus');

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

        },
    });

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

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'melt-shop-overview',
            id: 'melt-shop-overview',
            title: 'Melt Shop Overview',
            isCacheable: false,
            events: function () {
                return {
                    'click #TWIBtn': this.TWIBtn_click,
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #backNavBtn': this.backNavBtn_click,
                    'click #forwardNavBtn': this.forwardNavBtn_click,
                    'keyup #search': this.keyPressEventHandler,
                    //Handle drag
                    'click .draggable': 'clickHandler',
                    'dblclick .draggable': 'clickHandler',

                    '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 #btnJustifyCas1': 'onJustifyDelaysClick',
                    'click #btnJustifyCas2': 'onJustifyDelaysClick',
                    // Must Under Cover: drag red heat to green to assign; click green to go to report
                    'mousedown .must-under-cover-draggable': 'mustUnderCover_mousedown',
                    'dragstart .must-under-cover-draggable': 'mustUnderCover_dragstart',
                    'dragend .must-under-cover-draggable': 'mustUnderCover_dragend',
                    'dragover .must-under-cover-drop-zone': 'mustUnderCover_dragover',
                    'drop .must-under-cover-drop-zone': 'mustUnderCover_drop',
                    'dragenter .must-under-cover-drop-zone': 'mustUnderCover_dragenter',
                    'dragleave .must-under-cover-drop-zone': 'mustUnderCover_dragleave',
                    'click .must-under-cover-goto-report': 'mustUnderCover_gotoReport',
                    'click .must-under-cover-edit-alert': 'mustUnderCover_editAlert',
                };
            },
            bindings: 'data-bind',

            mousedownFired: false,
            clicks : 0,
            clickTimer : 0,
            dblClickTimeSpan : 300,

            subviews: null,
            viewParams: null,
            positions: null,
            dragItem: null,
            dropContainer: null,
            dropContainersAllowed: [],
            container: null,
            currentDropContainerId: null,
            dragEnterContainer: null,
            positionsView: null,
            attributesView: null,
            grid: null,
            topGrid: null,
            autoRefresh: null,
            pauseTimer: false,
            LMFCasterModal: null,
            PourbackModal: null,
            ChangeMOModal: null,
            LadleMaintenancePositions: ['#pos70', '#pos71', '#pos72', '#pos73', '#pos74', '#pos75', '#pos76', '#pos77', '#pos78', '#pos79', '#pos80', '#pos81', '#pos82', '#pos83', '#pos84'
                                        , '#pos0', '#pos24', '#pos30', '#pos40', '#pos51', '#pos52', '#pos54'], //Positions that are not Maintenance and are not on the screen
     
        initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            this.autoRefresh = {
                enabled: null
                , toid: null
               , every: 15 * 1000
            };
            this.templates = {

                splitHeatModal: null,
                changePositionModal: null,
                changeMeltOrderModal: null,
                changeHeatWeightsModal: null,
                assignHeatModal: null,
                returnLadleModal: null,
                reladleModal: null,
            };

            var that = this;
            this.model = new Screen.Models.Main();

            this.bus = _.extend({}, Backbone.Events);
            this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);

            this.bindingSources = {
                positions: that.model.positions,
                attributesCollection: that.model.attributesCollection,
                visualAttributes: that.model.visualAttributes,
            };
         
            this.bindEvents();

            //this.getPermissions();

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

        isInEditingModeRemainingHeats: function () {
            var input1 = document.getElementById("remainingHeatsCaster1");
            var input2 = document.getElementById("remainingHeatsCaster2");

            // if either of the inputs does not have the "disabled" attribute, return true
            if (!input1.hasAttribute("disabled") || !input2.hasAttribute("disabled")) {
                return true;
            }

            // if both inputs are disabled, return false
            return false;
        },
        addEventsToInputsCaster1: function () {
            var that = this;
            var input = document.getElementById("remainingHeatsCaster1");
            var button = document.getElementById("editRemainingHeatsCaster1");

            function handleInputUpdate(disable) {
                var newValue = input.value;
                if (disable) input.setAttribute("disabled", "disabled");
                that.model.updateRemainingHeats(newValue,1);
            }
            // Enable input when the button is clicked
            button.addEventListener("click", function () {
                input.setAttribute("disabled", "disabled");
                input.removeAttribute("disabled");
                that.model.set({ allowUpdateRemainingHeats: true });
                input.focus(); // focus on the input once enabled
            });

            //input.addEventListener("input", handleInputUpdate(false));

            // Handle input update if the user presses the "Enter" key
            input.addEventListener("keydown", function (e) {
                if (e.key === "Enter") {
                    handleInputUpdate(true);
                }
            });

            // Handle input update if the user clicks outside of it
            document.addEventListener("click", function (e) {
                if (e.target !== input && e.target !== button) {
                    handleInputUpdate(true);
                }
            });
            },

        addEventsToInputsCaster2: function () {
            var that = this;
            var input = document.getElementById("remainingHeatsCaster2");
            var button = document.getElementById("editRemainingHeatsCaster2");

            function handleInputUpdate(disable) {
                var newValue = input.value;
                if (disable) input.setAttribute("disabled", "disabled");
                that.model.updateRemainingHeats(newValue,2);
            }
            // Enable input when the button is clicked
            button.addEventListener("click", function () {
                input.setAttribute("disabled", "disabled");
                input.removeAttribute("disabled");
                that.model.set({ allowUpdateRemainingHeats: true });
                input.focus(); // focus on the input once enabled
            });

            input.addEventListener("input", handleInputUpdate(false));

            // Handle input update if the user presses the "Enter" key
            input.addEventListener("keydown", function (e) {
                if (e.key === "Enter") {
                    handleInputUpdate(true);
                }
            });

            // Handle input update if the user clicks outside of it
            document.addEventListener("click", function (e) {
                if (e.target !== input && e.target !== button) {
                    handleInputUpdate(true);
                }
            });
        },
        


        clickHandler : function (e)  {
            this.clicks++;
            if (this.clicks === 1) {
                this.clickTimer = setTimeout(() => {
                    this.clicks = 0;               
                }, this.dblClickTimeSpan);
            }
            if (this.clicks === 2) {
                // it is the second click in double-click event
                var widget = $(e.target).closest('.widget-container');
                var currentHeatName = $(widget).find('.current-heat-name:first')[0].innerText;
                clearTimeout(this.clickTimer);
                this.clicks = 0;
                //if (this.PourbackModal) {
                //    this.PourbackModal.close();
                //    this.PourbackModal = null;
                //}
                //if (this.LMFCasterModal) {
                //    this.LMFCasterModal.close();
                //    this.LMFCasterModal = null;
                //}
                Backbone.history.navigate('!/lab-real-time/' + currentHeatName, { trigger: true });


            }
        },

        getPermissions: function () {
            var write = $.inArray('meltshopoverview_readWrite', app.models.user.get('roles'));
            var ctx = {
                write: write != -1 ? true : false,
            };
            return ctx.write;
        },
        draggable_click: function (e) {
            var posId = e.currentTarget.id;
            var attrs = this.model.toJSON();
            var that = this;
            var ladlePositionId = null;
            var needToAccept = null;
            var roleName = 'LMF';

            var position = posId && posId.split("pos") && posId.split("pos")[1] ? posId.split("pos")[1] : null;

            if (position === '2cas1' || position === '1cas1') {               
                // position === '1cas1' ---> we have two options ---> 35 (CAS 1 Arm 2 Outboard) OR  33 (CAS 1 Arm 1 Outboard)
                // position === '2cas1' ---> we have two options ---> 32 (CAS 1 Arm 1 Inboard)  OR  34 (CAS 1 Arm 2 Inboard)
                ladlePositionId = position === '2cas1' ? 32 : (position === '3cas1' ? 33 : (position === '4cas1' ? 34 : 35))

                if (position === '1cas1') {
                    ladlePositionId = 33;
                    needToAccept = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: ladlePositionId });
                    if (!needToAccept) {

                        ladlePositionId = 35;
                        needToAccept = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: ladlePositionId });
                    }
                }

                if (position === '2cas1') {
                    ladlePositionId = 32;
                    needToAccept = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: ladlePositionId });
                    if (!needToAccept) {

                        ladlePositionId = 34;
                        needToAccept = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: ladlePositionId });
                    }
                }
            } else {
                ladlePositionId = position;
                var needToAccept = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: parseInt(ladlePositionId) });
          
            }
            if (needToAccept && (needToAccept._NotAcceptedCaster === true || needToAccept._NotAcceptedLMF === true || needToAccept._RequirePourbackAcceptance === true)) {

                var data = [];
                data = {
                    GradeName: needToAccept._popup_GradeName,
                    HeatNumber: needToAccept._popup_HeatNumber,
                    LadleID: needToAccept._popup_LadleID,
                    MaterialSize: needToAccept._popup_MaterialSize,
                    MeltOrderNumber: needToAccept._popup_MeltOrderNumber,
                    SteelWeight: needToAccept._popup_SteelWeight,
                };

                roleName = needToAccept._NotAcceptedLMF === true ? 'LMF' : (needToAccept._NotAcceptedCaster === true ? 'CASTER' : null);
              
                if (needToAccept._RequirePourbackAcceptance === true && position === '53') that.showModal(data, 'POURBACK');
                else if (needToAccept._NotAcceptedCaster === true || needToAccept._NotAcceptedLMF === true) that.showModal(data, roleName);          
              
            }
            

            
        },
        onJustifyDelaysClick: function () {
        Backbone.history.navigate('!/caster-delays-manager', { trigger: true });
        },
        showModal: function (data, roleName) {
            var that = this;

            if (that.LMFCasterModal == null && that.PourbackModal == null && $('.modal.in').length == 0)  {

                if (roleName === 'LMF' || roleName === 'CASTER') {
                    that.LMFCasterModal = new ModalTriggerAcceptance.Views.ModalTriggerAcceptance({
                        parent: this,
                        data: data,
                        roleName: roleName,
                        bus: null,
                    });

                    this.listenTo(that.LMFCasterModal, 'close', function () {
                        try {
                            that.LMFCasterModal = 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.LMFCasterModal.show();
                        }
                        else {
                            that.LMFCasterModal.close();
                            that.LMFCasterModal = null;

                            this.pauseTimer = false;
                            that.refresh();
                        }
                    }
                    catch (e) {
                        if (that.LMFCasterModal != null) {
                            that.LMFCasterModal.close();
                            that.LMFCasterModal = 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);
                    }

                }


                else {
                    //this.openPourbackModal(data);

                }


             
            }
        },

        openPourbackModal: function (data) {
            var roleName = 'POURBACK';    
            if (!data) {
                var {
                    _popup_GradeName,
                    _popup_HeatNumber,
                    _popup_LadleID,
                    _popup_MaterialSize,
                    _popup_MeltOrderNumber,
                    _popup_SteelWeight,
                } = this.model.get('dragModel');
                data = {
                    GradeName :  _popup_GradeName,
                    HeatNumber : _popup_HeatNumber,
                    LadleID :    _popup_LadleID,
                    MaterialSize : _popup_MaterialSize,
                    MeltOrderNumber :  _popup_MeltOrderNumber,
                    SteelWeight :  _popup_SteelWeight,
                }
            }
            var that = this;
            that.PourbackModal = new ModalTriggerAcceptance.Views.ModalTriggerAcceptance({
                parent: this,
                data: data,
                roleName: roleName,
                bus: null,
            });

            this.listenTo(that.PourbackModal, 'close', function () {
                try {

                    if (that.PourbackModal.model.get('Accepted')) { this.dropSuccess(); }
                    that.PourbackModal = 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.PourbackModal.show();
                }
                else {
                    that.PourbackModal.close();
                    that.PourbackModal = null;

                    this.pauseTimer = false;
                    that.refresh();
                }
            }
            catch (e) {
                if (that.PourbackModal != null) {
                    that.PourbackModal.close();
                    that.PourbackModal = 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);
            }
        },
        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 });
        },
        bindEvents: function () {
            this.listenTo(this.model.positions, 'fetch', this.positions_fetched);
            this.listenTo(this.model.attributesCollection, 'fetch', this.attributes_fetched);
            this.listenTo(this.model.visualAttributes, 'fetch', this.visualAttributes_fetched);
            this.listenTo(this.model, 'refreshStatus', this.refresh);
            this.listenTo(this.model, 'buildGrid', this.buildGrid);
            this.listenTo(this.model, 'open-pourback-modal', this.openPourbackModal);
        },
        meltOrderPopup: function (m) {
            var that = this;
            var model = m.toJSON();
            data = {
                GradeName: model._popup_GradeName
                , HeatNumber: model._popup_HeatNumber
                , LadleID: model._popup_LadleID
                , MaterialSize: model._popup_MaterialSize
                , MeltOrderNumber: model._popup_MeltOrderNumber
   
                , FromMeltOrder:    model._MeltOrder
                , FromGradeName:    model._popup_GradeName
                , FromMaterialSize: model._popup_MaterialSize
            };
            this.ChangeMOModal = new ModalChangeMeltOrder.Views.ModalChangeMeltOrder({
                parent: this,
                data: data,
                bus: null,
            });

            this.listenTo(that.ChangeMOModal, 'close', function () {
                try {
                    that.ChangeMOModal = 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.ChangeMOModal.show();
                }
                else {
                    that.ChangeMOModal.close();
                    that.ChangeMOModal = null;

                    this.pauseTimer = false;
                    that.refresh();
                }
            }
            catch (e) {
                if (that.ChangeMOModal != null) {
                    that.ChangeMOModal.close();
                    that.ChangeMOModal = 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);
            }

        },
        contextMenuClicked: function () {
            try {
                var that = this;
                var model = this.model.get('rowModel');
                var contextMenuOption = this.model.get('contextMenuOption');    
                
                this.model.set({ runOptionTrigger: true });
                //that.stopAutoRefresh();

                switch (contextMenuOption) {
                    case 1: //OPT-CHANGE-POSITION
                        this.changeLadlePosition(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;   
                    case 2: //"OPT-CHANGE-HEAT-WEIGHTS"
                        this.changeHeatWeights(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;  
                    case 3: //"OPT-CHANGE-MELT-ORDER"
                        //this.changeMeltOrder(model);
                        this.meltOrderPopup(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;                   
                                      
                    case 4: //"OPT-ASSIGN-HEAT"
                        this.assignHeat(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;                    
                    case 5: //"OPT-RETURN-LADLE"
                        this.returnLadle(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;                   
                    case 6: //"OPT-RELADLE"
                        this.reladle(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;    
                    case 7: //"OPT-SPLIT-HEAT"
                        this.splitHeat(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;   
                    case 8: //"OPT-FREE-OPEN"
                        this.nonFreeOpen(model);
                        this.model.set({ rowModel: null, runOptionTrigger: false });
                        break;   
                    default:
                        if (that.autoRefresh.enabled == false)
                            that.startAutoRefresh();
                }

            } catch (Error) { }
        },
      

        render: function (container, urlParams) {
            var that = this;
            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;

            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.templates.splitHeatModal = Handlebars.compile(that.$el.find('#split_heat_modal_template_melt_shop_overview').html());
                            that.templates.nonFreeOpenModal = Handlebars.compile(that.$el.find('#non_free_open_modal_template_melt_shop_overview').html());
                            that.templates.changePositionModal = Handlebars.compile(that.$el.find('#change_position_modal_template').html());
                            that.templates.changeMeltOrderModal = Handlebars.compile(that.$el.find('#change_melt_order_modal_template').html());
                            that.templates.changeHeatWeightsModal = Handlebars.compile(that.$el.find('#change_heat_weights_modal_template').html());
                            that.templates.assignHeatModal = Handlebars.compile(that.$el.find('#assign_heat_to_ladle_modal_template').html());
                            that.templates.returnLadleModal = Handlebars.compile(that.$el.find('#return_ladle_modal_template').html());
                            that.templates.reladleModal = Handlebars.compile(that.$el.find('#reladle_modal_template').html());



                            that.positionsView = Screen.Views.LadlePosition.extend({
                                template: Handlebars.compile(that.$el.find('#LadlesViewTemplate').html()),
                            });

                            that.attributesView = Screen.Views.Attributes.extend({
                                template: Handlebars.compile(that.$el.find('#AttributesViewTemplate').html()),
                            });

                                
                            
                            that.applyBindings();



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

                           



                            that.addEventsToInputsCaster1();
                            that.addEventsToInputsCaster2();
                            that.refresh();

                            that.startAutoRefresh();

                            //positions context-menu
                            $(function (obj) {
                                $.contextMenu({
                                    selector: '.drop-positon-container',
                                    callback: function (key, options) {
                                        const idValue = options.$trigger[0].id;
                                        const modifiedIdValue = idValue.replace(/^pos/, '');
                                        that.model.set({ contextMenuOption: key });
                                        that.contextMenuSetPositionStatus(modifiedIdValue);
                                    },
                                    items: {
                                        "opt-disable-position": {
                                            name: "Disable Postion",
                                            icon: "fa-times",
                                            disabled: function (key, opt) {
                                                const hasChildren = opt.$trigger.children().length > 0;
                                                if (hasChildren) {
                                                    const hasDraggableChild = opt.$trigger.find('.draggable-object').length > 0;
                                                    if (hasDraggableChild) return true;
                                                }
                                                return opt.$trigger.hasClass('not-allowed-locations');
                                            }
                                        },
                                        "opt-enable-position": {
                                            name: "Enable Positon",
                                            icon: "fa-check",
                                            disabled: function (key, opt) {
                                                const hasChildren = opt.$trigger.children().length > 0;
                                                if (hasChildren) {
                                                    const hasDraggableChild = opt.$trigger.find('.draggable-object').length > 0;
                                                    if (hasDraggableChild) return true;
                                                }
                                                return !opt.$trigger.hasClass('not-allowed-locations');
                                            }
                                        },

                                        events: {
                                            hide: function (options) {
                                                that.pauseTimer = false;
                                            },
                                            show: function () {
                                                that.pauseTimer = true;
                                            }
                                        }
                                    }
                                });
                            });

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

        getLadlePositionId: function (pos) {

            const cas1Positions = this.model.get('cas1Positions');
            const cas2Positions = this.model.get('cas2Positions');


            if (pos === '1cas1') pos = cas1Positions.cas1pos1.LadlePositionId;
            if (pos === '2cas1') pos = cas1Positions.cas1pos2.LadlePositionId;
            if (pos === '3cas1') pos = cas1Positions.cas1pos3.LadlePositionId;
            if (pos === '4cas1') pos = cas1Positions.cas1pos4.LadlePositionId;


            if (pos === '1cas2') pos = cas2Positions.cas2pos1.LadlePositionId;
            if (pos === '2cas2') pos = cas2Positions.cas2pos2.LadlePositionId;
            if (pos === '3cas2') pos = cas2Positions.cas2pos3.LadlePositionId;
            if (pos === '4cas2') pos = cas2Positions.cas2pos4.LadlePositionId;
            
            return pos;

        },


        contextMenuSetPositionStatus: function (pos) {
            var that = this;
            var contextMenuOption = this.model.get('contextMenuOption');
            var message = '';
            switch (contextMenuOption) {
                case "opt-enable-position":
                    that.model.enableOrDisableLadlePosition({
                        enable: true,
                        ladlePositionID: that.getLadlePositionId(pos),

                    });
                    break;
                case "opt-disable-position":
                    that.model.enableOrDisableLadlePosition({
                        enable: false,
                        ladlePositionID: that.getLadlePositionId(pos),

                    });
                    break;

            }
        },

        buildGrid: function (data,topTableData) {
            var keys = null,
                columnsName = [];
            var that = this;
            this.model.set({
                appendGrid: false,
            });

             var ActionsCellTWI = Backgrid.Cell.extend({
                template: _.template(that.$el.find("#actions_cell_twi_template").html()),
                className: "actions-cell align-center-cell", 
                initialize: function () {
                    Backgrid.Cell.prototype.initialize.apply(this, arguments);
                  
                },
                events: {
                    "click .btn-cell-action": "cellActionClick"
                },
                cellActionClick: function (e) {
                    var target = $(e.target);                    
                    Backbone.history.navigate('!/twi-management/' + this.model.get('TWI'), { trigger: true });;
                },
                render: function () {
                    this.$el.html(this.template());

                    this.$el.find("[data-toggle='tooltip']").tooltip();
                    this.delegateEvents();
                    
                    var btnTWI = this.$el.find(".btn-twi");
                    if (this.model.get('TWI') != null) btnTWI.removeClass("hide");

                    return this;
                },
            });


            if (data[0]) {


                keys = Object.keys(data[0]);

                _.each(keys, function (obj) {
                    if (obj[0] != '_' && obj != 'TWI') {
                        columnsName.push({
                            "name": obj,
                            "editable": false,
                            "label": app.translate([that, app], obj),
                            "cell": Backgrid.StringCell.extend({
                                //className: 'string-cell align-center-cell',
                                className: function () {
                                    var model = this.model.toJSON();
                                    if (obj == 'Heats' && model._HeatsFlag == 'WARNING') {
                                        return 'string-cell align-center-cell warningFlag';
                                    } else if (obj == 'Contact' && model._ContactFlag == 'WARNING') {
                                        return 'string-cell align-center-cell warningFlag';
                                    } else if (obj == 'MWH' && model._MWHFlag == 'WARNING') {
                                        return 'string-cell align-center-cell warningFlag';
                                    } else
                                        return 'string-cell align-center-cell';
                                }
                            }),
                            //"cell": "uri" // Renders the value in an HTML anchor element
                           
                        });
                    } else if (obj == 'TWI') {

                        columnsName.push({
                            "name": obj,
                            "editable": false,
                            "label": app.translate([that, app], obj),
                            "cell": ActionsCellTWI
                           
                        });

                       
                    }
                });

                that.grid = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    row: Backgrid.Row.extend({
                        initialize: function (options) {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                        },
                        events: {
                            contextmenu: 'onRightClick',
                        },
                        onRightClick: function (e) {
                            e.preventDefault();
                            var rowsView = that.model.get('grid').body.rows;
                            var newIndex = _.indexOf(rowsView, this);

                            var write = that.getPermissions();
                            if (write) { 
                                this.$el.addClass("onRightClickSelectedRow");
                                var model = this.model;
                                that.model.set({ 
                                    rowModel: model,
                                    index: newIndex,
                                });
                            }
                            
                        },
                    }),
                    collection: that.model.gridCollection
                });
                that.$el.find('.status-grid-container').append(that.grid.render().el);

                       

            }

            that.model.set({ grid: that.grid});
            $.contextMenu('destroy');


            var write = that.getPermissions();
            if (write) {
                $(function() {
                    $.contextMenu({
                        selector: '.status-grid-container .align-center-cell', 
                        callback: function(key, options) {
                            if (key === 'opt-change-position')  that.model.set({contextMenuOption:1});                                                    
                            if (key === 'opt-change-heat-weights')  that.model.set({contextMenuOption:2});                                                     
                            if (key === 'opt-change-melt-order')  that.model.set({contextMenuOption:3}); 
                            if (key === 'opt-assign-heat')  that.model.set({contextMenuOption:4});
                            if (key === 'opt-return-ladle')  that.model.set({contextMenuOption:5});
                            if (key === 'opt-reladle') that.model.set({ contextMenuOption: 6 });
                            if (key === 'opt-split-heat') that.model.set({ contextMenuOption: 7 });
                            if (key === 'opt-non-free-open') that.model.set({ contextMenuOption: 8 });
                            that.contextMenuClicked();
                        },
                        items: {
                            "opt-change-position": {name: "Change Ladle Position", icon: "fa-arrow-right"},
                            "sep1": "---------",
                            "opt-change-heat-weights": {name: "Change Heat Weights", icon: "fa-download"},  
                            "opt-change-melt-order": {name: "Change Melt Order", icon: "fa-indent"},  
                            "opt-assign-heat": {name: "Assign Heat To Ladle", icon: "fa-arrow-right"},       
                            "sep2": "---------",                                             
                            "opt-return-ladle": {
                                name: "Return Ladle", 
                                icon: "fa-mail-reply-all",
                                disabled: function(key, opt) { 
                                    return !that.model.get('inSource')
                                }
                            },                                                   
                            "opt-reladle": { name: "Reladle", icon: "fa-cloud-download" },
                            "opt-split-heat": { name: "Split Heat", icon: "fa-arrow-right" },    
                            "sep3": "---------",    
                            "opt-non-free-open": { 
                                name: "Quick Shroud | Non Free Open ", 
                                icon: "fa-arrow-down",
                                disabled: function(key, opt) { 
                                    var m = that.model.toJSON();
                                    var rm  = m.rowModel;
                                    var attrs = rm.toJSON();
                                    if (attrs._LadlePositionID !== 42 && attrs._LadlePositionID !== 44)
                                        return true;
                                    else return false;
                                } 

                            },    
                                                                          
                                                        
                        },
                        events: {
                            hide : function(options){
                                that.removeHighlightRow();
                            },
                        }
                    }); 
                });
            }

            // -------------------- //
            // ---- Top Table ---- //
            // ------------------- //
            if (topTableData && topTableData[0]) {
                columnsName = [];
                keys = Object.keys(topTableData[0]);

                _.each(keys, function (obj) {
                    columnsName.push({
                        "name": obj,
                        "editable": false,
                        "label": app.translate([that, app], obj),
                        "cell": Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    });
                });


                that.topGrid = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    row: Backgrid.Row.extend({
                        initialize: function (options) {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                        },
                    }),
                    collection: that.model.topGridCollection
                });
                that.$el.find('.top-grid-container').append(that.topGrid.render().el);
                that.model.set({ topGrid: that.topGrid });
            }
            
        },
        removeHighlightRow: function(){
            var previousIndex = this.model.get('index');
            var rowsView = this.model.get('grid').body.rows;
            rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");
        },
        positions_fetched: function () {
            try {
                var that = this;
                var id = null;
                $(".blink-bg").removeClass('blink-bg');
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_positions: (that.model.positions.length > 0),
                            isLoading_positions: false,
                        });
                        _.each(that.model.positions.toJSON(), function (obj) {
                            if (obj._NotAcceptedLMF === true || obj._NotAcceptedCaster === true) {
                                // In caster we have 4 Ids --> pos1cas1 / pos2cas1 / pos3cas1 / pos4cas1 
                                // Only In Transit respect the idea of id =  '#pos' + obj._LadlePositionID;

                                // position === '#pos1cas1' ---> we have two options ---> 35 (CAS 1 Arm 2 Outboard) OR  33 (CAS 1 Arm 1 Outboard)
                                // position === '#pos2cas1' ---> we have two options ---> 32 (CAS 1 Arm 1 Inboard)  OR  34 (CAS 1 Arm 2 Inboard)

                                if (obj._LadlePositionID === 32 || obj._LadlePositionID === 33 || obj._LadlePositionID === 34 || obj._LadlePositionID === 35) {
                                    id = obj._LadlePositionID === 32 ? '#pos2cas1' : (obj._LadlePositionID === 33 ? '#pos1cas1' : (obj._LadlePositionID === 34 ? '#pos2cas1' : '#pos1cas1'))
                                } else {
                                    id = '#pos' + obj._LadlePositionID;
                                }
                                if (id) $(id).addClass('blink-bg');

                            }
                            if (obj._RequirePourbackAcceptance === true) {
                                id = '#pos53';
                                $(id).addClass('blink-bg');
                            }
                        });
                    },
                    100



                );

                _.each(that.model.positions.toJSON(), function (obj) {
                    if (!obj._maintenancePosition) {    
                        $(obj._dropContainerId).empty();
                        that.append($(obj._dropContainerId), $(obj._dragId));
                    }
                });

                var write = that.getPermissions();
                if (!write) { 
                    var elems = document.querySelectorAll('[draggable="true"]');

                    for (var i = 0; i < elems.length; i++) {
                        elems[i].setAttribute("draggable", false);
                    }
                }


            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        attributes_fetched: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_attributes: (that.model.attributesCollection.length > 0),
                            isLoading_attributes: false,
                        });
                    },
                    100
                );

                _.each(that.model.attributesCollection.toJSON(), function (obj) {
                    that.append($(obj.containerId), $(obj.elementId));
                });

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        visualAttributes_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_visualAttributes: (that.model.visualAttributes.length > 0),
                                isLoading_visualAttributes: false,
                            });
                        },
                        100
                    );
                    this.setVisualAttributes();
                    
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        setVisualAttributes: function () {
            var id;
            $(".warning-color").css('background-color', '');
            $(".warning-color").removeClass('warning-color');
            if (this.model.visualAttributes.length > 0) {
                _.each(this.model.visualAttributes.toJSON(), function (obj) {
                    id = '#' + 'pos' + obj.LadlePositionID;
                    if (obj.Name == 'WARNING') {
                        $(id).css('background-color', obj.Value);
                        $(id).addClass('warning-color');
                    };
                });

            }
        },

        refresh: function () {
            var that = this;
            this.model.set({
                allowRefreshRemainingHeats: !that.isInEditingModeRemainingHeats(),
                allowUpdateRemainingHeats: that.isInEditingModeRemainingHeats(),
            })
            this.model.fetch({
                async: false,
            });
            this.updateLMF1_LadelPositionID();
            this.updateLMF2_LadelPositionID();

            this.setURLClassGrid();
            this.setNotAllowedPostions();

        },

        setNotAllowedPostions: function () {
            var that = this;
            let positions = this.model.positions.toJSON();
            that.removeNotAllowedLocationsClass();
            let lmf1Positions = [10, 16, 17];
            let lmf2Positions = [20, 28, 29];

            let occupiedPositions = [];
            _.each(positions, function (pos) {
                if (pos._LadlePositionID < 70) {
                    occupiedPositions.push(pos._LadlePositionID);
                }
            });

            // LMF 1

            // Step 1: Check if at least one element from lmf1Positions exists in occupiedPositions
            let hasCommonElement = lmf1Positions.some((element) => occupiedPositions.includes(element));
     
            // Step 2: If a common element is found, push the remaining items from lmf1Positions to occupiedPositions
            if (hasCommonElement) {
                for (let i = 0; i < lmf1Positions.length; i++) {
                    if (!occupiedPositions.includes(lmf1Positions[i])) {
                        occupiedPositions.push(lmf1Positions[i]);
                    }
                }
            }

            // LMF 2
            // Step 1: Check if at least one element from lmf1Positions exists in occupiedPositions
            hasCommonElement = lmf2Positions.some((element) => occupiedPositions.includes(element));

            // Step 2: If a common element is found, push the remaining items from lmf1Positions to occupiedPositions
            if (hasCommonElement) {
                for (let i = 0; i < lmf2Positions.length; i++) {
                    if (!occupiedPositions.includes(lmf2Positions[i])) {
                        occupiedPositions.push(lmf2Positions[i]);
                    }
                }
            }


            const cas1Positions = that.model.get('cas1Positions');
            const cas2Positions = that.model.get('cas2Positions');
            if (positions && positions[0] && positions[0]._NotAllowedLocation) {
                let notAllowed = positions[0]._NotAllowedLocation.split(',');
                _.each(notAllowed, function (obj) {
                    if (occupiedPositions.includes(parseInt(obj))) return;
                    _.each(cas1Positions, function (cas) {
                        if (cas && cas.LadlePositionId && parseInt(cas.LadlePositionId) === parseInt(obj)) {
                            if (!occupiedPositions.includes(parseInt(cas.LadlePositionId))) 
                                $('#' + cas.screenID).addClass('not-allowed-locations');
                        }
                    });
                    _.each(cas2Positions, function (cas) {
                        if (cas && parseInt(cas.LadlePositionId) === parseInt(obj)) {
                            if (!occupiedPositions.includes(parseInt(cas.LadlePositionId))) 
                                $('#' + cas.screenID).addClass('not-allowed-locations');

                        }
                    });                    
                    $('#pos' + obj).addClass('not-allowed-locations');
                });
                let notAllowedDivs = document.querySelectorAll('.not-allowed-locations');

                notAllowedDivs.forEach((div) => {
                    div.innerHTML = 'Maintenance';
                });
            }
        },
        removeNotAllowedLocationsClass: function () {
            let notAllowedDivs = document.querySelectorAll('.not-allowed-locations');

            notAllowedDivs.forEach((div) => {
                div.innerHTML = '';
            });
            this.$el.find('.not-allowed-locations').removeClass('not-allowed-locations');
        },

        removeNotAllowedCasterLocationsClass: function (pos) {
            let posId = null;
            // Caster 1 Pos 1
            if (pos === 33 || pos === 35) {
                posId = "#pos1cas1";
            }
            // Caster 1 Pos 2
            if (pos === 32 || pos === 34) {
                posId = "#pos2cas1";

            }
            // Caster 2 Pos 1
            if (pos === 43 || pos === 45) {
                posId = "#pos1cas2";

            }
            // Caster 2 Pos 2
            if (pos === 42 || pos === 44) {
                posId = "#pos2cas2";


            }

            let notAllowedDivs = document.querySelectorAll(posId);
            notAllowedDivs.forEach((div) => {
                div.innerHTML = '';

                div.classList.remove('not-allowed-locations');
            });
        },

        setURLClassGrid: function () {
            var found;
            var params;
            var gridElement = document.getElementById("grid");
            var aTags = gridElement.getElementsByTagName("td");
            for (var i = 0; i < aTags.length; i++) {
                if (aTags[i].textContent.includes("^")) {
                    found = aTags[i];
                    params = aTags[i].textContent.split("^");
                    aTags[i].textContent = '';
                    $(found).removeClass('string-cell');
                    $(found).addClass('uri-cell');
                    $(found).append("<a tabindex='- 1' " + "href='!/" + params[1] + "'" + "title='" + params[0] + "'" + "target='_blank'>" + params[0] + "</a>");
                }
            }
        },


        // Different Positions sharing place
        updateLMF1_LadelPositionID: function () {
            var pos11 = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: 16 }),
                pos12 = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: 17 });
                          
            if (pos11) this.model.set({ LMF1_LadlePositionID: 16 }); else
            if (pos12) this.model.set({ LMF1_LadlePositionID: 17 }); else
                       this.model.set({ LMF1_LadlePositionID: 10 });
        },
        updateLMF2_LadelPositionID: function () {
            var pos28 = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: 28 }),
                pos29 = _.findWhere(this.model.positions.toJSON(), { _LadlePositionID: 29 });

            if (pos28) this.model.set({ LMF2_LadlePositionID: 28 }); else 
            if (pos29) this.model.set({ LMF2_LadlePositionID: 29 }); else 
                       this.model.set({ LMF2_LadlePositionID: 20 });
        },
     
      
        getLMFLadlePositionIDTarget: function (ladleID, ladlePositionIDTarget) {
                var targetPositionID = parseInt(ladlePositionIDTarget),
                    originPositionID,
                    dragItemModel,
                    newTargetPositionID = null;

                dragItemModel = _.findWhere(this.model.positions.toJSON(), { _LadleID: parseInt(ladleID) });
                originPositionID = parseInt(dragItemModel._LadlePositionID);

                if (targetPositionID == 10) {
                    if (originPositionID == 6) newTargetPositionID = 16;
                    else if (originPositionID == 7) newTargetPositionID = 17;
                    else newTargetPositionID = targetPositionID;
                } else if (targetPositionID == 20) {
                    if (originPositionID == 8) newTargetPositionID = 28;
                    else if (originPositionID == 9) newTargetPositionID = 29;
                    else newTargetPositionID = targetPositionID;
                }


                if (newTargetPositionID == 10 || newTargetPositionID == 16 || newTargetPositionID == 17)
                    this.model.set({ LMF1_LadlePositionID: targetPositionID });

                if (newTargetPositionID == 20 || newTargetPositionID == 28 || newTargetPositionID == 29)
                    this.model.set({ LMF2_LadlePositionID: targetPositionID });


                return newTargetPositionID;
        },

        //Drag and drop functions
        detectdrag: function (event) {
            const LadleCastersPositions = ['#pos32', '#pos33', '#pos34', '#pos35', '#pos42', '#pos43', '#pos44', '#pos45'];

            if (!this.model.get('readOnlyPermissions')) {
                var that = this;
                this.pauseTimer = true;
                this.dragItem = $(event.currentTarget);

                var selectedDragId = '#' + this.dragItem.context.id;
                var dragModel = _.findWhere(this.model.positions.toJSON(), { _dragId: selectedDragId });
              
                this.model.set({ dragModel: dragModel });
                this.currentDropContainerId = dragModel._dropContainerId;
                that.dropContainersAllowed = [];

                const cas1Positions = that.model.get('cas1Positions');
                const cas2Positions = that.model.get('cas2Positions');

                _.each(dragModel._allowedLocations, function (obj) {
                    that.dropContainersAllowed.push('#pos' + obj);

                    if (LadleCastersPositions.includes('#pos' + obj)) {
                        let ladlePositionId = parseInt(obj);
                        _.each(cas1Positions, function (cas) {
                            if (cas && cas.LadlePositionId && parseInt(cas.LadlePositionId) === ladlePositionId) {
                                that.dropContainersAllowed.push('#' + cas.screenID);
                            }
                        });
                        _.each(cas2Positions, function (cas) {
                            if (cas && cas.LadlePositionId && parseInt(cas.LadlePositionId) === ladlePositionId) {
                                that.dropContainersAllowed.push('#' + cas.screenID);
                            }
                        });
                    }

                });
                _.each(that.dropContainersAllowed, function (obj) {
                    $(obj).addClass('allowed-locations');
                });
            } 
        },
        dragenter: function (event) {
            if (!this.model.get('readOnlyPermissions')) {
                var currentContainerId = $(this.dragItem.context.parentElement).attr('id');


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

                var dragEnterContainerId = this.dragEnterContainer.context.id;

                if (currentContainerId != dragEnterContainerId) {
                    this.dragEnterContainer.addClass('drag-over-drop-container');
                }
                event.preventDefault();
            };
        },

        dragleave: function (event) {
            if (!this.model.get('readOnlyPermissions')) {
                this.removeDragOverClass();
                //event = event.originalEvent || event;
                //var currentElement = document.elementFromPoint(event.pageX, event.pageY);
                //if (currentElement) {
                //    this.removeDragOverClass();
                //}
            }
        },

        drop: function (event) {
            var that = this;
            if (!this.model.get('readOnlyPermissions')) {

                this.removeDragOverClass();
                var dropContainer = $(event.currentTarget);
                var dropContainerId = "#" + $(event.currentTarget).context.id;
                var dragEnterContainerId = "#"+this.dragEnterContainer.context.id;
                if (this.currentDropContainerId && this.currentDropContainerId != dropContainerId && !(dropContainerId == '#pos70' && this.LadleMaintenancePositions.includes(this.currentDropContainerId))) {

                    this.dropContainer = dropContainer;
                    if (this.dropContainersAllowed.includes(dropContainerId))
                    {
                        if ((dragEnterContainerId == '#pos2' || dragEnterContainerId == '#pos4') && this.LadleMaintenancePositions.includes(this.currentDropContainerId) ) {
                            try {
                                var that = this;
                                modal = new Modal.Views.Main({
                                    focusOk: false,
                                    focusSelector: '#btn-cancel',
                                    title: 'Heat ' + that.model.get('dragModel')._HeatName +  ' - Moving Ladle ' + this.dragItem[0].innerText + ' to ' + this.dragEnterContainer[0].previousElementSibling.innerText,
                                    message: 'This will empty the ladle. Are you sure you want to continue? ',
                                    buttons_type: "CONTINUE-CANCEL",

                                });
                                this.listenToOnce(modal, "continue", function (modal) {
                                    try {
                                        this.dropSuccess();
                                        //this.removeAllowedLocationsClass();
                                    }
                                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                });
                                modal.show();
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }


                        }
                        else {
                            this.dropSuccess();
                        }
                    }
                    else {
                        this.openModalConfirmation();
                    }
                }


                //if (dropContainerId === '#pos53') {
                //    setTimeout(
                //        function () {
                //            that.openPourbackModal([], 'POURBACK');
                //        },
                //        300
                //    );

                //}

            };


        },
        dragend: function () {
            if (!this.model.get('readOnlyPermissions')) {
                this.removeDragOverClass();
                this.removeAllowedLocationsClass();
                this.pauseTimer = false;
                this.currentDropContainerId = null;
            }

        },
        mouseupdrag: function () {
            if (!this.model.get('readOnlyPermissions')) {
                this.removeAllowedLocationsClass();
                this.removeDragOverClass();
            }
        },
        dropSuccess: function () {
            var targetPositionIDLMF = null,
                target = null,
                casterNumber = null,
                sp = null;

            if (!this.model.get('readOnlyPermissions')) { 
                var ladlePositionID = this.dropContainer.context.id.split("pos")[1],
                    ladleID = this.dragItem.context.id.split("ladle")[1];
                if (ladlePositionID.includes("cas")) {

                    // check if it's a Caster Position
                    sp = parseInt(ladlePositionID.split("cas")[0]);
                    casterNumber =   parseInt(ladlePositionID.split("cas")[1]);

                    if (casterNumber == 1) {
                        target = _.findWhere(this.model.get('showCaster1Positions'), { ScreenPosition: sp }).LadlePositionId;

                    } else if (casterNumber == 2)  {
                        target = _.findWhere(this.model.get('showCaster2Positions'), { ScreenPosition: sp }).LadlePositionId;
                    }
                    this.removeNotAllowedCasterLocationsClass(target);
                   
                } else if (this.getLMFLadlePositionIDTarget(ladleID, ladlePositionID)) {
                    // check if it's a LMF Position
                    targetPositionIDLMF = this.getLMFLadlePositionIDTarget(ladleID, ladlePositionID);
                    target = targetPositionIDLMF;

                } else {
                    target = parseInt(ladlePositionID);
                }
                this.model.update({
                    ladlePositionID: target,
                    ladleID: ladleID,
                });
            }
        },
        removeDragOverClass: function () {
           this.$el.find('.drag-over-drop-container').removeClass('drag-over-drop-container');
        },
        removeAllowedLocationsClass: function () {
            this.$el.find('.allowed-locations').removeClass('allowed-locations');
        },

        // Must Under Cover: drag red heat to green column to open assign-cover modal; click green to go to report
        mustUnderCover_mousedown: function (ev) {
            if (this.model.get('readOnlyPermissions')) return;
            var that = this;
            this.$el.find('.must-under-cover-drop-zone').addClass('allowed-locations');
            $(document).one('mouseup', function () {
                that.$el.find('.must-under-cover-drop-zone').removeClass('allowed-locations drag-over-drop-container');
            });
        },
        mustUnderCover_dragstart: function (ev) {
            if (this.model.get('readOnlyPermissions')) return;
            var heatName = $(ev.currentTarget).attr('data-heat-name') || '';
            ev.originalEvent.dataTransfer.setData('text/plain', heatName);
            ev.originalEvent.dataTransfer.effectAllowed = 'move';
            this.$el.find('.must-under-cover-drop-zone').addClass('allowed-locations');
        },
        mustUnderCover_dragend: function () {
            this.$el.find('.must-under-cover-drop-zone').removeClass('allowed-locations drag-over-drop-container');
        },
        mustUnderCover_dragover: function (ev) {
            if (this.model.get('readOnlyPermissions')) return;
            ev.preventDefault();
            ev.originalEvent.dataTransfer.dropEffect = 'move';
        },
        mustUnderCover_dragenter: function (ev) {
            if (this.model.get('readOnlyPermissions')) return;
            $(ev.currentTarget).addClass('drag-over-drop-container');
        },
        mustUnderCover_dragleave: function (ev) {
            $(ev.currentTarget).removeClass('drag-over-drop-container');
        },
        mustUnderCover_drop: function (ev) {
            ev.preventDefault();
            $(ev.currentTarget).removeClass('drag-over-drop-container');
            this.$el.find('.must-under-cover-drop-zone').removeClass('allowed-locations');
            if (this.model.get('readOnlyPermissions')) return;
            var heatName = ev.originalEvent.dataTransfer.getData('text/plain');
            if (!heatName) return;
            var that = this;
            var modalView = new AssignCoverModal.Views.AssignHeatCover({
                parent: that,
                data: { HeatNumber: heatName, action: 'A' },
                bus: null
            });
            that.listenToOnce(modalView, 'close', function () {
                that.refresh();
            });
            if (!document.body.contains(modalView.el)) {
                $(document.body).append(modalView.$el);
            }
            modalView.show();
        },
        mustUnderCover_gotoReport: function (ev) {
            ev.preventDefault();
            if ($(ev.target).hasClass('must-under-cover-edit-alert')) return;
            app.router.navigate('!/covers-report/', { trigger: true });
        },
        mustUnderCover_editAlert: function (ev) {
            ev.preventDefault();
            ev.stopPropagation();
            if (this.model.get('readOnlyPermissions')) return;
            var that = this;
            var span = $(ev.currentTarget).closest('.must-under-cover-heat');
            var heatName = span.attr('data-heat-name') || '';
            var coverId = span.attr('data-cover-id') || '';
            var alertHours = span.attr('data-out-of-cover-alert-hours');
            var outOfCoverAlertHours = (alertHours === '' || alertHours === undefined) ? null : (parseInt(alertHours, 10) || null);
            var data = {
                CoverNumber: coverId ? parseInt(coverId, 10) : null,
                HeatNumber: heatName,
                OutOfCoverAlertHours: outOfCoverAlertHours
            };
            var modalView = new AssignCoverModal.Views.EditOutOfCoverAlert({
                parent: that,
                data: data
            });
            that.listenToOnce(modalView, 'close', function () {
                that.refresh();
            });
            if (!document.body.contains(modalView.el)) {
                $(document.body).append(modalView.$el);
            }
            modalView.show();
        },

        //Modal functions
        onModalAcceptBtn: function () {
            this.dropSuccess();
        },
        openModalConfirmation: function () {
            var modal = new Screen.Views.ConfirmationModalMain({

                bus: this.bus,
                model: this.model,
            });
            modal.show();
        },

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

            if (!this.pauseTimer) this.refresh();

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

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

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

                    this.autoRefresh.enabled = true;

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


        //Common functions
        append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.options.state == app.view_states.loading
                || this.options.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.options.state = app.view_states.shown;
                container.append(el);

                this.options.onappend(this);
            }

            if (this.options.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        bindViewScopedEvents: function () {
            var that = this;
        },
        unbindViewScopedEvents: function () {

        },
        close: function () {
            this.options.state = app.view_states.closed;
            this.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 (urlParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },

        //-------------------------------------------------------------------------------------------------------------
        //----------------------------------------- Contextual Menu Functions -----------------------------------------
        //-------------------------------------------------------------------------------------------------------------
        nonFreeOpen: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();
                if (attrs._LadlePositionID !== 42 && attrs._LadlePositionID !== 44) {
                        return;
                }
                this.currentModal = new Screen.Views.NonFreeOpenModal({
                    model: new Screen.Models.NonFreeOpenModal({
                        ladle: attrs.Ladle,
                        heat: attrs._HeatName,
                        curPositionId: attrs._LadlePositionID,
                        comments:  attrs._non_free_open_comments,
                        rods:  attrs._non_free_open_rods,
                        position: attrs.Position,
                        quickShroud: attrs._quick_shroud ? 'YES' : 'NO',        
                        isNonFreeOpen: attrs._is_non_free_open ? true : false,
                    }),
                    template: this.templates.nonFreeOpenModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };

                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {

                        try {
                            if (output.result == 'SUCCESS') {   
                                app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                              
                                that.refresh();

                            }
                        }
                        catch (e) {
                            if (that.autoRefresh.enabled == false)
                                that.startAutoRefresh();
                            console.error((e.stack) ? e.stack : new Error(e).stack);
                        }     


                        // try {
                        //     if (output.result == 'SUCCESS') {
                        //         app.views.topMessages.showMessage(output.data.Message, { stay: 5 * 1000, });
                        //     }
                        // }
                        // catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });;

                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        splitHeat: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();
                this.currentModal = new Screen.Views.SplitHeatModal({
                    model: new Screen.Models.SplitHeatModal({
                        ladle: attrs.Ladle,
                        heat: attrs._HeatName,
                        curPositionId: attrs._LadlePositionID,
                        position: attrs.Position,
                    }),
                    template: this.templates.splitHeatModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };

                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {
                                app.views.topMessages.showMessage(output.data.Message, { stay: 5 * 1000, });
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });;

                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        changeLadlePosition: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.ChangePositionModal({
                    model: new Screen.Models.ChangePositionModal({
                        ladle: attrs.Ladle,
                        heat: attrs._HeatName,
                        curPositionId: attrs._LadlePositionID,
                        position: attrs.Position,
                    }),
                    template: this.templates.changePositionModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };
                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {   
                                app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                              
                            }
                        }
                        catch (e) {
                            if (that.autoRefresh.enabled == false)
                                that.startAutoRefresh();
                            console.error((e.stack) ? e.stack : new Error(e).stack);
                        }
                    });
                this.listenToOnce(this.currentModal, "finish", function (modal) {
                    try {
                        if (that.autoRefresh.enabled == false)
                            that.startAutoRefresh();
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                });
                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        changeMeltOrder: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.ChangeMeltOrderModal({
                    model: new Screen.Models.ChangeMeltOrderModal({
                        heat: attrs._HeatName,
                        curMeltOrder: attrs._MeltOrder,
                        curGrade: attrs._GradeName,
                        curDim: attrs._Dim,
                    }),
                    template: this.templates.changeMeltOrderModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };

                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {
                                app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });
                this.listenToOnce(this.currentModal, "finish", function (modal) {
                    try {
                        if (that.autoRefresh.enabled == false)
                            that.startAutoRefresh();
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                });
                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        changeHeatWeights: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();
                this.currentModal = new Screen.Views.ChangeHeatWeightsModal({
                    model: new Screen.Models.ChangeHeatWeightsModal({
                        heat: attrs._HeatName,
                        net: attrs._NetWeight,
                        tare: attrs._TareWeight,
                        alloy: attrs._AlloyWeight ? attrs._AlloyWeight : '-',
                    }),
                    template: this.templates.changeHeatWeightsModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };

                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {
                                app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });
                this.listenToOnce(this.currentModal, "finish", function (modal) {
                    try {
                        if (that.autoRefresh.enabled == false)
                            that.startAutoRefresh();
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                });
                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        assignHeat: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.AssignHeatModal({
                    model: new Screen.Models.AssignHeatModal({
                        ladle: attrs._LadleID,
                        heat: attrs._HeatName,
                    }),
                    template: this.templates.assignHeatModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };

                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {
                                app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });
                this.listenToOnce(this.currentModal, "finish", function (modal) {
                    try {
                        if (that.autoRefresh.enabled == false)
                            that.startAutoRefresh();
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                });
                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        returnLadle: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.ReturnLadleModal({
                    model: new Screen.Models.ReturnLadleModal({
                        heat: attrs._HeatName,
                        ladle: attrs._LadleID,
                        position: attrs.Position,
                    }),
                    template: this.templates.returnLadleModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };

                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {
                                app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });
                this.listenToOnce(this.currentModal, "finish", function (modal) {
                    try {
                        if (that.autoRefresh.enabled == false)
                            that.startAutoRefresh();
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                });
                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },

        reladle: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();
                this.currentModal = new Screen.Views.ReladleModal({
                    model: new Screen.Models.ReladleModal({
                        ladle: attrs._LadleID,
                        position: attrs.Position,
                        heat: attrs._HeatName,
                    }),
                    template: this.templates.reladleModal,
                    i18n: this.options.i18n[this.template],
                });

                var fn_modal_shown_hidden = function () {
                    try {
                        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                        //or it is not executed for some reason.
                        //clickedBtn.attr("disabled", false);
                    }
                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                };

                this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {
                                app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });
                this.listenToOnce(this.currentModal, "finish", function (modal) {
                    try {
                        if (that.autoRefresh.enabled == false)
                            that.startAutoRefresh();
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                });
                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },

    });

    Screen.Collections.TopGrid = Backbone.Collection.extend({
        setDataColl: function (data) {
            this.set(data);
        }
    });

    Screen.Collections.Grid = Backbone.Collection.extend({
            LadleMaintenancePositions: [70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84
                , 0, 24, 30, 40, 51, 52, 54], //Positions that are not Maintenance and are not on the screen

            LadleCastersPositions: [32, 33, 34, 35, 42, 43, 44, 45],

        setDataColl: function (data) {
            var newColl = [],
                attrs,
                that = this;

            _.each(data, function (obj) {
                if (obj._ShowInGrid == true) {

                    obj._heatsOnLining = obj._HeatsOnLining ? ('On Lining: ' + obj._HeatsOnLining) : '';
                    obj._showHeat = obj.Heat ? true : false;
                    obj._maintenancePosition = that.LadleMaintenancePositions.includes(obj._LadlePositionID);
                    obj._allowedLocations = obj._AllowedLocations ? obj._AllowedLocations.split(",") : null;
                    obj._dropContainerId = !obj._LadlePositionID ? null :
                        (
                            that.LadleCastersPositions.includes(obj._LadlePositionID) ? ("#" + 'pos' + obj._ScreenPositionID) //if LadlePosition Id is a caster position
                                : ("#" + 'pos' + obj._LadlePositionID) // if LadlePositionId is not a Caster Position
                        );
                    obj._dragId = obj._LadleID ? ("#" + 'ladle' + obj._LadleID) : null;
                    obj._heatName = obj._HeatName;
                    obj._EAFPosition = obj.Position === 'EAF A' || obj.Position === 'EAF B' ? true : false; 

                    newColl.push(obj);
                }
            });
            that.set(newColl);
        },
    });


    Screen.Collections.Positions = Backbone.Collection.extend({
        LadleMaintenancePositions: [70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84
                                    , 0, 24, 30, 40, 51, 52, 54], //Positions that are not Maintenance and are not on the screen

        LadleCastersPositions: [32, 33, 34, 35, 42, 43, 44, 45],

        setDataColl: function (data, grid) {
            var newColl,
                attrs,
                that = this;

            newColl = data;
            newColl2 = [];
            _.each(newColl, function (obj) {
                obj._heatsOnLining = obj._HeatsOnLining ? ('On Lining: ' + obj._HeatsOnLining) : '';
                obj._showHeat = obj.Heat ? true : false;
                obj._maintenancePosition = that.LadleMaintenancePositions.includes(obj._LadlePositionID);
                obj._allowedLocations = obj._AllowedLocations ? obj._AllowedLocations.split(",") : null;
                obj._dropContainerId = !obj._LadlePositionID ? null :
                    (
                        that.LadleCastersPositions.includes(obj._LadlePositionID) ? ("#" + 'pos' + obj._ScreenPositionID) //if LadlePosition Id is a caster position
                        : ("#" + 'pos' + obj._LadlePositionID) // if LadlePositionId is not a Caster Position
                    ); 
                obj._dragId = obj._LadleID ? ("#" + 'ladle' + obj._LadleID) : null;      
                obj._heatName = obj._HeatName;

                obj._LadleIDWidget = parseInt(obj._LadleID) < 10 ? '0' + obj._LadleID : obj._LadleID;
                obj._HeatNameWidget = obj._HeatName ? obj._HeatName : '-';
                obj._MeltOrderAndSizeWidget = obj._MeltOrderAndSize ? obj._MeltOrderAndSize.trim() : '-';
                obj._GradeNameWidget = obj._GradeName ? obj._GradeName.trim() : '-';
                obj._EAFPosition = obj.Position === 'EAF A' || obj.Position === 'EAF B' ? true : false;
                obj._NotAllowedLocation = obj._NotAllowedLocation ? obj._NotAllowedLocation : null;
                obj._PlateAssembly = obj._PlateAssembly ? obj._PlateAssembly : 0;
                obj._PlateAssemblyWarning = obj._PlateAssembly === 3 ? true : false;
                obj._PlateAssemblyDanger = obj._PlateAssembly > 3 ? true : false;

                if (grid && obj._HeatName) newColl2.push(obj);
            });


            if (grid) that.set(newColl2).trigger('fetch', that, data);
            else that.set(newColl).trigger('fetch', that, data);
        },

    });


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

        initialize: function (attr) {
            this.model = attr.model;
            var params = this.model.toJSON();
            if (params._maintenancePosition) {
                $(this.el).addClass('maintenance');
                $(this.el).attr("draggable", true);
                if (params._heatName) {
                    $(this.el).css("background-color", "#ed5656"); 
                    $(this.el).attr('title', params._heatName);
                }
            } 


            $(this.el).attr("id", 'ladle' + params._LadleID);

            this.render();
        },

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

    });

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


    Screen.Collections.Attributes = Backbone.Collection.extend({

        setDataColl: function (data2) {
            var newColl = [],
                attrs = [],
                that = this,
                _attrs1 = null,
                _attrs2 = null,
                _attrs3 = null,
                _attrs4 = null,
                _attrs5 = null,
                _heatName = null,
                _show_attrs1 = false,
                _show_attrs2 = false,
                _show_attrs3 = false,
                _show_attrs4 = false,
                _show_attrs5 = false,
                _show_heatName = false,

                _warning_attrs1 = false,
                _warning_attrs2 = false,
                _warning_attrs3 = false,
                _warning_attrs4 = false,
                _warning_attrs5 = false;

            var group = _.groupBy(data2, 'LadlePositionID');
            var counter = 0;
            _.each(group, function (obj) {
                
                _attrs1 = null;
                _attrs2 = null;
                _attrs3 = null;
                _attrs4 = null;
                _attrs5 = null;
                _heatName = null;
                _show_attrs1 = false;
                _show_attrs2 = false;
                _show_attrs3 = false;
                _show_attrs4 = false;
                _show_attrs5 = false;
                _show_heatName = false;


                _warning_attrs1 = false;
                _warning_attrs2 = false;
                _warning_attrs3 = false;
                _warning_attrs4 = false;
                _warning_attrs5 = false;

                _.each(obj, function (attr, i) {
                    counter = i;
                    if (attr.Name == 'HeatNumber') {
                        _show_heatName = true;
                        _heatName = attr.Value;
                        
                    } else {
                        if (counter == 0) {
                            if (attr.Name == 'WARNING') {
                                _attrs1 = attr.Value;
                                _warning_attrs1 = true;
                            } else {
                                _attrs1 = attr.Name + ': ' + attr.Value;
                            }
                            _show_attrs1 = true;
                            
                        }
                        if (counter == 1) {
                            if (attr.Name == 'WARNING') {
                                _attrs2 = attr.Value;
                                _warning_attrs2 = true;
                            } else {
                                _attrs2 = attr.Name + ': ' + attr.Value;
                            }
                            _show_attrs2 = true;
                        }
                        if (counter == 2) {
                            if (attr.Name == 'WARNING') {
                                _attrs3 = attr.Value;
                                _warning_attrs3 = true;
                            } else {
                                _attrs3 = attr.Name + ': ' + attr.Value;
                            }
                            _show_attrs3 = true;
                        }
                        if (counter == 3) {
                            if (attr.Name == 'WARNING') {
                                _attrs4 = attr.Value;
                                _warning_attrs4 = true;
                            } else {
                                _attrs4 = attr.Name + ': ' + attr.Value;
                            }
                            _show_attrs4 = true;
                        }
                        if (counter == 4) {
                            if (attr.Name == 'WARNING') {
                                _attrs5 = attr.Value;
                                _warning_attrs5 = true;
                            } else {
                                _attrs5 = attr.Name + ': ' + attr.Value;
                            }
                            _show_attrs5 = true;
                        }
                    }
                });

                newColl.push({
                    _attrs1: _attrs1,
                    _attrs2: _attrs2,
                    _attrs3: _attrs3,
                    _attrs4: _attrs4,
                    _attrs5: _attrs5,
                    _show_attrs1: _show_attrs1,
                    _show_attrs2: _show_attrs2,
                    _show_attrs3: _show_attrs3,
                    _show_attrs4: _show_attrs4,
                    _show_attrs5: _show_attrs5,
                    _show_heatName: _show_heatName,
                    _heatName: _heatName,
                    LadlePositionID: obj[0].LadlePositionID,
                    containerId: obj[0].LadlePositionID ? ("#" + 'pos' + obj[0].LadlePositionID) : null, 
                    elementId: obj[0].LadlePositionID ? ("#" + 'attr' + obj[0].LadlePositionID) : null,

                    _warning_attrs1 : _warning_attrs1,
                    _warning_attrs2 : _warning_attrs2,
                    _warning_attrs3 : _warning_attrs3,
                    _warning_attrs4 : _warning_attrs4,
                    _warning_attrs5 : _warning_attrs5,
                })
            });
            that.set(newColl).trigger('fetch', that, data2);
        },
    });
    Screen.Views.Attributes = Backbone.Epoxy.View.extend({
        tagName: 'div',
        className:'pointer-events-none',
        initialize: function (attr) {
            this.model = attr.model;
            var params = this.model.toJSON();

            $(this.el).attr("id", 'attr' + params.LadlePositionID);

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


    Screen.Models.ConfirmationModalMain = Backbone.Epoxy.Model.extend({
        defaults: {
            errorMsg: '',
            title: '',
            processing: false,
        },
        computeds: {
        },

    });
    Screen.Views.ConfirmationModalMain = Backbone.Epoxy.View.extend({
        template: "melt-shop-overview",
        id: "confirmation-modal",
        className: "modal hide fade",
        bindings: "data-bind",
        isCacheable: true,
        events: function () {
            return {
                "click #acceptBtnClick": 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,

        initialize: function (options) {
            _.extend(this, options);
            if (!this.model) {
                this.model = new Screen.Models.ConfirmationModalMain();
            }

            this.bus = options.bus;
            this.model.set({
                title: "Error: Position out of service",
                errorMsg: '',
                processing: false,
            })
            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, "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 params = this.model.toJSON();
                //this.bus.trigger("modalAcceptBtn", params);

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

    });


    //-------------------------------------------------------------------------------------------------------------
    //----------------------------------------- Contextual Menu Collections -----------------------------------------
    //-------------------------------------------------------------------------------------------------------------

    // Ladle Dashboard
    Screen.Models.ChangePositionModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            position: null,
            curPositionId: null,
            newPositionId: null,

            positions: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasPositions: {
                deps: ['positions'],
                get: function (positions) {
                    return positions.length != 0;
                },
            },
        },
        fetchPositions: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailablePositions', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadlePositions",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Name, }; });

                                that.set("positions", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

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

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

            qp.Add('@GodMode', 'BIT', true);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.ChangeLadlePositionWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ChangePositionModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' change-position-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchPositions();

            this.bindEvents();

            return this;
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);
                try {
                    this.model.save({
                        params: [
                            { Name: '@ladleId', Type: 'INT', Value: attrs.ladle, },
                            { Name: '@ladlePositionId', Type: 'INT', Value: attrs.newPositionId, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();
            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    Screen.Models.ChangeMeltOrderModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            heat: null,
            curMeltOrder: null,
            curGrade: null,
            curDim: null,
            newMeltOrder: null,
            newGrade: null,
            newDim: null,
            meltOrderSequence: '1',
            comments: '',

            meltOrders: [],
            grades: [],
            dims: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasMeltOrders: {
                deps: ['meltOrders'],
                get: function (meltOrders) {
                    return meltOrders.length != 0;
                },
            },
        },
        fetchMeltOrders: function () {
            var that = this;

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetMeltOrders",
                null,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;
                                var meltOrders = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });
                                var grades = _.map(records, function (obj) { return { value: obj.Id, label: obj.Grade, }; });
                                var dims = _.map(records, function (obj) { return { value: obj.Id, label: obj.Dim, }; });

                                that.set("meltOrders", meltOrders);
                                that.set("grades", grades);
                                that.set("dims", dims);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        save: function (options) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                opt = _.extend({
                    async: true,
                }, options);
            _.each(opt.params, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.AssignMeltOrderToHeatWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ChangeMeltOrderModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' change-melt-order-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchMeltOrders();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #changeMeltOrderSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
            this.listenTo(this.model, "change:newMeltOrder", this.model_change_newMeltOrder);
        },

        model_change_newMeltOrder: function () {
            var that = this;

            this.model.set('newGrade', (_.find(this.model.get('grades'), function (grade) { return grade.value == that.model.get('newMeltOrder'); })).label);
            this.model.set('newDim', (_.find(this.model.get('dims'), function (dim) { return dim.value == that.model.get('newMeltOrder'); })).label);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);
                try {
                    this.model.save({
                        params: [
                            { Name: '@heatNumber', Type: 'VARCHAR', Value: attrs.heat, },
                            { Name: '@meltOrderNumber', Type: 'VARCHAR', Value: attrs.newMeltOrder, },
                            { Name: '@meltOrderSequence', Type: 'INT', Value: parseInt(attrs.meltOrderSequence), },
                            { Name: '@comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    Screen.Models.ChangeHeatWeightsModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            heat: null,
            net: null,
            tare: null,

            errorMsg: "",
            processing: false,
        },
        computeds: {
        },
        save: function (options) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                opt = _.extend({
                    async: true,
                }, options);

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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.UpsertHeatTareAndGrossWeightsWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ChangeHeatWeightsModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' change-heat-weights-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #changeHeatWeightsSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);
                try {
                    this.model.save({
                        params: [
                            { Name: '@HeatNumber', Type: 'VARCHAR', Value: attrs.heat, },
                            { Name: '@NetWeight', Type: 'FLOAT', Value: attrs.net, },
                            { Name: '@TareWeight', Type: 'FLOAT', Value: attrs.tare, },                         
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    Screen.Models.AssignHeatModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            newHeat: null,

            heats: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasHeats: {
                deps: ['heats'],
                get: function (heats) {
                    return heats.length != 0;
                },
            },
        },
        fetchHeats: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailableHeats', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetHeats",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });

                                that.set("heats", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

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

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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.AssignHeatToLadleWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.AssignHeatModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' assign-heat-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchHeats();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #assignHeatToLadleSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                            { Name: '@ladleId', Type: 'INT', Value: attrs.ladle, },
                            { Name: '@heatNumber', Type: 'VARCHAR', Value: attrs.newHeat, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    Screen.Models.ReturnLadleModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            position: null,
            newPosition: null,
            comments: '',

            positions: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasPositions: {
                deps: ['positions'],
                get: function (positions) {
                    return positions.length != 0;
                },
            },
        },
        fetchPositions: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailablePositions', 'BIT', 1);
            qp.Add('@onlyAvailableDestinations', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadlePositions",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Name, }; });

                                that.set("positions", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

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

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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.ReturnLadleWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ReturnLadleModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' return-ladle-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchPositions();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #returnLadleSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                            { Name: '@ladleId', Type: 'VARCHAR', Value: attrs.ladle, },
                            { Name: '@ladlePositionId', Type: 'VARCHAR', Value: attrs.newPosition, },
                            { Name: '@comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    Screen.Models.ReladleModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            position: null,
            newLadle: null,
            comments: '',

            ladles: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasLadles: {
                deps: ['ladles'],
                get: function (ladles) {
                    return ladles.length != 0;
                },
            },
        },
        fetchLadles: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailableLadles', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadles",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });

                                that.set("ladles", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

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

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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.ReladleWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ReladleModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' reladle-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchLadles();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #reladleSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                            { Name: '@oldLadleId', Type: 'VARCHAR', Value: attrs.ladle, },
                            { Name: '@newLadleId', Type: 'VARCHAR', Value: attrs.newLadle, },
                            { Name: '@comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    //--------------------------------------//
    //------------ SPLIT HEAT --------------//
    //--------------------------------------//
    Screen.Models.SplitHeatModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            toLadle: 1,
            heat: null,

            ladles: [],
            comments: '',
            errorMsg: "",
            processing: false,

            weight: null,
        },
        computeds: {
            hasLadles: {
                deps: ['ladles'],
                get: function (ladles) {
                    return ladles.length != 0;
                },
            },
        },
        fetchLadles: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailableLadles', 'BIT', 0);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadles",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });

                                that.set("ladles", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },

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

            _.each(opt.params, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.SplitHeat',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });
    Screen.Views.SplitHeatModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' split-heat-modal-melt-shop-overview',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchLadles();

            this.bindEvents();

            return this;
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();
            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                            { Name: '@LadleID1', Type: 'INT', Value: attrs.ladle, },
                            { Name: '@LadleID2', Type: 'INT', Value: attrs.toLadle, },
                            { Name: '@Weight', Type: 'FLOAT', Value: attrs.weight, },
                            { Name: '@Comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });




     //--------------------------------------//
    //------------ NON FREE OPEN --------------//
    //--------------------------------------//
    Screen.Models.NonFreeOpenModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            rods: 0,
            quickShroudOptions: [{value:'YES',label:'YES'},{value:'NO',label:'NO'}],   
            quickShroud: 'YES',        
            isNonFreeOpen: false,
            comments: '',
            errorMsg: "",
            processing: false,


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

            _.each(opt.params, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAS.DeclareNonFreeOpen',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                if (opt.success)
                                    opt.success(that, resp.Table[0]);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                    ? resp.Message
                                    : 'SERVER_RESPONSE_NOT_valid';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(that, errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (opt.error)
                                opt.error(that, errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });
    Screen.Views.NonFreeOpenModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' non-free-open-modal-melt-shop-overview',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.bindEvents();

            return this;
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();
            if (attrs.processing == false) {
                this.model.set('processing', true);
            
                try {
                    this.model.save({
                        params: [
                            { Name: '@LadleId', Type: 'INT', Value: attrs.ladle, },
                            { Name: '@PositionId', Type: 'INT', Value: attrs.curPositionId, },
                            { Name: '@Rods', Type: 'INT', Value: attrs.rods, },
                            { Name: '@HeatName', Type: 'VARCHAR', Value: attrs.heat, },
                            { Name: '@QuickShroud', Type: 'BIT', Value: attrs.quickShroud === 'YES' ? 1 : 0, },
                            { Name: '@isNonFreeOpen', Type: 'BIT', Value: attrs.isNonFreeOpen, },                            
                            { Name: '@Comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                that.finish({ result: 'SUCCESS', data: resp });

                                that.hide();
                                //setTimeout(_.bind(that.hide, that), 1500);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                    });
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

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