//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',

    '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',
            shifts: [],

            hasData_EAF_A: false,
            hasData_EAF_B: false,

            hasData_EAF: false,
            hasData_Recipes: false,
            hasData_DelaysEAFA: false,
            hasData_DelaysEAFB: false,
            hasData_LogBook: false,
            hasData_Pourback: false,
            hasData_AllDelays: false,
            hasData_AllHeats: false,
            hasData_Temperature: false,
            hasData_Slag: false,

            isLoading_EAF: true,
            isLoading_Recipes: true,
            isLoading_DelaysEAFA: true,
            isLoading_DelaysEAFB: true,
            isLoading_LogBook: true,
            isLoading_Pourback: true,
            isLoading_AllDelays: true,
            isLoading_AllHeats: true,
            isLoading_Temperature: true,
            isLoading_Slag: true,

            hasData_temperature_EAFA: false,
            hasData_temperature_EAFB: false,
            hasData_temperature_EAFA_2: false,
            hasData_temperature_EAFB_2: false,
            hasData_residuals_EAFA: false,
            hasData_residuals_EAFB: false,
            hasData_residuals_EAFA_2: false,
            hasData_residuals_EAFB_2: false,
            hasData_AllHeats_EAF_A: false,
            hasData_AllHeats_EAF_B: false,

            
            hasData_baghouse: false,

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

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

            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,


              CREW_ID: '-'
            , 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: '-'
        },
        initialize: function () {
           // this.itemsCollEAF = new Screen.Collections.ItemsCollEAF();
            this.itemsRecipes = new Screen.Collections.ItemsRecipes();
            this.itemsDelaysEAFA = new Screen.Collections.ItemsDelaysEAFA();
            this.itemsDelaysEAFB = new Screen.Collections.ItemsDelaysEAFB();
            this.itemsLogBook = new Screen.Collections.ItemsLogBook();
            this.itemsPourback = new Screen.Collections.ItemsPourback();
            this.itemsAllDelays = new Screen.Collections.ItemsAllDelays();
            this.itemsAllHeats = new Screen.Collections.ItemsAllHeats();
            this.itemsTemperature = new Screen.Collections.ItemsTemperature();
            this.itemsSlag = new Screen.Collections.ItemsSlag();
            this.itemsBaghouse = new Screen.Collections.ItemsBaghouse();

            this.itemsBucketFluxesEAFA = new Screen.Collections.BucketFluxesEAFA();
            this.itemsBucketFluxesEAFB = new Screen.Collections.BucketFluxesEAFB();

            this.itemsInjectionFluxesEAFA = new Screen.Collections.InjectionFluxesEAFA();
            this.itemsInjectionFluxesEAFB = new Screen.Collections.InjectionFluxesEAFB();

        },

        computeds: {
            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
                },
            },

            hasData: {
                deps: ['hasData_EAF', 'hasData_Recipes', 'hasData_DelaysEAFA', 'hasData_DelaysEAFB', 'hasData_LogBook', 'hasData_AllDelays', 'hasData_AllHeats', 'hasData_Slag'],
                get: function (eaf, recipes, delaysA, delaysB, logBook, allDelays, allHeats, slag) {
                     return (eaf || recipes || delaysA || delaysB || logBook || allDelays || allHeats || slag);
                },
            },
            isLoading: {
                deps: ['isLoading_EAF', 'isLoading_Recipes', 'isLoading_DelaysEAFA', 'isLoading_DelaysEAFB', 'isLoading_LogBook', 'isLoading_AllDelays', 'isLoading_AllHeats', 'isLoading_Slag'],
                get: function (eaf, recipes, delaysA, delaysB, logBook, allDelays, allHeats, slag) {      
                    if (!eaf && !recipes && !delaysA && !delaysB && !logBook && !allDelays && !allHeats && !slag) return false;
                    else return true;
                },
            },
            hasDataDelaysOrHeats: {
                deps: ['hasData_AllDelays', 'hasData_AllHeats'],
                get: function (allDelays, allHeats) {
                    if (allDelays || allHeats) return true;
                    else return false;
                },
            },

            hasData_bucket_fluxes: {
                deps: ['hasData_bucket_fluxes_EAFA', 'hasData_bucket_fluxes_EAFB'],
                get: function (A, B) {
                    if (A && B) return true;
                    else return false;
                },
            },
            isLoading_bucket_fluxes: {
                deps: ['isLoading_bucket_fluxes_EAFA', 'isLoading_bucket_fluxes_EAFB'],
                get: function (A, B) {
                    if (!A && !B) return false;
                    else return true;
                },
            },

            hasData_injection_fluxes: {
                deps: ['hasData_injection_fluxes_EAFA', 'hasData_injection_fluxes_EAFB'],
                get: function (A, B) {
                    if (A && B) return true;
                    else return false;
                },
            },
            isLoading_injection_fluxes: {
                deps: ['isLoading_injection_fluxes_EAFA', 'isLoading_injection_fluxes_EAFB'],
                get: function (A, B) {
                    if (!A && !B) return false;
                    else return true;
                },
            },

            Structural_MgO: {
                deps: ['Structural_MgOMin', 'Structural_MgOMax'],
                get: function (min, max) {
                    if (min && max) return min + '% ' + 'to ' + max + '%'
                    else return ''
                },
            },
            Rail_MgO: {
                deps: ['Rail_MgOMin', 'Rail_MgOMax'],
                get: function (min, max) {
                    if (min && max) return min + '% ' + 'to ' + max + '%'
                    else return ''
                },
            },
            Structural_FeO: {
                deps: ['Structural_FeOMin', 'Structural_FeOMax'],
                get: function (min, max) {
                    if (min && max) return min + '% ' + 'to ' + max + '%'
                    else return ''
                },
            },
            Rail_FeO: {
                deps: ['Rail_FeOMin', 'Rail_FeOMax'],
                get: function (min, max) {
                    if (min && max) return min + '% ' + 'to ' + max + '%'
                    else return ''
                },
            },

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

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

            if (data.length > 0) {
                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);
        },

        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) {
                                //if (resp.Table) that.itemsCollEAF.setDataColl(resp.Table);
                                if (resp.Table) that.totalsAndAverages(resp.Table);
                                if (resp.Table1) that.itemsRecipes.setDataColl(resp.Table1);
                                if (resp.Table2) {
                                    that.itemsDelaysEAFA.setDataColl(resp.Table2);
                                    that.itemsDelaysEAFB.setDataColl(resp.Table2);
                                };
                                if (resp.Table3) that.itemsLogBook.setDataColl(resp.Table3);
                                if (resp.Table13) that.itemsPourback.setDataColl(resp.Table13);
                                if (resp.Table4) that.itemsAllHeats.setDataColl(resp.Table4, params.shiftId, params.productionDate);
                                if (resp.Table5) that.itemsAllDelays.setDataColl(resp.Table5, params.shiftId, params.productionDate);
                                if (resp.Table6) that.itemsTemperature.setDataColl(resp.Table6);

                                if (resp.Table7) that.itemsBucketFluxesEAFA.setDataColl(resp.Table7);
                                if (resp.Table8) that.itemsBucketFluxesEAFB.setDataColl(resp.Table8);
                                if (resp.Table9) that.itemsInjectionFluxesEAFA.setDataColl(resp.Table9);
                                if (resp.Table10) that.itemsInjectionFluxesEAFB.setDataColl(resp.Table10);
                                if (resp.Table11) that.itemsSlag.setDataColl(resp.Table11);
                                if (resp.Table12) that.itemsBaghouse.setDataColl(resp.Table12);
                            }
                            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: 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;
                                        case 'SLAG-LIMITS':
                                            _.each(resp[tableKey], function (obj) {
                                                switch (obj.Name) {
                                                    case 'Structural':
                                                        switch (obj.Code) {
                                                            case 'SLAG_B3_MAX_LIMIT':
                                                                that.set('Structural_B3Max', obj.Value);
                                                                break;
                                                            case 'SLAG_B3_MIN_LIMIT':
                                                                that.set('Structural_B3Min', obj.Value);
                                                                break;
                                                            case 'SLAG_FeO_MAX_LIMIT':
                                                                that.set('Structural_FeOMax', obj.Value);
                                                                break;
                                                            case 'SLAG_FeO_MIN_LIMIT':
                                                                that.set('Structural_FeOMin', obj.Value);
                                                                break;
                                                            case 'SLAG_MgO_MAX_LIMIT':
                                                                that.set('Structural_MgOMax', obj.Value);
                                                                break;
                                                            case 'SLAG_MgO_MIN_LIMIT':
                                                                that.set('Structural_MgOMin', obj.Value);
                                                                break;
                                                            default:
                                                                break;
                                                        }
                                                        break;
                                                    case 'Rail':
                                                        switch (obj.Code) {
                                                            case 'SLAG_B3_MAX_LIMIT':
                                                                that.set('Rail_B3Max', obj.Value);
                                                                break;
                                                            case 'SLAG_B3_MIN_LIMIT':
                                                                that.set('Rail_B3Min', obj.Value);
                                                                break;
                                                            case 'SLAG_FeO_MAX_LIMIT':
                                                                that.set('Rail_FeOMax', obj.Value);
                                                                break;
                                                            case 'SLAG_FeO_MIN_LIMIT':
                                                                that.set('Rail_FeOMin', obj.Value);
                                                                break;
                                                            case 'SLAG_MgO_MAX_LIMIT':
                                                                that.set('Rail_MgOMax', obj.Value);
                                                                break;
                                                            case 'SLAG_MgO_MIN_LIMIT':
                                                                that.set('Rail_MgOMin', obj.Value);
                                                                break;
                                                            default:
                                                                break;
                                                        }
                                                        break;
                                                }

                                                
                                            });


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

    //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 'shift-report';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'shift-report'
        , id: 'shift-report'
        , title: '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
        
        , baghouseChart: null
        , baghouseChartPrint: 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.print();
            return false;
        }

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


        , bindEvents: function () {
            this.listenTo(this.model.itemsRecipes, 'fetch', this.itemsRecipes_ready)
                .listenTo(this.model, 'TotalsAndAverages', this.itemsTotalsAndAverages_ready)
                .listenTo(this.model.itemsDelaysEAFA, 'fetch', this.itemsDelaysEAFA_ready)
                .listenTo(this.model.itemsDelaysEAFB, 'fetch', this.itemsDelaysEAFB_ready)
                .listenTo(this.model.itemsLogBook, 'fetch', this.itemsLogBook_ready)
                .listenTo(this.model.itemsPourback, 'fetch', this.itemsPourback_ready)
                .listenTo(this.model.itemsAllDelays, 'fetch', this.itemsAllDelays_ready)
                .listenTo(this.model.itemsAllHeats, 'fetch', this.itemsAllHeats_ready)
                .listenTo(this.model.itemsBucketFluxesEAFA, 'fetch', this.itemsBucketFluxesEAFA_ready)
                .listenTo(this.model.itemsBucketFluxesEAFB, 'fetch', this.itemsBucketFluxesEAFB_ready)
                .listenTo(this.model.itemsInjectionFluxesEAFA, 'fetch', this.itemsInjectionFluxesEAFA_ready)
                .listenTo(this.model.itemsInjectionFluxesEAFB, 'fetch', this.itemsInjectionFluxesEAFB_ready)
                .listenTo(this.model.itemsTemperature, 'fetch', this.itemsTemperature_ready)
                .listenTo(this.model.itemsSlag, 'fetch', this.itemsSlag_ready)
                .listenTo(this.model.itemsBaghouse, 'fetch', this.itemsBaghouse_ready)
                .listenTo(this.model, 'change:hasDataDelaysOrHeats', this.EAFB_chart)
                .listenTo(this.model, 'EAFB_READY', this.EAFA_chart);
        }

        , itemsTotalsAndAverages_ready: function (hasData) {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_EAF: hasData,
                            isLoading_EAF: false,
                        });
                    },
                    100
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }



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

                            var grid_delaysEAFA = new Backgrid.Grid({
                                className: 'grid-styles table',
                                columns: [
                                    {
                                        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: 'MM/DD/YYYY 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: 'MM/DD/YYYY HH:mm',
                                        }),
                                    },
                                    {
                                        name: 'Furnace',
                                        label: app.translate(that, 'item_furnace_col_label'),
                                        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: app.translate(that, 'item_duration_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                ],
                                collection: that.model.itemsDelaysEAFA,
                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);

                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                }),
                            });

                            that.$el.find('.items-grid-container-delaysEAFA').append(grid_delaysEAFA.render().el);


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

                                    {
                                        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: 'MM/DD/YYYY 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: 'MM/DD/YYYY HH:mm',
                                        }),
                                    },
                                    {
                                        name: 'Furnace',
                                        label: app.translate(that, 'item_furnace_col_label'),
                                        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: app.translate(that, 'item_duration_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                ],
                                collection: that.model.itemsDelaysEAFB,
                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);

                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                }),
                            });

                            that.$el.find('.items-grid-container-delaysEAFB').append(grid_delaysEAFB.render().el);

                            var grid_LogBook = new Backgrid.Grid({
                                className: 'grid-styles table',
                                columns: [
                                    {
                                        name: 'Timestamp',
                                        label: 'Timestamp',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                    {
                                        name: 'Title',
                                        label: app.translate(that, 'item_title_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                    {
                                        name: 'Author',
                                        label: app.translate(that, 'item_author_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element shift-crew-column',
                                        }),
                                    },
                                    {
                                        name: 'ShiftId',
                                        label: app.translate(that, 'item_shift_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element 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 element shift-crew-column',
                                        }),
                                    },
                                    {
                                        name: 'Description',
                                        label: app.translate(that, 'item_description_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                ],
                                collection: that.model.itemsLogBook,
                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);

                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                }),
                            });

                            that.$el.find('.items-grid-container-itemsLogBook').append(grid_LogBook.render().el);

                            
                            var grid_Pourback = new Backgrid.Grid({
                                className: 'grid-styles table',
                                columns: [
                                    {
                                        name: 'Timestamp',
                                        label: 'Timestamp',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                    {
                                        name: 'FromHeatName',
                                        label: app.translate(that, 'item_from_heat_name_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                    {
                                        name: 'ToHeatName',
                                        label: app.translate(that, 'item_to_heat_name_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                    {
                                        name: 'Weight',
                                        label: app.translate(that, 'item_weight_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell element',
                                        }),
                                    },
                                   
                                    
                                ],
                                collection: that.model.itemsPourback,
                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);

                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                }),
                            });

                            that.$el.find('.items-grid-container-itemsPourback').append(grid_Pourback.render().el);

                            var grid_recipes = new Backgrid.Grid({
                                className: 'grid-styles table',
                                columns: [
                                    {
                                        name: 'Recipe',
                                        label: app.translate(that, 'item_scrapRecipe_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell recipes',
                                        }),
                                    },
                                    {
                                        name: 'Material',
                                        label: app.translate(that, 'item_scrapMaterial_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'Plan',
                                        label: app.translate(that, 'item_scrapPlan_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'Actual',
                                        label: app.translate(that, 'item_scrapActual_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'DiffWeight',
                                        label: app.translate(that, 'item_scrapDiffWeight_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'DiffPercent',
                                        label: app.translate(that, 'item_scrapDiffPercent_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    //{
                                    //    name: 'DiffUSD',
                                    //    label: app.translate(that, 'item_scrapDiffUSD_col_label'),
                                    //    editable: false,
                                    //    cell: Backgrid.NumberCell.extend({
                                    //        className: 'number-cell align-center-cell',
                                    //    }),
                                    //},
                                ],
                                collection: that.model.itemsRecipes,
                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);

                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                }),
                            });

                            that.$el.find('.items-grid-container-recipes').append(grid_recipes.render().el);


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

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

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

                                    {
                                        name: 'total',
                                        label: app.translate(that, 'total_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (this.model.get('TotalStatus') == 'WARNING') return 'number-cell warning';
                                                else return 'number-cell';
                                            },
                                            decimals: 1,
                                        }),
                                    },
                                    {
                                        name: 'Cr2O3',
                                        label: app.translate(that, 'cr2O3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell',
                                            decimals: 1,
                                        }),
                                    },
                                    {
                                        name: 'P2O5',
                                        label: app.translate(that, 'p2O5_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell',
                                            decimals: 1,
                                        }),
                                    },
                                    {
                                        name: 'SO3',
                                        label: app.translate(that, 'sO3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell',
                                            decimals: 1,
                                        }),
                                    },
                                    {
                                        name: 'dirtLoad',
                                        label: app.translate(that, 'dirtLoad_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell',
                                            decimals: 0,
                                        }),
                                    },
                                    {
                                        name: 'TotalSlagVolume',
                                        label: app.translate(that, 'TotalSlagVolume_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-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') == 'WARNING') return 'number-cell warning';
                                                else if (this.model.get('RefractoryWearStatus') == 'NORMAL') return 'number-cell normal';
                                                else return 'number-cell';
                                            },
                                            decimals: 0,
                                        }),
                                    },
                                    {
                                        name: 'steelLoss',
                                        label: app.translate(that, 'steelLoss_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell',
                                            decimals: 0,
                                        }),
                                    },

                                ],
                                collection: that.model.itemsSlag,
                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);

                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                }),
                            });

                            that.$el.find('.items-grid-container-slag').append(grid_slag.render().el);


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

                            
                            that.baghouseChart = new IndustrialChart(
                                that.$el.find('#baghouseChartContainer')[0],
                                {
                                    View: {
                                        Title: app.translate([that, app], 'process_chart_title'),
                                        Header: false,
                                        DisplayScales: {
                                            value: false,
                                        },
                                        Resize: false,
                                        Configuration: {
                                            CursorValue: true,
                                        },
                                    },
                                    DatabaseParameters: {
                                        ConnectionStringName: app.ConnectionStrings.app,
                                        Procedure: app.DatabaseNames.MES + '.EAF.GetBaghouseChartData',
                                        Secured: true,
                                    },
                                }
                            );

                            that.baghouseChartPrint = new IndustrialChart(
                                    that.$el.find('#baghouseChartPrintContainer')[0],
                                    {
                                        View: {
                                            Title: app.translate([that, app], 'process_chart_title'),
                                            Header: false,
                                            DisplayScales: {
                                                value: false,
                                            },
                                            Resize: false,
                                            Configuration: {
                                                CursorValue: true,
                                            },
                                        },
                                        DatabaseParameters: {
                                            ConnectionStringName: app.ConnectionStrings.app,
                                            Procedure: app.DatabaseNames.MES + '.EAF.GetBaghouseChartData',
                                            Secured: true,
                                        },
                                    }
                                );

                            // 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();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        }

        , refresh: function () {
            try {
                var params = this.model.toJSON();

                this.$el.find('.chart-EAF-A').html('');
                this.$el.find('.chart-EAF-B').html('');
                this.$el.find('.temperature_EAFA').html('');
                this.$el.find('.temperature_EAFB').html('');
                this.$el.find('.temperature_EAFA_2').html('');
                this.$el.find('.temperature_EAFB_2').html('');
                this.$el.find('.temperature_EAFA_print').html('');
                this.$el.find('.temperature_EAFB_print').html('');
                this.$el.find('.temperature_EAFA_2_print').html('');
                this.$el.find('.temperature_EAFB_2_print').html('');

                this.$el.find('.residuals_EAFA').html('');
                this.$el.find('.residuals_EAFB').html('');
                this.$el.find('.residuals_EAFA_2').html('');
                this.$el.find('.residuals_EAFB_2').html('');


                this.$el.find('.residuals_EAFA_print').html('');
                this.$el.find('.residuals_EAFB_print').html('');
                this.$el.find('.residuals_EAFA_2_print').html('');
                this.$el.find('.residuals_EAFB_2_print').html('');

                
                this.$el.find('.baghouse').html('');
                this.$el.find('.baghouse_print').html('');

                this.$el.find('.bucket_fluxes_EAFA').html('');
                this.$el.find('.bucket_fluxes_EAFB').html('');
                this.$el.find('.bucket_fluxes_EAFA_print').html('');
                this.$el.find('.bucket_fluxes_EAFB_print').html('');
                this.$el.find('.injection_fluxes_EAFA').html('');
                this.$el.find('.injection_fluxes_EAFB').html('');
                this.$el.find('.injection_fluxes_EAFA_print').html('');
                this.$el.find('.injection_fluxes_EAFB_print').html('');

                this.model.set({
                    CREW_ID: ''
                    , 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: '',

                    hasData_EAF_A: false,
                    hasData_EAF_B: false,


                    isLoading_EAF: true,
                    isLoading_Recipes: true,
                    isLoading_DelaysEAFA: true,
                    isLoading_DelaysEAFB: true,
                    isLoading_LogBook: true,
                    isLoading_Pourback: true,
                    isLoading_AllDelays: true,
                    isLoading_AllHeats: true,
                    isLoading_Slag: true,

                    hasData_EAF: false,
                    hasData_Recipes: false,
                    hasData_DelaysEAFA: false,
                    hasData_DelaysEAFB: false,
                    hasData_LogBook: false,
                    hasData_Pourback: false,
                    hasData_AllDelays: false,
                    hasData_AllHeats: false,
                    hasData_Slag: false,

                    hasData_temperature_EAFA: false,
                    hasData_temperature_EAFB: false,
                    hasData_temperature_EAFA_2: false,
                    hasData_temperature_EAFB_2: false,
                    hasData_residuals_EAFA: false,
                    hasData_residuals_EAFB: false,
                    hasData_residuals_EAFA_2: false,
                    hasData_residuals_EAFB_2: false,
                    hasData_AllHeats_EAF_A: false,
                    hasData_AllHeats_EAF_B: false,
                    hasData_baghouse: 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,

                });

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

                // reload collections 
                this.model.fetchData({
                    productionDate: params.productionDate,
                    shiftId: shift,
                });

                
                this.baghouseChart.Clear();
                this.baghouseChartPrint.Clear();

                 this.fetchTrendingChart({
                    shiftId:params.shiftId ? params.shiftId : 'D',                    
                    productionDate: params.productionDate,

                });

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        , fetchTrendingChart: function (params) {
                var qp = new QueryParameters();
                qp.Add('shiftId', 'CHAR(1)', params.shiftId);
                qp.Add('productionDate', 'DATETIME', params.productionDate);

                this.baghouseChart.RefreshData(qp);
                this.baghouseChartPrint.RefreshData(qp);
        }

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

        //-- Design functions
       
        , EAFA_chart: function () {
            var that = this;
            setTimeout(
                function () {
                    that.getChart(true);
                    that.model.trigger('EAFA_READY', that);
                },
                100
            );
        }
        , EAFB_chart: function () {
            var that = this;
            if (this.model.get('hasDataDelaysOrHeats')) {
                setTimeout(
                    function () {
                        that.getChart(false);
                        that.model.trigger('EAFB_READY', that);
                    },
                    100
                );
            }

        }

        , getChart(eafA) {
            var chartHeight = 100,
                chartWeight = 1008,

                dataHeight = chartHeight / 2,
                delayHeight = chartHeight / 4,
                divisions = 12,
                pixelHour = chartWeight / divisions,
                separationPixels = 10,
                axisHeight = 20,
                startHourPixel = 0,
                start = 0,
                start_yPos = 0,
                data = [],
                size_letter = 10;


            if (eafA) {
                _.each(this.model.itemsAllHeats.getHeats_eafA(), function (obj) {
                    data.push(obj);
                })
                _.each(this.model.itemsAllDelays.getDelay_eafA(), function (obj) {
                    data.push(obj);
                });
                var chart_class = ".chart-EAF-A";
            } else {
                _.each(this.model.itemsAllHeats.getHeats_eafB(), function (obj) {
                    data.push(obj);
                })
                _.each(this.model.itemsAllDelays.getDelay_eafB(), function (obj) {
                    data.push(obj);
                });
                var chart_class = ".chart-EAF-B";
            }
            if (data.length > 0) {
                var chart = d3.select(chart_class)
                    .attr("width", chartWeight + 1)
                    .attr("height", chartHeight + separationPixels + axisHeight)

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

                chart.append("rect")
                    .attr("class", "line")
                    .attr("width", chartWeight)
                    .attr("height", 0.5)
                    .style('opacity', 1)
                    .attr("transform", "translate(0," + (parseFloat(dataHeight / 4) + parseFloat(dataHeight) + separationPixels) + ")")
                    .style('fill', '#404040')

                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', '#404040')
                    .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', '#404040')
                            .attr('stroke-width', 1)
                    })
                    .append("svg:title")
                    .text(function (d) { return "Start: " + d.start + " " + "End: " + d.end + " Dur: " + d.duration })

                ////Append top text

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

                    })
                    .text(function (d) {
                        if (d.name) {
                            var text = ((d.name.length * size_letter) > (d.diffHours * pixelHour)) ? '' : d.name;
                            return text;
                        } else
                            return '';
                    })
                    .attr("id", function (d, i) { return "int_text" + "_" + i });

                // Center the top text in the rectangle
                chart.selectAll("g")
                    .select(".top_text")
                    .attr("x", function (d, i) {
                        var text_element = document.getElementById("int_text" + "_" + i);
                        var text_element_width = text_element.getBoundingClientRect().width;

                        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 - text_element_width) / 2);

                    });

                ////Append bottom text

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

                    })
                    .text(function (d) {
                        if (d.powerOn) {
                            var powerOn = "On: " + d.powerOn;
                            var text = ((powerOn.length * size_letter) > (d.diffHours * pixelHour)) ? '' : powerOn;
                            return text;
                        } else
                            return '';
                    })
                    .attr("id", function (d, i) { return "int_bottom_text" + "_" + i });

                //// Center the bottom text in the rectangle

                chart.selectAll("g")
                    .select(".bottom_text")
                    .attr("x", function (d, i) {
                        var text_element = document.getElementById("int_bottom_text" + "_" + i);
                        var text_element_width = text_element.getBoundingClientRect().width;
                        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 - text_element_width) / 2);

                    });

                //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", 10);

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





        // -- Scatter charts functions
        
        //Baghouse chart
         , 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 -32;
                    });

                
                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
                /*svg
                    .selectAll("whatever")
                    .data(baghouseData)
                    .enter()
                    .append("circle")
                    .attr("fill", "black")
                    .attr("cx", function (d) {
                        if (d.tagName === 'RU')
                            return x(new Date(d.datetime));
                    })
                    .attr("cy", function (d) {
                        if (d.tagName === 'RU') {
                            if (d.value > 3600) return y(3600);
                            else if (d.value < 1000) return y(1000);
                            else return y(d.value);
                        }
                    })
                    .attr("transform",
                        "translate(" + minValueBottomAxis + ", 0)")
                    .attr("r", function (d) {
                        if (d.tagName === 'RU')
                            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', 'black')
                            .attr('stroke-width', 1)
                    })
                    .append("svg:title")
                    .text(function (d) {
                      if (d.tagName === 'RU')
                            return "Convey Runtime: " + d.value + " Datetime: " + d.datetime;
                       else return '';
                    })*/

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

                  // Dust Silo Data
                 /* svg
                    .selectAll("whatever")
                    .data(baghouseData)
                    .enter()
                    .append("circle")
                    .attr("fill", "red")
                    .attr("cx", function (d) {
                        if (d.tagName === 'DU')
                            return x(new Date(d.datetime));
                    })
                    .attr("cy", function (d) {
                        if (d.tagName === 'DU') {
                            if (d.value > 100) return y0(maxValueLeft);
                            else if (d.value < 0) return y0(minValueLeft);
                            else return y0(d.value);
                        }
                    })
                    .attr("transform",
                        "translate(" + minValueBottomAxis + ", 0)")
                    .attr("r", function (d) {
                        if (d.tagName === 'DU')
                            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', 'red')
                            .attr('stroke-width', 1)
                    })
                    .append("svg:title")
                    .text(function (d) {
                      if (d.tagName === 'DU')
                            return "Dust Silo Level: " + d.value + " Datetime: " + d.datetime;
                       else return '';
                    })*/
                    //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);                    
                    
                    })
                    )

                 // VA Data
                  /*svg
                    .selectAll("whatever")
                    .data(baghouseData)
                    .enter()
                    .append("circle")
                    .attr("fill", "blue")
                    .attr("cx", function (d) {
                        if (d.tagName === 'VA'){
                                return x(new Date(d.datetime));
                            }
                    })
                    .attr("cy", function (d) {
                        if (d.tagName === 'VA') {
                            if (d.value > 0) return y1(0);
                            else if (d.value < -150) return y1(-150);
                            else return y1(d.value);
                        }
                    })
                    .attr("transform",
                        "translate(" + minValueBottomAxis + ", 0)")
                    .attr("r", function (d) {
                        if (d.tagName === 'VA')
                            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.tagName === 'VA')
                            return "VA: " + d.value + " Datetime: " + d.datetime;
                       else return '';
                    })*/

                   //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", 70)
                    .text("Convey Vacuum")

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

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

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

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


            }
            
        }

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

            _.each(data, function (obj, i) {
                domainBand[i] = obj.HeatName;
            });
            var title = '';
            var chartWidth = width;
            var chartHeight = 410;
            var chartMarginLeft = 60;
            var maxAxisBottom = chartWidth - 100;
            var maxAxisLeftHeight = 300;
            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 + "," + 350 + ")");

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

                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", -320)
                    .attr("x", -20)
                    .text("Residuals")

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 70)
                    .text("Cu")


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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 140)
                    .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 = 410;
            var chartMarginLeft = 60;
            var maxAxisBottom = chartWidth - 100;
            var maxAxisLeftHeight = 300;
            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 + "," + 350 + ")");

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

                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", -320)
                    .attr("x", -20)
                    .text("Residuals")

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 70)
                    .text("Mo")


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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 140)
                    .text("Sn")

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 210)
                    .text("P")

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 280)
                    .text("Zn")

            }

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

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

            var title = '';
            var chartWidth = width;
            var chartHeight = 410;
            var chartMarginLeft = 60;
            var maxAxisBottom = chartWidth - 100;
            var maxAxisLeftHeight = 300;
            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 + "," + 350 + ")");

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


                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.append("text")
                //    .attr("x", 23)
                //    .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("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 "EAF Last Temperature: " + d.EAFLastTemperature;
                        else return '';
                    })


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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 200)
                    .text("EAF 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


            }



        }
        , temperatureChart2: function (data, id,width) {
            var domainBand = [];
            _.each(data, function (obj, i) {
                domainBand[i] = obj.HeatName;
            });
            var title = '';
            var chartWidth = width;
            var chartHeight = 410;
            var chartMarginLeft = 60;
            var maxAxisBottom = chartWidth - 100;
            var maxAxisLeftHeight = 300;
            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 + "," + 350 + ")");

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

                if (id == '.temperature_EAFA_2') {
                    title = "EAF A - Oxygen";
                    this.model.set({ hasData_temperature_EAFA_2: true });
                }
                else if (id == '.temperature_EAFB_2') {
                    title = "EAF B - Oxygen";
                    this.model.set({ hasData_temperature_EAFB_2: 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 "EAF Last O2: " + d.EAFLastO2;
                        else return '';
                    })

                
                // References

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 130)
                    .text("EAF Last O2")



            }



        }
        , bucketFluxes: function (data, id, width) {
            var domainBand = [];
            _.each(data, function (obj, i) {
                domainBand[i] = obj.HeatName;
            });
            var title = '';
            var chartWidth = width;
            var chartHeight = 410;
            var chartMarginLeft = 60;
            var maxAxisBottom = chartWidth - 100;
            var maxAxisLeftHeight = 300;
            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 + "," + 350 + ")");

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

                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.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', '#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.InjDolo)
                            return "InjDolo: " + d.InjDolo;
                        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.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)")

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

                // Add the line
                svg.append("path")
                    .datum(data)
                    .attr("fill", "none")
                    .attr("stroke", "#56bd2c")
                    .attr("stroke-width", 0.7)
                    .attr("d", d3.line()
                        .x(function (d) { return x(d.HeatName) })
                        .y(function (d) {
                            if (d.TotalDolo) {
                                if (d.TotalDolo > maxValueLeft) return y(maxValueLeft);
                                else if (d.TotalDolo < minValueLeft) return y(minValueLeft);
                                else return y(d.TotalDolo);
                            }
                            else return 0;
                        })
                    )
                    .attr("transform",
                        "translate(" + minValueBottomAxis + ", 0)")
                // References
                svg.append("circle")
                    .attr("cy", -325)
                    .attr("cx", 0)
                    .attr("fill", "blue")
                    .attr("r", 6)

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


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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 100)
                    .text("Dolo")

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 170)
                    .text("Carbon")

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 250)
                    .text("Inj Carbon")

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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 330)
                    .text("Inj Dolo")

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

               svg.append("text")
                    .attr("y", -320)
                    .attr("x", 420)
                    .text("Tot Carbon")

                svg.append("circle")
                    .attr("cy", -325)
                    .attr("cx", 470)
                    .attr("fill", "#56bd2c")
                    .attr("r", 6)

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 510)
                    .text("Tot Dolo")

            }

        }
        , injectionFluxes: function (data, id, width) {
            var domainBand = [];
            _.each(data, function (obj, i) {
                domainBand[i] = obj.HeatName;
            });
            var title = '';
            var chartWidth = width;
            var chartHeight = 410;
            var chartMarginLeft = 60;
            var maxAxisBottom = chartWidth - 100;
            var maxAxisLeftHeight = 300;
            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 + "," + 350 + ")");

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

                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.append("text")
                //    .attr("x", 45)
                //    .attr("y", -335)
                //    .attr("text-anchor", "middle")
                //    .attr("class", "text")
                //    .style("font-size", "16px")
                //    .text(title);


                //---------------------------------DOLO-------------------------------------------
                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)")

                //---------------------------------Carbon-------------------------------------------
                //svg
                //    .selectAll("whatever")
                //    .data(data)
                //    .enter()
                //    .append("circle")
                //    .attr("fill", "red")
                //    .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", "red")
                //    .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)")


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

                svg.append("text")
                    .attr("y", -320)
                    .attr("x", 90)
                    .text("KWH/Ton")


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

                //svg.append("text")
                //    .attr("y", -320)
                //    .attr("x", 150)
                //    .text("Carbon")


            }

        }


        // -- 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_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.temperatureChart2(that.model.itemsTemperature.getDataChartEAFA(), ".temperature_EAFA_2", 750);
                            that.temperatureChart(that.model.itemsTemperature.getDataChartEAFB(), ".temperature_EAFB", 750);
                            that.temperatureChart2(that.model.itemsTemperature.getDataChartEAFB(), ".temperature_EAFB_2", 750);

                            
                            that.baghouse_Chart(".baghouse", 2100);                            
                            that.baghouse_Chart(".baghouse_print", 1100);

                            that.temperatureChart(that.model.itemsTemperature.getDataChartEAFA(), ".temperature_EAFA_print", 600);
                            that.temperatureChart2(that.model.itemsTemperature.getDataChartEAFA(), ".temperature_EAFA_2_print", 600);
                            that.temperatureChart(that.model.itemsTemperature.getDataChartEAFB(), ".temperature_EAFB_print", 600);
                            that.temperatureChart2(that.model.itemsTemperature.getDataChartEAFB(), ".temperature_EAFB_2_print", 600);

                            that.residualsChart(that.model.itemsTemperature.getDataChartEAFA(), ".residuals_EAFA_print", 600);
                            that.residualsChart2(that.model.itemsTemperature.getDataChartEAFA(), ".residuals_EAFA_2_print", 600);
                            that.residualsChart(that.model.itemsTemperature.getDataChartEAFB(), ".residuals_EAFB_print", 600);
                            that.residualsChart2(that.model.itemsTemperature.getDataChartEAFB(), ".residuals_EAFB_2_print", 600);
                        };
                    },
                    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", 600);
                        };
                    },
                    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", 600);
                        };
                    },
                    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", 600);

                        };
                    },
                    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", 600);
                        };
                    },
                    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
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        , itemsDelaysEAFA_ready: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_DelaysEAFA: (that.model.itemsDelaysEAFA.length > 0),
                            isLoading_DelaysEAFA: false,
                        });
                    },
                    100
                );

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        , itemsDelaysEAFB_ready: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_DelaysEAFB: (that.model.itemsDelaysEAFB.length > 0),
                            isLoading_DelaysEAFB: 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); }
        }
        , itemsAllDelays_ready: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_AllDelays: (that.model.itemsAllDelays.length > 0),
                            isLoading_AllDelays: false,
                        });
                    },
                    100
                );

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        , itemsAllHeats_ready: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_AllHeats: (that.model.itemsAllHeats.length > 0),
                            hasData_AllHeats_EAF_A: (that.model.itemsAllHeats.eafA_heats.length > 0),
                            hasData_AllHeats_EAF_B: (that.model.itemsAllHeats.eafB_heats.length > 0),
                            isLoading_AllHeats: 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.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.Models.ItemSlag = Backbone.Epoxy.Model.extend({
        parse: function (obj) {
            var result = {
                heatName: obj.HeatName,
                typeName: obj.TypeName,
                timestamp: new moment(obj.TimestampString).format("MM-DD-YY 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.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.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.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.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.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.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({
        model: Screen.Models.ItemRecipe,

        fixedParameters: [],

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

    });


    Screen.Models.ItemDelayEAFA = 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,
            };
            return result;
        },
    });
    Screen.Collections.ItemsDelaysEAFA = Backbone.Collection.extend({
        model: Screen.Models.ItemDelayEAFA,

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

        },
    });

    Screen.Models.ItemDelayEAFB = 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,
            };
            return result;
        },
    });
    Screen.Collections.ItemsDelaysEAFB = Backbone.Collection.extend({
        model: Screen.Models.ItemDelayEAFB,

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

        },

    });

    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('MM/DD/YYYY 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.ItemPourback = Backbone.Epoxy.Model.extend({
        parse: function (obj) {
            var result = {
                Comment: obj.Comment
               ,EAFProcessId: obj.EAFProcessId
               ,FromHeatId: obj.FromHeatId
               ,FromHeatName: obj.FromHeatName
               ,Timestamp: new moment(obj.Timestamp).format('MM/DD/YYYY HH:mm:ss')
               ,ToHeatName: obj.ToHeatName
               ,Weight: obj.Weight

            };
            return result;
        },
    });
    Screen.Collections.ItemsPourback = Backbone.Collection.extend({
        model: Screen.Models.ItemPourback,

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

    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,

        eafA_heats: [],
        eafB_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 eafA_heats = [],
                eafB_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') {
                        eafA_heats.push({
                            type: 'heat',
                            name: obj.HeatName.substr(obj.HeatName.length - 3),
                            diffHours: diffHours,
                            duration: obj.Duration + ' Min',
                            color: aux_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 / 60,
                        });
                    } else if (obj.Furnace == 'EAF B') {
                        eafB_heats.push({
                            type: 'heat',
                            name: obj.HeatName.substr(obj.HeatName.length - 3),
                            diffHours: diffHours,
                            color: aux_color,
                            duration: obj.Duration + ' Min',
                            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 / 60,
                        });
                    }
                }


            });
            this.eafA_heats = eafA_heats;
            this.eafB_heats = eafB_heats;
        },
        getHeats_eafA: function () {
            return this.eafA_heats;
        },
        getHeats_eafB: function () {
            return this.eafB_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,

        eafA_delays: [],
        eafB_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 eafA_delays = [],
                eafB_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') {
                        eafA_delays.push({
                            type: 'delay',
                            name: obj.Duration + ' Min',
                            diffHours: diffHours,
                            duration: obj.Duration + ' Min',
                            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') {
                        eafB_delays.push({
                            type: 'delay',
                            name: obj.Duration + ' Min',
                            diffHours: diffHours,
                            duration: obj.Duration + ' Min',
                            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.eafA_delays = eafA_delays;
            this.eafB_delays = eafB_delays;
        },
        getDelay_eafA: function () {
            return this.eafA_delays;
        },
        getDelay_eafB: function () {
            return this.eafB_delays;
        },

    });

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

});