//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',
  'js/d3v4/d3.v4',
  'modules/navigation-buttons/navigation-buttons',
  '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, d3, NavigationButton) {

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

    Screen.Models.ItemSlag = Backbone.Epoxy.Model.extend({
        parse: function (obj) {
            var result = {
                gradeGroupName: obj.GradeGroupName,
                heatName: obj.HeatName,
                typeName: obj.TypeName,
                timestamp: new moment(obj.TimestampString).format("YYYY-MM-DD HH:mm:ss"),
                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,

           
                dirtLoad: obj.DirtLoad,

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

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

            return result;
        },
    });

    Screen.Collections.ItemsCollEAFA = Backbone.Collection.extend({
        model: Screen.Models.ItemSlag,

        isFetching: false,
        currentPage: 1,
        pageSize: 15,

        fetch: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                options = params ? _.clone(params) : {};
            if (options.refresh) {
                this.resetPagination(true);
                var to = new moment(params.to, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD');
                this.fixedParameters = [
                    { Name: '@heatName', Type: 'VARCHAR', Value: params.heatName, },
                    { Name: '@from', Type: 'DATE', Value: params.from, },
                    { Name: '@to', Type: 'DATE', Value: to, },
                    { Name: '@timeZoneCode', Type: 'CHAR(10)', Value: params.timezoneCode },
                    { Name: '@furnaceCode', Type: 'CHAR(1)', Value: 1 },
                ];
            }
            this.isFetching = true;

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

            if (!options.refresh) {
                qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            } else {
                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@toRow', 'INT', this.currentPage * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            }




            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAB.EAFGetSlagChemistrySamplesReport',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp) {
                                if (resp.Table) {
                                    var newColl = _.map(resp.Table, that.model.prototype.parse);

                                    var method = (options.refresh) ? 'set' : 'add';

                                    that[method](newColl)
                                        .trigger('fetch', resp.Table2 ? resp.Table2 : null);

                                    if (newColl.length == 0 && method == 'add')
                                        that.currentPage--;


                                    that.isFetching = false;
                                }
                                //if (resp.Table1) that.trigger('fetch-nav-buttons', resp.Table1);
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    console.error(new Error(resp.Message).stack);
                                    app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                }
                                else {
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                }
                            }
                        }
                        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;
        },

        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },
        getGridId: function () {
            return 'EAFA';
        },

    });


    Screen.Collections.ItemsCollEAFB = Backbone.Collection.extend({
        model: Screen.Models.ItemSlag,

        isFetching: false,
        currentPage: 1,
        pageSize: 15,

        fetch: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                options = params ? _.clone(params) : {};
            if (options.refresh) {
                this.resetPagination(true);
                var to = new moment(params.to, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD');
                this.fixedParameters = [
                    { Name: '@heatName', Type: 'VARCHAR', Value: params.heatName, },
                    { Name: '@from', Type: 'DATE', Value: params.from, },
                    { Name: '@to', Type: 'DATE', Value: to, },
                    { Name: '@timeZoneCode', Type: 'CHAR(10)', Value: app.models.user.get('timezoneCode') },
                    { Name: '@furnaceCode', Type: 'CHAR(1)', Value: 2 },
                ];
            }
            this.isFetching = true;

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

            if (!options.refresh) {
                qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            } else {
                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@toRow', 'INT', this.currentPage * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            }



            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAB.EAFGetSlagChemistrySamplesReport',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp) {
                                if (resp.Table) {
                                    var newColl = _.map(resp.Table, that.model.prototype.parse);

                                    var method = (options.refresh) ? 'set' : 'add';

                                    that[method](newColl)
                                        .trigger('fetch', resp.Table2 ? resp.Table2 : null);

                                    if (newColl.length == 0 && method == 'add')
                                        that.currentPage--;


                                    that.isFetching = false;
                                }

                                if (resp.Table1) that.trigger('fetch-nav-buttons', resp.Table1);
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    console.error(new Error(resp.Message).stack);
                                    app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                }
                                else {
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                }
                            }
                        }
                        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;
        },

        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },
        getGridId: function () {
            return 'EAFB';
        },

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

            from: new moment().subtract(2, 'days').format('YYYY-MM-DD'),
            to: new moment().format('YYYY-MM-DD'),

            typeName: null,
            types: [],

            hasData: false,
            isLoading: false,

            heatName: '-',

            isLoading_EAFA: true,
            hasData_EAFA: false,
            isLoading_EAFB: true,
            hasData_EAFB: 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,

            gradeGroupsLimits:[],
            gradeGroups: [],
            limitByGrade: [],


            EAFA_Product: '-',
            EAFA_B3ratio: '-',
            EAFA_MgO: '-',
            EAFA_FeO: '-',


            EAFB_Product: '-',
            EAFB_B3ratio: '-',
            EAFB_MgO: '-',
            EAFB_FeO: '-',
        },

        initialize: function () {
            this.itemsCollEAFA = new Screen.Collections.ItemsCollEAFA();
            this.itemsCollEAFB = new Screen.Collections.ItemsCollEAFB();
        },

        computeds: {
            hasHeatName: {
                deps: ['heatName'],
                get: function (heatName) {
                    return (heatName != '-' ? true : false);
                },
            },
            hasData: {
                deps: ['hasData_EAFA', 'hasData_EAFB'],
                get: function (eafa, eafb) {
                    return eafa || eafb;
                },
            },
            isLoading: {
                deps: ['isLoading_EAFA', 'isLoading_EAFB'],
                get: function (eafa,eafb) {
                    return eafa || eafb;
                },
            },
            from$: {
                deps: ['from'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { from: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            to$: {
                deps: ['to'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { to: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            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 ''
                },
            },
        },

        getLimitsByGradeGroup: function () {
            var that = this;
            var limits;
            var limitMsg = [];
            var allLimitsMsg = [];
            _.each(that.get('gradeGroups'), function (grade) {
                limits = _.where(that.get('gradeGroupsLimits'), { Name: grade.Name });
                limitMsg = '';
                _.each(limits, function (limit, i) {
                    limitMsg = limit.CodeName + ': ' + limit.Value + ' ' + limitMsg;
                });
                limitMsg = limits[0].Name + ' - ' + limitMsg;
                allLimitsMsg.push({ Name: limits[0].Name, Msg: limitMsg, Color: grade.Color, Abbrev:grade.Abbrev });
            

            });
            that.set({ limitByGrade: allLimitsMsg });

        },


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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAB.EAFGetSlagChemistrySamplesReportPickers',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                that.set('gradeGroupsLimits', resp.Table);
                                that.set('gradeGroups', resp.Table1);
                                that.getLimitsByGradeGroup();

                                _.each(resp.Table, 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;
        },

    });

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'slag-chemistry-samples-report-eaf',
        id: 'slag-chemistry-samples-report-eaf',
        title: 'EAF Slag Chemistries Report',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                "click .btn-export-to-excel": this.exportToExcel,
                'click #periodViewBtn': this.periodViewBtn_click,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,
        items: null,
        eafProcess: null,
        subviews: null,
        viewParams: null,
        NavigationButtonView: null,

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

            var that = this;

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

            this.bindingSources = {
                eafProcess: this.eafProcess,
            };

            this.grids = { items: null };

            this.subviews = {
            };
            this.NavigationButtonView = new NavigationButton.Views.Main();

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

            this.bindEvents();
        },
        bindEvents: function () {
            this.listenTo(this.model.itemsCollEAFA, 'fetch', this.itemsCollEAFA_ready)
                .listenTo(this.model.itemsCollEAFB, 'fetch', this.itemsCollEAFB_ready);
            this.listenTo(this.model.itemsCollEAFB, 'fetch-nav-buttons', this.fetchnavbuttons);
        },
        periodViewBtn_click: function () {
            this.model.set({ heatName: '-' });
            this.refreshBtn_click();

        },
        itemsCollEAFA_ready: function (resp) {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_EAFA: (that.model.itemsCollEAFA.length > 0),
                            isLoading_EAFA: false,
                        });
                        if (resp && resp[0]) {
                            that.model.set({
                                EAFA_Product: resp[0].Product,
                                EAFA_B3ratio: resp[0].B3ratio,
                                EAFA_MgO: resp[0].MgO,
                                EAFA_FeO: resp[0].FeO,

                            })
                        }
                    },
                    100
                );

                that.setURLClassGrid('EAFA');

                var rows = Array.from(document.querySelectorAll('tr.highlight'));
                if (this.model.get('heatName') == '-') {
                    _.each(rows, function (row) {
                        row.classList.remove('highlight');
                    });
                }


                if (that.model.itemsCollEAFA.length > 0)
                    that.scrollToBottomTrigger(that.model.itemsCollEAFA);

                that.residualsChart(that.model.itemsCollEAFA, '.residuals_EAFA');

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

        },
        itemsCollEAFB_ready: function (resp) {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_EAFB: (that.model.itemsCollEAFB.length > 0),
                            isLoading_EAFB: false,
                        });
                        if (resp && resp[0]) {
                            that.model.set({
                                EAFB_Product: resp[0].Product,
                                EAFB_B3ratio: resp[0].B3ratio,
                                EAFB_MgO: resp[0].MgO,
                                EAFB_FeO: resp[0].FeO,

                            })
                        }
                    },
                    100
                );

                that.setURLClassGrid('EAFB');
                if (that.model.itemsCollEAFB.length > 0)
                    that.scrollToBottomTrigger(that.model.itemsCollEAFB);

                that.residualsChart(that.model.itemsCollEAFB, '.residuals_EAFB');

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

        },

        scrollToBottomTrigger: function (collection) {
            let listContainer = document.getElementById(collection.getGridId());
            listContainer.addEventListener('scroll', function (e) {
                if (listContainer.scrollTop >= (listContainer.scrollHeight - listContainer.offsetHeight))
                    collection.getNextPage();
            });
        },

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

            this.refreshHeat(opt);

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

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refresh: function (viewParams) {
            var fixedParams = _.extend({}, viewParams);
            if (viewParams.from)
                fixedParams.from = new moment(fixedParams.from, 'YYYYMMDD').format('YYYY-MM-DD');
            if (viewParams.to)
                fixedParams.to = new moment(fixedParams.to, 'YYYYMMDD').format('YYYY-MM-DD');
            //if (viewParams.typeCode)
            //    fixedParams.typeCode = (viewParams.typeCode == '-') ? null : viewParams.typeCode;
        
            this.model.set(fixedParams);

            this._refresh({
                reset: true,
                params: _.extend(
                    {},
                    fixedParams,
                    {}
                ),
            });
        },
        render: function (container, viewParams) {
            var that = this;

            this.viewParams = viewParams;

            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/custom-screens/' + this.template + '/';

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

                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.options.i18n[that.template] = i18nJED;

                            //loading the view and appeding it to the views's $el.
                            that.$el.html(tmp());

                            that.applyBindings();

                            //start: the view was already loaded an is on a div element, but not appended to the main container
                            //here you can perform anything you want DOM related, by getting the dom element via that.$el.find('#id')
                            //or this.$('#id')
                            that.$el.find('.input-date').datepicker();

                            var grid = that.grids = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                id: 'slag-eaf-a',
                                columns: [].concat(
                                    {
                                        name: 'heatName',
                                        label: app.translate(that, 'heat_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell heatName',
                                        }),
                                    },
                                    {
                                        name: 'gradeGroupName',
                                        label: app.translate(that, 'grade_group_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: function () {
                                                return 'string-cell align-center-cell heatName gradeGroupName';
                                            },
                                        }),
                                    },

                                    
                                    [
                                    {
                                        name: 'timestamp',
                                        editable: false,
                                        sortable:false,
                                        label: app.translate(that, 'timestamp_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-right-cell timestamp-cell date-cell timestamp-date',
                                            formatter: Backgrid.Extension.DatetimeToDateFormatter.extend({
                                                columnName: 'timestamp',
                                                displayFormat: app.translate([that, app], 'MM/DD/YYYY'),
                                                modelDateFormat: 'YYYY-MM-DD',
                                            }),
                                            editor: Backgrid.Extension.CalendarCellEditor.extend({
                                                dateFormat: 'mm/dd/yy',
                                                momentFormat: app.translate([that, app], 'mmddyyyy'),
                                            }),
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            attributes: {
                                                colspan: 2,
                                            },
                                            className: 'timestamp-date'
                                        }),
                                    },
                                    {
                                        name: 'timestamp',
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-left-cell timestamp-cell time-cell timestamp-time',
                                            formatter: Backgrid.Extension.DatetimeToTimeFormatter.extend({
                                                columnName: ' timestamp',
                                                displayFormat: app.translate([that, app], 'HH:mm'),
                                                modelDateFormat: 'YYYY-MM-DD',
                                            }),
                                            editor: Backgrid.Extension.TimeCellEditor.extend({
                                                showOn: false,
                                            }),
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            attributes: {
                                                style: 'display: none;',
                                            },
                                            className: 'timestamp-time'
                                        }),
                                    }],
                                    {
                                        name: 'CaO',
                                        label: app.translate(that, 'caO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            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 element',
                                            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 element',
                                            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 element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'B3ratio',
                                        label: app.translate(that, 'b3Ratio_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (this.model.get('B3Status') == 'DANGER') return 'number-cell element danger';
                                                if (this.model.get('B3Status') == 'WARNING') return 'number-cell element warning';
                                                if (this.model.get('B3Status') == 'NORMAL') return 'number-cell element normal';
                                                else return 'number-cell element';
                                            },
                                            decimals: 2,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),

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

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

                                    {
                                        name: 'MnO',
                                        label: app.translate(that, 'mnO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'total',
                                        label: app.translate(that, 'total_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (this.model.get('TotalStatus') == 'DANGER') return 'number-cell element danger';
                                                else return 'number-cell';
                                            },
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'Cr2O3',
                                        label: app.translate(that, 'cr2O3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element' ,
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'P2O5',
                                        label: app.translate(that, 'p2O5_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'SO3',
                                        label: app.translate(that, 'sO3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'dirtLoad',
                                        label: app.translate(that, 'dirtLoad_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell lbs',
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                    {
                                        name: 'TotalSlagVolume',
                                        label: app.translate(that, 'TotalSlagVolume_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell lbs',
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                    {
                                        name: 'refractoryWear',
                                        label: app.translate(that, 'refractoryWear_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (this.model.get('RefractoryWearStatus') == 'DANGER') return 'number-cell lbs danger';
                                                else if (this.model.get('RefractoryWearStatus') == 'NORMAL') return 'number-cell lbs normal';
                                                else return 'number-cell lbs';
                                            },
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                    {
                                        name: 'steelLoss',
                                        label: app.translate(that, 'steelLoss_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell lbs',
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                ),
                                row: Backgrid.Row.extend({
                                    initialize: function (options) {
                                        Backgrid.Row.prototype.initialize.apply(this, arguments);


                                        if (this.model.get('heatName') && this.model.get('heatName') == that.viewParams.heatName)
                                            this.$el.addClass('highlight');
                                    },
                                }),
                                collection: that.model.itemsCollEAFA,
                            });

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


                            var gridEAFB  = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                columns: [].concat(
                                    {
                                        name: 'heatName',
                                        label: app.translate(that, 'heat_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell heatName',
                                        }),
                                    },
                                    {
                                        name: 'gradeGroupName',
                                        label: app.translate(that, 'grade_group_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: function (e) {
                                                //if (this.model.get('gradeGroupName') == 'Rail') return 'string-cell align-center-cell heatName gradeGroupName rail';
                                                //else return 'string-cell align-center-cell heatName gradeGroupName';
                                                return 'string-cell align-center-cell heatName gradeGroupName';
                                            },
                                        }),
                                    },

                                    [
                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            sortable: false,
                                            label: app.translate(that, 'timestamp_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-right-cell timestamp-cell date-cell timestamp-date',
                                                formatter: Backgrid.Extension.DatetimeToDateFormatter.extend({
                                                    columnName: 'timestamp',
                                                    displayFormat: app.translate([that, app], 'MM/DD/YYYY'),
                                                    modelDateFormat: 'YYYY-MM-DD',
                                                }),
                                                editor: Backgrid.Extension.CalendarCellEditor.extend({
                                                    dateFormat: 'mm/dd/yy',
                                                    momentFormat: app.translate([that, app], 'mmddyyyy'),
                                                }),
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                attributes: {
                                                    colspan: 2,
                                                },
                                                className: 'timestamp-date'
                                            }),
                                        },
                                        {
                                            name: 'timestamp',
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-left-cell timestamp-cell time-cell timestamp-time',
                                                formatter: Backgrid.Extension.DatetimeToTimeFormatter.extend({
                                                    columnName: ' timestamp',
                                                    displayFormat: app.translate([that, app], 'HH:mm'),
                                                    modelDateFormat: 'YYYY-MM-DD',
                                                }),
                                                editor: Backgrid.Extension.TimeCellEditor.extend({
                                                    showOn: false,
                                                }),
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                attributes: {
                                                    style: 'display: none;',
                                                },
                                                className: 'timestamp-time'
                                            }),
                                        }],
                                    {
                                        name: 'CaO',
                                        label: app.translate(that, 'caO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            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 element',
                                            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 element',
                                            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 element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'B3ratio',
                                        label: app.translate(that, 'b3Ratio_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (this.model.get('B3Status') == 'DANGER') return 'number-cell element danger';
                                                if (this.model.get('B3Status') == 'WARNING') return 'number-cell element warning';
                                                if (this.model.get('B3Status') == 'NORMAL') return 'number-cell element normal';
                                                else return 'number-cell element';
                                            },
                                            decimals: 2,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),

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

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

                                    {
                                        name: 'MnO',
                                        label: app.translate(that, 'mnO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'total',
                                        label: app.translate(that, 'total_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (this.model.get('TotalStatus') == 'DANGER') return 'number-cell element danger';
                                                else return 'number-cell';
                                            },
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'Cr2O3',
                                        label: app.translate(that, 'cr2O3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'P2O5',
                                        label: app.translate(that, 'p2O5_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'SO3',
                                        label: app.translate(that, 'sO3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'dirtLoad',
                                        label: app.translate(that, 'dirtLoad_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell lbs',
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                    {
                                        name: 'TotalSlagVolume',
                                        label: app.translate(that, 'TotalSlagVolume_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell lbs',
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                    {
                                        name: 'refractoryWear',
                                        label: app.translate(that, 'refractoryWear_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (this.model.get('RefractoryWearStatus') == 'DANGER') return 'number-cell lbs danger';
                                                else if (this.model.get('RefractoryWearStatus') == 'NORMAL') return 'number-cell lbs normal';
                                                else return 'number-cell lbs';
                                            },
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                    {
                                        name: 'steelLoss',
                                        label: app.translate(that, 'steelLoss_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell lbs',
                                            decimals: 0,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'lbs',
                                        }),
                                    },
                                ),
                                row: Backgrid.Row.extend({
                                    initialize: function (options) {
                                        Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        if (this.model.get('heatName') && this.model.get('heatName') == that.viewParams.heatName)
                                            this.$el.addClass('highlight');

                                    },
                                }),
                                collection: that.model.itemsCollEAFB,
                            });

                            that.$el.find('.items-grid-container-eaf-b').append(gridEAFB.render().el);


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

                            //appending view to the main container
                            that.append(thatContainer, that.$el);
                            
                            that.model.fetchPickers({ async: false });

                            //Set model with view params here to prevent changes on the model when the view bindings are applied.
                            var fixedParams = _.extend({}, viewParams);

                            if (fixedParams.from)
                                fixedParams.from = new moment(fixedParams.from, 'YYYYMMDD').format('YYYY-MM-DD');
                            if (fixedParams.to)
                                fixedParams.to = new moment(fixedParams.to, 'YYYYMMDD').format('YYYY-MM-DD');
                            //if (fixedParams.typeCode)
                            //    fixedParams.typeCode = (fixedParams.typeCode == '-') ? null : fixedParams.typeCode;

                            that.model.set(fixedParams); 

                            //Call first refresh.
                            var params = that.model.toJSON();

                            that._refresh({
                                reset: true,
                                params: _.extend(
                                    {},
                                    params,
                                    {
                                    }
                                ),
                            });


                            //that.startAutoRefresh();
                           
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },

    
        setURLClassGrid: function (id) {
            var that = this;
            var found;
            var grades;
            var params;
            var gridElement = document.getElementById(id);
            var rowTags = gridElement.getElementsByTagName("tr");
            var aTags = gridElement.getElementsByTagName("td");
            var limitByGrade = that.model.get('limitByGrade');

            for (var i = 0; i < aTags.length; i++) {              

                _.each(limitByGrade, function (limit) {
                    if (aTags[i].textContent.includes(limit.Name)) {
                        found = aTags[i];
                        grades = _.where(that.model.get('gradeGroupsLimits'), { Name: aTags[i].textContent })
                        params = aTags[i].textContent.split("^");
                        aTags[i].textContent = '';
                        $(found).removeClass('string-cell');
                        $(found).addClass('uri-cell');
                        $(found).css("background-color", limit.Color);
                        $(found).append("<a tabindex='- 1' " + "href='!/" + "ih/configuration/kpivariables/"+ limit.Abbrev + "'" + "title='" + limit.Msg + "'" + "target='_blank'>" + params[0] + "</a>");
                       

                    }
                });
            }
        },


        fetchnavbuttons: function (resp) {
            this.NavigationButtonView.setDataColl(resp);
        },
        refreshHeat: function (options) {
            var that = this,
                attrs = this.model.toJSON(),
                opt = _.extend({}, { params: {  }, }, options);

            if ((attrs.mainView == true) && ((opt.refresh == true) || (opt.reset == true)))
                this.model.set('isLoadingProcess', true);


            let listContainerA = document.getElementById(this.model.itemsCollEAFA.getGridId());
            let listContainerB = document.getElementById(this.model.itemsCollEAFB.getGridId());
            if (listContainerA && listContainerA.scrollTop) listContainerA.scrollTop = 0;
            if (listContainerB && listContainerB.scrollTop) listContainerB.scrollTop = 0;


            if (this.$el.find('.residuals_EAFA'))
                this.$el.find('.residuals_EAFA').html('');

            if (this.$el.find('.residuals_EAFB'))
                this.$el.find('.residuals_EAFB').html('');

            this.model.set({
                isLoading_EAFA: true,
                hasData_EAFA: false,

                isLoading_EAFB: true,
                hasData_EAFB: false,
            })
            this.model.itemsCollEAFA.fetch({
                from: attrs.from,
                to: attrs.to,
                timezoneCode: app.models.user.get('timezoneCode'),
                refresh: true,
                heatName: attrs.heatName,
            });
            this.model.itemsCollEAFB.fetch({
                from: attrs.from,
                to: attrs.to,
                timezoneCode: app.models.user.get('timezoneCode'),
                refresh: true,
                heatName: attrs.heatName,
            });


        },
        refreshBtn_click: function (e) {
            try {
                var params = this.model.toJSON();
                this.model.set({
                    EAFA_Product: '-',
                    EAFA_B3ratio: '-',
                    EAFA_MgO: '-',
                    EAFA_FeO: '-',
                    EAFB_Product: '-',
                    EAFB_B3ratio: '-',
                    EAFB_MgO: '-',
                    EAFB_FeO: '-'

                })

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                heatName: params.heatName,
                                from: new moment(params.from, 'YYYY-MM-DD').format('YYYYMMDD'),
                                to: new moment(params.to, 'YYYY-MM-DD').format('YYYYMMDD'),
                                
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );

                this._refresh({
                    reset: true,
                    params: _.extend(
                        {},
                        params,
                        {}
                    ),
                });

                window.scrollTo(0, 0);
            }
            catch (Error) { console.error(Error.stack); }
        },

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

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

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

                this.options.onappend(this);
            }

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

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

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

            this.stopAutoRefresh();

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

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

            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.set("subnavbar", false);
        },
        reRender: function (viewParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },
        startAutoRefresh: function () {
            try {
                if (this.autoRefresh.enabled !== true) {
                    var that = this;

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

                    this.autoRefresh.enabled = true;

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

        residualsChart: function (coll, className) {
            var that = this;
            var collection = coll.toJSON();
            var data = _.sortBy(collection, 'timestamp');

            if (data.length < 70) {
                if (this.$el.find(className))
                    this.$el.find(className).html('');
            }
            var domainBand = [];

            _.each(data, function (obj, i) {
                domainBand[i] = obj.heatName;
            });
            var title = '';
            var width = 500;
            var chartWidth = width;
            var chartHeight = 360;
            var chartMarginLeft = 60;
             var maxAxisBottom = chartWidth - 50;
            var maxAxisLeftHeight = 250;
            var minValueBottomAxis = 0;
            var maxValueLeft = 40;
            var minValueLeft = 0;
            if (data.length > 0 && data.length < 70) {
                minValueBottomAxis = maxAxisBottom / (2 * data.length);
                var svg = d3.select(className)
                    .append("svg")
                    .attr("width", chartWidth)
                    .attr("height", chartHeight)
                    .append("g")
                    .attr("transform",
                        "translate(" + 25 + "," + 295 + ")");

                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;
                    })
                    .attr("class", "hide");

                svg.selectAll("g")
                    .select(".x_text .tick line")
                    .attr("class", "hide");


                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 -12;
                    })
                    .attr("fill", "blue");

                svg.append("text")
                    .attr("x", 45)
                    .attr("y", -335)
                    .attr("text-anchor", "middle")
                    .attr("class", "text")
                    .style("font-size", "16px")
                    .text(title);



                svg.selectAll("g")
                    .select(".y_text .tick line")

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

                 svg.append("g")
                    .attr("class", "y_text_right")
                    .call(d3.axisRight(y1).ticks(6))

                svg.selectAll("g")
                    .select(".y_text_right .tick text")
                    .attr("x", function (d, i) {
                        return 460;
                    })
                    .attr("fill","red");


                svg.selectAll("g")
                    .select(".y_text_right .tick line")
                    .attr("class", "hide");

                svg
                    .selectAll("whatever")
                    .data(data)
                    .enter()
                    .append("circle")
                    .attr("fill", "blue")
                    .attr("cx", function (d) {
                        if (d.FeO)
                            return x(d.heatName);
                    })
                    .attr("cy", function (d) {
                        if (d.FeO) {
                            if (d.FeO > maxValueLeft) return y(maxValueLeft);
                            else if (d.FeO < minValueLeft) return y(minValueLeft);
                            else return y(d.FeO);
                        }
                    })
                    .attr('stroke', function (d) {
                        if (d.heatName == that.model.get('heatName')) return 'black';
                    })
                    .attr('stroke-width', function (d) {
                        if (d.heatName == that.model.get('heatName')) return '2';
                    })
                    .attr("transform",
                        "translate(" + minValueBottomAxis + ", 0)")
                    .attr("r", function (d) {
                        if (d.FeO) {
                            if (d.heatName == that.model.get('heatName')) return 7;
                            else 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.FeO)
                            return "FeO: " + d.FeO.toFixed(1) 
                                + " Heat: " + d.heatName
                                + " Timestamp: " + d.timestamp;
                        else return '';
                    })

                svg
                    .selectAll("whatever")
                    .data(data)
                    .enter()
                    .append("circle")
                    .attr("fill", "red")
                    .attr("cx", function (d) {
                        if (d.B3ratio)
                            return x(d.heatName);
                    })
                    .attr("cy", function (d) {
                        if (d.B3ratio) {
                            if (d.B3ratio > 4.5) return y1(4.5);
                            else if (d.B3ratio < 0.5) return y1(0.5);
                            else return y1(d.B3ratio);
                        }

                    })
                    .attr('stroke', function (d) {
                        if (d.heatName == that.model.get('heatName')) return 'black';
                    })
                    .attr('stroke-width', function (d) {
                        if (d.heatName == that.model.get('heatName')) return '2';
                    })
                    .attr("transform",
                        "translate(" + minValueBottomAxis + ", 0)")
                    .attr("r", function (d) {
                        if (d.B3ratio) {
                            if (d.heatName == that.model.get('heatName')) return 7;
                            else 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.B3ratio)
                            return "B3ratio: " + d.B3ratio.toFixed(2)
                                + " Heat: " + d.heatName
                                + " Timestamp: " + d.timestamp;
                        else return '';
                    })

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

                svg.append("text")
                    .attr("y", -275)
                    .attr("x", 20)
                    .text("FeO")


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

                svg.append("text")
                    .attr("y", -275)
                    .attr("x", 100)
                    .text("B3ratio")


                svg.append("text")
                    .attr("y", 15)
                    .attr("x", 405)
                    .text("Newest")
                    .attr("fill","gray")

                svg.append("text")
                    .attr("y", 15)
                    .attr("x", 0)
                    .text("Oldest")
                    .attr("fill", "gray")
            }

        },

        exportToExcel: function () {
            var that = this,
                from = that.model.get('from'),
                to = that.model.get('to');
                timezoneCode = app.models.user.get('timezoneCode');
                
            var params = [
                { Name: '@from', Type: 'DATETIME', Value: from, },
                { Name: '@to', Type: 'DATETIME', Value: to, },
                { Name: '@excel', Type: 'BIT', Value: true },
                { Name: '@timeZoneCode', Type: 'VARCHAR', Value: timezoneCode }

            ];

            var qp = new QueryParameters();

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

            var cellsData = [
                { Column: 'A', Value: 'Heat'  },
                { Column: 'B', Value: 'Grade' },
                { Column: 'C', Value: 'Timestamp' },
                { Column: 'D', Value: 'CaO' },
                { Column: 'E', Value: 'SiO2' },
                { Column: 'F', Value: 'Al2O3' },
                { Column: 'G', Value: 'TiO2' },
                { Column: 'H', Value: 'B3ratio' },
                { Column: 'I', Value: 'MgO' },
                { Column: 'J', Value: 'FeO' },
                { Column: 'K', Value: 'MnO' },
                { Column: 'L', Value: 'Total' },
                { Column: 'M', Value: 'Cr2O3'  },
                { Column: 'N', Value: 'P2O5'  },
                { Column: 'O', Value: 'SO3' },
                { Column: 'P', Value: 'DirtLoad' },
                { Column: 'Q', Value: 'SlagVolume' },
                { Column: 'R', Value: 'BrickWear' },
                { Column: 'S', Value: 'SteelLoss' },
                           
                           
            ];             

            var SQLCellsData= [
                { ExcelColumnName: 'A', SQLDataColumnName: 'HeatName', DataType: 'String' },
                { ExcelColumnName: 'B', SQLDataColumnName: 'GradeGroupName', DataType: 'String' },
                { ExcelColumnName: 'C', SQLDataColumnName: 'TimestampString', DataType: 'String' },
                { ExcelColumnName: 'D', SQLDataColumnName: 'CaO', DataType: 'Float' },
                { ExcelColumnName: 'E', SQLDataColumnName: 'SiO2', DataType: 'Float' },
                { ExcelColumnName: 'F', SQLDataColumnName: 'Al2O3', DataType: 'Float' },
                { ExcelColumnName: 'G', SQLDataColumnName: 'TiO2', DataType: 'Float' },
                { ExcelColumnName: 'H', SQLDataColumnName: 'B3ratio', DataType: 'Float' },
                { ExcelColumnName: 'I', SQLDataColumnName: 'MgO', DataType: 'Float' },
                { ExcelColumnName: 'J', SQLDataColumnName: 'FeO', DataType: 'Float' },
                { ExcelColumnName: 'K', SQLDataColumnName: 'MnO', DataType: 'Float' },
                { ExcelColumnName: 'L', SQLDataColumnName: 'Total', DataType: 'Float' },
                { ExcelColumnName: 'M', SQLDataColumnName: 'Cr2O3', DataType: 'Float' },
                { ExcelColumnName: 'N', SQLDataColumnName: 'P2O5', DataType: 'Float' },
                { ExcelColumnName: 'O', SQLDataColumnName: 'SO3', DataType: 'Float' },
                { ExcelColumnName: 'P', SQLDataColumnName: 'DirtLoad', DataType: 'Float' },
                { ExcelColumnName: 'Q', SQLDataColumnName: 'TotalSlagVolume', DataType: 'Float' },
                { ExcelColumnName: 'R', SQLDataColumnName: 'RefractoryWear', DataType: 'Float' },
                { ExcelColumnName: 'S', SQLDataColumnName: 'FeinSlag', DataType: 'Float' },
            ];


            Core.Export.Excel({
                Data: [
                    {
                        SheetName: 'EAF A',
                        RowsData: [{
                            CellsData: cellsData
                        }],
                        StartRowIndex: 1,
                    },
                    {
                        SheetName: 'EAF A',
                        RowsData: [],
                        StartRowIndex: 2,
                        DataSourceName: 'data',
                        DataSourceTableIndex: 0,
                        SQLCellsData: SQLCellsData
                    },
                    {
                        SheetName: 'EAF B',
                        RowsData: [{
                            CellsData: cellsData
                        }],
                        StartRowIndex: 1,
                    },
                    {
                        SheetName: 'EAF B',
                        RowsData: [],
                        StartRowIndex: 2,
                        DataSourceName: 'data',
                        DataSourceTableIndex: 1,
                        SQLCellsData: SQLCellsData
                    }
                ],
                ConnectionStringName: 'APP',
                ExportMethod: 3,
                FileName: 'SlagReport',
                TemplateFileFullPath: 'generic.xls',
                SQLDataSources: [
                    {
                        Name: 'data',
                        DatabaseParameters: {
                            DBEngine: 'SQLSERVER',
                            Procedure: app.DatabaseNames.MES + '.LAB.EAFGetSlagChemistrySamplesReport',
                            QueryParameters: qp,
                        },
                    },
                ]
            },
            function (resp) {
                try {
                    if ((resp) && (resp.Success == true) && (resp.Data)) {
                        location.href = app.foldersRoot + '/excel/' + resp.Data;
                    }
                    else {
                        if ((resp) && (resp.Message))
                            console.error(resp.Message);
                        else
                            console.error('Server response not valid.');
                    }
                }
                catch (Error) { console.error(Error); }
            }, function (resp) {
                console.error(resp);
            });

        },
    });



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