//SCREEN-BOILERPLATE

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

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

    //templates-loader: this loads templates async.
    'js/templates-loader',
    'backgrid',
    'moment',
    'modules/modal2',
    'js/d3v4/d3.v4',
    'backgrid/grouped-columns',
    'js/jquery.clearsearch/jquery.clearsearch',
    'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',
    'backgrid/calendar-cell',
    'backgrid/moment-cell',
    'js/jquery.timepicker/jquery.timepicker',
    'backgrid/time-cell'

],
    function (app, T, Backgrid, moment, Modal, d3) {
        //replace all 'Screen' with your view's name.
        var Screen = {
            Models: {},
            Views: {},
            Collections: {},
        };

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

                productionDate: new moment().subtract(1, 'days').format('MM/DD/YYYY'),

                shiftId: 'D',
                crewId: 'C',
                shifts: [],
                hasData: true,
                isLoading: false,
                tphValues: null,

                showFurnace2Data: true,
                showFurnace1Data: true,

                hasData_yield: false,
                chartsWidth: 450,
                chartHeight: 310,
                heightOffset: 280,
                isLoading_Temperature: false,
                hasData_Temperature: false,
                hasData_temperature_EAFA: false,
                hasData_temperature_EAFB: false,
                hasData_oxygen_EAFA: false,
                hasData_oxygen_EAFB: false,

                hasData_residuals_EAFA: false,
                hasData_residuals_EAFB: false,
                hasData_residuals_EAFA_2: false,
                hasData_residuals_EAFB_2: false,

                hasData_bucket_fluxes_EAFA: false,
                hasData_bucket_fluxes_EAFB: false,

                isLoading_bucket_fluxes_EAFA: true,
                isLoading_bucket_fluxes_EAFB: true,

                hasData_injection_fluxes_EAFA: false,
                hasData_injection_fluxes_EAFB: false,

                isLoading_injection_fluxes_EAFA: true,
                isLoading_injection_fluxes_EAFB: true,

                hasData_baghouse: false,

                hasData_Recipes: false,
                hasData_RecipesAverage: false,

                hasData_manualTemps: false,
                hasData_tapHoleNonFreeOpen: false,

                hasData_EAF: true,
                isLoading_EAF: false,

                hasData_EAF_A: true,
                hasData_EAF_B: true,
                hasData_AllHeats_EAF_A: true,
                hasData_AllHeats_EAF_B: true,

                EAF_A_TotalHeats: '-'
                , EAF_A_TotalSteelWeight: '-'
                , EAF_A_TotalScrapWeight: '-'
                , EAF_A_TotalElectricEnergy: '-'
                , EAF_A_TotalElectrodeAdds: '-'
                , EAF_A_SteelWeight: '-'
                , EAF_A_ScrapWeight: '-'
                , EAF_A_Fluxes: '-'
                , EAF_A_Yield: '-'
                , EAF_A_TapToTap: '-'
                , EAF_A_PowerOn: '-'
                , EAF_A_InjectedC: '-'
                , EAF_A_EAFLastTemperature: '-'
                , EAF_A_ElectricEnergy: '-'
                , EAF_A_SpecificEnergy: '-'
                , EAF_A_ElectricPower: '-'
                , EAF_A_SmartARC: '-'
                , EAF_B_TotalHeats: '-'
                , EAF_B_TotalSteelWeight: '-'
                , EAF_B_TotalScrapWeight: '-'
                , EAF_B_TotalElectricEnergy: '-'
                , EAF_B_TotalElectrodeAdds: '-'
                , EAF_B_SteelWeight: '-'
                , EAF_B_ScrapWeight: '-'
                , EAF_B_Fluxes: '-'
                , EAF_B_Yield: '-'
                , EAF_B_TapToTap: '-'
                , EAF_B_PowerOn: '-'
                , EAF_B_InjectedC: '-'
                , EAF_B_EAFLastTemperature: '-'
                , EAF_B_ElectricEnergy: '-'
                , EAF_B_SpecificEnergy: '-'
                , EAF_B_ElectricPower: '-'
                , EAF_B_SmartARC: '-'
                , TOTAL_TotalHeats: '-'
                , TOTAL_TotalSteelWeight: '-'
                , TOTAL_TotalScrapWeight: '-'
                , TOTAL_TotalElectricEnergy: '-'
                , TOTAL_TotalElectrodeAdds: '-'
                , TOTAL_SteelWeight: '-'
                , TOTAL_ScrapWeight: '-'
                , TOTAL_Fluxes: '-'
                , TOTAL_Yield: '-'
                , TOTAL_TapToTap: '-'
                , TOTAL_PowerOn: '-'
                , TOTAL_InjectedC: '-'
                , TOTAL_EAFLastTemperature: '-'
                , TOTAL_ElectricEnergy: '-'
                , TOTAL_SpecificEnergy: '-'
                , TOTAL_ElectricPower: '-'
                , TOTAL_SmartARC: '-'
                , TOTAL_SteelWeightSTD: '-'
                , TOTAL_ScrapWeightSTD: '-'
                , TOTAL_YieldSTD: '-'
                , TOTAL_TapToTapSTD: '-'
                , TOTAL_PowerOnSTD: '-'
                , TOTAL_SpecificEnergySTD: '-'

                , Structural_B3Max: '-'
                , Structural_B3Min: '-'
                , Structural_FeOMax: '-'
                , Structural_FeOMin: '-'
                , Structural_MgOMax: '-'
                , Structural_MgOMin: '-'
                , Rail_B3Max: '-'
                , Rail_B3Min: '-'
                , Rail_FeOMax: '-'
                , Rail_FeOMin: '-'
                , Rail_MgOMax: '-'
                , Rail_MgOMin: '-'



                , EAFASprayRingEffectiveness: '-'
                , EAFBSprayRingEffectiveness: '-'
                , EAFABypass: '-'

            },
            initialize: function () {
                this.itemsAllHeats = new Screen.Collections.ItemsAllHeats();
                this.itemsAllDelays = new Screen.Collections.ItemsAllDelays();
                this.itemsTemperature = new Screen.Collections.ItemsTemperature();
                this.itemsInjectionFluxesEAFA = new Screen.Collections.InjectionFluxesEAFA();
                this.itemsInjectionFluxesEAFB = new Screen.Collections.InjectionFluxesEAFB();
                this.itemsBucketFluxesEAFA = new Screen.Collections.BucketFluxesEAFA();
                this.itemsBucketFluxesEAFB = new Screen.Collections.BucketFluxesEAFB();
                this.itemsSlag = new Screen.Collections.ItemsSlag();
                this.itemsBaghouse = new Screen.Collections.ItemsBaghouse();
                this.itemsDelays = new Screen.Collections.ItemsDelays();
                this.itemsRecipes = new Screen.Collections.ItemsRecipes();
                this.itemsRecipesAverage = new Screen.Collections.ItemsRecipesAverage();
                this.itemsLogBook = new Screen.Collections.ItemsLogBook();
                this.itemsManualTemps = new Screen.Collections.ItemsManualTemps();
                this.itemsTapHoleNonFreeOpen = new Screen.Collections.TapHoleNonFreeOpen();

                this.itemsYield = new Screen.Collections.ItemsYield();
                this.srdCategories = new Screen.Collections.SRDCategories();



            },

            computeds: {

                structuralAims: {
                    deps: [
                        'Structural_B3Max'
                        , 'Structural_B3Min'
                        , 'Structural_FeOMax'
                        , 'Structural_FeOMin'
                        , 'Structural_MgOMax'
                        , 'Structural_MgOMin'

                    ],
                    get: function (
                        B3Max
                        , B3Min
                        , FeOMax
                        , FeOMin
                        , MgOMax
                        , MgOMin
                    ) {
                        return `Structural Aims:  B3 ratio ${B3Min} - ${B3Max} | MgO ${MgOMin} - ${MgOMax} | FeO ${FeOMin} - ${FeOMax} `
                    },
                },
                railAims: {
                    deps: [
                        'Rail_B3Max'
                        , 'Rail_B3Min'
                        , 'Rail_FeOMax'
                        , 'Rail_FeOMin'
                        , 'Rail_MgOMax'
                        , 'Rail_MgOMin'

                    ],
                    get: function (
                        B3Max
                        , B3Min
                        , FeOMax
                        , FeOMin
                        , MgOMax
                        , MgOMin
                    ) {
                        return `Rail Aims:  B3 ratio ${B3Min} - ${B3Max} | MgO ${MgOMin} - ${MgOMax} | FeO ${FeOMin} - ${FeOMax} `
                    },
                },
                currentShift: {
                    deps: ['shiftId', 'productionDate', 'crewId'],
                    get: function (shiftId, productionDate, crewId) {
                        let shift = shiftId === 'D' ? 'Day Shift' : 'Night Shift';
                        let crew = `${crewId} Crew`;
                        return `${productionDate} | ${shift} | ${crew}`
                    },
                },
                SteelWeightConcat: {
                    deps: ['TOTAL_SteelWeight', 'TOTAL_SteelWeightSTD'],
                    get: function (avg, std) {
                        return avg + ' | ' + std
                    },
                },
                ScrapWeightConcat: {
                    deps: ['TOTAL_ScrapWeight', 'TOTAL_ScrapWeightSTD'],
                    get: function (avg, std) {
                        return avg + ' | ' + std
                    },
                },
                YieldConcat: {
                    deps: ['TOTAL_Yield', 'TOTAL_YieldSTD'],
                    get: function (avg, std) {
                        return avg + ' | ' + std
                    },
                },
                PowerOnConcat: {
                    deps: ['TOTAL_PowerOn', 'TOTAL_PowerOnSTD'],
                    get: function (avg, std) {
                        return avg + ' | ' + std
                    },
                },
                TapToTapConcat: {
                    deps: ['TOTAL_TapToTap', 'TOTAL_TapToTapSTD'],
                    get: function (avg, std) {
                        return avg + ' | ' + std
                    },
                },
                SpecificEnergyConcat: {
                    deps: ['TOTAL_SpecificEnergy', 'TOTAL_SpecificEnergySTD'],
                    get: function (avg, std) {
                        return avg + ' | ' + std
                    },
                },


            },

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

                this.fixedParameters = [
                    { Name: '@ProductionDate', Type: 'DATE', Value: params.productionDate, },
                    { Name: '@ShiftId', Type: 'INT', Value: params.shiftId == '1' ? 1 : (params.shiftId == '2' ? 2 : null), },
                    { Name: '@timeZoneCode', Type: 'CHAR(10)', Value: app.models.user.get('timezoneCode') },
                ];

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


                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.EAF.GetShiftReport',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp) {
                                    // Totals and Averages
                                    if (resp.Table) that.totalsAndAverages(resp.Table);

                                    // Recipes table
                                    if (resp.Table1) {

                                        const mergedModels = {};

                                        resp.Table1.forEach(model => {
                                            const materialName = model['Material'];
                                            if (!mergedModels[materialName]) {
                                                mergedModels[materialName] = { ...model };
                                            } else {
                                                Object.keys(model).forEach(key => {
                                                    if (key !== 'Material') {
                                                        if (model[key] !== null) {
                                                            mergedModels[materialName][key] = model[key];
                                                        }
                                                    }
                                                });
                                            }
                                        });

                                        const mergedList = Object.values(mergedModels);

                                        that.itemsRecipes.setDataColl(mergedList);
                                    } 

                                    // Top 3 delays
                                    if (resp.Table2) that.itemsDelays.setDataColl(resp.Table2);

                                    // Log book table
                                    if (resp.Table3) that.itemsLogBook.setDataColl(resp.Table3);

                                    // GANTT Charts
                                    if (resp.Table4) that.itemsAllHeats.setDataColl(resp.Table4, params.shiftId, params.productionDate);
                                    that.set({
                                        showFurnace1Data: _.where(resp.Table4, { Furnace: 'EAF A' }) ? true : false,
                                        showFurnace2Data: _.where(resp.Table4, { Furnace: 'EAF B' }) ? true : false,
                                    });
                                    if (resp.Table5) that.itemsAllDelays.setDataColl(resp.Table5, params.shiftId, params.productionDate);


                                    //Temperature Charts
                                    if (resp.Table6) that.itemsTemperature.setDataColl(resp.Table6);

                                    // KWH / Ton Charts
                                    if (resp.Table9) that.itemsInjectionFluxesEAFA.setDataColl(resp.Table9);
                                    if (resp.Table10) that.itemsInjectionFluxesEAFB.setDataColl(resp.Table10);

                                    //Bucket Charts
                                    if (resp.Table7) that.itemsBucketFluxesEAFA.setDataColl(resp.Table7);
                                    if (resp.Table8) that.itemsBucketFluxesEAFB.setDataColl(resp.Table8);

                                    // Slag chemistries table
                                    if (resp.Table11) that.itemsSlag.setDataColl(resp.Table11);

                                    //Baghouse Chart
                                    if (resp.Table12) that.itemsBaghouse.setDataColl(resp.Table12);


                                    //Yield Chart
                                    if (resp.Table13) {
                                        that.set({ hasData_yield: true });
                                        that.itemsYield.setDataColl(resp.Table13);
                                    }
                                    // ByPass
                                    if (resp.Table14 && resp.Table14[0]) {
                                        that.set({
                                            EAFASprayRingEffectiveness: resp.Table14[0].EAFASprayRingEffectiveness
                                            , EAFBSprayRingEffectiveness: resp.Table14[0].EAFBSprayRingEffectiveness
                                            , EAFABypass: `${resp.Table14[0].EAFABypassBreakerUtilization || resp.Table14[0].EAFABypassBreakerUtilization === 0 ? resp.Table14[0].EAFABypassBreakerUtilization : '-'} | ${resp.Table14[0].EAFAConditionsBypassBreakerMaintained || resp.Table14[0].EAFAConditionsBypassBreakerMaintained === 0 ? resp.Table14[0].EAFAConditionsBypassBreakerMaintained : '-'} `

                                        })
                                    }
                                    // SRD Categories
                                    if (resp.Table15) {
                                        that.srdCategories.setDataColl(resp.Table15);
                                    }

                                    if (resp.Table16) {
                                        that.itemsRecipesAverage.setDataColl(resp.Table16);
                                    }

                                    if (resp.Table17) {
                                        // filter those Heats with Manual Temps performed
                                        that.itemsManualTemps.setDataColl(resp.Table17.filter(x => x.ManualTemp != 0));
                                    }

                                    if (resp.Table18) {
                                        // filter those Heats with Manual Temps performed
                                        that.itemsTapHoleNonFreeOpen.setDataColl(resp.Table18);
                                    }
                                    that.trigger('fetch', resp);
                                }
                                else {
                                    if ((resp) && (resp.Message))
                                        console.error(new Error(resp.Message).stack);
                                    else
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);

                                    that.set({
                                        isLoading: false,
                                        hasData: false
                                    });
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );

                return this;
            },

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

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.EAF.GetShiftReportPickers',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    _.each(resp.Table, function (obj) {
                                        var tableKey = 'Table' + obj.Index;

                                        switch (obj.Name) {
                                            case 'SHIFTS':
                                                that.set('shifts', _.map(resp[tableKey], function (obj) {
                                                    return {
                                                        value: obj.Shift,
                                                        label: obj.Shift,
                                                    };
                                                }));
                                                break;

                                        }
                                    });
                                }
                                if ((resp) && (resp.Table3)) {
                                    _.each(resp.Table3, function (obj) {


                                        if (obj.Name.includes('Struct')) {
                                            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;
                                            }
                                        }
                                        if (obj.Name.includes('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;
                                            }
                                        }

                                    });
                                }
                                else {
                                    if ((resp) && (resp.Message))
                                        console.error(new Error(resp.Message).stack);
                                    else
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: opt.async,
                    },
                    app.ConnectionStrings.app
                );

                return this;
            },

            totalsAndAverages: function (data) {
                var hasData = false;

                if (data.length > 0) {
                    this.set({ crewId: data[0].CrewId });
                    if (data.length == 3) {
                        this.set({
                            hasData_EAF_A: true,
                            hasData_EAF_B: true,
                            CREW_ID: data[0].CrewId ? data[0].CrewId : '-'

                            , EAF_A_TotalHeats: data[0].TotalHeats ? data[0].TotalHeats : '-'
                            , EAF_A_TotalSteelWeight: data[0].TotalSteelWeight ? data[0].TotalSteelWeight.toFixed(1) : '-'
                            , EAF_A_TotalScrapWeight: data[0].TotalScrapWeight ? data[0].TotalScrapWeight.toFixed(1) : '-'
                            , EAF_A_TotalElectricEnergy: data[0].TotalElectricEnergy ? data[0].TotalElectricEnergy.toFixed(1) : '-'
                            , EAF_A_TotalElectrodeAdds: data[0].TotalElectrodeAdds ? data[0].TotalElectrodeAdds : '-'
                            , EAF_A_SteelWeight: data[0].SteelWeight ? data[0].SteelWeight.toFixed(1) : '-'
                            , EAF_A_ScrapWeight: data[0].ScrapWeight ? data[0].ScrapWeight.toFixed(1) : '-'
                            , EAF_A_Fluxes: data[0].Fluxes ? data[0].Fluxes.toFixed(1) : '-'
                            , EAF_A_Yield: data[0].Yield ? data[0].Yield.toFixed(1) : '-'
                            , EAF_A_TapToTap: data[0].TapToTap ? data[0].TapToTap.toFixed(1) : '-'
                            , EAF_A_PowerOn: data[0].PowerOn ? data[0].PowerOn.toFixed(1) : '-'
                            , EAF_A_InjectedC: data[0].InjectedC ? data[0].InjectedC.toFixed(1) : '-'
                            , EAF_A_EAFLastTemperature: data[0].EAFLastTemperature ? data[0].EAFLastTemperature.toFixed(1) : '-'
                            , EAF_A_ElectricEnergy: data[0].ElectricEnergy ? data[0].ElectricEnergy.toFixed(1) : '-'
                            , EAF_A_SpecificEnergy: data[0].SpecificEnergy ? data[0].SpecificEnergy.toFixed(1) : '-'
                            , EAF_A_ElectricPower: data[0].ElectricPower ? data[0].ElectricPower.toFixed(1) : '-'
                            , EAF_A_SmartARC: data[0].SmartARC ? data[0].SmartARC : '-'

                            , EAF_B_TotalHeats: data[1].TotalHeats ? data[1].TotalHeats : '-'
                            , EAF_B_TotalSteelWeight: data[1].TotalSteelWeight ? data[1].TotalSteelWeight.toFixed(1) : '-'
                            , EAF_B_TotalScrapWeight: data[1].TotalScrapWeight ? data[1].TotalScrapWeight.toFixed(1) : '-'
                            , EAF_B_TotalElectricEnergy: data[1].TotalElectricEnergy ? data[1].TotalElectricEnergy.toFixed(1) : '-'
                            , EAF_B_TotalElectrodeAdds: data[1].TotalElectrodeAdds ? data[1].TotalElectrodeAdds : '-'
                            , EAF_B_SteelWeight: data[1].SteelWeight ? data[1].SteelWeight.toFixed(1) : '-'
                            , EAF_B_ScrapWeight: data[1].ScrapWeight ? data[1].ScrapWeight.toFixed(1) : '-'
                            , EAF_B_Fluxes: data[1].Fluxes ? data[1].Fluxes.toFixed(1) : '-'
                            , EAF_B_Yield: data[1].Yield ? data[1].Yield.toFixed(1) : '-'
                            , EAF_B_TapToTap: data[1].TapToTap ? data[1].TapToTap.toFixed(1) : '-'
                            , EAF_B_PowerOn: data[1].PowerOn ? data[1].PowerOn.toFixed(1) : '-'
                            , EAF_B_InjectedC: data[1].InjectedC ? data[1].InjectedC.toFixed(1) : '-'
                            , EAF_B_EAFLastTemperature: data[1].EAFLastTemperature ? data[1].EAFLastTemperature.toFixed(1) : '-'
                            , EAF_B_ElectricEnergy: data[1].ElectricEnergy ? data[1].ElectricEnergy.toFixed(1) : '-'
                            , EAF_B_SpecificEnergy: data[1].SpecificEnergy ? data[1].SpecificEnergy.toFixed(1) : '-'
                            , EAF_B_ElectricPower: data[1].ElectricPower ? data[1].ElectricPower.toFixed(1) : '-'
                            , EAF_B_SmartARC: data[1].SmartARC ? data[1].SmartARC : '-'

                            , TOTAL_TotalHeats: data[2].TotalHeats ? data[2].TotalHeats : '-'
                            , TOTAL_TotalSteelWeight: data[2].TotalSteelWeight ? data[2].TotalSteelWeight.toFixed(1) : '-'
                            , TOTAL_TotalScrapWeight: data[2].TotalScrapWeight ? data[2].TotalScrapWeight.toFixed(1) : '-'
                            , TOTAL_TotalElectricEnergy: data[2].TotalElectricEnergy ? data[2].TotalElectricEnergy.toFixed(1) : '-'
                            , TOTAL_TotalElectrodeAdds: data[2].TotalElectrodeAdds ? data[2].TotalElectrodeAdds : '-'
                            , TOTAL_SteelWeight: data[2].SteelWeight ? data[2].SteelWeight.toFixed(1) : '-'
                            , TOTAL_ScrapWeight: data[2].ScrapWeight ? data[2].ScrapWeight.toFixed(1) : '-'
                            , TOTAL_Fluxes: data[2].Fluxes ? data[2].Fluxes.toFixed(1) : '-'
                            , TOTAL_Yield: data[2].Yield ? data[2].Yield.toFixed(1) : '-'
                            , TOTAL_TapToTap: data[2].TapToTap ? data[2].TapToTap.toFixed(1) : '-'
                            , TOTAL_PowerOn: data[2].PowerOn ? data[2].PowerOn.toFixed(1) : '-'
                            , TOTAL_InjectedC: data[2].InjectedC ? data[2].InjectedC.toFixed(1) : '-'
                            , TOTAL_EAFLastTemperature: data[2].EAFLastTemperature ? data[2].EAFLastTemperature.toFixed(1) : '-'
                            , TOTAL_ElectricEnergy: data[2].ElectricEnergy ? data[2].ElectricEnergy.toFixed(1) : '-'
                            , TOTAL_SpecificEnergy: data[2].SpecificEnergy ? data[2].SpecificEnergy.toFixed(1) : '-'
                            , TOTAL_ElectricPower: data[2].ElectricPower ? data[2].ElectricPower.toFixed(1) : '-'
                            , TOTAL_SmartARC: data[2].SmartARC ? data[2].SmartARC : '-'

                            , TOTAL_SteelWeightSTD: data[2].SteelWeightSTD ? data[2].SteelWeightSTD : '-'
                            , TOTAL_ScrapWeightSTD: data[2].ScrapWeightSTD ? data[2].ScrapWeightSTD : '-'
                            , TOTAL_YieldSTD: data[2].YieldSTD ? data[2].YieldSTD : '-'
                            , TOTAL_TapToTapSTD: data[2].TapToTapSTD ? data[2].TapToTapSTD : '-'
                            , TOTAL_PowerOnSTD: data[2].PowerOnSTD ? data[2].PowerOnSTD : '-'
                            , TOTAL_SpecificEnergySTD: data[2].SpecificEnergySTD ? data[2].SpecificEnergySTD : '-'
                        });
                    } else if (data.length == 2) {
                        if (data[0].EAF == 'EAF A') {
                            this.set({
                                hasData_EAF_A: true,

                                CREW_ID: data[0].CrewId ? data[0].CrewId : '-'

                                , EAF_A_TotalHeats: data[0].TotalHeats ? data[0].TotalHeats : '-'
                                , EAF_A_TotalSteelWeight: data[0].TotalSteelWeight ? data[0].TotalSteelWeight.toFixed(1) : '-'
                                , EAF_A_TotalScrapWeight: data[0].TotalScrapWeight ? data[0].TotalScrapWeight.toFixed(1) : '-'
                                , EAF_A_TotalElectricEnergy: data[0].TotalElectricEnergy ? data[0].TotalElectricEnergy.toFixed(1) : '-'
                                , EAF_A_TotalElectrodeAdds: data[0].TotalElectrodeAdds ? data[0].TotalElectrodeAdds : '-'
                                , EAF_A_SteelWeight: data[0].SteelWeight ? data[0].SteelWeight.toFixed(1) : '-'
                                , EAF_A_ScrapWeight: data[0].ScrapWeight ? data[0].ScrapWeight.toFixed(1) : '-'
                                , EAF_A_Fluxes: data[0].Fluxes ? data[0].Fluxes.toFixed(1) : '-'
                                , EAF_A_Yield: data[0].Yield ? data[0].Yield.toFixed(1) : '-'
                                , EAF_A_TapToTap: data[0].TapToTap ? data[0].TapToTap.toFixed(1) : '-'
                                , EAF_A_PowerOn: data[0].PowerOn ? data[0].PowerOn.toFixed(1) : '-'
                                , EAF_A_InjectedC: data[0].InjectedC ? data[0].InjectedC.toFixed(1) : '-'
                                , EAF_A_EAFLastTemperature: data[0].EAFLastTemperature ? data[0].EAFLastTemperature.toFixed(1) : '-'
                                , EAF_A_ElectricEnergy: data[0].ElectricEnergy ? data[0].ElectricEnergy.toFixed(1) : '-'
                                , EAF_A_SpecificEnergy: data[0].SpecificEnergy ? data[0].SpecificEnergy.toFixed(1) : '-'
                                , EAF_A_ElectricPower: data[0].ElectricPower ? data[0].ElectricPower.toFixed(1) : '-'
                                , EAF_A_SmartARC: data[0].SmartARC ? data[0].SmartARC : '-'

                                , EAF_B_TotalHeats: '-'
                                , EAF_B_TotalSteelWeight: '-'
                                , EAF_B_TotalScrapWeight: '-'
                                , EAF_B_TotalElectricEnergy: '-'
                                , EAF_B_TotalElectrodeAdds: '-'
                                , EAF_B_SteelWeight: '-'
                                , EAF_B_ScrapWeight: '-'
                                , EAF_B_Fluxes: '-'
                                , EAF_B_Yield: '-'
                                , EAF_B_TapToTap: '-'
                                , EAF_B_PowerOn: '-'
                                , EAF_B_InjectedC: '-'
                                , EAF_B_EAFLastTemperature: '-'
                                , EAF_B_ElectricEnergy: '-'
                                , EAF_B_SpecificEnergy: '-'
                                , EAF_B_ElectricPower: '-'
                                , EAF_B_SmartARC: '-'
                            });
                        } else if (data[0].EAF == 'EAF B') {
                            this.set({
                                hasData_EAF_B: true,

                                CREW_ID: data[0].CrewId ? data[0].CrewId : '-'

                                , EAF_B_TotalHeats: data[0].TotalHeats ? data[0].TotalHeats : '-'
                                , EAF_B_TotalSteelWeight: data[0].TotalSteelWeight ? data[0].TotalSteelWeight.toFixed(1) : '-'
                                , EAF_B_TotalScrapWeight: data[0].TotalScrapWeight ? data[0].TotalScrapWeight.toFixed(1) : '-'
                                , EAF_B_TotalElectricEnergy: data[0].TotalElectricEnergy ? data[0].TotalElectricEnergy.toFixed(1) : '-'
                                , EAF_B_TotalElectrodeAdds: data[0].TotalElectrodeAdds ? data[0].TotalElectrodeAdds : '-'
                                , EAF_B_SteelWeight: data[0].SteelWeight ? data[0].SteelWeight.toFixed(1) : '-'
                                , EAF_B_ScrapWeight: data[0].ScrapWeight ? data[0].ScrapWeight.toFixed(1) : '-'
                                , EAF_B_Fluxes: data[0].Fluxes ? data[0].Fluxes.toFixed(1) : '-'
                                , EAF_B_Yield: data[0].Yield ? data[0].Yield.toFixed(1) : '-'
                                , EAF_B_TapToTap: data[0].TapToTap ? data[0].TapToTap.toFixed(1) : '-'
                                , EAF_B_PowerOn: data[0].PowerOn ? data[0].PowerOn.toFixed(1) : '-'
                                , EAF_B_InjectedC: data[0].InjectedC ? data[0].InjectedC.toFixed(1) : '-'
                                , EAF_B_EAFLastTemperature: data[0].EAFLastTemperature ? data[0].EAFLastTemperature.toFixed(1) : '-'
                                , EAF_B_ElectricEnergy: data[0].ElectricEnergy ? data[0].ElectricEnergy.toFixed(1) : '-'
                                , EAF_B_SpecificEnergy: data[0].SpecificEnergy ? data[0].SpecificEnergy.toFixed(1) : '-'
                                , EAF_B_ElectricPower: data[0].ElectricPower ? data[0].ElectricPower.toFixed(1) : '-'
                                , EAF_B_SmartARC: data[0].SmartARC ? data[0].SmartARC : '-'


                                , EAF_A_TotalHeats: '-'
                                , EAF_A_TotalSteelWeight: '-'
                                , EAF_A_TotalScrapWeight: '-'
                                , EAF_A_TotalElectricEnergy: '-'
                                , EAF_A_TotalElectrodeAdds: '-'
                                , EAF_A_SteelWeight: '-'
                                , EAF_A_ScrapWeight: '-'
                                , EAF_A_Fluxes: '-'
                                , EAF_A_Yield: '-'
                                , EAF_A_TapToTap: '-'
                                , EAF_A_PowerOn: '-'
                                , EAF_A_InjectedC: '-'
                                , EAF_A_EAFLastTemperature: '-'
                                , EAF_A_ElectricEnergy: '-'
                                , EAF_A_SpecificEnergy: '-'
                                , EAF_A_ElectricPower: '-'
                                , EAF_A_SmartARC: '-'
                            })
                        }

                        this.set({

                            CREW_ID: data[0].CrewId ? data[0].CrewId : '-'

                            , TOTAL_TotalHeats: data[1].TotalHeats ? data[1].TotalHeats : '-'
                            , TOTAL_TotalSteelWeight: data[1].TotalSteelWeight ? data[1].TotalSteelWeight.toFixed(1) : '-'
                            , TOTAL_TotalScrapWeight: data[1].TotalScrapWeight ? data[1].TotalScrapWeight.toFixed(1) : '-'
                            , TOTAL_TotalElectricEnergy: data[1].TotalElectricEnergy ? data[1].TotalElectricEnergy.toFixed(1) : '-'
                            , TOTAL_TotalElectrodeAdds: data[1].TotalElectrodeAdds ? data[1].TotalElectrodeAdds : '-'
                            , TOTAL_SteelWeight: data[1].SteelWeight ? data[1].SteelWeight.toFixed(1) : '-'
                            , TOTAL_ScrapWeight: data[1].ScrapWeight ? data[1].ScrapWeight.toFixed(1) : '-'
                            , TOTAL_Fluxes: data[1].Fluxes ? data[1].Fluxes.toFixed(1) : '-'
                            , TOTAL_Yield: data[1].Yield ? data[1].Yield.toFixed(1) : '-'
                            , TOTAL_TapToTap: data[1].TapToTap ? data[1].TapToTap.toFixed(1) : '-'
                            , TOTAL_PowerOn: data[1].PowerOn ? data[1].PowerOn.toFixed(1) : '-'
                            , TOTAL_InjectedC: data[1].InjectedC ? data[1].InjectedC.toFixed(1) : '-'
                            , TOTAL_EAFLastTemperature: data[1].EAFLastTemperature ? data[1].EAFLastTemperature.toFixed(1) : '-'
                            , TOTAL_ElectricEnergy: data[1].ElectricEnergy ? data[1].ElectricEnergy.toFixed(1) : '-'
                            , TOTAL_SpecificEnergy: data[1].SpecificEnergy ? data[1].SpecificEnergy.toFixed(1) : '-'
                            , TOTAL_ElectricPower: data[1].ElectricPower ? data[1].ElectricPower.toFixed(1) : '-'
                            , TOTAL_SmartARC: data[1].SmartARC ? data[1].SmartARC : '-'

                            , TOTAL_SteelWeightSTD: data[1].SteelWeightSTD ? data[1].SteelWeightSTD : '-'
                            , TOTAL_ScrapWeightSTD: data[1].ScrapWeightSTD ? data[1].ScrapWeightSTD : '-'
                            , TOTAL_YieldSTD: data[1].YieldSTD ? data[1].YieldSTD : '-'
                            , TOTAL_TapToTapSTD: data[1].TapToTapSTD ? data[1].TapToTapSTD : '-'
                            , TOTAL_PowerOnSTD: data[1].PowerOnSTD ? data[1].PowerOnSTD : '-'
                            , TOTAL_SpecificEnergySTD: data[1].SpecificEnergySTD ? data[1].SpecificEnergySTD : '-'
                        })
                    }
                    hasData = true;
                }
                this.trigger('TotalsAndAverages', hasData);
            },
        });

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

        //the generate id method is called everytime a view is going to be shown by the router and returns and id that
        //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
        //this is useful in case your view is reusable, and displays different data depending on url parameters 
        //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
        //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
        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-shift-report';
            } catch (Error) { }
        }

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'eaf-shift-report'
            , id: 'eaf-shift-report'
            , title: 'EAF Shift Report'

            //default not cacheable, change this if you want the view to be cacheable
            // if the view is set as cacheable should also have a _refresh method to reset the view without erasing the DOM.
            , isCacheable: false
            , events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #printBtn': this.printBtn_click,
                    'click #forwardNavBtn': this.forwardNavBtn_click,
                    'click #backNavBtn': this.backNavBtn_click,
                };
            }
            , bindings: 'data-bind'
            , viewParams: null
            , initialize: function () {
                this.options.state = app.view_states.loading;
                this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

                this.model = new Screen.Models.Main();
                this.bindEvents();
            }


            , forwardNavBtn_click: function () {
                this.UpdateNav(true);
            }
            , backNavBtn_click: function () {
                this.UpdateNav(false);
            }

            , printBtn_click: function () {
                window.scrollTo(0, 0);
                window.print();
                return false;
            }

            , refreshBtn_click: function (model) {
                this.UpdateURL();
                this.refresh();
            }


            , bindEvents: function () {
                this.listenTo(this.model, 'fetch', this.fetched);

                this.listenTo(this.model, 'furnace2_READY', this.furnace1_chart);
                this.listenTo(this.model.itemsAllHeats, 'fetch', this.itemsAllHeats_ready);
                this.listenTo(this.model.itemsTemperature, 'fetch', this.itemsTemperature_ready);
                this.listenTo(this.model.itemsInjectionFluxesEAFA, 'fetch', this.itemsInjectionFluxesEAFA_ready);
                this.listenTo(this.model.itemsInjectionFluxesEAFB, 'fetch', this.itemsInjectionFluxesEAFB_ready);
                this.listenTo(this.model.itemsBucketFluxesEAFA, 'fetch', this.itemsBucketFluxesEAFA_ready);
                this.listenTo(this.model.itemsBucketFluxesEAFB, 'fetch', this.itemsBucketFluxesEAFB_ready);
                this.listenTo(this.model.itemsBaghouse, 'fetch', this.itemsBaghouse_ready);

                this.listenTo(this.model.itemsDelays, 'fetch', this.itemsDelaysEAFA_ready);
                this.listenTo(this.model.itemsSlag, 'fetch', this.itemsSlag_ready);
                this.listenTo(this.model.itemsRecipes, 'fetch', this.itemsRecipes_ready);
                this.listenTo(this.model.itemsRecipesAverage, 'fetch', this.recipesAverage_ready);
                this.listenTo(this.model.itemsManualTemps, 'fetch', this.manualTemps_ready);
                this.listenTo(this.model.itemsTapHoleNonFreeOpen, 'fetch', this.tapHoleNonFreeOpen_ready);
                this.listenTo(this.model.itemsLogBook, 'fetch', this.itemsLogBook_ready);
            },

            itemsAllHeats_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_allHeats: (that.model.itemsAllHeats.length > 0),
                                isLoading_allHeats: false,
                            });
                            that.furnace2_chart();
                        },
                        100
                    );

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

            furnace1_chart: function () {
                var that = this;

                setTimeout(
                    function () {
                        that.getChart(true, 820, true);
                        that.getChart(true, 1400, false);
                        that.model.set({
                            isLoading_furnace1: false,
                        });
                    },
                    100
                );

            },
            furnace2_chart: function () {
                var that = this;
                setTimeout(
                    function () {
                        that.getChart(false, 820, true);
                        that.getChart(false, 1400, false);
                        that.model.trigger('furnace2_READY', that);
                    },
                    100
                );
            },

            // Charts
            getYieldChart: function (className, width, height) {
                // Define the data for the chart
                var data = this.model.itemsYield.toJSON();

                // Set the dimensions for the chart
                var margin = { top: 20, right: 10, bottom: 100, left: 30 };
                var width = width - margin.left - margin.right;
                var height = height - margin.top - margin.bottom;

                // Create the x and y scales
                var xScale = d3.scaleBand()
                    .domain(data.map(function (d) { return d.date + " " + d.shift; }))
                    .range([0, width])
                //.paddingInner(0.2)
                //.paddingOuter(0.2);
                var yScale = d3.scaleLinear()
                    .domain([80, 110])
                    .range([height, 0]);

                // Create the x and y axes
                var xAxis = d3.axisBottom(xScale);
                var yAxis = d3.axisLeft(yScale);

                // Create the chart
                var svg = d3.select(className)
                    .append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom)
                    .append("g")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                // Add the x and y axes to the chart
                svg.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis)
                    .selectAll("text")
                    .style("text-anchor", "end")
                    .attr("dx", "-.8em")
                    .attr("dy", ".15em")
                    .attr("transform", "rotate(-65)");
                svg.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);


                // Add dashed lines vertically on each x axis tick
                svg.selectAll(".x.axis .tick")
                    .append("line")
                    .attr("class", "grid-line-x")
                    .attr("x1", 0)
                    .attr("x2", 0)
                    .attr("y1", -height)
                    .attr("y2", 0)
                    .style("stroke-dasharray", "3,3")
                    .style("stroke", "gray");

                // Add dashed lines horizontally on each y axis tick
                svg.selectAll(".y.axis .tick")
                    .append("line")
                    .attr("class", "grid-line-y")
                    .attr("x1", 0)
                    .attr("x2", width)
                    .attr("y1", 0)
                    .attr("y2", 0)
                    .style("stroke-dasharray", "3,3")
                    .style("stroke", "gray");

                svg
                    .selectAll("whatever")
                    .data(data)
                    .enter()
                    .append("circle")
                    .attr("fill", "rgb(130, 128, 252)")
                    .attr("cx", function (d) { return (xScale(d.date + " " + d.shift) + xScale.bandwidth() / 2); })
                    .attr("cy",
                        function (d) {
                            if (d.yieldEAFA > 110) return yScale(110);
                            else if (d.yieldEAFA < 80) return yScale(80);
                            else return yScale(d.yieldEAFA)
                        }
                    )
                    .attr("r", 3)
                    .on('mouseover', function () {
                        d3.select(this)
                            .transition()
                            .duration(500)
                            .attr('stroke', 'green')
                            .attr('stroke-width', 3)
                    })
                    .on('mouseout', function () {
                        d3.select(this)
                            .transition()
                            .duration(500)
                            .attr('stroke', 'rgb(130, 128, 252)')
                            .attr('stroke-width', 1)
                    })
                    .append("svg:title")
                    .text(function (d) {
                        if (d.yieldEAFA)
                            return `EAF A - ${d.date} ${d.shift} - Yield: ${d.yieldEAFA}`;
                        else return '';
                    })
                    .attr("transform", "translate(" + margin.left + "," + 0 + ")");

                // Add the line
                svg.append("path")
                    .datum(data)
                    .attr("fill", "none")
                    .attr("stroke", "rgb(130, 128, 252)")
                    .attr("stroke-width", 0.7)
                    .attr("d", d3.line()
                        .x(function (d) { return (xScale(d.date + " " + d.shift) + xScale.bandwidth() / 2); })
                        .y(
                            function (d) {
                                if (d.yieldEAFA > 110) return yScale(110);
                                else if (d.yieldEAFA < 80) return yScale(80);
                                else return yScale(d.yieldEAFA)
                            }
                        )
                    )


                svg
                    .selectAll("whatever")
                    .data(data)
                    .enter()
                    .append("circle")
                    .attr("fill", "rgb(237, 86, 86)")
                    .attr("cx", function (d) { return xScale(d.date + " " + d.shift) + xScale.bandwidth() / 2; })
                    .attr("cy",
                        function (d) {
                            if (d.yieldEAFB > 110) return yScale(110);
                            else if (d.yieldEAFB < 80) return yScale(80);
                            else return yScale(d.yieldEAFB)
                        }
                    )
                    .attr("r", 3)
                    .on('mouseover', function () {
                        d3.select(this)
                            .transition()
                            .duration(500)
                            .attr('stroke', 'green')
                            .attr('stroke-width', 3)
                    })
                    .on('mouseout', function () {
                        d3.select(this)
                            .transition()
                            .duration(500)
                            .attr('stroke', 'rgb(237, 86, 86)')
                            .attr('stroke-width', 1)
                    })
                    .append("svg:title")
                    .text(function (d) {
                        if (d.yieldEAFB)
                            return `EAF B - ${d.date} ${d.shift} - Yield: ${d.yieldEAFB}`;
                        else return '';
                    })

                // Add the line
                svg.append("path")
                    .datum(data)
                    .attr("fill", "none")
                    .attr("stroke", "rgb(237, 86, 86)")
                    .attr("stroke-width", 0.7)

                    .attr("d", d3.line()
                        .x(function (d) { return xScale(d.date + " " + d.shift) + xScale.bandwidth() / 2; })
                        .y(function (d) {
                            if (d.yieldEAFB > 110) return yScale(110);
                            else if (d.yieldEAFB < 80) return yScale(80);
                            else return yScale(d.yieldEAFB)
                        })
                    )
                // References
                svg.append("circle")
                    .attr("cy", -12)
                    .attr("cx", 40)
                    .attr("fill", "rgb(130, 128, 252)")
                    .attr("r", 6)

                svg.append("text")
                    .attr("y", -8)
                    .attr("x", 50)
                    .text("Yield EAF A")


                svg.append("circle")
                    .attr("cy", -12)
                    .attr("cx", 150)
                    .attr("fill", "#ed5656")
                    .attr("r", 6)

                svg.append("text")
                    .attr("y", -8)
                    .attr("x", 160)
                    .text("Yield EAF B")

            },


            getChart(furnace1, width, print) {
                var chartHeight = 110,
                    chartWeight = width,

                    /*dataHeight = chartHeight / 2,*/
                    dataHeight = chartHeight / 2,
                    delayHeight = chartHeight / 4,
                    divisions = 12,
                    pixelHour = (chartWeight) / divisions,
                    pixelMinute = pixelHour / 60,
                    separationPixels = 10,
                    axisHeight = 20,
                    startHourPixel = 0,
                    start = 0,
                    start_yPos = 0,
                    data = [],
                    size_letter = 10;
                var strandsData = [];
                var that = this;
                if (furnace1) {
                    _.each(this.model.itemsAllHeats.getHeats_furnace1(), function (obj) {
                        data.push(obj);
                    })
                    _.each(this.model.itemsAllDelays.getDelay_furnace1(), function (obj) {
                        data.push(obj);
                    });
                    var chart_class = print ? ".furnace1-gantt" : ".furnace1-gantt-screen";
                } else {
                    _.each(this.model.itemsAllHeats.getHeats_furnace2(), function (obj) {
                        data.push(obj);
                    })
                    _.each(this.model.itemsAllDelays.getDelay_furnace2(), function (obj) {
                        data.push(obj);
                    });
                    var chart_class = print ? ".furnace2-gantt" : ".furnace2-gantt-screen";
                }
                if (data.length > 0) {
                    var chart = d3.select(chart_class)
                        .attr("width", 1650)
                        .attr("height", chartHeight + separationPixels + axisHeight + 10)

                    // Append the horizontal lines
                    chart.append("rect")
                        .attr("class", "line")
                        .attr("width", chartWeight)
                        .attr("height", 0.5)
                        .style('opacity', 1)
                        .attr("transform", "translate(" + 0 + "," + 55 + ")")
                        .style('fill', '#505050')

                    chart.append("rect")
                        .attr("class", "line")
                        .attr("width", chartWeight)
                        .attr("height", 0.5)
                        .style('opacity', 1)
                        .attr("transform", "translate(" + 0 + "," + 105 + ")")
                        .style('fill', '#505050')



                    var bar = chart.selectAll("g")
                        .data(data)
                        .enter().append("g")

                    //Append delays and heats
                    bar.append("rect")
                        .attr("width", function (d) { return (d.diffHours > 0) ? d.diffHours * pixelHour : 0; })
                        .attr("height", function (d) {
                            if (d.type == 'delay') return delayHeight;
                            return dataHeight;
                        })
                        .attr("transform", function (d) {
                            start = parseFloat(d.startHour);
                            start_yPos = (d.type == "heat") ? parseInt(0) : (dataHeight + separationPixels);
                            if (d.shift == "D") {
                                startHourPixel = start - 9;
                            }
                            else if (d.shift == "N") {
                                if (d.startHour >= 21) {
                                    startHourPixel = start - 21;
                                }
                                else if (d.startHour < 21) {
                                    startHourPixel = start + 3;
                                }
                            }
                            return "translate(" + startHourPixel * pixelHour + "," + start_yPos + ")";
                        })
                        .style('fill', function (d) { return d.color; })
                        .style('opacity', 1)
                        .attr('stroke', '#505050')
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'red')
                                .attr('stroke-width', 2)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', '#505050')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            return d.heatName
                                ? `Heat: ${d.heatName} | Start: ${new moment(d.start).format('HH:mm')} | End: ${new moment(d.end).format('HH:mm')} | Dur: ${d.duration}`
                                : `Start: ${new moment(d.start).format('HH:mm')} | End: ${new moment(d.end).format('HH:mm')} | Dur: ${d.duration}`;
                        })


                    //-----------------------------------
                    //-----------------------------------

                    ////Append top text

                    bar.append("text")
                        .attr("class", "top_text")
                        .attr("y", function (d) {
                            var currentY = (d.type == "heat") ? (parseInt(0) + 2 * size_letter) : (dataHeight + separationPixels + 2 * size_letter);
                            return (d.type == "heat") ? currentY - 8 : currentY + 4;


                        })
                        .text(function (d) {
                            if (d.name) {
                                //var text = ((d.name.length * size_letter) > (d.diffHours * pixelHour)) ? '' : d.name;
                                var text = d.name;
                                return text;
                            } else
                                return '';
                        })
                        .attr('font-size', '10px')
                        .style('fill', '#505050')
                        .attr("id", function (d, i) { return "int_text" + "_" + i });

                    // Center the top text in the rectangle
                    chart.selectAll("g")
                        .select(".top_text")
                        .style('fill', '#505050')
                        .attr("x", function (d, i) {

                            var text_element_width = 20.02;

                            if (d.type === 'delay') {
                                if (d.name.length === 2) text_element_width = 10;
                                if (d.name.length === 3) text_element_width = 16.67;
                            }

                            start = parseFloat(d.startHour);
                            if (d.shift == "D") startHourPixel = start - 9;
                            else if (d.shift == "N") {
                                if (d.startHour >= 21) startHourPixel = start - 21;
                                else if (d.startHour < 21) startHourPixel = start + 3;
                            }
                            var rect_start = startHourPixel * pixelHour,
                                rect_width = d.diffHours * pixelHour;
                            return (rect_start + rect_width - (rect_width / 2.0) - (text_element_width / 2.0));

                        });


                    chart.selectAll("g")
                        .select("rect")
                        .attr("height", function (d, i) {
                            if (d.type == 'delay') return delayHeight;
                            return dataHeight;
                        })
                        .attr("y", function (d, i) {
                            if (d.type == 'delay') return "28"
                            return "22";
                        });



                    //Select the correct scale
                    var params = this.model.toJSON();
                    if (params.shiftId == 'D') {
                        var scale = d3.scalePoint()
                            .domain(["9AM", "10AM", "11AM", "12PM", "1PM", "2PM", "3PM", "4PM", "5PM", "6PM", "7PM", "8PM", "9PM"])
                            .range([0, chartWeight]);
                    } else if (params.shiftId == 'N') {
                        var scale = d3.scalePoint()
                            .domain(["9PM", "10PM", "11PM", "12AM", "1AM", "2AM", "3AM", "4AM", "5AM", "6AM", "7AM", "8AM", "9AM"])
                            .range([0, chartWeight]);
                    }
                    // Append x axis
                    var x_axis = d3.axisBottom()
                        .scale(scale);

                    chart.append("g")
                        .attr("class", "axis_label")
                        .attr("transform", "translate(" + 0 + "," + (chartHeight + separationPixels + 4) + ")")
                        .call(x_axis);

                    var array_id = [];
                    chart.selectAll("g")
                        .select(".tick text")
                        .attr("id", function (d, i) {
                            array_id.push(i);
                            return "text_hour" + "_" + i
                        });

                    chart.selectAll("g")
                        .select("#text_hour_" + array_id[1]).attr("x", 12);

                    chart.selectAll("g")
                        .select("#text_hour_" + array_id[13]).attr("x", -10);
                }

            },

            referencesChart: function () {
                // create svg element:
                var svgDuration = d3.select("#refsDuration").append("svg").attr("width", 755).attr("height", 45)
                var svgCategories = d3.select("#refsCategories").append("svg").attr("width", 755).attr("height", 45)

                //avoid repeat Colors and 1st hierarchy names
                var srdCategories = [...new Map(this.model.srdCategories.models.map(item => [item.get('description'), item])).values()];
                // Add the path using this helper function
                svgDuration.append("text")
                    .attr("y", 18)
                    .attr("x", 0)
                    .attr("font-size", 16)
                    .attr("font-weight", "bold")
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Heat Duration");

                svgDuration.append('rect')
                    .attr('x', 180)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', '#3ebf3c');


                svgDuration.append("text")
                    .attr('y', 18)
                    .attr("x", 212)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("< 40 Min");


                svgDuration.append('rect')
                    .attr('x', 290)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', '#f3f317');

                svgDuration.append("text")
                    .attr('y', 18)
                    .attr("x", 322)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Btw 40 & 50 Min");



                svgDuration.append('rect')
                    .attr('x', 444)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', '#ff5900');


                svgDuration.append("text")
                    .attr('y', 18)
                    .attr("x", 474)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("> 50 Min");


                svgCategories.append("text")
                    .attr("y", 18)
                    .attr("x", 0)
                    .attr("font-size", 16)
                    .attr("font-weight", "bold")
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Delay Cat.");

                svgCategories.append('rect')
                    .attr('x', 85)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', "f84e4e");

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 115)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Not Declared");

                svgCategories.append('rect')
                    .attr('x', 195)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Caster')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 225)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Caster");


                svgCategories.append('rect')
                    .attr('x', 280)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'EAF')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 310)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("EAF");


                svgCategories.append('rect')
                    .attr('x', 350)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Flux')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 380)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Flux");

                svgCategories.append('rect')
                    .attr('x', 420)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Ladle crane')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 450)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Ladle Crane");

                svgCategories.append('rect')
                    .attr('x', 540)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'LMF')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 570)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("LMF");

                svgCategories.append('rect')
                    .attr('x', 610)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Scrap')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 640)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Scrap");


                svgCategories.append('rect')
                    .attr('x', 690)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'VTD')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 720)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("VTD");

                // create svg element:
                svgDuration = d3.select("#refs-screen-duration").append("svg").attr("width", 755).attr("height", 45)
                svgCategories = d3.select("#refs-screen-categories").append("svg").attr("width", 755).attr("height", 45)

                // Add the path using this helper function
                svgDuration.append("text")
                    .attr("y", 18)
                    .attr("x", 0)
                    .attr("font-size", 16)
                    .attr("font-weight", "bold")
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Heat Duration");

                svgDuration.append('rect')
                    .attr('x', 180)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', '#3ebf3c');


                svgDuration.append("text")
                    .attr('y', 18)
                    .attr("x", 212)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("< 40 Min");


                svgDuration.append('rect')
                    .attr('x', 290)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', '#f3f317');

                svgDuration.append("text")
                    .attr('y', 18)
                    .attr("x", 322)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Btw 40 & 50 Min");



                svgDuration.append('rect')
                    .attr('x', 444)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', '#ff5900');


                svgDuration.append("text")
                    .attr('y', 18)
                    .attr("x", 474)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("> 50 Min");


                svgCategories.append("text")
                    .attr("y", 18)
                    .attr("x", 0)
                    .attr("font-size", 16)
                    .attr("font-weight", "bold")
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Delay Cat.");

                svgCategories.append('rect')
                    .attr('x', 85)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Baghouse')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 115)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Baghouse");

                svgCategories.append('rect')
                    .attr('x', 195)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Caster')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 225)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Caster");


                svgCategories.append('rect')
                    .attr('x', 280)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'EAF')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 310)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("EAF");


                svgCategories.append('rect')
                    .attr('x', 350)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Flux')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 380)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Flux");

                svgCategories.append('rect')
                    .attr('x', 420)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Ladle crane')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 450)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Ladle Crane");

                svgCategories.append('rect')
                    .attr('x', 540)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'LMF')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 570)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("LMF");

                svgCategories.append('rect')
                    .attr('x', 610)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'Scrap')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 640)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("Scrap");

                svgCategories.append('rect')
                    .attr('x', 690)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25)
                    .attr('stroke', 'rgb(80, 80, 80)')
                    .attr('fill', srdCategories.filter(x => x.get('description') == 'VTD')[0].get('color'));

                svgCategories.append("text")
                    .attr('y', 18)
                    .attr("x", 720)
                    .attr("font-size", 16)
                    .attr("fill", "#505050")
                    .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                    .text("VTD");
            },
            temperatureChart: function (data, id, width) {

                var domainBand = [];

                _.each(data, function (obj, i) {
                    domainBand[i] = obj.HeatName;
                });

                var title = '';
                var chartWidth = width;
                //var chartHeight =  310;  this.model.get('chartHeight');
                //var heightOffset = 285; this.model.get('heightOffset');

                var chartHeight = this.model.get('chartHeight');
                var heightOffset = this.model.get('heightOffset');
                var chartMarginLeft = 80;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 250;
                var minValueBottomAxis = 0;
                var maxValueLeft = 3200;
                var minValueLeft = 2700;
                if (data.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * data.length);

                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + heightOffset + ")");

                    var x = d3.scaleBand()
                        .domain(domainBand)
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'dashed x_text')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(7))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })


                    var y = d3.scaleLinear()
                        .domain([minValueLeft, maxValueLeft])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y_text dashed")
                        .call(d3.axisLeft(y).tickSize(-maxAxisBottom).ticks(10))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y_text .tick text")
                        .attr("x", function (d, i) {
                            return -20;
                        });


                    if (id == '.temperature_EAFA') {
                        title = "EAF A - Temperature";
                        this.model.set({ hasData_temperature_EAFA: true });
                    }
                    else if (id == '.temperature_EAFB') {
                        title = "EAF B - Temperature";
                        this.model.set({ hasData_temperature_EAFB: true });
                    }

                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("color", "black")
                        .attr("cx", function (d) {
                            if (d.EAFLastTemperature)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.EAFLastTemperature) {
                                if (d.EAFLastTemperature > maxValueLeft) return y(maxValueLeft);
                                else if (d.EAFLastTemperature < minValueLeft) return y(minValueLeft);
                                else return y(d.EAFLastTemperature);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.EAFLastTemperature)
                                return 4
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'black')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.EAFLastTemperature)
                                return "Last Temperature: " + d.EAFLastTemperature;
                            else return '';
                        })


                    // References
                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 0)
                        .attr("fill", "black")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 10)
                        .text("Last Temperature")


                    // Add the line
                    svg.append("line")          // attach a line
                        .style("stroke", "red")  // colour the line
                        .attr("x1", 0)     // x position of the first end of the line
                        .attr("y1", y(3000))      // y position of the first end of the line
                        .attr("x2", maxAxisBottom)     // x position of the second end of the line
                        .attr("y2", y(3000))    // y position of the second end of the line




                    // ---------------------------
                    // ------ Aim Temps ---------
                    // ---------------------------

                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 150)
                        .attr("fill", "blue")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 160)
                        .text("Temperature Aim")

                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "blue")
                        .attr("cx", function (d) {
                            if (d.EAFAimTemperature)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.EAFAimTemperature) {
                                if (d.EAFAimTemperature > maxValueLeft) return y(maxValueLeft);
                                else if (d.EAFAimTemperature < minValueLeft) return y(minValueLeft);
                                else return y(d.EAFAimTemperature);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.EAFAimTemperature)
                                return 2
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'blue')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.EAFLastTemperature)
                                return "Temperature Aim: " + d.EAFAimTemperature;
                            else return '';
                        })
                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "blue")
                        .attr("stroke-width", 0.7)
                        //.style("stroke-dasharray", ("3, 3"))  
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.EAFAimTemperature) {
                                    if (d.EAFAimTemperature > maxValueLeft) return y(maxValueLeft);
                                    else if (d.EAFAimTemperature < minValueLeft) return y(minValueLeft);
                                    else return y(d.EAFAimTemperature);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")



                }



            },
            oxygenChart: function (data, id, width) {
                var domainBand = [];
                _.each(data, function (obj, i) {
                    domainBand[i] = obj.HeatName;
                });

                var chartWidth = width;

                var chartHeight = this.model.get('chartHeight');
                var heightOffset = this.model.get('heightOffset');
                var chartMarginLeft = 80;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 250;
                var minValueBottomAxis = 0;

                var maxValueLeft = 1500;
                var minValueLeft = 0;

                if (data.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * data.length);

                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + heightOffset + ")");

                    var x = d3.scaleBand()
                        .domain(domainBand)
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'dashed x_text')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(7))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })


                    var y = d3.scaleLinear()
                        .domain([minValueLeft, maxValueLeft])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y_text dashed")
                        .call(d3.axisLeft(y).tickSize(-maxAxisBottom).ticks(20))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y_text .tick text")
                        .attr("x", function (d, i) {
                            return -20;
                        });
                    if (id == '.oxygen_EAFA' || id == '.oxygen_EAFA_print') {
                        title = "EAF A - Oxygen";
                        this.model.set({ hasData_oxygen_EAFA: true });
                    }
                    else if (id == '.oxygen_EAFB' || id == '.oxygen_EAFA_print') {
                        title = "EAF B - Oxygen";
                        this.model.set({ hasData_oxygen_EAFB: true });
                    }
                    //svg.append("text")
                    //    .attr("x", 5)
                    //    .attr("y", -335)
                    //    .attr("text-anchor", "middle")
                    //    .attr("class", "text")
                    //    .style("font-size", "16px")
                    //    .text(title);

                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "blue")
                        .attr("cx", function (d) {
                            if (d.EAFLastO2)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.EAFLastO2) {
                                if (d.EAFLastO2 > maxValueLeft) return y(maxValueLeft);
                                else if (d.EAFLastO2 < minValueLeft) return y(minValueLeft);
                                else return y(d.EAFLastO2);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.EAFLastO2)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'blue')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.EAFLastO2)
                                return "Last O2: " + d.EAFLastO2;
                            else return '';
                        })


                    // References

                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 0)
                        .attr("fill", "blue")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 10)
                        .text("Last O2")





                    // -----------------------
                    // ----- Aim Last O2 -----
                    // -----------------------
                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 100)
                        .attr("fill", "green")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 110)
                        .text("O2 Aim")

                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "green")
                        .attr("cx", function (d) {
                            if (d.EAFAimO2)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.EAFAimO2) {
                                if (d.EAFAimO2 > maxValueLeft) return y(maxValueLeft);
                                else if (d.EAFAimO2 < minValueLeft) return y(minValueLeft);
                                else return y(d.EAFAimO2);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.EAFAimO2)
                                return 2
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'red')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.EAFAimO2)
                                return "Oygen Aim: " + d.EAFAimO2;
                            else return '';
                        })
                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "green")
                        .attr("stroke-width", 0.7)
                        //.style("stroke-dasharray", ("5, 5"))  
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.EAFAimO2) {
                                    if (d.EAFAimO2 > maxValueLeft) return y(maxValueLeft);
                                    else if (d.EAFAimO2 < minValueLeft) return y(minValueLeft);
                                    else return y(d.EAFAimO2);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")




                }



            },
            residualsChart: function (data, id, width) {
                var domainBand = [];

                _.each(data, function (obj, i) {
                    domainBand[i] = obj.HeatName;
                });

                var title = '';
                var chartWidth = width;

                var chartHeight = this.model.get('chartHeight');
                var heightOffset = this.model.get('heightOffset');
                var chartMarginLeft = 80;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 250;
                var minValueBottomAxis = 0;
                var maxValueLeft = 0.7;
                var minValueLeft = 0;
                if (data.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * data.length);
                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + heightOffset + ")");

                    var x = d3.scaleBand()
                        .domain(domainBand)
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'x_text dashed')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(7))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })


                    var y = d3.scaleLinear()
                        .domain([minValueLeft, maxValueLeft])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y_text dashed")
                        .call(d3.axisLeft(y).tickSize(-maxAxisBottom).ticks(10))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y_text .tick text")
                        .attr("x", function (d, i) {
                            return -20;
                        });

                    if (id == '.residuals_EAFA') {
                        title = "EAF A - Residual Graph 1";
                        this.model.set({ hasData_residuals_EAFA: true });
                    }
                    else if (id == '.residuals_EAFB') {
                        title = "EAF B - Residual Graph 1";
                        this.model.set({ hasData_residuals_EAFB: true });
                    }
                    //svg.append("text")
                    //    .attr("x", 45)
                    //    .attr("y", -335)
                    //    .attr("text-anchor", "middle")
                    //    .attr("class", "text")
                    //    .style("font-size", "16px")
                    //    .text(title);

                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "black")
                        .attr("cx", function (d) {
                            if (d.Cu)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.Cu) {
                                if (d.Cu > maxValueLeft) return y(maxValueLeft);
                                else if (d.Cu < minValueLeft) return y(minValueLeft);
                                else return y(d.Cu);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.Cu)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'black')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.Cu)
                                return "Cu: " + d.Cu;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "black")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.Cu) {
                                    if (d.Cu > maxValueLeft) return y(maxValueLeft);
                                    else if (d.Cu < minValueLeft) return y(minValueLeft);
                                    else return y(d.Cu);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")


                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "red")
                        .attr("cx", function (d) {
                            if (d.Cr)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.Cr) {
                                if (d.Cr > maxValueLeft) return y(maxValueLeft);
                                else if (d.Cr < minValueLeft) return y(minValueLeft);
                                else return y(d.Cr);
                            }

                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.Cr)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'black')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.Cr)
                                return "Cr: " + d.Cr;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "red")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.Cr) {
                                    if (d.Cr > maxValueLeft) return y(maxValueLeft);
                                    else if (d.Cr < minValueLeft) return y(minValueLeft);
                                    else return y(d.Cr);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")


                    // Y axis label
                    //svg.append("text")
                    //    .attr("y", -265)
                    //    .attr("x", -55)
                    //    .text("Residuals")

                    // References
                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 0)
                        .attr("color", "black")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 10)
                        .text("Cu")


                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 50)
                        .attr("fill", "red")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 60)
                        .text("Cr")

                }

            }
            , residualsChart2: function (data, id, width) {
                var domainBand = [];

                _.each(data, function (obj, i) {
                    domainBand[i] = obj.HeatName;
                });

                var title = '';
                var chartWidth = width;

                var chartHeight = this.model.get('chartHeight');
                var heightOffset = this.model.get('heightOffset');
                var chartMarginLeft = 80;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 250;
                var minValueBottomAxis = 0;
                var maxValueLeft = 0.05;
                var minValueLeft = 0;
                if (data.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * data.length);
                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + heightOffset + ")");

                    var x = d3.scaleBand()
                        .domain(domainBand)
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'x_text dashed')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(7))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })


                    var y = d3.scaleLinear()
                        .domain([minValueLeft, maxValueLeft])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y_text dashed")
                        .call(d3.axisLeft(y).tickSize(-maxAxisBottom).ticks(10))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y_text .tick text")
                        .attr("x", function (d, i) {
                            return -20;
                        });

                    if (id == '.residuals_EAFA_2') {
                        title = "EAF A - Residual Graph 2";
                        this.model.set({ hasData_residuals_EAFA_2: true });
                    }
                    else if (id == '.residuals_EAFB_2') {
                        title = "EAF B - Residual Graph 2";
                        this.model.set({ hasData_residuals_EAFB_2: true });
                    }
                    //svg.append("text")
                    //    .attr("x", 45)
                    //    .attr("y", -335)
                    //    .attr("text-anchor", "middle")
                    //    .attr("class", "text")
                    //    .style("font-size", "16px")
                    //    .text(title);

                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "black")
                        .attr("cx", function (d) {
                            if (d.Mo)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.Mo) {
                                if (d.Mo > maxValueLeft) return y(maxValueLeft);
                                else if (d.Mo < minValueLeft) return y(minValueLeft);
                                else return y(d.Mo);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.Mo)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'black')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.Mo)
                                return "Mo: " + d.Mo;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "black")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.Mo) {
                                    if (d.Mo > maxValueLeft) return y(maxValueLeft);
                                    else if (d.Mo < minValueLeft) return y(minValueLeft);
                                    else return y(d.Mo);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")


                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "red")
                        .attr("cx", function (d) {
                            if (d.Sn)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.Sn) {
                                if (d.Sn > maxValueLeft) return y(maxValueLeft);
                                else if (d.Sn < minValueLeft) return y(minValueLeft);
                                else return y(d.Sn);
                            }

                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.Sn)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'red')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.Sn)
                                return "Sn: " + d.Sn;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "red")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.Sn) {
                                    if (d.Sn > maxValueLeft) return y(maxValueLeft);
                                    else if (d.Sn < minValueLeft) return y(minValueLeft);
                                    else return y(d.Sn);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")


                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "blue")
                        .attr("cx", function (d) {
                            if (d.P)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.P) {
                                if (d.P > maxValueLeft) return y(maxValueLeft);
                                else if (d.P < minValueLeft) return y(minValueLeft);
                                else return y(d.P);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.P)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'blue')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.P)
                                return "P: " + d.P;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "blue")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.P) {
                                    if (d.P > maxValueLeft) return y(maxValueLeft);
                                    else if (d.P < minValueLeft) return y(minValueLeft);
                                    else return y(d.P);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")


                    /*
                    ZN 
                     */
                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "green")
                        .attr("cx", function (d) {
                            if (d.Zn)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.Zn) {
                                if (d.Zn > maxValueLeft) return y(maxValueLeft);
                                else if (d.Zn < minValueLeft) return y(minValueLeft);
                                else return y(d.Zn);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.Zn)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'blue')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.Zn)
                                return "Zn: " + d.Zn;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "green")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.Zn) {
                                    if (d.Zn > maxValueLeft) return y(maxValueLeft);
                                    else if (d.Zn < minValueLeft) return y(minValueLeft);
                                    else return y(d.Zn);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")





                    // Y axis label
                    //svg.append("text")
                    //    .attr("y", -265)
                    //    .attr("x", -55)
                    //    .text("Residuals")

                    // References
                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 0)
                        .attr("color", "black")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 10)
                        .text("Mo")


                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 50)
                        .attr("fill", "red")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 60)
                        .text("Sn")

                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 100)
                        .attr("fill", "blue")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 110)
                        .text("P")

                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 150)
                        .attr("fill", "green")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 160)
                        .text("Zn")

                }

            }
            , injectionFluxes: function (data, id, width) {
                var domainBand = [];

                _.each(data, function (obj, i) {
                    domainBand[i] = obj.HeatName;
                });

                var title = '';
                var chartWidth = width;

                var chartHeight = this.model.get('chartHeight');
                var heightOffset = this.model.get('heightOffset');
                var chartMarginLeft = 80;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 250;
                var minValueBottomAxis = 0;
                var maxValueLeft = 480;
                var minValueLeft = 280;
                //var minValueLeft = 300;
                if (data.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * data.length);
                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + heightOffset + ")");

                    var x = d3.scaleBand()
                        .domain(domainBand)
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'x_text dashed')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(7))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })


                    var y = d3.scaleLinear()
                        .domain([minValueLeft, maxValueLeft])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y_text dashed")
                        .call(d3.axisLeft(y).tickSize(-maxAxisBottom).ticks(10))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y_text .tick text")
                        .attr("x", function (d, i) {
                            return -20;
                        });

                    if (id == '.injection_fluxes_EAFA') {
                        title = "EAF A - Injection Fluxes";
                        this.model.set({ hasData_injection_fluxes_EAFA: true });
                    }
                    else if (id == '.injection_fluxes_EAFB') {
                        title = "EAF B - Injection Fluxes";
                        this.model.set({ hasData_injection_fluxes_EAFB: true });
                    }


                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "red")
                        .attr("cx", function (d) {
                            if (d.SpecificEnergy)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.SpecificEnergy) {
                                if (d.SpecificEnergy > maxValueLeft) return y(maxValueLeft);
                                else if (d.SpecificEnergy < minValueLeft) return y(minValueLeft);
                                else return y(d.SpecificEnergy);
                            }

                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.SpecificEnergy)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'red')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'red')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.SpecificEnergy)
                                return "SpecificEnergy: " + d.SpecificEnergy;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "red")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.SpecificEnergy) {
                                    if (d.SpecificEnergy > maxValueLeft) return y(maxValueLeft);
                                    else if (d.SpecificEnergy < minValueLeft) return y(minValueLeft);
                                    else return y(d.SpecificEnergy);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")

                    // References
                    svg.append("circle")
                        .attr("cy", -270)
                        .attr("cx", 0)
                        .attr("fill", "red")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -265)
                        .attr("x", 10)
                        .text("KWH/Ton")




                }

            }
            , bucketFluxes: function (data, id, width) {
                var domainBand = [];

                _.each(data, function (obj, i) {
                    domainBand[i] = obj.HeatName;
                });

                var title = '';
                var chartWidth = width;

                var chartHeight = this.model.get('chartHeight');
                var heightOffset = this.model.get('heightOffset');
                var chartMarginLeft = 80;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 250;
                var minValueBottomAxis = 0;
                var maxValueLeft = 10000;
                var minValueLeft = 0;
                if (data.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * data.length);
                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + heightOffset + ")");

                    var x = d3.scaleBand()
                        .domain(domainBand)
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'x_text dashed')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(7))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })


                    var y = d3.scaleLinear()
                        .domain([minValueLeft, maxValueLeft])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y_text dashed")
                        .call(d3.axisLeft(y).tickSize(-maxAxisBottom).ticks(10))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y_text .tick text")
                        .attr("x", function (d, i) {
                            return -20;
                        });

                    if (id == '.bucket_fluxes_EAFA') {
                        title = "EAF A - Bucket Fluxes";
                        this.model.set({ hasData_bucket_fluxes_EAFA: true });
                    }
                    else if (id == '.bucket_fluxes_EAFB') {
                        title = "EAF B - Bucket Fluxes";
                        this.model.set({ hasData_bucket_fluxes_EAFB: true });
                    }
                    //svg.append("text")
                    //    .attr("x", 45)
                    //    .attr("y", -335)
                    //    .attr("text-anchor", "middle")
                    //    .attr("class", "text")
                    //    .style("font-size", "16px")
                    //    .text(title);



                    //----------------------------- HiCal-----------------------

                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "blue")
                        .attr("cx", function (d) {
                            if (d.HiCal)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.HiCal) {
                                if (d.HiCal > maxValueLeft) return y(maxValueLeft);
                                else if (d.HiCal < minValueLeft) return y(minValueLeft);
                                else return y(d.HiCal);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.HiCal)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'black')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.HiCal)
                                return "HiCal: " + d.HiCal;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "blue")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.HiCal) {
                                    if (d.HiCal > maxValueLeft) return y(maxValueLeft);
                                    else if (d.HiCal < minValueLeft) return y(minValueLeft);
                                    else return y(d.HiCal);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")

                    //---------------------------------DOLO-------------------------------------------
                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "red")
                        .attr("cx", function (d) {
                            if (d.Dolo)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.Dolo) {
                                if (d.Dolo > maxValueLeft) return y(maxValueLeft);
                                else if (d.Dolo < minValueLeft) return y(minValueLeft);
                                else return y(d.Dolo);
                            }

                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.Dolo)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'red')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.Dolo)
                                return "Dolo: " + d.Dolo;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "red")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.Dolo) {
                                    if (d.Dolo > maxValueLeft) return y(maxValueLeft);
                                    else if (d.Dolo < minValueLeft) return y(minValueLeft);
                                    else return y(d.Dolo);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")

                    //---------------------------------Carbon-------------------------------------------
                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "green")
                        .attr("cx", function (d) {
                            if (d.Carbon)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.Carbon) {
                                if (d.Carbon > maxValueLeft) return y(maxValueLeft);
                                else if (d.Carbon < minValueLeft) return y(minValueLeft);
                                else return y(d.Carbon);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.Carbon)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'green')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', 'blue')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.Carbon)
                                return "Carbon: " + d.Carbon;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "green")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.Carbon) {
                                    if (d.Carbon > maxValueLeft) return y(maxValueLeft);
                                    else if (d.Carbon < minValueLeft) return y(minValueLeft);
                                    else return y(d.Carbon);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")


                    //---------------------------------Injected Carbon-------------------------------------------
                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "#e0640d")
                        .attr("cx", function (d) {
                            if (d.InjCarbon)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.InjCarbon) {
                                if (d.InjCarbon > maxValueLeft) return y(maxValueLeft);
                                else if (d.InjCarbon < minValueLeft) return y(minValueLeft);
                                else return y(d.InjCarbon);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.InjCarbon)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', '#e0640d')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', '#e0640d')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.InjCarbon)
                                return "Inj Carbon: " + d.InjCarbon;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "#e0640d")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.InjCarbon) {
                                    if (d.InjCarbon > maxValueLeft) return y(maxValueLeft);
                                    else if (d.InjCarbon < minValueLeft) return y(minValueLeft);
                                    else return y(d.InjCarbon);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")

                    //---------------------------------INJ DOLO-------------------------------------------
                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "#2aa89d")
                        .attr("cx", function (d) {
                            if (d.InjCarbon_N)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.InjCarbon_N) {
                                if (d.InjCarbon_N > maxValueLeft) return y(maxValueLeft);
                                else if (d.InjCarbon_N < minValueLeft) return y(minValueLeft);
                                else return y(d.InjCarbon_N);
                            }

                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.InjCarbon_N)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', '#2aa89d')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', '#2aa89d')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.InjCarbon_N)
                                return "N. Inj Carbon: " + d.InjCarbon_N;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "#2aa89d")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.InjCarbon_N) {
                                    if (d.InjCarbon_N > maxValueLeft) return y(maxValueLeft);
                                    else if (d.InjCarbon_N < minValueLeft) return y(minValueLeft);
                                    else return y(d.InjCarbon_N);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")

                    //---------------------------------Total Carbon-------------------------------------------
                    svg
                        .selectAll("whatever")
                        .data(data)
                        .enter()
                        .append("circle")
                        .attr("fill", "#bd2dbf")
                        .attr("cx", function (d) {
                            if (d.TotalCarbon)
                                return x(d.HeatName);
                        })
                        .attr("cy", function (d) {
                            if (d.TotalCarbon) {
                                if (d.TotalCarbon > maxValueLeft) return y(maxValueLeft);
                                else if (d.TotalCarbon < minValueLeft) return y(minValueLeft);
                                else return y(d.TotalCarbon);
                            }
                        })
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")
                        .attr("r", function (d) {
                            if (d.TotalCarbon)
                                return 4;
                            else return 0;
                        })
                        .on('mouseover', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', '#bd2dbf')
                                .attr('stroke-width', 3)
                        })
                        .on('mouseout', function () {
                            d3.select(this)
                                .transition()
                                .duration(500)
                                .attr('stroke', '#bd2dbf')
                                .attr('stroke-width', 1)
                        })
                        .append("svg:title")
                        .text(function (d) {
                            if (d.TotalCarbon)
                                return "Total Carbon: " + d.TotalCarbon;
                            else return '';
                        })

                    // Add the line
                    svg.append("path")
                        .datum(data)
                        .attr("fill", "none")
                        .attr("stroke", "#bd2dbf")
                        .attr("stroke-width", 0.7)
                        .attr("d", d3.line()
                            .x(function (d) { return x(d.HeatName) })
                            .y(function (d) {
                                if (d.TotalCarbon) {
                                    if (d.TotalCarbon > maxValueLeft) return y(maxValueLeft);
                                    else if (d.TotalCarbon < minValueLeft) return y(minValueLeft);
                                    else return y(d.TotalCarbon);
                                }
                                else return 0;
                            })
                        )
                        .attr("transform",
                            "translate(" + minValueBottomAxis + ", 0)")


                            //---------------------------------Dolo Injection-------------------------------------------
                        svg
                            .selectAll("whatever")
                            .data(data)
                            .enter()
                            .append("circle")
                            .attr("fill", "#14213d")
                            .attr("cx", function (d) {
                                if (d.InjDolo)
                                    return x(d.HeatName);
                            })
                            .attr("cy", function (d) {
                                if (d.InjDolo) {
                                    if (d.InjDolo > maxValueLeft) return y(maxValueLeft);
                                    else if (d.InjDolo < minValueLeft) return y(minValueLeft);
                                    else return y(d.InjDolo);
                                }
                            })
                            .attr("transform",
                                "translate(" + minValueBottomAxis + ", 0)")
                            .attr("r", function (d) {
                                if (d.InjDolo)
                                    return 4;
                                else return 0;
                            })
                            .on('mouseover', function () {
                                d3.select(this)
                                    .transition()
                                    .duration(500)
                                    .attr('stroke', '#14213d')
                                    .attr('stroke-width', 3)
                            })
                            .on('mouseout', function () {
                                d3.select(this)
                                    .transition()
                                    .duration(500)
                                    .attr('stroke', '#bd2dbf')
                                    .attr('stroke-width', 1)
                            })
                            .append("svg:title")
                            .text(function (d) {
                                if (d.InjDolo)
                                    return "Dolo Injection: " + d.InjDolo;
                                else return '';
                            })

                        // Add the line
                        svg.append("path")
                            .datum(data)
                            .attr("fill", "none")
                            .attr("stroke", "#14213d")
                            .attr("stroke-width", 0.7)
                            .attr("d", d3.line()
                                .x(function (d) { return x(d.HeatName) })
                                .y(function (d) {
                                    if (d.InjDolo) {
                                        if (d.InjDolo > maxValueLeft) return y(maxValueLeft);
                                        else if (d.InjDolo < minValueLeft) return y(minValueLeft);
                                        else return y(d.InjDolo);
                                    }
                                    else return 0;
                                })
                            )
                            .attr("transform",
                                "translate(" + minValueBottomAxis + ", 0)")

                    // References
                    svg.append("circle")
                        .attr("cy", -260)
                        .attr("cx", 0)
                        .attr("fill", "blue")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -255)
                        .attr("x", 10)
                        .text("HiCal")
                        .attr("class", "reference")

                    svg.append("circle")
                        .attr("cy", -274)
                        .attr("cx", 0)
                        .attr("fill", "red")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -270)
                        .attr("x", 10)
                        .text("Charge Dolo")  // Changed from Dolo in ticket #1038
                        .attr("class", "reference")

                    svg.append("circle")
                        .attr("cy", -260)
                        .attr("cx", 55)
                        .attr("fill", "green")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -255)
                        .attr("x", 65)
                        .text("Charge Carbon") // Changed from Carbon in ticket #912
                        .attr("class", "reference")

                    svg.append("circle")
                        .attr("cy", -274)
                        .attr("cx", 90)
                        .attr("fill", "#e0640d")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -270)
                        .attr("x", 100)
                        .text("#1&4 Inj. Carbon")  // Changed from Inj. Carbon in ticket #912
                        .attr("class", "reference")

                    svg.append("circle")
                        .attr("cy", -274)
                        .attr("cx", 210)
                        .attr("fill", "#2aa89d")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -270)
                        .attr("x", 220)
                        .text("N. Inj Carbon")  // Changed from InjDolo in ticket #514
                        .attr("class", "reference")


                    svg.append("circle")
                        .attr("cy", -260)
                        .attr("cx", 170)
                        .attr("fill", "#bd2dbf")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -255)
                        .attr("x", 180)
                        .text("Tot Carbon")
                        .attr("class", "reference")

                    svg.append("circle")
                        .attr("cy", -260)
                        .attr("cx", 260)
                        .attr("fill", "#14213d")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -255)
                        .attr("x", 270)
                        .text("Dolo Injection")
                        .attr("class", "reference")

                }

            }

            , baghouse_Chart: function (id, width) {
                var baghouseData = this.model.itemsBaghouse.toJSON()
                var params = this.model.toJSON();
                var minDatetime = new moment(params.productionDate, 'MM/DD/YYYY').format('YYYY-MM-DD') + ' ' + (params.shiftId === 'D' ? '09:00:00' : '21:00:00')
                var maxDatetime = (params.shiftId === 'D' ? new moment(params.productionDate, 'MM/DD/YYYY').format('YYYY-MM-DD') : new moment(params.productionDate, 'MM/DD/YYYY').add(1, 'days').format('YYYY-MM-DD'))
                    + ' ' + (params.shiftId === 'D' ? '21:00:00' : '09:00:00');

                var title = '';
                var chartWidth = width;
                var chartHeight = 410;
                var chartMarginLeft = 110;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 300;
                var minValueBottomAxis = 0;
                if (baghouseData.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * baghouseData.length);
                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth + chartMarginLeft)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + 350 + ")");
                    var x = d3.scaleTime()
                        .domain([new Date(minDatetime), new Date(maxDatetime)])
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'x_text dashed')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(20))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })


                    var y = d3.scaleLinear()
                        .domain([1000, 3600])
                        .range([0, -maxAxisLeftHeight]);


                    svg.append("g")
                        .attr("class", "y_text dashed")
                        .call(d3.axisLeft(y))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y_text .tick text")
                        .attr("x", function (d, i) {
                            return -20;
                        });


                    var y0 = d3.scaleLinear()
                        .domain([0, 100])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y0_text dashed")
                        .style("fill", "red")
                        .call(d3.axisLeft(y0))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y0_text .tick text")
                        .style("fill", "red")
                        .attr("x", function (d, i) {
                            return -64;
                        });


                    var y1 = d3.scaleLinear()
                        .domain([-20, 0])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y1_text dashed")
                        .style("fill", "blue")
                        .call(d3.axisLeft(y1))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y1_text .tick text")
                        .style("fill", "blue")
                        .attr("x", function (d, i) {
                            return -96;
                        });



                    if (id == '.baghouse' || id == '.baghouse_print') {
                        title = "Baghouse";
                        this.model.set({ hasData_baghouse: true });
                    }

                    ru_data = _.where(baghouseData, { tagName: 'RU' });
                    svg.append("path")
                        .datum(ru_data)
                        .attr("fill", "none")
                        .attr("stroke", "black")
                        .attr("stroke-width", 1)
                        .attr("d", d3.line()
                            .x(function (d) { return x(new Date(d.datetime)) })
                            .y(function (d) {
                                if (d.value > 3600) return y(3600);
                                else if (d.value < 1000) return y(1000);
                                else return y(d.value);

                            })
                        )


                    //Add the line

                    du_data = _.where(baghouseData, { tagName: 'DU' });
                    svg.append("path")
                        .datum(du_data)
                        .attr("fill", "none")
                        .attr("stroke", "red")
                        .attr("stroke-width", 1)
                        .attr("d", d3.line()
                            .x(function (d) { return x(new Date(d.datetime)) })
                            .y(function (d) {
                                if (d.value > 100) return y0(100);
                                else if (d.value < 0) return y0(0);
                                else return y0(d.value);

                            })
                        )


                    //Add the line
                    va_data = _.where(baghouseData, { tagName: 'VA' });
                    svg.append("path")
                        .datum(va_data)
                        .attr("fill", "none")
                        .attr("stroke", "blue")
                        .attr("stroke-width", 1)
                        .attr("d", d3.line()
                            .x(function (d) { return x(new Date(d.datetime)) })
                            .y(function (d) {
                                if (d.value > 0) return y1(0);
                                else if (d.value < -150) return y1(-150);
                                else return y1(d.value);

                            })
                        )
                    // References

                    svg.append("circle")
                        .attr("cy", -325)
                        .attr("cx", 15)
                        .attr("fill", "blue")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -320)
                        .attr("x", 30)
                        .text("Convey Vacuum")

                    svg.append("circle")
                        .attr("cy", -325)
                        .attr("cx", 140)
                        .attr("fill", "red")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -320)
                        .attr("x", 155)
                        .text("Dust Silo Level")

                    svg.append("circle")
                        .attr("cy", -325)
                        .attr("cx", 260)
                        .attr("fill", "black")
                        .attr("r", 6)

                    svg.append("text")
                        .attr("y", -320)
                        .attr("x", 275)
                        .text("Convey Runtime")


                }

            }



            , render: function (container, viewParams) {
                var that = this;

                var thatContainer = (this.options.container) ? this.options.container : container;
                this.options.container = thatContainer;
                var flag = false;
                //the screens have a custompath, so it has to be specified in the customPath variable that is
                //then sent to the template loader.
                var customPath = '/app/custom-screens/' + this.template + '/';

                T.render.call(
                    this,
                    this.template,
                    function (tmp) {
                        //getInternationalizationData
                        if (!that.options.i18n) that.options.i18n = {};

                        app.getI18NJed(
                            that,
                            that.template,
                            function (i18nJED) {
                                //storing internationalization data
                                that.options.i18n[that.template] = i18nJED;
                                that.$el.html(tmp());
                                that.applyBindings();
                                that.append(thatContainer, that.$el);


                                // Top 3 Delays
                                var grid_delays = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'Furnace',
                                            label: app.translate(that, 'item_furnace_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'TopDelayCodeReason',
                                            label: 'Area',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'Code',
                                            label: app.translate(that, 'item_code_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'Duration',
                                            label: 'Min',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'Start',
                                            label: app.translate(that, 'item_start_col_label'),
                                            editable: false,
                                            cell: Backgrid.Extension.MomentCell.extend({
                                                className: 'moment-cell align-center-cell element',
                                                modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                                displayFormat: 'HH:mm',
                                            }),
                                        },
                                        {
                                            name: 'End',
                                            label: app.translate(that, 'item_end_col_label'),
                                            editable: false,
                                            cell: Backgrid.Extension.MomentCell.extend({
                                                className: 'moment-cell align-center-cell element',
                                                modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                                displayFormat: 'HH:mm',
                                            }),
                                        },
                                    ],
                                    collection: that.model.itemsDelays,
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Delays', children: [
                                                        { name: 'Furnace' }
                                                        , { name: 'TopDelayCodeReason' }
                                                        , { name: 'Code' }
                                                        , { name: 'Duration' }
                                                        , { name: 'Start' }
                                                        , { name: 'End' }
                                                    ]

                                                },
                                            ],
                                        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;
                                        },
                                    }),
                                });
                                that.$el.find('.items-grid-container-delays').append(grid_delays.render().el);

                                var grid_delays_screen = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'Furnace',
                                            label: app.translate(that, 'item_furnace_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'TopDelayCodeReason',
                                            label: 'Top Delay Code',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'Code',
                                            label: app.translate(that, 'item_code_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'Duration',
                                            label: 'Min',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element',
                                            }),
                                        },
                                        {
                                            name: 'Start',
                                            label: app.translate(that, 'item_start_col_label'),
                                            editable: false,
                                            cell: Backgrid.Extension.MomentCell.extend({
                                                className: 'moment-cell align-center-cell element',
                                                modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                                displayFormat: 'HH:mm',
                                            }),
                                        },
                                        {
                                            name: 'End',
                                            label: app.translate(that, 'item_end_col_label'),
                                            editable: false,
                                            cell: Backgrid.Extension.MomentCell.extend({
                                                className: 'moment-cell align-center-cell element',
                                                modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                                displayFormat: 'HH:mm',
                                            }),
                                        },
                                    ],
                                    collection: that.model.itemsDelays,
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Delays', children: [
                                                        { name: 'Furnace' }
                                                        , { name: 'TopDelayCodeReason' }
                                                        , { name: 'Code' }
                                                        , { name: 'Duration' }
                                                        , { name: 'Start' }
                                                        , { name: 'End' }
                                                    ]

                                                },
                                            ],
                                        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;
                                        },
                                    }),
                                });
                                that.$el.find('.items-grid-container-delays-screen').append(grid_delays_screen.render().el);

                                // Slag Chemistries

                                var grid_slag = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'heatName',
                                            label: app.translate(that, 'heat_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            sortable: false,
                                            label: 'Time',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'CaO',
                                            label: app.translate(that, 'caO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'SiO2',
                                            label: app.translate(that, 'siO2_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'Al2O3',
                                            label: app.translate(that, 'al2O3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'TiO2',
                                            label: app.translate(that, 'tiO2_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-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') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    if (this.model.get('B3Status') == 'WARNING') return 'number-cell element warning align-center-cell';
                                                    if (this.model.get('B3Status') == 'NORMAL') return 'number-cell element normal align-center-cell';
                                                    else return 'number-cell element align-center-cell';
                                                },
                                                decimals: 2,
                                            }),

                                        },
                                        {
                                            name: 'MgO',
                                            label: app.translate(that, 'mgO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('MgOStatus') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    else return 'number-cell element align-center-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') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    else return 'number-cell element align-center-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'MnO',
                                            label: app.translate(that, 'mnO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-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') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    else return 'number-cell align-center-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'Cr2O3',
                                            label: app.translate(that, 'cr2O3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'P2O5',
                                            label: app.translate(that, 'p2O5_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'SO3',
                                            label: app.translate(that, 'sO3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'dirtLoad',
                                            label: app.translate(that, 'dirtLoad_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 0,
                                            }),
                                        },
                                        {
                                            name: 'TotalSlagVolume',
                                            label: app.translate(that, 'TotalSlagVolume_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 0,
                                            }),
                                        },
                                        {
                                            name: 'refractoryWear',
                                            label: app.translate(that, 'refractoryWear_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('RefractoryWearStatus') == 'DANGER') return 'number-cell lbs danger align-center-cell';
                                                    else if (this.model.get('RefractoryWearStatus') == 'NORMAL') return 'number-cell lbs normal align-center-cell';
                                                    else return 'number-cell lbs align-center-cell';
                                                },
                                                decimals: 0,
                                            }),
                                        },
                                        {
                                            name: 'steelLoss',
                                            label: app.translate(that, 'steelLoss_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 0,
                                            }),
                                        },

                                    ],
                                    collection: that.model.itemsSlag,
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Slag Chemistries', children: [
                                                        { name: 'heatName' }
                                                        , { 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;
                                        },
                                    }),
                                });
                                that.$el.find('.items-grid-container-slag').append(grid_slag.render().el);

                                var grid_slag_screen = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'heatName',
                                            label: app.translate(that, 'heat_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            sortable: false,
                                            label: 'Time',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'CaO',
                                            label: app.translate(that, 'caO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'SiO2',
                                            label: app.translate(that, 'siO2_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'Al2O3',
                                            label: app.translate(that, 'al2O3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'TiO2',
                                            label: app.translate(that, 'tiO2_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-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') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    if (this.model.get('B3Status') == 'WARNING') return 'number-cell element warning align-center-cell';
                                                    if (this.model.get('B3Status') == 'NORMAL') return 'number-cell element normal align-center-cell';
                                                    else return 'number-cell element align-center-cell';
                                                },
                                                decimals: 2,
                                            }),

                                        },
                                        {
                                            name: 'MgO',
                                            label: app.translate(that, 'mgO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('MgOStatus') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    else return 'number-cell element align-center-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') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    else return 'number-cell element align-center-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'MnO',
                                            label: app.translate(that, 'mnO_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-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') == 'DANGER') return 'number-cell element danger align-center-cell';
                                                    else return 'number-cell align-center-cell';
                                                },
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'Cr2O3',
                                            label: app.translate(that, 'cr2O3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'P2O5',
                                            label: app.translate(that, 'p2O5_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'SO3',
                                            label: app.translate(that, 'sO3_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 1,
                                            }),
                                        },
                                        {
                                            name: 'dirtLoad',
                                            label: app.translate(that, 'dirtLoad_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 0,
                                            }),
                                        },
                                        {
                                            name: 'TotalSlagVolume',
                                            label: app.translate(that, 'TotalSlagVolume_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 0,
                                            }),
                                        },
                                        {
                                            name: 'refractoryWear',
                                            label: app.translate(that, 'refractoryWear_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: function () {
                                                    if (this.model.get('RefractoryWearStatus') == 'DANGER') return 'number-cell lbs danger align-center-cell';
                                                    else if (this.model.get('RefractoryWearStatus') == 'NORMAL') return 'number-cell lbs normal align-center-cell';
                                                    else return 'number-cell lbs align-center-cell';
                                                },
                                                decimals: 0,
                                            }),
                                        },
                                        {
                                            name: 'steelLoss',
                                            label: app.translate(that, 'steelLoss_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'number-cell align-center-cell',
                                                decimals: 0,
                                            }),
                                        },

                                    ],
                                    collection: that.model.itemsSlag,
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Slag Chemistries', children: [
                                                        { name: 'heatName' }
                                                        , { 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;
                                        },
                                    }),
                                });
                                that.$el.find('.items-grid-container-slag-screen').append(grid_slag_screen.render().el);

                                
                                

                                

                                
                                

                                // Log Book
                                var grid_LogBook = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'Timestamp',
                                            label: 'Time',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'ShiftId',
                                            label: app.translate(that, 'item_shift_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shift-crew-column',
                                            }),
                                        },
                                        {
                                            name: 'CrewId',
                                            label: app.translate(that, 'item_crew_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shift-crew-column',
                                            }),
                                        },
                                        {
                                            name: 'Title',
                                            label: app.translate(that, 'item_title_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },


                                        {
                                            name: 'Description',
                                            label: app.translate(that, 'item_description_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'Author',
                                            label: app.translate(that, 'item_author_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shift-crew-column',
                                            }),
                                        },
                                    ],
                                    collection: that.model.itemsLogBook,
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Log Book', children: [
                                                        { name: 'Timestamp' }
                                                        , { name: 'ShiftId' }
                                                        , { name: 'CrewId' }
                                                        , { name: 'Title' }
                                                        , { name: 'Description' }
                                                        , { name: 'Author' }

                                                    ]

                                                },
                                            ],
                                        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;
                                        },
                                    }),
                                });
                                that.$el.find('.items-grid-container-itemsLogBook').append(grid_LogBook.render().el);

                                var grid_LogBook_screen = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'Timestamp',
                                            label: 'Time',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'ShiftId',
                                            label: app.translate(that, 'item_shift_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shift-crew-column',
                                            }),
                                        },
                                        {
                                            name: 'CrewId',
                                            label: app.translate(that, 'item_crew_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shift-crew-column',
                                            }),
                                        },
                                        {
                                            name: 'Title',
                                            label: app.translate(that, 'item_title_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },


                                        {
                                            name: 'Description',
                                            label: app.translate(that, 'item_description_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'Author',
                                            label: app.translate(that, 'item_author_col_label'),
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shift-crew-column',
                                            }),
                                        },
                                    ],
                                    collection: that.model.itemsLogBook,
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Log Book', children: [
                                                        { name: 'Timestamp' }
                                                        , { name: 'ShiftId' }
                                                        , { name: 'CrewId' }
                                                        , { name: 'Title' }
                                                        , { name: 'Description' }
                                                        , { name: 'Author' }

                                                    ]

                                                },
                                            ],
                                        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;
                                        },
                                    }),
                                });
                                that.$el.find('.items-grid-container-itemsLogBook-screen').append(grid_LogBook_screen.render().el);

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





                                // Load pickers synchronously
                                that.model.fetchPickers({ async: false });

                                var fixedParams = _.extend({}, viewParams);

                                if (fixedParams.productionDate)
                                    fixedParams.productionDate = new moment(fixedParams.productionDate, 'YYYYMMDD').format('MM/DD/YYYY');
                                if (fixedParams.shiftId)
                                    fixedParams.shiftId = fixedParams.shiftId;
                                if (fixedParams.crewId) {
                                    fixedParams.crewId = fixedParams.crewId;

                                }
                                that.model.set(fixedParams);
                                // refresh collection
                                that.refresh();
                                that.UpdateURL();
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            }

            , refresh: function () {
                try {
                    //Remove all Charts

                    this.$el.find('#refsDuration').html('');
                    this.$el.find('#refsCategories').html('');

                    this.$el.find('#refs-screen-duration').html('');
                    this.$el.find('#refs-screen-categories').html('');

                    this.$el.find('.items-grid-container-recipes-screen').html('');
                    this.$el.find('.items-grid-container-recipes').html('');

                    this.$el.find('.items-grid-container-recipes-average-screen').html('');
                    this.$el.find('.items-grid-container-recipes-average').html('');

                    this.$el.find('.items-grid-container-manualTemps-screen').html('');
                    this.$el.find('.items-grid-container-manualTemps').html('');

                    this.$el.find('.items-grid-container-tapHoleNonFreeOpen').html('');
                    this.$el.find('.items-grid-container-tapHoleNonFreeOpen-screen').html('');

                    this.$el.find('.yield').html('');
                    this.$el.find('.yield_print').html('');
                    //Screen Gantt Charts
                    this.$el.find('.furnace1-gantt-screen').html('');
                    this.$el.find('.furnace2-gantt-screen').html('');

                    // Screen EAF A
                    this.$el.find('.temperature_EAFA').html('');
                    this.$el.find('.oxygen_EAFA').html('');
                    this.$el.find('.residuals_EAFA').html('');
                    this.$el.find('.residuals_EAFA_2').html('');
                    this.$el.find('.bucket_fluxes_EAFA').html('');
                    this.$el.find('.injection_fluxes_EAFA').html('');

                    // Screen EAF B
                    this.$el.find('.temperature_EAFB').html('');
                    this.$el.find('.oxygen_EAFB').html('');
                    this.$el.find('.residuals_EAFB').html('');
                    this.$el.find('.residuals_EAFB_2').html('');
                    this.$el.find('.bucket_fluxes_EAFB').html('');
                    this.$el.find('.injection_fluxes_EAFB').html('');


                    // Screen Baghouse
                    this.$el.find('.baghouse').html('');




                    // Print Gantt Charts
                    this.$el.find('.furnace1-gantt').html('');
                    this.$el.find('.furnace2-gantt').html('');


                    // Print EAF A
                    this.$el.find('.temperature_EAFA_print').html('');
                    this.$el.find('.oxygen_EAFA_print').html('');
                    this.$el.find('.residuals_EAFA_print').html('');
                    this.$el.find('.residuals_EAFA_2_print').html('');
                    this.$el.find('.injection_fluxes_EAFA_print').html('');
                    this.$el.find('.bucket_fluxes_EAFA_print').html('');

                    // Print EAF B
                    this.$el.find('.temperature_EAFB_print').html('');
                    this.$el.find('.oxygen_EAFB_print').html('');
                    this.$el.find('.residuals_EAFB_print').html('');
                    this.$el.find('.residuals_EAFB_2_print').html('');
                    this.$el.find('.injection_fluxes_EAFB_print').html('');
                    this.$el.find('.bucket_fluxes_EAFB_print').html('');

                    // Print Baghouse
                    this.$el.find('.baghouse_print').html('');


                    var params = this.model.toJSON();

                    var shift = '1';
                    if (params.shiftId == 'D') shift = '1';
                    else if (params.shiftId == 'N') shift = '2';

                    this.model.set({
                        isLoading: true,
                        hasData: false,
                    })
                    // reload collections 
                    this.model.fetchData({
                        productionDate: params.productionDate,
                        shiftId: shift,
                    });


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

            , UpdateNav: function (nav) {
                var params = this.model.toJSON();
                if (nav && this.model.get('shiftId') == 'N')
                    this.model.set('productionDate', new moment(params.productionDate, 'MM/DD/YYYY').add(1, 'day').format('MM/DD/YYYY'));

                if (!nav && this.model.get('shiftId') == 'D')
                    this.model.set('productionDate', new moment(params.productionDate, 'MM/DD/YYYY').subtract(1, 'day').format('MM/DD/YYYY'));


                if (this.model.get('shiftId') == 'N') this.model.set('shiftId', 'D');
                else
                    if (this.model.get('shiftId') == 'D') this.model.set('shiftId', 'N');

                this.UpdateURL();
                this.refresh();
            }


            , UpdateURL: function () {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    productionDate: new moment(params.productionDate, "MM/DD/YYYY").format("YYYYMMDD"),
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },





            fetched: function (resp) {

                var model = this.model.toJSON();
                let shiftId = model.shiftId;
                let productionDate = model.productionDate;
                let crewId = model.crewId;
                let shift = shiftId === 'D' ? 'Day Shift' : 'Night Shift';
                let crew = `${crewId} Crew`;


                this.setURLClassGrid('eaf-a-production');
                this.setURLClassGrid('eaf-b-production');

                document.getElementById("shift-name").textContent = `${productionDate} | ${shift} | ${crew}`;
                this.model.set({
                    isLoading: false,
                    hasData:
                        (resp && resp.Table && resp.Table.length > 0) ||
                            (resp && resp.Table1 && resp.Table1.length > 0) ||
                            (resp && resp.Table2 && resp.Table2.length > 0) ? true : false,
                });


            },
            setURLClassGrid: function (id) {
                return;
                var heatFound = '';
                var found;
                var gridElement = document.getElementById(id);
                var aTags = gridElement.getElementsByTagName("td");
                for (var i = 0; i < aTags.length; i++) {
                    if (aTags[i].textContent[0] && (aTags[i].textContent[0] === 'A' || aTags[i].textContent[0] === 'B' || aTags[i].textContent[0] === 'C' || aTags[i].textContent[0] === 'D')
                        && !isNaN(aTags[i].textContent[1])
                        && !isNaN(aTags[i].textContent[2])
                        && !isNaN(aTags[i].textContent[3])
                        && !isNaN(aTags[i].textContent[4])
                        && !isNaN(aTags[i].textContent[5])
                        && !isNaN(aTags[i].textContent[6])
                    ) {
                        heatFound = aTags[i].textContent;
                        found = aTags[i];
                        aTags[i].textContent = '';
                        $(found).removeClass('string-cell');
                        $(found).addClass('uri-cell');
                        $(found).append("<a tabindex='- 1' " + "href='!/" + "caster-heat-report/" + heatFound + "'" + "target='_blank'>" + heatFound + "</a>");
                    }
                }
            }


            // -- Collection functions
            , itemsBaghouse_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_baghouse: (that.model.itemsBaghouse.length > 0),
                            });

                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , itemsSlag_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_Slag: (that.model.itemsSlag.length > 0),
                                isLoading_Slag: false,
                            });

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

            }
            , itemsTemperature_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_Temperature: (that.model.itemsTemperature.length > 0),
                                isLoading_Temperature: false,
                            });




                            if (that.model.get('hasData_yield')) {
                                that.getYieldChart('.yield', 1200, 500)
                                that.getYieldChart('.yield_print', 850, 400)

                            }


                            that.baghouse_Chart(".baghouse", 1000);
                            that.baghouse_Chart(".baghouse_print", 800);


                            if (that.model.get('hasData_Temperature')) {
                                that.residualsChart(that.model.itemsTemperature.getDataChartEAFA(), ".residuals_EAFA", 750);
                                that.residualsChart2(that.model.itemsTemperature.getDataChartEAFA(), ".residuals_EAFA_2", 750);
                                that.residualsChart(that.model.itemsTemperature.getDataChartEAFB(), ".residuals_EAFB", 750);
                                that.residualsChart2(that.model.itemsTemperature.getDataChartEAFB(), ".residuals_EAFB_2", 750);
                                that.temperatureChart(that.model.itemsTemperature.getDataChartEAFA(), ".temperature_EAFA", 750);
                                that.oxygenChart(that.model.itemsTemperature.getDataChartEAFA(), ".oxygen_EAFA", 750);
                                that.temperatureChart(that.model.itemsTemperature.getDataChartEAFB(), ".temperature_EAFB", 750);
                                that.oxygenChart(that.model.itemsTemperature.getDataChartEAFB(), ".oxygen_EAFB", 750);


                                that.temperatureChart(that.model.itemsTemperature.getDataChartEAFA(), ".temperature_EAFA_print", that.model.get('chartsWidth'));
                                that.oxygenChart(that.model.itemsTemperature.getDataChartEAFA(), ".oxygen_EAFA_print", that.model.get('chartsWidth'));
                                that.temperatureChart(that.model.itemsTemperature.getDataChartEAFB(), ".temperature_EAFB_print", that.model.get('chartsWidth'));
                                that.oxygenChart(that.model.itemsTemperature.getDataChartEAFB(), ".oxygen_EAFB_print", that.model.get('chartsWidth'));

                                that.residualsChart(that.model.itemsTemperature.getDataChartEAFA(), ".residuals_EAFA_print", that.model.get('chartsWidth'));
                                that.residualsChart2(that.model.itemsTemperature.getDataChartEAFA(), ".residuals_EAFA_2_print", that.model.get('chartsWidth'));
                                that.residualsChart(that.model.itemsTemperature.getDataChartEAFB(), ".residuals_EAFB_print", that.model.get('chartsWidth'));
                                that.residualsChart2(that.model.itemsTemperature.getDataChartEAFB(), ".residuals_EAFB_2_print", that.model.get('chartsWidth'));
                            };

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

            }
            , itemsBucketFluxesEAFA_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_bucket_fluxes_EAFA: (that.model.itemsBucketFluxesEAFA.length > 0),
                                isLoading_bucket_fluxes_EAFA: false,
                            });
                            if (that.model.get('hasData_bucket_fluxes_EAFA')) {
                                that.bucketFluxes(that.model.itemsBucketFluxesEAFA.getDataChart(), ".bucket_fluxes_EAFA", 750);
                                that.bucketFluxes(that.model.itemsBucketFluxesEAFA.getDataChart(), ".bucket_fluxes_EAFA_print", that.model.get('chartsWidth'));
                            };
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , itemsBucketFluxesEAFB_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_bucket_fluxes_EAFB: (that.model.itemsBucketFluxesEAFB.length > 0),
                                isLoading_bucket_fluxes_EAFB: false,
                            });
                            if (that.model.get('hasData_bucket_fluxes_EAFB')) {
                                that.bucketFluxes(that.model.itemsBucketFluxesEAFB.getDataChart(), ".bucket_fluxes_EAFB", 750);
                                that.bucketFluxes(that.model.itemsBucketFluxesEAFB.getDataChart(), ".bucket_fluxes_EAFB_print", that.model.get('chartsWidth'));
                            };
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , itemsInjectionFluxesEAFA_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_injection_fluxes_EAFA: (that.model.itemsInjectionFluxesEAFA.length > 0),
                                isLoading_injection_fluxes_EAFA: false,
                            });
                            if (that.model.get('hasData_injection_fluxes_EAFA')) {
                                that.injectionFluxes(that.model.itemsInjectionFluxesEAFA.getDataChart(), ".injection_fluxes_EAFA", 750);
                                that.injectionFluxes(that.model.itemsInjectionFluxesEAFA.getDataChart(), ".injection_fluxes_EAFA_print", that.model.get('chartsWidth'));

                            };
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , itemsInjectionFluxesEAFB_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_injection_fluxes_EAFB: (that.model.itemsInjectionFluxesEAFB.length > 0),
                                isLoading_injection_fluxes_EAFB: false,
                            });
                            if (that.model.get('hasData_injection_fluxes_EAFB')) {
                                that.injectionFluxes(that.model.itemsInjectionFluxesEAFB.getDataChart(), ".injection_fluxes_EAFB", 750);
                                that.injectionFluxes(that.model.itemsInjectionFluxesEAFB.getDataChart(), ".injection_fluxes_EAFB_print", that.model.get('chartsWidth'));
                            };
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }

            , itemsRecipes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_Recipes: (that.model.itemsRecipes.length > 0),
                                isLoading_Recipes: false,
                            });
                        },
                        100
                    );
                    that.buildRecipesGrid();
                    
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            buildRecipesGrid: function () {
                var that = this;

                var columnLayout = [{
                    name: ' ', children:
                        [
                            { name: 'Material' }
                        ]
                }]

                var recipeNames = Object.keys(that.model.itemsRecipes.at(0).attributes).filter(key => key.endsWith('-Plan')).map(key => key.slice(0, -5));

                var recipesColumns = recipeNames.map(key => {
                    return {
                        name: key,
                        children: [
                            { name: key + "-Plan"}, 
                            { name: key + "-Actual"}
                        ]
                    };
                });


                columnLayout = columnLayout.concat(recipesColumns);

                columnLayout.push({
                    name: 'Recipe Scrap Tracking',
                    children: recipesColumns
                });
                var columns = [].concat(
                    [{
                        name: 'Material',
                        label: app.translate(that, 'item_scrapMaterial_col_label'),
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    }],
                    recipeNames.flatMap(function (obj) {
                        return [
                            {
                                name: obj + '-Plan',
                                label: 'Plan',
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                    render: function () {
                                        this.$el.empty();

                                        var columnName = this.column.get('name');
                                        var rawData = this.model.get(columnName);

                                        var value = rawData === null ? 0 : rawData;

                                        this.$el.text(value);

                                        this.delegateEvents();

                                        return this;
                                    }
                                }),
                            },
                            {
                                name: obj + '-Actual',
                                label: 'Actual',
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                    render: function () {
                                        this.$el.empty();

                                        var columnName = this.column.get('name');
                                        var rawData = this.model.get(columnName);

                                        var value = rawData === null ? 0 : rawData;

                                        this.$el.text(value);

                                        this.delegateEvents();

                                        return this;
                                    }
                                }),
                            }
                        ];
                    })
                );


                var grid_recipes_screen = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columns,
                    collection: that.model.itemsRecipes,
                    header: Backgrid.Extension.GroupedHeader.extend({
                        columnLayout: columnLayout,
                        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;
                        },
                    }),
                });
                that.$el.find('.items-grid-container-recipes-screen').append(grid_recipes_screen.render().el);


                var renderedGrid = grid_recipes_screen.render().el;

                that.$el.find('.items-grid-container-recipes-screen').append(renderedGrid);
                
                that.$el.find('.items-grid-container-recipes').append(renderedGrid.cloneNode(true));



            }
            , recipesAverage_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_RecipesAverage: (that.model.itemsRecipesAverage.length > 0),
                                isLoading_RecipesAverage: false,
                            });
                            that.buildRecipesAverageGrid(); 
                        },
                        100
                    );
                    

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , buildRecipesAverageGrid: function () {
                var that = this;

                var table = document.createElement('table');
                var tbody = document.createElement('tbody');
                table.appendChild(tbody);

                var fixedColumns = [
                    { name: 'HeatsProduced', label: 'Heats Produced', highlight: false},
                    { name: 'Yield', label: '% Yield', highlight: false},
                    { name: 'CrMiss', label: 'Cr Miss', highlight: true },
                    { name: 'CuMiss', label: 'Cu Miss', highlight: true },
                    { name: 'MoMiss', label: 'Mo Miss', highlight: true },
                    { name: 'NiMiss', label: 'Ni Miss', highlight: true },
                    { name: 'PMiss', label: 'P Miss', highlight: true },
                    { name: 'PbMiss', label: 'Pb Miss', highlight: true },
                    { name: 'SnMiss', label: 'Sn Miss', highlight: true },
                ];

                // Create a row for each fixed column
                fixedColumns.forEach(function (column) {
                    var tr = document.createElement('tr');

                    // Add label cell
                    var tdLabel = document.createElement('td');
                    tdLabel.textContent = column.label;
                    tr.appendChild(tdLabel);


                    // calculate to match the width in the grid above
                    var totalModels = that.model.itemsRecipesAverage.length;
                    var columnWidth = totalModels > 0 ? (80 / totalModels) + '%' : 'auto';
                    // Add values for each model

                    
                    that.model.itemsRecipesAverage.forEach(function (model) {
                        var cellValue = model.get(column.name) || '';
                        var tdValue = document.createElement('td');
                        if (parseFloat(cellValue) > 0 && column.highlight) {
                            tdValue.classList.add('highlight-chemistry');
                        }
                        tdValue.textContent = cellValue || '';
                        tdValue.style.width = columnWidth; // Set the width dynamically
                        tdValue.classList.add('averageValuesTD')
                        tr.appendChild(tdValue);
                    });

                    tbody.appendChild(tr);
                });
                
                that.$el.find('.items-grid-container-recipes-average-screen').append(table);

                var pdfTable = table.cloneNode(true);

                // Copy styles from the original table to the cloned table
                var computedStyle = window.getComputedStyle(table);
                pdfTable.style.cssText = computedStyle.cssText;

                // Append the cloned table to another container
                that.$el.find('.items-grid-container-recipes-average').append(pdfTable);
            }

            , manualTemps_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_manualTemps: (that.model.itemsManualTemps.length > 0),
                            });
                            that.buildManualTempGrid();
                        },
                        100
                    );


                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , buildManualTempGrid: function () {
                var that = this;

                var columnLayout = [{
                    name: 'Manual Temperatures Performed', children:
                        [
                            { name: 'FurnaceCode' },
                            { name: 'HeatName' },
                            { name: 'ManualTemp' }
                        ]
                }]
                
                var columns = [].concat(
                    [{
                        name: 'FurnaceCode',
                        label: 'EAF Name',
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    },
                    {
                        name: 'HeatName',
                        label: 'Heat Name',
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    }
                    ,
                    {
                        name: 'ManualTemp',
                        label: 'Manual Temps',
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    }
                    ],
                );


                var grid_manual_temp_screen = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columns,
                    collection: that.model.itemsManualTemps,
                    header: Backgrid.Extension.GroupedHeader.extend({
                        columnLayout: columnLayout,
                        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;
                        },
                    }),
                });


                var renderedGrid = grid_manual_temp_screen.render().el;

                if (that.model.itemsManualTemps.length === 0) {
                    var colCount = columns.length; 

                    // Find the table body inside the rendered grid
                    var tbody = renderedGrid.querySelector('tbody');

                    // Append the empty row to the tbody
                    var emptyRow = document.createElement('tr');
                    emptyRow.classList.add('empty-row');
                
                    // Create a single table cell spanning all columns
                    var emptyCell = document.createElement('td');
                    emptyCell.colSpan = colCount;
                    emptyCell.classList.add('text-center');
                    emptyCell.style.textAlign = "center";
                    emptyCell.style.fontStyle = "bold";
                    emptyCell.style.color = "#777";
                    emptyCell.style.fontSize = "14px";
                    emptyCell.textContent = "Zero Manual Temperaturess Recorded";
                
                    // Append the cell to the row
                    emptyRow.appendChild(emptyCell);
                
                    // Append the row to tbody
                    tbody.appendChild(emptyRow);
                }

                that.$el.find('.items-grid-container-manualTemps-screen').append(renderedGrid);
                renderedGrid.offsetHeight; 

                var pdfGrid = renderedGrid.cloneNode(true);

                // Copy styles from the original table to the cloned grid
                var computedStyle = window.getComputedStyle(pdfGrid);
                pdfGrid.style.cssText = computedStyle.cssText;

                // Append the cloned grid to another container
                that.$el.find('.items-grid-container-manualTemps').append(pdfGrid);



            }
            , tapHoleNonFreeOpen_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_tapHoleNonFreeOpen: (that.model.itemsTapHoleNonFreeOpen.length > 0),
                            });
                            that.buildTapHoleNonFreeOpenGrid();
                        },
                        100
                    );


                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , buildTapHoleNonFreeOpenGrid: function () {
                var that = this;

                var columnLayout = [{
                    name: 'Heats on Tap Hole and Non Free Open Duration', children:
                        [
                            { name: 'FurnaceCode' },
                            { name: 'HeatName' },
                            { name: 'HeatsOnTapHole' },
                            { name: 'NonFreeOpenDuration' }
                        ]
                }]

                var columns = [].concat(
                    [{
                        name: 'FurnaceCode',
                        label: 'EAF Name',
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    },
                    {
                        name: 'HeatName',
                        label: 'Heat Name',
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    }
                        ,
                    {
                        name: 'HeatsOnTapHole',
                        label: 'Heats on Tap Hole',
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell',
                        }),
                    },
                        {
                            name: 'NonFreeOpenDuration',
                            label: 'Non Free Open Duration',
                            editable: false,
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell',
                                render: function () {
                                    // Get the epoch time from the model
                                    var epochTime = this.model.get('NonFreeOpenDuration');

                                    // Convert epoch time to minutes
                                    var minutes = Math.round(epochTime / 60);

                                    // Set the cell content to display the duration in minutes
                                    this.$el.html(minutes + ' mins.');

                                    return this;
                                }
                            }),
                        }

                    ],
                );

              

                var grid_tapHoleNonFreeDuration_screen = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columns,
                    collection: that.model.itemsTapHoleNonFreeOpen,
                    header: Backgrid.Extension.GroupedHeader.extend({
                        columnLayout: columnLayout,
                        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;
                        },
                    }),
                });


                var renderedGrid = grid_tapHoleNonFreeDuration_screen.render().el;


                // Add an empty row manually if the collection is empty
                if (that.model.itemsTapHoleNonFreeOpen.length === 0) {
                    var colCount = columns.length; 

                    // Find the table body inside the rendered grid
                    var tbody = renderedGrid.querySelector('tbody');
                    
                        // Append the empty row to the tbody
                        var emptyRow = document.createElement('tr');
                        emptyRow.classList.add('empty-row');
                    
                        // Create a single table cell spanning all columns
                        var emptyCell = document.createElement('td');
                        emptyCell.colSpan = colCount;
                        emptyCell.classList.add('text-center');
                        emptyCell.style.textAlign = "center";
                        emptyCell.style.fontStyle = "bold";
                        emptyCell.style.color = "#777";
                        emptyCell.style.fontSize = "14px";
                        emptyCell.textContent = "Zero Non-Free Opens Recorded";
                    
                        // Append the cell to the row
                        emptyRow.appendChild(emptyCell);
                    
                        // Append the row to tbody
                        tbody.appendChild(emptyRow);
                    
                }

                that.$el.find('.items-grid-container-tapHoleNonFreeOpen-screen').empty().append(renderedGrid);
                renderedGrid.offsetHeight; 

                var pdfGrid = renderedGrid.cloneNode(true);

                // Copy styles from the original table to the cloned grid
                var computedStyle = window.getComputedStyle(pdfGrid);
                pdfGrid.style.cssText = computedStyle.cssText;

                // Append the cloned grid to another container
                that.$el.find('.items-grid-container-tapHoleNonFreeOpen').empty().append(pdfGrid);



            }

            , itemsDelaysEAFA_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            //that.model.set({
                            //    hasData_DelaysEAFA: (that.model.itemsDelays.length > 0),
                            //    isLoading_DelaysEAFA: false,
                            //});
                        },
                        100
                    );

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

            , itemsPourback_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_Pourback: (that.model.itemsPourback.length > 0),
                                isLoading_Pourback: false,
                            });
                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); } 
            }
            , itemsLogBook_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_LogBook: (that.model.itemsLogBook.length > 0),
                                isLoading_LogBook: false,
                            });
                        },
                        100
                    );

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

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

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

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

                    this.options.onappend(this);
                }

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

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

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

                this.remove();
                this.unbindViewScopedEvents();
                this.unbind();
            }
            , show: function () {
                this.options.state = app.view_states.shown;

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

                this.$el.hide();
                this.unbind();
                this.stopListening();
            }
            , preRender: function () {
                app.models.subnavbar.set('subnavbar', false);
            }
            , reRender: function (viewParams) {
                try {
                    this.refresh();
                } catch (Error) { }
            }


        });






        Screen.Models.ItemAllHeat = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    Furnace: obj.Furnace,
                    HeatName: obj.HeatName,
                    Start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                    End: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                    PowerOn: obj.PowerOn,

                };
                return result;
            },
        });

        Screen.Collections.ItemsAllHeats = Backbone.Collection.extend({
            model: Screen.Models.ItemAllHeat,

            furnace1_heats: [],
            furnace2_heats: [],
            setDataColl: function (data, shiftId, productionDate) {
                var newColl,
                    that = this;
                that.setDataChart(data, shiftId, productionDate);
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },

            setDataChart: function (heats, shiftId, prodDate) {
                var furnace1_heats = [],
                    furnace2_heats = [],
                    aux_heats = [];

                var aux_start = null,
                    aux_end = null,
                    shift = 'D',
                    aux_duration = null;

                var START_D = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                    END_D = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                    START_N = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                    END_N = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').add(1, 'd').format('YYYY-MM-DD HH:mm:ss');

                if (shiftId == '1') shift = 'D';
                else if (shiftId == '2') shift = 'N';

                _.each(heats, function (obj) {
                    var start = new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss");
                    var end = new moment(obj.End).format("YYYY-MM-DD HH:mm:ss");
                    var push = false;
                    if (shift == 'D') {
                        if (moment(START_D).isBefore(end) && moment(start).isBefore(END_D)) {
                            push = true;
                            if (moment(start).isBefore(START_D)) aux_start = START_D;
                            else aux_start = start;
                            if (moment(END_D).isBefore(end)) aux_end = END_D;
                            else aux_end = end;
                        }
                    } else if (shift == 'N') {
                        if (moment(START_N).isBefore(end) && moment(start).isBefore(END_N)) {
                            push = true;
                            if (moment(start).isBefore(START_N)) aux_start = START_N;
                            else aux_start = start;
                            if (moment(END_N).isBefore(end)) aux_end = END_N;
                            else aux_end = end;
                        }
                    };

                    if (push) {
                        var aux_start_diff = moment(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                        var aux_end_diff = moment(new moment(aux_end, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                        var diffHours = aux_end_diff.diff(aux_start_diff, 'hours', true).toFixed(2);
                        var m = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('mm')) / 60;
                        var s = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('ss')) / 3600;
                        var aux = parseFloat(parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('HH')) + m + s).toFixed(2);

                        var aux_color = '#3ebf3c';
                        if (parseFloat(obj.Duration) > parseFloat(40) && parseFloat(obj.Duration) <= parseFloat(50)) aux_color = '#f3f317';
                        else if (parseFloat(obj.Duration) > parseFloat(50)) aux_color = '#ff5900';

                        if (obj.Furnace == 'EAF A') {
                            furnace1_heats.push({
                                type: 'heat',
                                name: obj.HeatName.substr(obj.HeatName.length - 3),
                                diffHours: diffHours,
                                duration: `${obj.Duration}'`,
                                color: obj.Color,
                                start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                                startHour: aux,
                                end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                                shift: shift,
                                powerOn: obj.PowerOn,
                                enabledS1: obj.EnabledS1,
                                enabledS2: obj.EnabledS2,
                                enabledS3: obj.EnabledS3,
                                enabledS4: obj.EnabledS4,
                                heatName: obj.HeatName,
                            });
                        } else if (obj.Furnace == 'EAF B') {
                            furnace2_heats.push({
                                type: 'heat',
                                name: obj.HeatName.substr(obj.HeatName.length - 3),
                                diffHours: diffHours,
                                color: obj.Color,
                                duration: `${obj.Duration}'`,
                                start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                                startHour: aux,
                                end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                                shift: shift,
                                powerOn: obj.PowerOn,
                                enabledS1: obj.EnabledS1,
                                enabledS2: obj.EnabledS2,
                                enabledS3: obj.EnabledS3,
                                enabledS4: obj.EnabledS4,
                                heatName: obj.HeatName,
                            });
                        }
                    }


                });
                this.furnace1_heats = furnace1_heats;
                this.furnace2_heats = furnace2_heats;
            },
            getHeats_furnace1: function () {
                return this.furnace1_heats;
            },
            getHeats_furnace2: function () {
                return this.furnace2_heats;
            },


        });


        Screen.Models.ItemAllDelay = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    Furnace: obj.Furnace,
                    Code: obj.Code,
                    Start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                    End: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                    Duration: obj.Duration,
                    Color: obj.Color,
                };
                return result;
            },
        });
        Screen.Collections.ItemsAllDelays = Backbone.Collection.extend({
            model: Screen.Models.ItemAllDelay,

            furnace1_delays: [],
            furnace2_delays: [],

            setDataColl: function (data, shiftId, productionDate) {
                var newColl,
                    that = this;
                that.setDataChart(data, shiftId, productionDate);
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },

            setDataChart: function (delays, shiftId, prodDate) {
                var furnace1_delays = [],
                    furnace2_delays = [],
                    aux_delay = [];

                var aux_start = null,
                    aux_end = null,
                    shift = 'D',
                    aux_duration = null;

                var START_D = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                    END_D = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                    START_N = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                    END_N = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').add(1, 'd').format('YYYY-MM-DD HH:mm:ss');

                if (shiftId == '1') shift = 'D';
                else if (shiftId == '2') shift = 'N';

                _.each(delays, function (obj) {
                    var start = new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss");
                    var end = new moment(obj.End).format("YYYY-MM-DD HH:mm:ss");
                    var push = false;
                    if (shift == 'D') {
                        if (moment(START_D).isBefore(end) && moment(start).isBefore(END_D)) {
                            push = true;
                            if (moment(start).isBefore(START_D)) aux_start = START_D;
                            else aux_start = start;
                            if (moment(END_D).isBefore(end)) aux_end = END_D;
                            else aux_end = end;
                        }
                    } else if (shift == 'N') {
                        if (moment(START_N).isBefore(end) && moment(start).isBefore(END_N)) {
                            push = true;
                            if (moment(start).isBefore(START_N)) aux_start = START_N;
                            else aux_start = start;
                            if (moment(END_N).isBefore(end)) aux_end = END_N;
                            else aux_end = end;
                        }
                    };

                    if (push) {
                        var aux_start_diff = moment(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                        var aux_end_diff = moment(new moment(aux_end, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                        var diffHours = aux_end_diff.diff(aux_start_diff, 'hours', true).toFixed(2);
                        var m = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('mm')) / 60;
                        var s = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('ss')) / 3600;
                        var aux = parseFloat(parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('HH')) + m + s).toFixed(2);
                        if (obj.Furnace == 'EAF A') {
                            furnace1_delays.push({
                                type: 'delay',
                                name: `${obj.Duration}'`,
                                diffHours: diffHours,
                                duration: `${obj.Duration}'`,
                                color: obj.Color,
                                start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                                startHour: aux,
                                end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                                shift: shift,
                            });
                        } else if (obj.Furnace == 'EAF B') {
                            furnace2_delays.push({
                                type: 'delay',
                                name: `${obj.Duration}'`,
                                diffHours: diffHours,
                                duration: `${obj.Duration}'`,
                                color: obj.Color,
                                start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                                startHour: aux,
                                end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                                shift: shift,
                            });
                        }
                    }


                });
                this.furnace1_delays = furnace1_delays;
                this.furnace2_delays = furnace2_delays;
            },
            getDelay_furnace1: function () {
                return this.furnace1_delays;
            },
            getDelay_furnace2: function () {
                return this.furnace2_delays;
            },

        });

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

            setDataChart: function (data) {
                var that = this;

                this.data_EAFA = [];
                this.data_EAFB = [];
                _.each(data, function (obj) {
                    if (obj.EAFName == 'EAF A') that.data_EAFA.push(obj);
                    else that.data_EAFB.push(obj);
                });
            },

            getDataChartEAFA: function () {
                return this.data_EAFA;
            },
            getDataChartEAFB: function () {
                return this.data_EAFB;
            },
        });

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

            setDataChart: function (data) {
                this.data = [];
                this.data = data;
            },

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

            setDataChart: function (data) {
                this.data = [];
                this.data = data;
            },

            getDataChart: function () {
                return this.data;
            },
        });

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

            setDataChart: function (data) {
                this.data = [];
                this.data = data;
            },

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

            setDataChart: function (data) {
                this.data = [];
                this.data = data;
            },

            getDataChart: function () {
                return this.data;
            },
        });

        Screen.Models.ItemBaghouse = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    tagName: obj.tagName,
                    value: obj.Value,
                    datetime: new moment(obj.Datetime).format("MM-DD-YY HH:mm:ss"),
                };

                return result;
            },
        });
        Screen.Collections.ItemsBaghouse = Backbone.Collection.extend({
            fixedParameters: [],
            model: Screen.Models.ItemBaghouse,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },

        });



        Screen.Models.ItemYield = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    date: obj.ProductionDate,
                    shift: obj.ShiftId === 'D' ? 'Day' : 'Night',
                    yieldEAFA: obj.EAFAYield,
                    yieldEAFB: obj.EAFBYield,
                };

                return result;
            },
        });
        Screen.Collections.ItemsYield = Backbone.Collection.extend({
            fixedParameters: [],
            model: Screen.Models.ItemYield,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },

        });


        Screen.Models.ItemDelay = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    RN: obj.rn,
                    Furnace: obj.Furnace,
                    Code: obj.Code,
                    Start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                    End: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                    Duration: obj.Duration,
                    TopDelayCodeReason: obj.TopDelayCodeReason
                };
                return result;
            },
        });
        Screen.Collections.ItemsDelays = Backbone.Collection.extend({
            model: Screen.Models.ItemDelay,

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

            },
        });


        Screen.Models.ItemSlag = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    heatName: obj.HeatName,
                    typeName: obj.TypeName,
                    timestamp: new moment(obj.TimestampString).format("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.ItemsSlag = Backbone.Collection.extend({
            model: Screen.Models.ItemSlag,
            fixedParameters: [],

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

        });

        Screen.Models.ItemRecipe = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    Recipe: obj.Recipe,
                    Material: obj.Material,
                    Plan: obj.Plan,
                    Actual: obj.Actual,
                    DiffWeight: obj.DiffWeight,
                    DiffPercent: obj.DiffPercent,
                    DiffUSD: obj.DiffUSD,
                    Heats: obj.Heats,
                };

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

        });

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

        });

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

        });

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

        });

        Screen.Models.ItemLogBook = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    Title: obj.Title,
                    Author: obj.Author,
                    ShiftId: obj.ShiftID,
                    CrewId: obj.CrewId,
                    Description: obj.Description,
                    Timestamp: new moment(obj.Timestamp).format('HH:mm')
                };
                return result;
            },
        });
        Screen.Collections.ItemsLogBook = Backbone.Collection.extend({
            model: Screen.Models.ItemLogBook,

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

        Screen.Models.SRDCategory = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    id: obj.SRDCategoryId,
                    description: obj.Description,
                    color: obj.Color
                };

                return result;
            },
        });
        Screen.Collections.SRDCategories = Backbone.Collection.extend({
            fixedParameters: [],
            model: Screen.Models.SRDCategory,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },

        });

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

    });