//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',
    'chart',
    'moment',
    'chartjs-date-fns-adapter',
    'modules/navigation-buttons/navigation-buttons',
    'backgrid/moment-cell',
    'js/autocomplete/backbone.autocomplete',
    'backgrid/grouped-columns',
    'js/multiselect/virtual-select.min',

],
    function (app, T, Backgrid, ChartJS, moment, ChartJsDateFnsAdapter, NavigationButton) {

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


        Screen.Models.SecondaryInfo1 = Backbone.Epoxy.Model.extend({
            defaults: {
                regulationModeName: null,
                burnerProgram: null,
                powerProgram: null,
                electrode1Changed: false,
                electrode2Changed: false,
                electrode3Changed: false,
                yield: false,
                tapWeight: null,
                tapAndDrainWeight: null,
                regulation_burner_power: null,
                electrodes_changes: false,
            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    var regulationModeName = obj.RegulationModeName ? obj.RegulationModeName : '-';
                    var burnerProgram = obj.BurnerProgram ? obj.BurnerProgram : '-';
                    var powerProgram = obj.PowerProgram ? obj.PowerProgram : '-';

                    var TapAndDrainWeight = (obj.SteelWeight ? obj.SteelWeight.toFixed(2) : '-') + ' | ' + (obj.DrainWeight ? obj.DrainWeight.toFixed(2) : '-');

                    this.set({

                        electrode1Changed: obj.Electrode1Changed ? obj.Electrode1Changed : false,
                        electrode2Changed: obj.Electrode2Changed ? obj.Electrode2Changed : false,
                        electrode3Changed: obj.Electrode3Changed ? obj.Electrode3Changed : false,
                        yield: obj.Yield ? obj.Yield.toFixed(2) : '-',
                        tapWeight: obj.SteelWeight ? obj.SteelWeight : '-',
                        tapAndDrainWeight: TapAndDrainWeight,

                        regulation_burner_power: `${regulationModeName} | ${burnerProgram} | ${powerProgram}`

                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });
        Screen.Models.SecondaryInfo2 = Backbone.Epoxy.Model.extend({
            defaults: {
                powerOn: null,
                powerOff: null,
                tapToTap: null,
                ncc1: null,
                ncc2: null,
                ncc3: null,
                caveIn1: null,
                caveIn2: null,
                caveIn3: null,
                nccs: null,
                caves: null,
                PhaseSprayRingEffectiveness: null,
                BypassBreakerUtilization: null,
                ConditionsBypassBreakerMaintained: null,
            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    var ncc1 = obj.NCC1 ? obj.NCC1 : '-';
                    var ncc2 = obj.NCC2 ? obj.NCC2 : '-';
                    var ncc3 = obj.NCC3 ? obj.NCC3 : '-';
                    var caveIn1 = obj.CaveIn1 ? obj.CaveIn1 : '-';
                    var caveIn2 = obj.CaveIn2 ? obj.CaveIn2 : '-';
                    var caveIn3 = obj.CaveIn3 ? obj.CaveIn3 : '-';

                    this.set({
                        powerOn: obj.PowerOn ? obj.PowerOn : '-',
                        powerOff: obj.PowerOff ? obj.PowerOff : '-',
                        tapToTap: obj.TapToTap ? obj.TapToTap : '-',

                        PhaseSprayRingEffectiveness: `${obj.APhaseSprayRingEffectiveness ? obj.APhaseSprayRingEffectiveness : '-'} | ${obj.BPhaseSprayRingEffectiveness ? obj.BPhaseSprayRingEffectiveness : '-'} | ${obj.CPhaseSprayRingEffectiveness ? obj.CPhaseSprayRingEffectiveness : '-'}`,
                        BypassBreakerUtilization: obj.BypassBreakerUtilization ? obj.BypassBreakerUtilization : '-',
                        ConditionsBypassBreakerMaintained: obj.ConditionsBypassBreakerMaintained ? obj.ConditionsBypassBreakerMaintained : '-',

                        nccs: `${ncc1} | ${ncc2} | ${ncc3}`,
                        caves: `${caveIn1} | ${caveIn2} | ${caveIn3}`,
                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });
        Screen.Models.HeatReportMainData = Backbone.Epoxy.Model.extend({
            defaults: {
                heatName: null,
                meltOrder: null,
                date: null,
                shift: null,
                crew: null,
                start: null,
                end: null,
                energy: null,
                gradeName: null,
                ladleName: null,
                headerInfo: null,
                pourbackInfo: null,
                kwhton: null,
                electrode1: null,
                electrode2: null,
                electrode3: null,
                heatsOnTapHole: null,
                heatsOnDelta: null,

            },
            setDataModel: function (model, pourback) {
                if (model && model[0]) {
                    var obj = model[0];
                    var shift = obj.ShiftId === 1 ? 'Day' : 'Night';
                    this.set({
                        heatName: obj.HeatName ? obj.HeatName : '-',
                        treatment: obj.TreatmentCurrentAndTotal ? obj.TreatmentCurrentAndTotal : '-',
                        meltOrder: obj.MeltOrder ? obj.MeltOrder : '-',
                        date: obj.StartLocal ? new moment(obj.StartLocal).format('MM/DD/YYYY') : '-',
                        shift: obj.ShiftId === 1 ? 'D / ' + obj.CrewId : 'N / ' + obj.CrewId,
                        crew: obj.CrewId ? obj.CrewId : '-',
                        start: obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : null,
                        end: obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : null,
                        energy: obj.Energy ? obj.Energy.toFixed(2) : '-',
                        gradeName: obj.GradeName ? obj.GradeName : '-',
                        ladleName: obj.LadleName ? obj.LadleName : '-',
                        headerInfo: `Heat: ${obj.HeatName ? obj.HeatName : ''} | Furnace ${obj.FurnaceCode === 1 ? '1' : '2'} | Date: ${obj.StartLocal ? new moment(obj.StartLocal).format('MM/DD/YYYY') : ''} | Shift: ${shift} | Crew: ${obj.CrewId ? obj.CrewId : obj.CrewId} | Start : ${obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : ''} | End: ${obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : ''} | Grade: ${obj.GradeName ? obj.GradeName : ''} | Ladle: ${obj.LadleName ? obj.LadleName : ''}`,
                        kwhton: obj.KwhTon ? obj.KwhTon.toFixed(2) : '-',

                        electrode1: obj.Electrode1 ? obj.Electrode1 + ' | ' : '- |',
                        electrode2: obj.Electrode2 ? obj.Electrode2 + ' | ' : '- |',
                        electrode3: obj.Electrode3 ? obj.Electrode3 : '-',
                        heatsOnTapHole: obj.HeatsOnTapHole ? obj.HeatsOnTapHole : '-',
                        heatsOnDelta: obj.HeatsOnDelta ? obj.HeatsOnDelta : '-',
                    }).trigger('fetch', this, obj);


                    if (pourback && pourback[0]) {
                        var p = pourback[0];
                        this.set({
                            pourbackInfo: `From ${p.HeatName} | Weight: ${p.Weight}  | Timestamp: ${new moment(p.Timestamp).format('HH:mm')}`
                        })
                    } else {
                        this.set({
                            pourbackInfo: null,

                        })
                    }

                }

                else this.trigger('fetch', this, model);
            },
        });



        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                furnaceCodes: [{ label: 'A', value: 1 }, { label: 'B', value: 2 }],
                furnaceCode: 1,

                //URL parameters

                hasData_process: false,
                isLoading_process: false,

                hasData_phases: false,
                isLoading_phases: false,

                hasData_buckets: false,
                isLoading_buckets: false,

                hasData_temperatures: false,
                isLoading_temperatures: false,

                hasData_alloys: false,
                isLoading_alloys: false,


                hasData_slagChemistries: false,
                isLoading_slagChemistries: false,

                hasData_consumptions: false,
                isLoading_consumptions: false,

                hasData_injectors: false,
                isLoading_injectors: false,


                hasData_pourback: false,
                isLoading_pourback: false,

                pouredbackLegend: 'Test',
                hasData_pouredbackLegend: false,

                processId: null,
                heatId: null,
                direction: null,
                navigation: null,
                enterPress: false,
                changeEAF: false,


                Structural_MgOMin: null,
                Structural_MgOMax: null,
                Structural_FeOMin: null,
                Structural_FeOMax: null,
                Structural_B3Min: null,
                Structural_B3Max: null,

                Rail_MgOMin: null,
                Rail_MgOMax: null,
                Rail_FeOMin: null,
                Rail_FeOMax: null,
                Rail_B3Min: null,
                Rail_B3Max: null,





                heatName: null,
                heatNames: [],
            },
            computeds: {
                hasData: {
                    deps: ['hasData_process'],
                    get: function (process) {
                        return process;
                    },
                },
                isLoading: {
                    deps: ['isLoading_process'],
                    get: function (process) {
                        return process;
                    },
                },
                Structural_MgO: {
                    deps: ['Structural_MgOMin', 'Structural_MgOMax'],
                    get: function (min, max) {
                        if (min && max) return min + '% ' + 'to ' + max + '%'
                        else return ''
                    },
                },
                Rail_MgO: {
                    deps: ['Rail_MgOMin', 'Rail_MgOMax'],
                    get: function (min, max) {
                        if (min && max) return min + '% ' + 'to ' + max + '%'
                        else return ''
                    },
                },
                Structural_FeO: {
                    deps: ['Structural_FeOMin', 'Structural_FeOMax'],
                    get: function (min, max) {
                        if (min && max) return min + '% ' + 'to ' + max + '%'
                        else return ''
                    },
                },
                Rail_FeO: {
                    deps: ['Rail_FeOMin', 'Rail_FeOMax'],
                    get: function (min, max) {
                        if (min && max) return min + '% ' + 'to ' + max + '%'
                        else return ''
                    },
                },

                Structural_B3: {
                    deps: ['Structural_B3Min', 'Structural_B3Max'],
                    get: function (min, max) {
                        if (min && max) return min + ' to ' + max
                        else return ''
                    },
                },
                Rail_B3: {
                    deps: ['Rail_B3Min', 'Rail_B3Max'],
                    get: function (min, max) {
                        if (min && max) return min + ' to ' + max
                        else return ''
                    },
                },
            },
            initialize: function () {

                this.mainData = new Screen.Models.HeatReportMainData();
                this.secondaryData1 = new Screen.Models.SecondaryInfo1();
                this.secondaryData2 = new Screen.Models.SecondaryInfo2();

                this.process = new Screen.Models.Process();
                this.phases = new Screen.Collections.PhasesColl();
                this.buckets = new Screen.Collections.BucketsColl();
                this.temperatures = new Screen.Collections.TemperaturesColl();
                this.alloys = new Screen.Collections.AlloysColl();
                this.slagChemistries = new Screen.Collections.SlagChemistriesColl();
                this.consumptions = new Screen.Collections.ConsumptionsColl();
                this.injectors = new Screen.Collections.InjectorsColl();
                this.pourback = new Screen.Collections.PourbackColl();
            },
            fetchNavigateHeat: function (params) {
                var qp = new Core.Database.QueryParameters();
                var that = this;
                qp.Add('@heatName', 'VARCHAR(10)', that.get('heatName'));
                qp.Add('@direction', 'SMALLINT', params.direction);
                qp.Add('@Asset', 'CHAR(3)', 'EAF');

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetNavigatedHeat',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table && resp.Table[0] && resp.Table[0].HeatName && resp.Table[0].HeatName !== '') {
                                    that.set({
                                        heatName: resp.Table[0].HeatName,
                                        heatNames: [{
                                            value: resp.Table[0].HeatName,
                                            label: resp.Table[0].HeatName
                                        }],
                                    });
                                    that.trigger('heat-name-changed');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                        });
                                    }

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            fetchCatalogs: function () {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', that.get('heatName'));
                qp.Add('@Asset', 'CHAR(3)', 'EAF');

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    that.set({
                                        heatNames: resp.Table,
                                        heatName: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                        processId: resp.Table[0] && resp.Table[0].processId ? resp.Table[0].processId : null,
                                    });
                                    that.trigger('catalogs-fetched');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,


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

                                }


                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
            fetch: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@heatName', 'VARCHAR', that.get('heatName'));
                qp.Add('@timeZoneCode', 'CHAR(10)', app.models.user.get('timezoneCode'));

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

                                if (resp && resp.Table) {
                                    that.set({
                                        processId: resp.Table[0].Id,
                                    })
                                    if (resp.Table) that.mainData.setDataModel(resp.Table, resp.Table10); // resp.Table10 --> Pourback
                                    if (resp.Table) that.secondaryData1.setDataModel(resp.Table);
                                    if (resp.Table) that.secondaryData2.setDataModel(resp.Table);
                                    if (resp.Table) that.process.setDataModel(resp.Table); // remove in the next refactor
                                    if (resp.Table1) that.phases.setDataColl(resp.Table1);
                                    if (resp.Table2) that.buckets.setDataColl(resp.Table2);
                                    if (resp.Table3) that.temperatures.setDataColl(resp.Table3);
                                    if (resp.Table4) that.slagChemistries.setDataColl(resp.Table4);
                                    if (resp.Table5) that.consumptions.setDataColl(resp.Table5);
                                    if (resp.Table6) that.injectors.setDataColl(resp.Table6);
                                    if (resp.Table7) that.alloys.setDataColl(resp.Table7);

                                    if (resp.Table9) {
                                        _.each(resp.Table9, function (obj) {
                                            switch (obj.Name) {
                                                case 'Structural':
                                                    switch (obj.Code) {
                                                        case 'SLAG_B3_MAX_LIMIT':
                                                            that.set('Structural_B3Max', obj.Value);
                                                            break;
                                                        case 'SLAG_B3_MIN_LIMIT':
                                                            that.set('Structural_B3Min', obj.Value);
                                                            break;
                                                        case 'SLAG_FeO_MAX_LIMIT':
                                                            that.set('Structural_FeOMax', obj.Value);
                                                            break;
                                                        case 'SLAG_FeO_MIN_LIMIT':
                                                            that.set('Structural_FeOMin', obj.Value);
                                                            break;
                                                        case 'SLAG_MgO_MAX_LIMIT':
                                                            that.set('Structural_MgOMax', obj.Value);
                                                            break;
                                                        case 'SLAG_MgO_MIN_LIMIT':
                                                            that.set('Structural_MgOMin', obj.Value);
                                                            break;
                                                        default:
                                                            break;
                                                    }
                                                    break;
                                                case 'Rail':
                                                    switch (obj.Code) {
                                                        case 'SLAG_B3_MAX_LIMIT':
                                                            that.set('Rail_B3Max', obj.Value);
                                                            break;
                                                        case 'SLAG_B3_MIN_LIMIT':
                                                            that.set('Rail_B3Min', obj.Value);
                                                            break;
                                                        case 'SLAG_FeO_MAX_LIMIT':
                                                            that.set('Rail_FeOMax', obj.Value);
                                                            break;
                                                        case 'SLAG_FeO_MIN_LIMIT':
                                                            that.set('Rail_FeOMin', obj.Value);
                                                            break;
                                                        case 'SLAG_MgO_MAX_LIMIT':
                                                            that.set('Rail_MgOMax', obj.Value);
                                                            break;
                                                        case 'SLAG_MgO_MIN_LIMIT':
                                                            that.set('Rail_MgOMin', obj.Value);
                                                            break;
                                                        default:
                                                            break;
                                                    }
                                                    break;
                                            }
                                        });
                                    }
                                    if (resp.Table10) that.pourback.setDataColl(resp.Table10);
                                    if (resp.Table11 && resp.Table11.length > 0) {
                                        var pouredBackData = resp.Table11[0];
                                        that.set({
                                            pouredbackLegend: 'This heat was poured back into heat ' + pouredBackData.HeatName
                                                + ' on ' + new moment(pouredBackData.Timestamp).format('MM/DD/YYYY HH:mm:ss')
                                                + ' , Total ' + pouredBackData.Weight + ' tons.',
                                            hasData_pouredbackLegend: true,
                                        });
                                    }

                                    if (resp.Table8) that.trigger('fetch-nav-buttons', resp.Table8);


                                    if (resp.Table12) that.trigger('chart-data-ready', resp.Table12, resp.Table13);


                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                            hasData_phases: false,
                                            isLoading_phases: false,
                                            hasData_buckets: false,
                                            isLoading_buckets: false,
                                            hasData_temperatures: false,
                                            isLoading_temperatures: false,
                                            hasData_alloys: false,
                                            isLoading_alloys: false,
                                            hasData_slagChemistries: false,
                                            isLoading_slagChemistries: false,
                                            hasData_consumptions: false,
                                            isLoading_consumptions: false,
                                            hasData_injectors: false,
                                            isLoading_injectors: false,
                                            hasData_pourback: false,
                                            isLoading_pourback: false,
                                            hasData_pouredbackLegend: false,

                                        });
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData_process: false,
                                            isLoading_process: false,
                                            hasData_phases: false,
                                            isLoading_phases: false,
                                            hasData_buckets: false,
                                            isLoading_buckets: false,
                                            hasData_temperatures: false,
                                            isLoading_temperatures: false,
                                            hasData_alloys: false,
                                            isLoading_alloys: false,
                                            hasData_slagChemistries: false,
                                            isLoading_slagChemistries: false,
                                            hasData_consumptions: false,
                                            isLoading_consumptions: false,
                                            hasData_injectors: false,
                                            isLoading_injectors: false,
                                            hasData_pourback: false,
                                            isLoading_pourback: false,
                                            hasData_pouredbackLegend: false,

                                        });
                                    }

                                }


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

                return this;

            },
        });

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

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'eaf-heat-report',
            id: 'eaf-heat-report',
            title: 'EAF Heat Report',
            isCacheable: false,
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #printBtn': this.printBtn_click,
                    'click #backNavBtn': this.heatNavigationBtn_click,
                    'click #forwardNavBtn': this.heatNavigationBtn_click,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,

            process: null,

            phases: null,
            phaseChartView: null,
            autoCompleteCollection: null,
            autocompleteView: null,

            NavigationButtonView: null,

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

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

                this.NavigationButtonView = new NavigationButton.Views.Main();

                this.bindingSources = {
                    process: that.model.process,
                    phases: that.model.phases,
                    mainData: that.model.mainData,
                    secondaryData1: that.model.secondaryData1,
                    secondaryData2: that.model.secondaryData2,
                };


                this.bindEvents();

            },
            bindEvents: function () {
                this.listenTo(this.model.process, 'fetch', this.process_fetched);
                this.listenTo(this.model.phases, 'fetch', this.phases_fetched);
                this.listenTo(this.model.buckets, 'fetch', this.buckets_fetched);
                this.listenTo(this.model, 'fetch-nav-buttons', this.fetchnavbuttons);
                this.listenTo(this.model.temperatures, 'fetch', this.temperatures_fetched);
                this.listenTo(this.model.alloys, 'fetch', this.alloys_fetched);
                this.listenTo(this.model.slagChemistries, 'fetch', this.slagChemistries_fetched);
                this.listenTo(this.model.consumptions, 'fetch', this.consumptions_fetched);
                this.listenTo(this.model.injectors, 'fetch', this.injectors_fetched);
                this.listenTo(this.model.pourback, 'fetch', this.pourback_fetched);
                this.listenTo(this.model, 'heat-name-changed', this.heatNameChanged);
                this.listenTo(this.model, 'catalogs-fetched', this.catalogsFetched);
                this.listenTo(this.model, 'fetch-nav-buttons', this.fetchnavbuttons);

                this.listenTo(this.model, 'chart-data-ready', this.buildChart);
            },
            catalogsFetched: function () {
                this.UpdateURL();
            },

            fetchnavbuttons: function (resp) {
                this.NavigationButtonView.setDataColl(resp);
            },
            heatNameChanged: function () {
                const value = this.model.get('heatName');
                const options = this.model.get('heatNames');
                document.querySelector('#heat-picker-multi-select').setOptions(options);
                document.querySelector('#heat-picker-multi-select').setValue(value);
                this.UpdateURL();
                this.refresh();
            },
            printBtn_click: function () {
                window.print();
                return false;
            },
            heatNavigationBtn_click: function (e) {
                const { id } = e.target;
                const direction = id === 'backNavBtn' ? -1 : 1;
                this.model.fetchNavigateHeat({
                    direction
                });

            },

            buildChart: function (names, all) {
                var ctx = document.getElementById('EAFChart').getContext('2d');
                var datasets = [];
                var scales = {};
                var position = 'left';
                var radius = 1;
                var type = 'line';
                var pointStyle = 'circle';
                var displayLegend = true;
                var displayLegendByType = true;
                if (this.chart) {
                    this.chart.destroy();
                };
                _.each(names, function (obj, i) {
                    if (obj.isEvent == true) {
                        radius = 5
                        type = 'bubble';
                        displayLegendByType = false;
                        pointStyle = 'triangle';
                    }
                    else {
                        radius = 1;
                        type = 'line';
                        displayLegendByType = true;
                        pointStyle = 'circle';
                    }
                    displayLegend = names[i].ShowYAxis != null ? names[i].ShowYAxis : displayLegendByType;
                    datasets.push({
                        label: obj.Name,
                        data: _.where(all, { Name: obj.Name }),
                        fill: false,
                        yAxisID: 'y' + i,
                        borderColor: obj.Color,
                        backgroundColor: obj.FillColor,
                        tension: 0.1,
                        borderWidth: 1,
                        radius: radius,
                        type: type,
                        pointStyle: pointStyle,

                    })
                    //position = i % 2 == 0 ? 'left' : 'right';
                    position = names[i].YAxisPosition ? names[i].YAxisPosition.replaceAll(/\s/g, '') : 'left';
                    if (i === 0) {
                        scales['x'] = {
                            type: 'time',
                            ticks: {
                                maxTicksLimit: 16,
                                autoSkip: true,
                                maxRotation: 0,
                                minRotation: 0
                            },
                        };
                        scales['y' + i] = {
                            type: 'linear',
                            position: position,
                            min: names[i].MinValue,
                            max: names[i].MaxValue,
                            display: true,
                            ticks: {
                                color: names[i].Color,
                                callback: function (value, index, values) {
                                    if (obj.UnitName) {
                                        return value + ' ' + obj.UnitName
                                    } else
                                        return value;
                                },

                            }
                        };

                    } else {
                        scales['y' + i] = {
                            type: 'linear',
                            position: position,
                            min: names[i].MinValue,
                            max: names[i].MaxValue,
                            display: displayLegend,
                            ticks: {
                                color: names[i].Color,
                                callback: function (value, index, values) {
                                    if (obj.UnitName) {
                                        return value + ' ' + obj.UnitName
                                    } else
                                        return value;
                                },
                            },
                            grid: {
                                drawOnChartArea: false, // only want the grid lines for one axis to show up
                            },

                        };
                    }
                });
                var pluginLabels = {
                    id: 'plugin_labels',
                    afterDatasetsDraw: (chart, args, options) => {
                        var { ctx } = chart;
                        ctx.save();
                        ctx.font = '12px sans-serif';
                        for (let x = 0; x < chart.config.data.datasets.length; x++) {
                            if (chart.config.data.datasets[x].type === 'bubble') {

                                for (let i = 0; i < chart.config.data.datasets[x].data.length; i++) {
                                    if (chart.config.data.datasets[x].data[i].isEvent === true) {
                                        let textWidth = ctx.measureText(chart.config.data.datasets[x].data[i].EventDescription).width;
                                        let text = chart.config.data.datasets[x].data[i].EventDescription;
                                        ctx.fillText(text, chart.getDatasetMeta(x).data[i].x - (textWidth / 2), chart.getDatasetMeta(x).data[i].y - 10);
                                    }
                                }
                            }

                        }
                        ctx.restore();
                    },

                }
                this.chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        spanGaps: true,
                        plugins: {
                            title: {
                                display: true,
                            },
                        },
                        scales: scales,

                    },
                    plugins: [pluginLabels],
                });



            },

            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.phaseChartView = Backbone.Epoxy.View.extend({
                                    template: Handlebars.compile(that.$el.find('#phase_chart_view').html()),
                                    initialize: function () {
                                        this.render();
                                    },
                                    render: function () {
                                        this.$el.html(this.template(this.model.toJSON()));
                                        return this;
                                    },
                                });


                                var grid = new Backgrid.Grid({
                                    //className: 'backgrid table table-hover table-condensed',
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'code',
                                            label: app.translate([that, app], 'process_phases_code_col'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: Backgrid.StringCell.prototype.className + ' align-left-cell',
                                                template: Handlebars.compile('<div class="bullet phase-{{order}}-color"></div><span>{{value}}</span>'),
                                                render: function () {
                                                    this.$el.html(this.template({
                                                        value: this.formatter.fromRaw(this.model.get(this.column.get('name')), this.model),
                                                        order: this.model.get('order'),
                                                    }));

                                                    this.delegateEvents();

                                                    return this;
                                                },
                                            }),
                                        },
                                        {
                                            name: 'energy',
                                            editable: false,
                                            label: app.translate([that, app], 'process_phases_energy_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 2,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'carbon',
                                            editable: false,
                                            label: app.translate([that, app], 'process_phases_carbon_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'naturalGas',
                                            editable: false,
                                            label: app.translate([that, app], 'process_phases_natural_gas_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'oxygen',
                                            editable: false,
                                            label: app.translate([that, app], 'process_phases_oxygen_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'o2ss',
                                            editable: false,
                                            label: app.translate([that, app], 'process_phases_o2ss_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'formattedDuration',
                                            editable: false,
                                            label: 'Duration',
                                            cell: Backgrid.StringCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                    ],
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Phases', children:
                                                        [
                                                            { name: 'code' }
                                                            , { name: 'energy' }
                                                            , { name: 'carbon' }
                                                            , { name: 'naturalGas' }
                                                            , { name: 'oxygen' }
                                                            , { name: 'o2ss' }
                                                            , { name: 'formattedDuration' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.phases,
                                });
                                that.$el.find('.process-phases-grid-container').append(grid.render().el);

                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [

                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            label: 'Timestamp',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell timestmap',
                                            }),
                                        },
                                        {
                                            name: 'bucketName',
                                            editable: false,
                                            label: app.translate([that, app], 'process_buckets_bucket_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'scrapWeight',
                                            editable: false,
                                            label: app.translate([that, app], 'process_buckets_scrap_weight_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'hiCal',
                                            editable: false,
                                            label: app.translate([that, app], 'process_buckets_hiCal_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'carbon',
                                            editable: false,
                                            label: app.translate([that, app], 'process_buckets_carbon_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'proSlag',
                                            editable: false,
                                            label: app.translate([that, app], 'process_buckets_proSlag_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'dolo',
                                            editable: false,
                                            label: app.translate([that, app], 'process_buckets_dolo_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'othersWeight',
                                            editable: false,
                                            label: app.translate([that, app], 'process_buckets_othersWeight_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                    ],
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Buckets', children:
                                                        [
                                                            { name: 'timestamp' }
                                                            , { name: 'bucketName' }
                                                            , { name: 'scrapWeight' }
                                                            , { name: 'hiCal' }
                                                            , { name: 'carbon' }
                                                            , { name: 'proSlag' }
                                                            , { name: 'dolo' }
                                                            , { name: 'othersWeight' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.buckets,
                                });
                                that.$el.find('.process-buckets-grid-container').append(grid.render().el);


                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            label: 'Timestamp',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell timestmap',
                                            }),
                                        },
                                        {
                                            name: 'temperature',
                                            editable: false,
                                            label: app.translate([that, app], 'process_temperatures_temperature_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'oxygen',
                                            editable: false,
                                            label: app.translate([that, app], 'process_temperatures_oxygen_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'estimatedO2ppm',
                                            editable: false,
                                            label: app.translate([that, app], 'process_temperatures_estimatedO2ppm_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'carbon',
                                            editable: false,
                                            label: app.translate([that, app], 'process_temperatures_carbon_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'estimatedCarbon',
                                            editable: false,
                                            label: app.translate([that, app], 'process_temperatures_estimatedCarbon_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'celoxbathlvl',
                                            editable: false,
                                            label: 'Celox Bath',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'isManual',
                                            editable: false,
                                            label: 'is Manual',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                    ],

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Probes', children:
                                                        [

                                                            { name: 'timestamp' }
                                                            , { name: 'temperature' }
                                                            , { name: 'oxygen' }
                                                            , { name: 'estimatedO2ppm' }
                                                            , { name: 'carbon' }
                                                            , { name: 'estimatedCarbon' }
                                                            , { name: 'celoxbathlvl' }
                                                            , { name: 'isManual' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.temperatures,
                                });
                                that.$el.find('.process-temperatures-grid-container').append(grid.render().el);



                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'datetime',
                                            editable: false,
                                            label: 'Timestamp',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'material',
                                            editable: false,
                                            label: app.translate([that, app], 'process_material_alloys_col'),
                                            cell: Backgrid.StringCell.extend({
                                                decimals: 0,
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'weight',
                                            editable: false,
                                            label: app.translate([that, app], 'process_weight_alloys_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                    ],

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Manual Additions', children:
                                                        [
                                                            { name: 'datetime' }
                                                            , { name: 'material' }
                                                            , { name: 'weight' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.alloys,
                                });
                                that.$el.find('.process-alloys-grid-container').append(grid.render().el);

                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            sortable: false,
                                            label: app.translate(that, 'timestamp_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                className: 'timestamp-date',
                                            }),
                                        },
                                        {
                                            name: 'CaO',
                                            label: app.translate(that, 'caO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                className: 'element',
                                            }),
                                        },
                                        {
                                            name: 'SiO2',
                                            label: app.translate(that, 'siO2_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                className: 'element',
                                            }),
                                        },
                                        {
                                            name: 'Al2O3',
                                            label: app.translate(that, 'al2O3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                className: 'element',
                                            }),
                                        },
                                        {
                                            name: 'TiO2',
                                            label: app.translate(that, 'tiO2_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'B3ratio',
                                            label: app.translate(that, 'b3Ratio_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('B3Status') == 'WARNING') return 'number-cell warning';
                                                    else return 'number-cell';
                                                },
                                                decimals: 1,
                                            }),

                                        },
                                        {
                                            name: 'MgO',
                                            label: app.translate(that, 'mgO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('MgOStatus') == 'WARNING') return 'number-cell warning';
                                                    else return 'number-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },

                                        {
                                            name: 'FeO',
                                            label: app.translate(that, 'feO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('FeOStatus') == 'WARNING') return 'number-cell warning';
                                                    else return 'number-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'MnO',
                                            label: app.translate(that, 'mnO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },

                                        {
                                            name: 'total',
                                            label: app.translate(that, 'total_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('TotalStatus') == 'WARNING') return 'number-cell warning';
                                                    else return 'number-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'Cr2O3',
                                            label: app.translate(that, 'cr2O3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'P2O5',
                                            label: app.translate(that, 'p2O5_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'SO3',
                                            label: app.translate(that, 'sO3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'dirtLoad',
                                            label: app.translate(that, 'dirtLoad_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'TotalSlagVolume',
                                            label: app.translate(that, 'TotalSlagVolume_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'refractoryWear',
                                            label: app.translate(that, 'refractoryWear_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('RefractoryWearStatus') == 'WARNING') return 'number-cell warning';
                                                    else if (this.model.get('RefractoryWearStatus') == 'NORMAL') return 'number-cell normal';
                                                    else return 'number-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'steelLoss',
                                            label: app.translate(that, 'steelLoss_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell',
                                                decimals: 1,
                                            }),
                                        },
                                    ],
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Slag Samples', children:
                                                        [
                                                            , { name: 'timestamp' }
                                                            , { name: 'CaO' }
                                                            , { name: 'SiO2' }
                                                            , { name: 'Al2O3' }
                                                            , { name: 'TiO2' }
                                                            , { name: 'B3ratio' }
                                                            , { name: 'MgO' }
                                                            , { name: 'FeO' }
                                                            , { name: 'MnO' }
                                                            , { name: 'total' }
                                                            , { name: 'Cr2O3' }
                                                            , { name: 'P2O5' }
                                                            , { name: 'SO3' }
                                                            , { name: 'dirtLoad' }
                                                            , { name: 'TotalSlagVolume' }
                                                            , { name: 'refractoryWear' }
                                                            , { name: 'steelLoss' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.slagChemistries,
                                });
                                that.$el.find('.process-slag-chemistries-grid-container').append(grid.render().el);


                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'code',
                                            editable: false,
                                            label: app.translate([that, app], 'process_consumptions_code_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'total',
                                            editable: false,
                                            label: app.translate([that, app], 'process_consumptions_total_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                    ],

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Total Consumptions', children:
                                                        [
                                                            { name: 'code' }
                                                            , { name: 'total' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.consumptions,
                                });
                                that.$el.find('.process-total-consumptions-grid-container').append(grid.render().el);



                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'injector',
                                            editable: false,
                                            label: app.translate([that, app], 'process_injectors_injector_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'pos1',
                                            editable: false,
                                            label: app.translate([that, app], 'process_injectors_pos1_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'pos2',
                                            editable: false,
                                            label: app.translate([that, app], 'process_injectors_pos2_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'pos3',
                                            editable: false,
                                            label: app.translate([that, app], 'process_injectors_pos3_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'pos4',
                                            editable: false,
                                            label: app.translate([that, app], 'process_injectors_pos4_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'pos5',
                                            editable: false,
                                            label: app.translate([that, app], 'process_injectors_pos5_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                    ],

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'By Injectors', children:
                                                        [
                                                            { name: 'injector' }
                                                            , { name: 'pos1' }
                                                            , { name: 'pos2' }
                                                            , { name: 'pos3' }
                                                            , { name: 'pos4' }
                                                            , { name: 'pos5' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.injectors,
                                });
                                that.$el.find('.process-injectors-grid-container').append(grid.render().el);



                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            label: app.translate([that, app], 'process_pourback_timestamp_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell timestmap',
                                            }),
                                        },
                                        {
                                            name: 'heatName',
                                            editable: false,
                                            label: app.translate([that, app], 'process_heatName_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'weight',
                                            editable: false,
                                            label: app.translate([that, app], 'process_weight_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                    ],

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Pourback', children:
                                                        [
                                                            { name: 'timestamp' }
                                                            , { name: 'heatName' }
                                                            , { name: 'weight' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.pourback,
                                });
                                that.$el.find('.process-pourback-grid-container').append(grid.render().el);

                                that.applyBindings();

                                //rendering Navigation Buttons
                                that.NavigationButtonView.render(that.$el.find(".navigation-buttons"), null);

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

                                var fixedParams = _.extend({}, urlParams);
                                if (fixedParams && fixedParams.heatName && fixedParams.heatName.length === 7) {
                                    that.model.set(fixedParams);
                                } else {
                                    that.UpdateURL();
                                }
                                that.model.fetchCatalogs();

                                that.renderMultipicker();


                                that.refresh();

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

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

            },

            onSampleSelectServerSearch: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', searchValue);
                qp.Add('@SelectedHeatName', 'VARCHAR(10)', this.selectedValues[0]);
                qp.Add('@Asset', 'CHAR(3)', 'EAF');

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                virtualSelect.setServerOptions(resp.Table);

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

            refresh: function () {
                this.model.set({
                    isLoading_process: true,
                    hasData_process: false,
                    isLoading_phases: true,
                    hasData_phases: false,
                    isLoading_buckets: true,
                    hasData_buckets: false,
                    hasData_temperatures: false,
                    isLoading_temperatures: true,
                    hasData_alloys: false,
                    isLoading_alloys: true,
                    hasData_slagChemistries: false,
                    isLoading_slagChemistries: true,
                    hasData_consumptions: false,
                    isLoading_consumptions: true,
                    hasData_injectors: false,
                    isLoading_injectors: true,
                    hasData_pourback: false,
                    isLoading_pourback: true,

                    hasData_pouredbackLegend: false,
                });


                this.model.fetch();



            },

            fetchnavbuttons: function (resp) {
                this.NavigationButtonView.setDataColl(resp);
            },
            process_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_process: that.model.process.get('id') ? true : false,
                                isLoading_process: false,
                                processId: that.model.process.get('id'),
                                heatName: that.model.process.get('heatName'),
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            phases_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_phases: (that.model.phases.length > 0),
                                isLoading_phases: false,
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            buckets_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_buckets: (that.model.buckets.length > 0),
                                isLoading_buckets: false,
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            temperatures_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_temperatures: (that.model.temperatures.length > 0),
                                isLoading_temperatures: false,
                            });

                        },
                        100
                    );

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

            alloys_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_alloys: (that.model.alloys.length > 0),
                                isLoading_alloys: false,
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            slagChemistries_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_slagChemistries: (that.model.slagChemistries.length > 0),
                                isLoading_slagChemistries: false,
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            consumptions_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_consumptions: (that.model.consumptions.length > 0),
                                isLoading_consumptions: false,
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            pourback_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_pourback: (that.model.pourback.length > 0),
                                isLoading_pourback: false,
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            injectors_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_injectors: (that.model.injectors.length > 0),
                                isLoading_injectors: false,
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            UpdateURL: function () {
                try {
                    var params = this.model.toJSON();

                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    heatName: params.heatName,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            refreshBtn_click: function (e) {
                //this.model.set({ changeEAF: true });
                this.refresh();
                this.UpdateURL();

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

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

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

                    this.options.onappend(this);
                }

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

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

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

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

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

                this.hideSubviews();

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

        });

        //Remove this in the next refactor
        Screen.Models.Process = Backbone.Epoxy.Model.extend({
            defaults: {

                //Header
                heatName: null,
                productionDate: null,
                start: null,
                end: null,
                shiftId: null,
                crewId: null,

                //Main data
                id: null,

                initGradeName: null,
                gradeName: null,
                ladleName: null,
                operatorName: null,

                furnaceCode: null,
                boreInTime: null,
                meltTime: null,
                refineTime: null,
                tappingTime: null,
                tapToTap: null,
                meltOrder: null,

                chargeWeight: null,
                steelWeight: null,
                pourbackHeat: null,
                pourbackWeight: null,
                heel: null,
                yield: null,

                regulationMode: null,
                powerProgram: null,
                burnerProgram: null,
                powerOn: null,
                powerOff: null,
                energy: null,

                ncc1: null,
                ncc2: null,
                ncc3: null,
                caveIn1: null,
                caveIn2: null,
                caveIn3: null,
                electrode1Changed: false,
                electrode2Changed: false,
                electrode3Changed: false,


              

                argon: null,
            },
            computeds: {
                shiftName: {
                    deps: ['shiftId'],
                    get: function (shift) {
                        if (shift == 1) return 'Day'
                        else if (shift == 2) return 'Night'
                    },
                },
                productionDateAndShift: {
                    deps: ['shiftId', 'productionDate'],
                    get: function (shift, date) {
                        if (shift == 1) return date + ' - ' + 'Day'
                        else if (shift == 2) return date + ' - ' + 'Night'
                    },
                }
            },
            setDataModel: function (model) {
                if (model && model[0]) {
                    var obj = model[0];
                    this.set({
                        heatName: obj.HeatName ? obj.HeatName : null,
                        productionDate: obj.ProductionDate ? new moment(obj.ProductionDate).format('MM/DD/YYYY') : null,
                        shiftId: obj.ShiftId ? obj.ShiftId : null,
                        crewId: obj.CrewId ? obj.CrewId : null,
                        start: obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : null,
                        end: obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : null,

                        id: obj.Id ? obj.Id : null,

                        initGradeName: obj.InitialGradeName ? obj.InitialGradeName : null,
                        gradeName: obj.GradeName ? obj.GradeName : null,
                        ladleName: obj.LadleName ? obj.LadleName : null,
                        operatorName: obj.OperatorName ? obj.OperatorName : null,

                        furnaceCode: obj.FurnaceCode ? obj.FurnaceCode : null,
                        boreInTime: obj.BoreInTime ? obj.BoreInTime : null,
                        meltTime: obj.MeltTime ? obj.MeltTime : null,
                        refineTime: obj.RefineTime ? obj.RefineTime : null,
                        tappingTime: obj.TappingTime ? obj.TappingTime : null,
                        tapToTap: obj.TapToTap ? obj.TapToTap : null,
                        meltOrder: obj.MeltOrder ? obj.MeltOrder : null,

                        chargeWeight: obj.ChargeWeight ? obj.ChargeWeight : null,
                        steelWeight: obj.SteelWeight ? obj.SteelWeight : null,
                        pourbackHeat: obj.PourbackHeatName ? obj.PourbackHeatName : null,
                        pourbackWeight: obj.PourbackWeight ? obj.PourbackWeight : null,
                        heel: obj.Heel ? obj.Heel : null,
                        yield: obj.Yield ? obj.Yield.toFixed(2) : null,

                        regulationMode: obj.RegulationModeName ? obj.RegulationModeName : null,
                        powerProgram: obj.PowerProgram ? obj.PowerProgram : null,
                        burnerProgram: obj.BurnerProgram ? obj.BurnerProgram : null,
                        powerOn: obj.PowerOnCalculated ? obj.PowerOnCalculated : null,
                        powerOff: obj.PowerOff ? obj.PowerOff : null,
                        energy: obj.EnergyCalculated ? obj.EnergyCalculated.toFixed(2) : null,

                        ncc1: obj.NCC1 ? obj.NCC1 : null,
                        ncc2: obj.NCC2 ? obj.NCC2 : null,
                        ncc3: obj.NCC3 ? obj.NCC3 : null,
                        caveIn1: obj.CaveIn1 ? obj.CaveIn1 : null,
                        caveIn2: obj.CaveIn2 ? obj.CaveIn2 : null,
                        caveIn3: obj.CaveIn3 ? obj.CaveIn3 : null,


                        electrode1Changed: obj.Electrode1Changed ? obj.Electrode1Changed : null,
                        electrode2Changed: obj.Electrode2Changed ? obj.Electrode2Changed : null,
                        electrode3Changed: obj.Electrode3Changed ? obj.Electrode3Changed : null,



                        argon: obj.Argon ? obj.Argon : null,

                    }).trigger('fetch', this, obj);

                }
                else this.trigger('fetch', this, model);
            },
        });

        Screen.Models.InjectorsColl = Backbone.Epoxy.Model.extend({
            defaults: {
                injector: null,
                pos1: null,
                pos2: null,
                pos3: null,
                pos4: null,
                pos5: null,

            },

            parse: function (obj) {
                var result = {
                    injector: obj.Injector ? obj.Injector : null,
                    pos1: obj.Pos1 ? obj.Pos1 : null,
                    pos2: obj.Pos2 ? obj.Pos2 : null,
                    pos3: obj.Pos3 ? obj.Pos3 : null,
                    pos4: obj.Pos4 ? obj.Pos4 : null,
                    pos5: obj.Pos5 ? obj.Pos5 : null,

                };
                return result;
            }

        });
        Screen.Collections.InjectorsColl = Backbone.Collection.extend({
            model: Screen.Models.InjectorsColl,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });


        Screen.Models.PourbackColl = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                timestamp: null,
                fromHeatId: null,
                eafProcessId: null,
                weight: null,
                comment: null,
                heatName: null,
            },

            parse: function (obj) {
                var result = {
                    id: obj.Id,
                    timestamp: new moment(obj.Timestamp).format('MM/DD HH:mm'),
                    fromHeatId: obj.FromHeatId,
                    eafProcessId: obj.EAFProcessId,
                    weight: obj.Weight,
                    comment: obj.Comment,
                    heatName: obj.HeatName,

                };
                return result;
            }

        });

        Screen.Collections.PourbackColl = Backbone.Collection.extend({
            model: Screen.Models.PourbackColl,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });


        Screen.Models.ConsumptionsColl = Backbone.Epoxy.Model.extend({
            defaults: {
                code: null,
                total: null,
            },

            parse: function (obj) {
                var result = {
                    code: obj.Code ? obj.Code : null,
                    total: obj.Total ? obj.Total : null,
                };
                return result;
            }

        });
        Screen.Collections.ConsumptionsColl = Backbone.Collection.extend({
            model: Screen.Models.ConsumptionsColl,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });

        Screen.Models.SlagChemistriesColl = Backbone.Epoxy.Model.extend({
            defaults: {
                Timestamp: null,
                MgO: null,
                CaO: null,
                Fe2O3: null,
                Al2O3: null,
                SiO2: null,
                MnO: null,
                Cr2O3: null,
                TiO2: null,
                ZrO2: null,
                P2O5: null,
                SO3: null,
                F: null,
                Lime: null,
                Vratio: null,
                B3ratio: null,
                FeO: null,
                Total: null,
                Operator: null,
                Comments: null,

            },

            parse: function (obj) {
                var result = {
                    heatName: obj.HeatName,
                    typeName: obj.TypeName,
                    timestamp: new moment(obj.TimestampString).format("MM/DD HH:mm"),
                    MgO: obj.MgO,
                    CaO: obj.CaO,
                    Fe2O3: obj.Fe2O3,
                    Al2O3: obj.Al2O3,
                    SiO2: obj.SiO2,
                    MnO: obj.MnO,
                    Cr2O3: obj.Cr2O3,
                    TiO2: obj.TiO2,
                    P2O5: obj.P2O5,
                    SO3: obj.SO3,
                    B3ratio: obj.B3ratio,
                    FeO: obj.FeO,
                    total: obj.Total,
                    refractoryWear: obj.RefractoryWear,
                    steelLoss: obj.FeinSlag,
                    comments: obj.Comments,



                    totalMin: obj.TotalMin,
                    dirtLoad: obj.DirtLoad,

                    TotalSlagVolume: obj.TotalSlagVolume,
                    LbsMgOAdded: obj.LbsMgOAdded,
                    LbsMgOnSlag: obj.LbsMgOnSlag,


                    B3Status: obj.B3Status,
                    MgOStatus: obj.MgOStatus,
                    FeOStatus: obj.FeOStatus,
                    RefractoryWearStatus: obj.RefractoryWearStatus,
                    TotalStatus: obj.TotalStatus,
                };
                return result;
            }

        });
        Screen.Collections.SlagChemistriesColl = Backbone.Collection.extend({
            model: Screen.Models.SlagChemistriesColl,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });

        Screen.Models.TemperaturesColl = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                processId: null,
                oxygen: null,
                carbon: null,
                temperature: null,
                timestamp: null,
                isManul: null,
            },

            parse: function (obj) {
                var result = {
                    id: obj.Id,
                    processId: obj.ProcessId,
                    oxygen: obj.Oxygen ? obj.Oxygen : null,
                    carbon: obj.Carbon ? obj.Carbon : null,
                    temperature: obj.Temperature ? obj.Temperature : null,
                    timestamp: obj.Timestamp ? new moment(obj.Timestamp).format('MM/DD HH:mm') : null,
                    estimatedCarbon: obj.EstimatedCarbon ? obj.EstimatedCarbon : null,
                    estimatedO2ppm: obj.EstimatedO2ppm ? obj.EstimatedO2ppm : null,
                    isManual: obj.isManual ? 'Yes' : 'No',
                    celoxbathlvl: obj.CeloxBathLvl ? obj.CeloxBathLvl : null

                };
                return result;
            }

        });
        Screen.Collections.TemperaturesColl = Backbone.Collection.extend({
            model: Screen.Models.TemperaturesColl,
            comparator: 'timestamp',
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });

        Screen.Models.AlloysColl = Backbone.Epoxy.Model.extend({
            defaults: {
                datetime: null,
                weight: null,
                material: null,
            },

            parse: function (obj) {
                var result = {
                    datetime: obj.Datetime ? new moment(obj.Datetime).format('MM/DD HH:mm') : null,
                    weight: obj.Weight,
                    material: obj.Material,

                };
                return result;
            }

        });
        Screen.Collections.AlloysColl = Backbone.Collection.extend({
            model: Screen.Models.AlloysColl,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });


        Screen.Models.BucketsColl = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                processId: null,
                hiCal: null,
                carbon: null,
                proSlag: null,
                dolo: null,
                bucketId: null,
                bucketName: null,
                othersWeight: null,
                scrapWeight: null,
                timestamp: null,
            },

            parse: function (obj) {
                var result = {
                    id: obj.Id ? obj.Id : null,
                    processId: obj.ProcessId ? obj.ProcessId : null,
                    hiCal: obj.HiCal ? obj.HiCal : null,
                    carbon: obj.Carbon ? obj.Carbon : null,
                    proSlag: obj.ProSlag ? obj.ProSlag : null,
                    dolo: obj.Dolo ? obj.Dolo : null,
                    bucketId: obj.BucketId ? obj.BucketId : null,
                    bucketName: obj.BucketName ? obj.BucketName : null,
                    othersWeight: obj.OthersWeight ? obj.OthersWeight : null,
                    scrapWeight: obj.ScrapWeight ? obj.ScrapWeight : null,
                    timestamp: obj.Timestamp ? new moment(obj.Timestamp).format('MM/DD HH:mm') : null,
                };
                return result;
            }

        });
        Screen.Collections.BucketsColl = Backbone.Collection.extend({
            model: Screen.Models.BucketsColl,
            comparator: 'timestamp',
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });

        Screen.Models.PhasesColl = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                processId: null,
                code: null,
                order: null,
                energy: null,
                carbon: null,
                naturalGas: null,
                o2ss: null,
                oxygen: null,
                duration: null,
                timestamp: null,
                processDuration: null,
                formattedDuration: null,
            },

            parse: function (obj) {
                var result = {
                    id: obj.Id ? obj.Id : null,
                    processId: obj.ProcessId ? obj.ProcessId : null,
                    code: obj.Code ? obj.Code : null,
                    order: obj.Order ? obj.Order : null,
                    energy: obj.Energy ? obj.Energy : null,
                    carbon: obj.Carbon ? obj.Carbon : null,
                    naturalGas: obj.NaturalGas ? obj.NaturalGas : null,
                    o2ss: obj.O2SS ? obj.O2SS : null,
                    oxygen: obj.Oxygen ? obj.Oxygen : null,
                    duration: obj.Duration ? obj.Duration : null,
                    timestamp: obj.Timestamp ? obj.Timestamp : null,
                    processDuration: obj.ProcessDuration ? obj.ProcessDuration : null,
                    formattedDuration: obj.Duration ? moment.duration(obj.Duration, 'seconds').get('minutes') + ':' + moment.duration(obj.Duration, 'seconds').get('seconds') : null,
                };
                return result;
            }

        });
        Screen.Collections.PhasesColl = Backbone.Collection.extend({
            model: Screen.Models.PhasesColl,
            comparator: 'order',
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });

        Screen.Models.HeatName = Backbone.Model.extend({
            label: function () {
                return this.get("name");
            }
        });
        Screen.Collections.HeatNames = Backbone.Collection.extend({
            model: Screen.Models.HeatName,

            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl);
            },
        });

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