//SCREEN-BOILERPLATE

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

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

    //templates-loader: this loads templates async.
    'js/templates-loader',
    'backgrid',
    'moment',

    'modules/eaf-process/eaf-process',

    '/IHBox/IndustrialDashboard/Widgets/IndustrialGantt/Scripts/IndustrialGantt.js',

    'backgrid/computed-cell',
    'backgrid/duration-cell',
    'backgrid/moment-cell',
    'js/backgrid-0.3.5/extensions/valid-limit-cell/backgrid-valid-limit-cell',
],
    function (app, T, Backgrid, moment, EafProcess) {

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                date: new moment().format('YYYY-MM-DD'),

                hasData: false,
                isLoading: false,
            },
            computeds: {
                date$: {
                    deps: ['date'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { date: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },

        });

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'lines-production',
            id: 'lines-production',
            title: 'Meltshop Production',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    "click .btn-export-to-excel": this.exportToExcel,
                    'click #getPreviousDateBtn': this.getPreviousDateBtn_click,
                    'click #getNextDateBtn': this.getNextDateBtn_click,
                    'click #getCurrentDateBtn': this.getCurrentDateBtn_click,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,

            eafProcesses: null,
            linesGantt: null,
            subviews: null,
            viewParams: 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.eafProcesses = new Screen.Collections.EafProcesses();
                this.lmfProcesses = new Screen.Collections.LMFProcesses();

                this.bindingSources = {};

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

            getPermissions: function () {
                var write = $.inArray('mes_linesproduction_readWrite', app.models.user.get('roles'));
                var ctx = {
                    write: write != -1 ? true : false,
                };
                return ctx.write;
            },

            bindEvents: function () {
                //this function should be in every view that uses listenTo anywhere
                //all the model bindings or view-model binding should be here, to manage
                //the show/hide view easily
                this.listenTo(this.eafProcesses, 'backgrid:rowclick', this.eafProcesses_backgrid_rowclick)
                    .listenTo(this.lmfProcesses, 'backgrid:rowclick', this.lmfProcesses_backgrid_rowclick)
                    .listenTo(this.model, 'change:date', this.model_change_date);

            },
            _refresh: function (opt) {
                //console.log('autorefresh: ' + new Date().toString()); 
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }

                this.refreshProcesses(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({}, Screen.Models.Main.prototype.defaults, viewParams);

                if (viewParams.date)
                    fixedParams.date = new moment(fixedParams.date, 'YYYYMMDD').format('YYYY-MM-DD');

                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
                                Screen.i18n =
                                    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 write = that.getPermissions();
                                that.linesGantt = new IndustrialGantt(
                                    that.$el.find('#linesGanttContainer')[0],
                                    {
                                        View: {
                                            Header: false,
                                            Configuration: {
                                                References: {
                                                    Size: {
                                                        Height: 21,
                                                    },
                                                },
                                                FontSizes: {
                                                    CenterBar: 10,
                                                },
                                                PrimaryEntailment: 'HeatName',
                                                SecondaryEntailment: null,
                                                Visibility: {
                                                    CenterBar: {
                                                        Fix: {
                                                            Mode: 'AUTOSUBSTRING',
                                                        },
                                                    },
                                                },
                                            },
                                        },
                                        DatabaseParameters: {
                                            ConnectionStringName: app.ConnectionStrings.app,
                                            Procedure: app.DatabaseNames.MES + '.MES.GetLinesProductionGanttData',
                                            Secured: true,
                                        },
                                        Events: {
                                            //onDelayClick: DelayClick,
                                            onError: function (Error) { console.error(Error.stack); },
                                            onLineClick: write ? _.bind(that.linesGantt_LineClick, that) : null,
                                            onPrimaryDataClick: write ? _.bind(that.linesGantt_PrimaryDataClick, that) : null,
                                        },
                                    }
                                );


                                var grid = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'heatName',
                                            label: app.translate([that, app], 'process_heat_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heatName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'start',
                                            label: app.translate([that, app], 'process_start_col'),
                                            cell: Backgrid.Extension.MomentCell.extend({
                                                className: 'momment-cell align-center-cell start',
                                                modelFormat: 'YYYY-MM-DD HH:mm:ss.SSS',
                                                displayFormat: app.translate([that, app], 'MM/DD/YYYY') + ' HH:mm',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'crewId',
                                            label: app.translate([that, app], 'process_crew_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell crewId',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'shiftName',
                                            label: app.translate([that, app], 'process_shift_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell shiftName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'gradeName',
                                            label: app.translate([that, app], 'process_grade_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell gradeName',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'scrapRecipe',
                                            label: app.translate([that, app], 'scrap_recipe_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'charges',
                                            label: app.translate([that, app], 'charges_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'scrapWeight',
                                            label: app.translate([that, app], 'process_scrap_weight_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell scrapWeight',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'steelWeight',
                                            label: app.translate([that, app], 'process_steel_weight_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'numeric-cell align-center-cell steelWeight',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'fluxesHiCal',
                                            label: app.translate([that, app], 'process_fluxesHiCal_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell process_fluxesHiCal',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'fluxesDolomite',
                                            label: app.translate([that, app], 'process_fluxesDolomite_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell process_fluxesDolomite',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'fluxesCarbon',
                                            label: app.translate([that, app], 'process_fluxesCarbon_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell process_fluxesCarbon',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'yield',
                                            label: app.translate([that, app], 'process_yield_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'powerProgram',
                                            label: app.translate([that, app], 'power_program_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'tapToTap',
                                            label: app.translate([that, app], 'process_tap_to_tap_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell tapToTap',
                                                formatter: Backgrid.Extension.DurationFormatter.extend({
                                                    displayFormat: 'm:s',
                                                    modelFormat: 's',
                                                }),
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'powerOn',
                                            label: app.translate([that, app], 'process_power_on_col'),
                                            cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.StringCell).extend({
                                                className: 'string-cell align-center-cell powerOn',
                                                formatter: Backgrid.Extension.DurationFormatter.extend({
                                                    displayFormat: 'm:s',
                                                    modelFormat: 's',
                                                }),
                                                invalidMessage: function (value, limit) {
                                                    return app.translate([that, app], 'process_power_on_invalid_value', [parseInt(limit / 60, 10),]);
                                                },
                                                validLimitProp: 'powerOnValidLimit',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'powerOff',
                                            label: app.translate([that, app], 'process_power_off_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell powerOff',
                                                formatter: Backgrid.Extension.DurationFormatter.extend({
                                                    displayFormat: 'm:s',
                                                    modelFormat: 's',
                                                }),
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'energy',
                                            label: app.translate([that, app], 'process_energy_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'numeric-cell align-center-cell energy',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'energyPerTon',
                                            label: app.translate([that, app], 'process_energy_per_ton_col'),
                                            cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.Extension.ComputedCell).extend({
                                                className: 'computed-cell align-center-cell energyPerTon',
                                                deps: ['energy', 'scrapWeight',],
                                                calculate: function (energy, scrapWeight) {
                                                    if (!energy) energy = 0;
                                                    if (!scrapWeight) scrapWeight = 1;

                                                    //Convert MWH to KWH.
                                                    return (energy * 1000 / (scrapWeight / 2000)).toFixed(2);
                                                },
                                                invalidMessage: function (value, limit) {
                                                    return app.translate([that, app], 'process_energy_per_ton_invalid_value', [limit,]);
                                                },
                                                validLimitProp: 'energyPerTonValidLimit',
                                                update: function () {
                                                    var value = this.calculate.apply(this, _.map(this.deps, this.model.get, this.model)),
                                                        limit = this.model.get(this.validLimitProp);

                                                    if (this.validate(value, limit) == true) {
                                                        this.$el.attr('title', '')
                                                            .removeClass('invalid');
                                                    }
                                                    else {
                                                        var invMsg = ($.isFunction(this.invalidMessage) == true)
                                                            ? this.invalidMessage(value, limit)
                                                            : this.invalidMessage;

                                                        this.$el.attr('title', invMsg)
                                                            .addClass('invalid');
                                                    }
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'mwhMin',
                                            label: app.translate([that, app], 'process_mwhMin_col'),
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'numeric-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'burnerProgram',
                                            label: app.translate([that, app], 'burner_program_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsNaturalGas',
                                            label: app.translate([that, app], 'process_consumptions_natural_gas_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedLime',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsOxygen',
                                            label: app.translate([that, app], 'process_consumptions_oxygen_col'),
                                            cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.IntegerCell).extend({
                                                className: 'integer-cell align-center-cell consumptionsOxygen',
                                                invalidMessage: function (value, limit) {
                                                    return app.translate([that, app], 'process_oxygen_invalid_value', [limit,]);
                                                },
                                                validLimitProp: 'oxygenValidLimit',
                                                validate: function (value, limit) {
                                                    return (value >= limit);
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsInjectedCarbon',
                                            label: app.translate([that, app], 'process_consumptions_injected_carbon_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedCarbon',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'consumptionsInjectedLime',
                                            label: app.translate([that, app], 'process_consumptions_injected_lime_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedLime',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'lastTemperature',
                                            label: app.translate([that, app], 'process_last_temperature_col'),
                                            cell: Backgrid.Extension.MakeCellValidLimit(Backgrid.IntegerCell).extend({
                                                className: 'integer-cell align-center-cell lastTemperature',
                                                invalidMessage: function (value, limit) {
                                                    return app.translate([that, app], 'high_temperature_value', [limit,]);
                                                },
                                                validLimitProp: 'tapTemp',
                                                validate: function (value, limit) {
                                                    return (value < limit);
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'latestOxygen',
                                            label: app.translate([that, app], 'latest_oxygen_col'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'integer-cell align-center-cell consumptionsInjectedLime',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'ladleName',
                                            label: app.translate([that, app], 'process_ladle_col'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ladleName',
                                            }),
                                            editable: false,
                                        },
                                    ],

                                    collection: that.eafProcesses,
                                    row: Backgrid.Row.extend({
                                        events: function () {
                                            return {
                                                'click': this.click,
                                            };
                                        },
                                        click: function (e) {
                                            try {
                                                if (write)
                                                    this.model.trigger('backgrid:rowclick', this.model);
                                            }
                                            catch (Error) { console.error(Error.stack); }
                                        }
                                    })
                                });
                                that.$el.find('.eaf-processes-grid-container').append(grid.render().el);

                                var columns = [
                                    {
                                        name: 'heatName',
                                        label: app.translate(that, 'item_heat_name_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'treatment',
                                        label: app.translate(that, 'item_treatment_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'startLocal',
                                        label: app.translate(that, 'item_start_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'crewId',
                                        label: app.translate(that, 'item_crew_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'shiftId',
                                        label: app.translate(that, 'item_shift_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'ladleFurnaceCode',
                                        label: app.translate(that, 'item_ladleFurnaceCode_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'duration',
                                        label: app.translate(that, 'item_duration_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'initialTemperature',
                                        label: app.translate(that, 'item_initial_temperature_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'finalTemperature',
                                        label: app.translate(that, 'item_final_temperature_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'finalCarbon',
                                        label: app.translate(that, 'item_final_carbon_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'finalOxygen',
                                        label: app.translate(that, 'item_final_oxygen_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'powerOn',
                                        label: app.translate(that, 'item_power_on_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'argonVolume',
                                        label: app.translate(that, 'item_argon_volume_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Lime',
                                        label: app.translate(that, 'item_lime_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'FeVn',
                                        label: app.translate(that, 'item_FeVn_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Ni',
                                        label: app.translate(that, 'item_Ni_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Carbon',
                                        label: app.translate(that, 'item_Carbon_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'SiMn',
                                        label: app.translate(that, 'item_SiMn_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'LoAlSi',
                                        label: app.translate(that, 'item_LoAlSi_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ten-percent',
                                        }),
                                        editable: false,
                                    },
                                ];

                                var grid = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    collection: that.lmfProcesses,
                                    columns: columns,
                                    row: Backgrid.Row.extend({
                                        events: function () {
                                            return {
                                                'click': this.click,
                                            };
                                        },
                                        click: function (e) {
                                            try {
                                                if (write)
                                                    this.model.trigger('backgrid:rowclick', this.model);
                                            }
                                            catch (Error) { console.error(Error.stack); }
                                        }
                                    })
                                });

                                //container.append(grid.render().el);
                                that.$el.find('.lf-processes-grid-container').append(grid.render().el);



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


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

                                if (fixedParams.date)
                                    fixedParams.date = new moment(fixedParams.date, 'YYYYMMDD').format('YYYY-MM-DD');

                                that.model.set(fixedParams);

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

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

                                //that.startAutoRefresh();
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            getNextDateBtn_click: function () {
                try {
                    this.model.set('date', new moment(this.model.get('date')).add(1, 'days').format('YYYY-MM-DD'));
                    this.model_change_date();
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },
            getPreviousDateBtn_click: function () {
                try {
                    this.model.set('date', new moment(this.model.get('date')).add(-1, 'days').format('YYYY-MM-DD'));
                    this.model_change_date();
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },
            getCurrentDateBtn_click: function () {
                try {
                    this.model.set('date', new moment().format('YYYY-MM-DD'));
                    this.model_change_date();
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },
            refreshProcesses: function (options) {
                var attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {}, });

                if (opt.refresh == true)
                    this.model.set('isLoading', true);


                var start = new moment(attrs.date, 'YYYY-MM-DD').subtract(3, 'hours').format('YYYY-MM-DD HH:MM');
                var end = new moment(attrs.date, 'YYYY-MM-DD').add(21, 'hours').format('YYYY-MM-DD HH:MM');

               
                var qp = new QueryParameters();
                qp.Add('start', 'VARCHAR', start);
                qp.Add('end', 'VARCHAR', end);

                this.linesGantt.RefreshData(qp);

                this.eafProcesses.fetch(_.extend(opt, {
                    refresh: true,
                    params: {
                        start: start,
                        end: end,
                    },
                }));

                this.lmfProcesses.fetch({
                    start: start,
                    end: end,
                })

            },
            exportToExcel: function () {
                var that = this,
                    modelDate = that.model.get('date')
                    start = new moment(modelDate, 'YYYY-MM-DD').subtract(3, 'hours').format('YYYY-MM-DD HH:MM'),
                    end = new moment(modelDate, 'YYYY-MM-DD').add(21, 'hours').format('YYYY-MM-DD HH:MM');



                var params = [
                    { Name: '@fromRow', Type: 'INT', Value: -1 },
                    { Name: '@toRow', Type: 'INT', Value: -1 },
                    { Name: '@start', Type: 'DATETIME', Value: start, },
                    { Name: '@end', Type: 'DATETIME', Value: end, },
                    { Name: '@summarizedData', Type: 'BIT', Value: 1, },
                    { Name: '@timezoneCode', Type: 'VARCHAR', Value: app.models.user.get("timezoneCode"), },
                ];


                var QP = new QueryParameters();

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


                var data = {
                    Data: [],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'EAF-Production',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.EAF.GetProcesses',
                                QueryParameters: QP,
                            },
                        },
                    ]
                },
                    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                    chari = 0;

                /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'Heat' },
                                { Column: 'B', Value: 'Start' },
                                { Column: 'C', Value: 'Crew' },
                                { Column: 'D', Value: 'Shift' },
                                { Column: 'E', Value: 'Grade' },
                                //Column: 'F' -> 2nd Table
                                { Column: 'G', Value: 'Charges' },
                                //Column: 'H' -> 2nd Table
                                { Column: 'I', Value: 'SteelWeight' },
                                //Column: 'J' -> 2nd Table
                                //Column: 'K' -> 2nd Table
                                //Column: 'L' -> 2nd Table
                                //Column: 'M' -> 2nd Table
                                { Column: 'N', Value: 'PowerProgram' },
                                { Column: 'O', Value: 'TTT' },
                                { Column: 'P', Value: 'On' },
                                { Column: 'Q', Value: 'Off' },
                                { Column: 'R', Value: 'MWH' },
                                { Column: 'S', Value: 'KWH/tn' },
                                { Column: 'T', Value: 'MWH/min' },
                                { Column: 'U', Value: 'BurnerProgram' },
                                //Column: 'V' -> 2nd Table
                                //Column: 'W' -> 2nd Table
                                //Column: 'X' -> 2nd Table
                                //Column: 'Y' -> 2nd Table
                                //Column: 'Z' -> 2nd Table
                                //Column: 'AA'-> 2nd Table
                                { Column: 'AB', Value: 'Ladle' },



                            ],
                    }],
                    StartRowIndex: 1,
                });
                charHeaderContinue = chari;

                chari = 0;

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'HeatName', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'StartString', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'ShiftName', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'CrewId', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'GradeName', DataType: 'String' },
                            //ExcelColumnName: 'F' -> 2nd Table
                            { ExcelColumnName: 'G', SQLDataColumnName: 'Charges', DataType: 'String' },
                            //ExcelColumnName: 'H' -> 2nd Table
                            { ExcelColumnName: 'I', SQLDataColumnName: 'SteelWeight', DataType: 'String' },
                            //ExcelColumnName: 'J' -> 2nd Table
                            //ExcelColumnName: 'K' -> 2nd Table
                            //ExcelColumnName: 'L' -> 2nd Table
                            //ExcelColumnName: 'M' -> 2nd Table
                            { ExcelColumnName: 'N', SQLDataColumnName: 'PowerProgram', DataType: 'String' },
                            { ExcelColumnName: 'O', SQLDataColumnName: 'TapToTapString', DataType: 'String' },
                            { ExcelColumnName: 'P', SQLDataColumnName: 'PowerOnString', DataType: 'String' },
                            { ExcelColumnName: 'Q', SQLDataColumnName: 'PowerOffString', DataType: 'String' },
                            { ExcelColumnName: 'R', SQLDataColumnName: 'Energy', DataType: 'String' },
                            { ExcelColumnName: 'S', SQLDataColumnName: 'KwhTon', DataType: 'String' },
                            { ExcelColumnName: 'T', SQLDataColumnName: 'MwhMin', DataType: 'String' },
                            { ExcelColumnName: 'U', SQLDataColumnName: 'BurnerProgram', DataType: 'String' },
                            //ExcelColumnName: 'V' -> 2nd Table
                            //ExcelColumnName: 'W' -> 2nd Table
                            //ExcelColumnName: 'X' -> 2nd Table
                            //ExcelColumnName: 'Y' -> 2nd Table
                            //ExcelColumnName: 'Z' -> 2nd Table
                            //ExcelColumnName: 'AA'-> 2nd Table
                            { ExcelColumnName: 'AB', SQLDataColumnName: 'LadleName', DataType: 'String' },


                        ],
                });

                charValueContinue = chari;
                /* -------------------------------------------------------- 2nd Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                //Column: 'A' -> 1st Table
                                //Column: 'B' -> 1st Table
                                //Column: 'C' -> 1st Table
                                //Column: 'D' -> 1st Table
                                //Column: 'E' -> 1st Table
                                { Column: 'F', Value: 'ScrapRecipe' },
                                //Column: 'G' -> 1st Table
                                { Column: 'H', Value: 'ScrapWeight' },
                                //Column: 'I' -> 1st Table
                                { Column: 'J', Value: 'HiCal' },
                                { Column: 'K', Value: 'Dolo' },
                                { Column: 'L', Value: 'Carbon' },
                                { Column: 'M', Value: 'Yield' },
                                //Column: 'N' -> 1st Table
                                //Column: 'O' -> 1st Table
                                //Column: 'P' -> 1st Table
                                //Column: 'Q' -> 1st Table
                                //Column: 'R' -> 1st Table
                                //Column: 'S' -> 1st Table
                                //Column: 'T' -> 1st Table
                                //Column: 'U' -> 1st Table
                                { Column: 'V', Value: 'NaturalGas' },
                                { Column: 'W', Value: 'Oxygen' },
                                { Column: 'X', Value: 'InjCarbon' },
                                { Column: 'Y', Value: 'InjLime' },
                                { Column: 'Z', Value: 'LastTemp' },
                                { Column: 'AA', Value: 'LastO2' },
                                //Column: 'AB' -> 1st Table
                            ],
                    }],
                    StartRowIndex: 1,
                });

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 1,
                    SQLCellsData:
                        [
                            //ExcelColumnName: 'A' -> 1st Table
                            //ExcelColumnName: 'B' -> 1st Table
                            //ExcelColumnName: 'C' -> 1st Table
                            //ExcelColumnName: 'D' -> 1st Table
                            //ExcelColumnName: 'E' -> 1st Table
                            { ExcelColumnName: 'F', SQLDataColumnName: 'ScrapRecipe', DataType: 'String' },
                            //ExcelColumnName: 'G' -> 1st Table
                            { ExcelColumnName: 'H', SQLDataColumnName: 'BucketsWeight', DataType: 'String' },
                            //ExcelColumnName: 'I' -> 1st Table
                            { ExcelColumnName: 'J', SQLDataColumnName: 'FluxesHiCal', DataType: 'String' },
                            { ExcelColumnName: 'K', SQLDataColumnName: 'FluxesDolomite', DataType: 'String' },
                            { ExcelColumnName: 'L', SQLDataColumnName: 'FluxesCarbon', DataType: 'String' },
                            { ExcelColumnName: 'M', SQLDataColumnName: 'Yield', DataType: 'String' },
                            //ExcelColumnName: 'N' -> 1st Table
                            //ExcelColumnName: 'O' -> 1st Table
                            //ExcelColumnName: 'P' -> 1st Table
                            //ExcelColumnName: 'Q' -> 1st Table
                            //ExcelColumnName: 'R' -> 1st Table 
                            //ExcelColumnName: 'S' -> 1st Table
                            //ExcelColumnName: 'T' -> 1st Table
                            //ExcelColumnName: 'U' -> 1st Table
                            { ExcelColumnName: 'V', SQLDataColumnName: 'ConsumptionsNaturalGas', DataType: 'String' },
                            { ExcelColumnName: 'W', SQLDataColumnName: 'ConsumptionsOxygen', DataType: 'String' },
                            { ExcelColumnName: 'X', SQLDataColumnName: 'ConsumptionsInjectedCarbon', DataType: 'String' },
                            { ExcelColumnName: 'Y', SQLDataColumnName: 'ConsumptionsInjectedLime', DataType: 'String' },
                            { ExcelColumnName: 'Z', SQLDataColumnName: 'LastTemperature', DataType: 'String' },
                            { ExcelColumnName: 'AA', SQLDataColumnName: 'LatestOxygen', DataType: 'String' },
                            //ExcelColumnName: 'AB' -> 1st Table
                        ],
                });

                Core.Export.Excel(
                    data,
                    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); }
                        that.model.setExportButtonExporting(false);
                    },
                    function (resp) {
                        that.model.refreshProcesses();
                        that.model.setExportButtonExporting(false);
                        console.error(resp);
                    }
                );
            },
            setExportButtonExporting: function (val) {
                var btn_export = this.$el.find('.btn-export-to-excel');
                var export_state = btn_export.find('.excel-export-state');
                var loading_state = btn_export.find('.loading-state');

                if (val) {
                    export_state.css('display', 'none', 'important');
                    loading_state.removeClass('hide');

                    btn_export.attr('disabled', true);
                } else {
                    loading_state.addClass('hide');
                    export_state.css('display', 'inline-block', 'important');

                    btn_export.attr('disabled', false);
                }
            },
            eafProcesses_backgrid_rowclick: function (model) {
                try {
                    app.router.navigate(
                        app.router.resolveURL(
                            'eaf-heat-report',
                            {
                                heatName: model.get('heatName'),
                            },
                            false
                        ),
                        { trigger: true, }
                    );
                }
                catch (Error) { console.error(Error.stack); }
            },
            lmfProcesses_backgrid_rowclick: function (model) {
                try {
                    app.router.navigate(
                        app.router.resolveURL(
                            'lmf-heat-report',
                            {
                                heatName: model.get('heatName'),
                                treatmentNumber: model.get('treatment'),
                            },
                            false
                        ),
                        { trigger: true, }
                    );

                    //app.router.navigate(
                    //    app.router.resolveURL(
                    //        'heat',
                    //        {
                    //            heatId: model.get('heatId'),
                    //        },
                    //        false
                    //    ),
                    //    { trigger: true, }
                    //);
                }
                catch (Error) { console.error(Error.stack); }
            },
            linesGantt_LineClick: function (data) {
                try {
                    //var route;

                    //switch (data.AreaCode.toUpperCase()) {
                    //    case 'EAF':
                    //        route = 'eaf-production';
                    //        break;
                    //    case 'LF':
                    //        route = 'lf-production';
                    //        break;
                    //}

                    //app.router.navigate(
                    //    app.router.resolveURL(
                    //        route,
                    //        {
                    //            start: new moment(this.model.get('date'), 'YYYY-MM-DD').format('YYYYMMDD'),
                    //            end: new moment(this.model.get('date'), 'YYYY-MM-DD').format('YYYYMMDD'),
                    //        },
                    //        false
                    //    ),
                    //    { trigger: true, }
                    //);
                }
                catch (Error) { console.error(Error.stack); }
            },
            linesGantt_PrimaryDataClick: function (data) {
                try {
                    var route;
                    switch (data.AreaCode.toUpperCase()) {
                        case 'EAF':
                            route = 'eaf-heat-report';
                            break;
                        case 'LF':
                            route = 'lmf-heat-report';
                            break;
                        case 'VTD':
                            route = 'vtd-heat-report';
                            break;
                        case 'CAS':
                            route = 'caster-heat-report';
                            break;
                        case 'CAS2':
                            route = 'caster-heat-report';
                            break;
                    }

                    if (route == 'lmf-heat-report') {
                        var treatment = data.Heat.split('.')[1];

                        app.router.navigate(
                            app.router.resolveURL(
                                'lmf-heat-report',
                                {
                                    heatName: data.HeatName,
                                    treatmentNumber: treatment,
                                },
                                false
                            ),
                            { trigger: true, }
                        );
                    };
                    if (route == 'eaf-heat-report') {
                        app.router.navigate(
                            app.router.resolveURL(
                                'eaf-heat-report',
                                {
                                    heatName: data.HeatName,
                                },
                                false
                            ),
                            { trigger: true, }
                        );
                    };
                    if (route == 'vtd-heat-report') {
                        var treatment = data.Heat.split('.')[1];

                        app.router.navigate(
                            app.router.resolveURL(
                                'vtd-heat-report',
                                {
                                    heatName: data.HeatName,
                                    treatmentNumber: treatment,
                                },
                                false
                            ),
                            { trigger: true, }
                        );
                    }
                    if (route == 'caster-heat-report') {
                        app.router.navigate(
                            app.router.resolveURL(
                                'caster-heat-report',
                                {
                                    heatName: data.HeatName,
                                },
                                false
                            ),
                            { trigger: true, }
                        );
                    }

                    //app.router.navigate(
                    //    app.router.resolveURL(
                    //        'heat',
                    //        {
                    //            heatId: data.HeatId,
                    //            section: data.AreaCode.toUpperCase(),
                    //        },
                    //        false
                    //    ),
                    //    { trigger: true, }
                    //);
                
                }
                catch (Error) { console.error(Error.stack); }
            },
            //model_change_pickers: function (model) {
            //    try {
            //        var params = this.model.toJSON();

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

            //        this.refreshProcesses({
            //            reset: true,
            //            params: _.extend(
            //                {},
            //                params,
            //                {}
            //            ),
            //        });
            //    }
            //    catch (Error) { console.error(Error.stack); }
            //},
            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();

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

                    this._refresh({
                        reset: true,
                        params: _.extend(
                            {},
                            params,
                            {}
                        ),
                    });
                }
                catch (Error) { console.error(Error.stack); }
            },
            model_change_date: function () {
                try {
                    var params = this.model.toJSON();

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

                    this._refresh({
                        reset: true,
                        params: _.extend(
                            {},
                            params,
                            {}
                        ),
                    });
                }
                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;
            },
        });

        Screen.Models.EafProcess = EafProcess.Models.EafProcess.extend({
            defaults: _.extend(
                {},
                EafProcess.Models.EafProcess.prototype.defaults,
                {
                    scrapWeight: null,
                    consumptionsCarbon: null,
                    consumptionsInjectedLime: null,
                    consumptionsNaturalGas: null,
                    consumptionsOxygen: null,
                    consumptionsO2SS: null,
                    lastTemperature: null,
                    lastOxygen: null,
                    recipeName: null,

                    energyPerTonValidLimit: null,
                    oxygenValidLimit: null,
                    o2ssValidLimit: null,
                    powerOnValidLimit: null,

                }
            ),

            parse: function (obj, objManualVariables, objSummarized, objValidLimits) {
                if (!objSummarized) objSummarized = {};
                if (!objValidLimits) objValidLimits = {};

                return _.extend(EafProcess.Models.EafProcess.prototype.parse.apply(this, arguments), {
                    shiftName: obj.ShiftName,
                    scrapWeight: objSummarized.BucketsWeight,
                    consumptionsCarbon: objSummarized.ConsumptionsCarbon,
                    consumptionsInjectedLime: objSummarized.ConsumptionsInjectedLime,
                    consumptionsNaturalGas: objSummarized.ConsumptionsNaturalGas,
                    consumptionsOxygen: objSummarized.ConsumptionsOxygen,
                    consumptionsO2SS: objSummarized.ConsumptionsO2SS,
                    lastTemperature: objSummarized.LastTemperature,
                    lastOxygen: objSummarized.LatestOxygen,
                    recipeName: objSummarized.ScrapRecipe,
                    yield: objSummarized.Yield,
                    

                    energyPerTonValidLimit: objValidLimits.EnergyPerTon,
                    oxygenValidLimit: objValidLimits.Oxygen,
                    o2ssValidLimit: objValidLimits.O2SS,
                    powerOnValidLimit: objValidLimits.PowerOn,


                    fluxesHiCal: objSummarized.FluxesHiCal,
                    fluxesCarbon: objSummarized.FluxesCarbon,
                    fluxesProSlag: objSummarized.FluxesProSlag,
                    fluxesDolomite: objSummarized.FluxesDolomite,

                    yield: objSummarized.Yield ? objSummarized.Yield.toFixed(2) : '',
                    scrapRecipe: objSummarized.ScrapRecipe,
                    latestOxygen: objSummarized.LatestOxygen,
                    charges: obj.Charges,
                    powerProgram: obj.PowerProgram,
                    burnerProgram: obj.BurnerProgram,
                    
                });
            },
        });

        Screen.Collections.EafProcesses = EafProcess.Collections.EafProcesses.extend({
            model: Screen.Models.EafProcess,

            parseResponse: function (resp, opt) {
                if ((resp) && (resp.Table)) {
                    var that = this,
                        newColl,
                        validLimits = resp.Table2[0];

                    newColl = _.map(resp.Table, function (obj) {
                        return that.model.prototype.parse(obj, null, _.findWhere(resp.Table1, { Id: obj.Id, }), validLimits);
                    });

                    var method = ((opt.refresh) || ((opt.reset))) ? 'set' : 'add';

                    var editingItems = _.where(this.toJSON(), { isNew: true });
                    [].push.apply(newColl, editingItems);

                    this[method](newColl, { from: 'fetch' });

                    return true;
                }

                return false;
            },
            updateFixedParameters: function (params) {
                EafProcess.Collections.EafProcesses.prototype.updateFixedParameters.apply(this, arguments);

                this.fixedParameters.push({ name: 'summarizedData', value: true, type: 'VARCHAR', });
                this.fixedParameters.push({ name: 'includeValidLimits', value: true, type: 'VARCHAR', });
            },
        });

        Screen.Models.LMFProcesses = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    start: obj.Start ? new moment(obj.Start).format('MM/DD/YYYY HH:mm:ss') : null,
                    startLocal: obj.StartLocal ? new moment(obj.StartLocal).format('MM/DD/YYYY HH:mm:ss') : null,
                    end: obj.End ? new moment(obj.End).format('MM/DD/YYYY HH:mm:ss') : null,
                    ladleFurnaceCode: obj.LadleFurnaceCode ? (obj.LadleFurnaceCode == 1 ? 'South' : 'North') : null,
                    treatment: obj.Treatment,
                    shiftId: obj.ShiftId ? (obj.ShiftId == 1 ? 'D' : 'N') : null,
                    crewId: obj.CrewId,
                    heatName: obj.HeatName,
                    duration: obj.Duration ? obj.Duration : null,
                    initialTemperature: obj.InitialTemperature ? obj.InitialTemperature : null,
                    finalTemperature: obj.FinalTemperature ? obj.FinalTemperature : null,
                    finalOxygen: obj.FinalOxygen ? obj.FinalOxygen : null,
                    finalCarbon: obj.FinalCarbon ? obj.FinalCarbon : null,
                    powerOn: obj.PowerOn ? obj.PowerOn : null,
                    energy: obj.Energy ? obj.Energy.toFixed(2) : null,
                    argonVolume: obj.TotalArgonVolume ? obj.TotalArgonVolume.toFixed(0) : null,
                    Lime: obj.Lime ? obj.Lime.toFixed(2) : null,
                    FeVn: obj.FeVn ? obj.FeVn.toFixed(2) : null,
                    Ni: obj.Ni ? obj.Ni.toFixed(2) : null,
                    LCFeCr: obj.LCFeCr ? obj.LCFeCr.toFixed(2) : null,
                    Carbon: obj.Carbon ? obj.Carbon.toFixed(0) : null,
                    SiMn: obj.SiMn ? obj.SiMn.toFixed(2) : null,
                    LoAlSi: obj.LoAlSi ? obj.LoAlSi.toFixed(2) : null,
                };

                return result;
            }
        })


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

            fetch(params) {

                var that = this
                qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};

                this.fixedParameters = [
                    { Name: '@start', Type: 'DATETIME', Value: params.start },
                    { Name: '@end', Type: 'DATETIME', Value: params.end },
                ];

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

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

                                if ((resp) && (resp.Table)) {

                                    var records = resp.Table,
                                        newColl;

                                    newColl = _.map(records, that.model.prototype.parse);

                                    that.set(newColl).trigger('fetch', that, resp);

                                }
                                else {
                                    if ((resp) && (resp.Message))
                                        console.error(resp.Message);
                                    else
                                        console.error('Server response not valid.');
                                }
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                    },
                    app.ConnectionStrings.app
                );

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