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

  'modules/product-type',

  'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',
  'js/backgrid-0.3.5/extensions/i18n-cell/backgrid-i18n-cell',
],
function (app, T, Backgrid, moment, Base, ProductType) {

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            year: moment().day("Monday").add(-1, 'week').year(),
            week: moment().day("Monday").add(-1, 'week').week(),
            productTypeId: null,

            productTypes: [],

            hasData: false,
            isLoading: false,
        },
        computeds: {
            hasProductTypes: {
                deps: ['productTypes'],
                get: function (value) {
                    return ((value) && (value.length > 0));
                }
            },
            //start$: {
            //    deps: ['year', 'week'],
            //    get: function (year, week) {
            //        return moment().year(year).week(week).day("Monday").format('YYYY-MM-DD');
            //    },                
            //},
            //end$: {
            //    deps: ['year', 'week'],
            //    get: function (year, week) {
            //        return moment().year(year).week(week).day("Monday").add(6, 'days').format('YYYY-MM-DD');
            //    },
            //},
        },
    });    

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'kpi-weekly',
        id: 'kpi-weekly',
        title: 'Weekly KPIs',
        events: function () {
            return {
                'click #currentBtn': this.currentBtn_click,
                'click #nextBtn': this.nextBtn_click,
                'click #previousBtn': this.previousBtn_click,
                'click #refreshBtn': this.refreshBtn_click,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,

        eafCostItems: null,
        eafSlagItems: null,
        eafTapTempItems: null,
        eafUsageItems: null,
        lfCostItems: null,
        lfSuperHeatItems: null,
        lfUsageItems: 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.eafKpiWeeklyColl = new Screen.Collections.EafKpiWeekly();

            this.eafCostItems = new Backbone.Collection();

            this.eafSlagItems = new Backbone.Collection();

            this.eafTapTempItems = new Backbone.Collection();

            this.eafUsageItems = new Backbone.Collection();

            this.lfCostItems = new Backbone.Collection();

            this.lfSuperHeatItems = new Backbone.Collection();

            this.lfUsageItems = new Backbone.Collection();

            this.bindingSources = {};


            ProductType.Collections.ProductTypes.fetch({
                async: false,
                success: function (records) {
                    try {
                        that.model.set('productTypes', _.map(records, function (obj) { return { value: obj.id, label: obj.name, }; }));
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                },
            });


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

            this.bindEvents();
        },
        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.eafKpiWeeklyColl, 'fetch', this.eafKpiWeeklyColl_fetch);
        },
        _refresh: function (opt) {
            //console.log('autorefresh: ' + new Date().toString()); 
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshItems(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.start)
                fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
            if (viewParams.end)
                fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
            if (fixedParams.productTypeId)
                fixedParams.productTypeId = parseInt(fixedParams.productTypeId, 10);

            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/kpi-weekly2/';

            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 = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_cost_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'energyCostPerTon',
                                        label: app.translate([that, app], 'eaf_cost_energy_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'energyCostPerTonMin',
                                            maxProp: 'energyCostPerTonMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'oxygenCostPerTon',
                                        label: app.translate([that, app], 'eaf_cost_oxygen_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'oxygenCostPerTonMin',
                                            maxProp: 'oxygenCostPerTonMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'naturalGasCostPerTon',
                                        label: app.translate([that, app], 'eaf_cost_natural_gas_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'naturalGasCostPerTonMin',
                                            maxProp: 'naturalGasCostPerTonMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'carbonCostPerTon',
                                        label: app.translate([that, app], 'eaf_cost_carbon_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'carbonCostPerTonMin',
                                            maxProp: 'carbonCostPerTonMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'limeCostPerTon',
                                        label: app.translate([that, app], 'eaf_cost_lime_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'limeCostPerTonMin',
                                            maxProp: 'limeCostPerTonMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'totalCostPerTon',
                                        label: app.translate([that, app], 'eaf_cost_total_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'totalCostPerTonMin',
                                            maxProp: 'totalCostPerTonMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.eafKpiWeeklyColl,
                            });
                            that.$el.find('.eaf-cost-grid-container').append(grid.render().el);

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_slag_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'heatsCount',
                                        label: app.translate([that, app], 'eaf_slag_heats_count_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagHeatsCount',
                                        label: app.translate([that, app], 'eaf_slag_samples_count_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagHeatsPercentage',
                                        label: app.translate([that, app], 'eaf_slag_samples_percentage_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'slagHeatsPercentageMin',
                                            maxProp: 'slagHeatsPercentageMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagFe2O3',
                                        label: app.translate([that, app], 'eaf_slag_Fe2O3_col'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'numeric-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagMgO',
                                        label: app.translate([that, app], 'eaf_slag_MgO_col'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'numeric-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagB3Ratio',
                                        label: app.translate([that, app], 'eaf_slag_B3_col'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'numeric-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.eafKpiWeeklyColl,
                            });
                            that.$el.find('.eaf-slag-grid-container').append(grid.render().el);

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_tap_temp_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'temperaturesCount',
                                        label: app.translate([that, app], 'eaf_tap_temp_temperatures_count_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'temperaturesPercentage',
                                        label: app.translate([that, app], 'eaf_tap_temp_temperatures_percentage_col'),
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'temperaturesPercentageMin',
                                            maxProp: 'temperaturesPercentageMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.eafKpiWeeklyColl,
                            });
                            that.$el.find('.eaf-tap-temp-grid-container').append(grid.render().el);

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_usage_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'heatsCount',
                                        label: app.translate([that, app], 'eaf_usage_heats_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'steelWeight',
                                        label: app.translate([that, app], 'eaf_usage_steel_weight_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'energy',
                                        label: app.translate([that, app], 'eaf_usage_energy_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'oxygen',
                                        label: app.translate([that, app], 'eaf_usage_oxygen_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'naturalGas',
                                        label: app.translate([that, app], 'eaf_usage_natural_gas_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'carbon',
                                        label: app.translate([that, app], 'eaf_usage_carbon_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'lime',
                                        label: app.translate([that, app], 'eaf_usage_lime_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.eafKpiWeeklyColl,
                            });
                            that.$el.find('.eaf-usage-grid-container').append(grid.render().el);

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'lf_cost_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'energy',
                                        label: app.translate([that, app], 'lf_cost_energy_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'CaC2',
                                        label: app.translate([that, app], 'lf_cost_CaC2_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'spar',
                                        label: app.translate([that, app], 'lf_cost_spar_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'HiCal',
                                        label: app.translate([that, app], 'lf_cost_HiCal_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'lime',
                                        label: app.translate([that, app], 'lf_cost_lime_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'total',
                                        label: app.translate([that, app], 'lf_cost_total_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.lfCostItems,
                            });
                            that.$el.find('.lf-cost-grid-container').append(grid.render().el);

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'lf_super_heats_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'temperatureAvg',
                                        label: app.translate([that, app], 'lf_super_heats_temperature_avg_col'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'numeric-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'heatsCount',
                                        label: app.translate([that, app], 'lf_super_heats_heats_count_col'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'numeric-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'heatsPercentage',
                                        label: app.translate([that, app], 'lf_super_heats_heats_percentage_col'),
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'numeric-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.lfSuperHeatItems,
                            });
                            that.$el.find('.lf-super-heats-grid-container').append(grid.render().el);

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'lf_usage_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'heatsCount',
                                        label: app.translate([that, app], 'lf_usage_heats_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'energy',
                                        label: app.translate([that, app], 'lf_usage_energy_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'CaC2',
                                        label: app.translate([that, app], 'lf_usage_CaC2_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'spar',
                                        label: app.translate([that, app], 'lf_usage_spar_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'HiCal',
                                        label: app.translate([that, app], 'lf_usage_HiCal_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'lime',
                                        label: app.translate([that, app], 'lf_usage_lime_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.lfUsageItems,
                            });
                            that.$el.find('.lf-usage-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.start)
                                fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                            if (fixedParams.end)
                                fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                            if (fixedParams.standId)
                                fixedParams.standId = parseInt(fixedParams.standId, 10);

                            that.model.set(fixedParams);

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

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

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

        refreshItems: function (options) {
            var attrs = this.model.toJSON(),
                opt = _.extend({}, options, { params: {}, });

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

            this.eafKpiWeeklyColl.fetch(_.extend(opt, {
                params: {
                    year: attrs.year,
                    week: attrs.week,
                    productTypeId: (opt.params.productTypeId)
                                ? (opt.params.productTypeId != '0')
                                        ? opt.params.productTypeId
                                        : null
                                : (attrs.productTypeId != '0')
                                        ? attrs.productTypeId
                                        : null,
                },
            }));            
        },

        currentBtn_click: function (e) {
            try {
                var date = moment().day("Monday").add(-1, 'week');

                this.model.set({ year: date.year(), week: date.week(), });
            }
            catch (Error) { console.error(Error.stack); }
        },
        eafKpiWeeklyColl_fetch: function () {
            this.model.set({
                isLoading: false,
                hasData: true,
            });
        },
        nextBtn_click: function (e) {
            try {
                var params = this.model.toJSON();

                var date = moment().year(params.year).week(params.week).day("Monday").add(1, 'week');

                this.model.set({ year: date.year(), week: date.week(), });
            }
            catch (Error) { console.error(Error.stack); }
        },
        previousBtn_click: function (e) {
            try {
                var params = this.model.toJSON();

                var date = moment().year(params.year).week(params.week).day("Monday").add(-1, 'week');

                this.model.set({ year: date.year(), week: date.week(), });
            }
            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,
                            {
                                year: params.year,
                                week: params.week,
                            }
                        ),
                        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;
        },
    });

    var superRef, superProto, classRef;

    superRef = Base.Models.Base;
    superProto = superRef.prototype;

    Screen.Models.EafKpiWeeklyItem = Base.Models.Base.extend({
        defaults: {
            year: null,
            week: null,
            productTypeId: null,
            crewId: null,

            heatsCount: null,
            steelWeight: null,

            slagHeatsCount: null,
            slagHeatsPercentage: null,
            slagHeatsPercentageMin: null,
            slagHeatsPercentageMax: null,
            slagB3Ratio: null,
            slagFe2O3: null,
            slagMgO: null,
            temperaturesCount: null,
            temperaturesPercentage: null,
            temperaturesPercentageMin: null,
            temperaturesPercentageMax: null,

            carbon: null,
            carbonCostPerTon: null,
            carbonCostPerTonMin: null,
            carbonCostPerTonMax: null,
            energy: null,
            energyCostPerTon: null,
            energyCostPerTonMin: null,
            energyCostPerTonMax: null,
            lime: null,
            limeCostPerTon: null,
            limeCostPerTonMin: null,
            limeCostPerTonMax: null,
            naturalGas: null,
            naturalGasCostPerTon: null,
            naturalGasCostPerTonMin: null,
            naturalGasCostPerTonMax: null,
            oxygen: null,
            oxygenCostPerTon: null,
            oxygenCostPerTonMin: null,
            oxygenCostPerTonMax: null,
            totalCostPerTon: null,
            totalCostPerTonMin: null,
            totalCostPerTonMax: null,
        },
        procedures: {
            get: app.DatabaseNames.MES + '.EAF.GetKpiWeekly',
        },

        parse: function (objs) {
            var result = {};

            if (objs) {
                var obj = objs[0];

                result = {
                    year: obj.Year,
                    week: obj.Week,
                    productTypeId: obj.ProductTypeId,
                    crewId: obj.CrewId,
                };

                _.each(objs, function (obj) {
                    switch (obj.Code.toUpperCase()) {
                        case 'CARBON':
                            result.carbon = obj.Value;
                            break;
                        case 'CARBON_COST_PER_TON':
                            result.carbonCostPerTon = obj.Value;
                            break;
                        case 'CARBON_COST_PER_TON_MAX':
                            result.carbonCostPerTonMax = obj.Value;
                            break;
                        case 'CARBON_COST_PER_TON_MIN':
                            result.carbonCostPerTonMin = obj.Value;
                            break;
                        case 'ENERGY':
                            result.energy = obj.Value;
                            break;
                        case 'ENERGY_COST_PER_TON':
                            result.energyCostPerTon = obj.Value;
                            break;
                        case 'ENERGY_COST_PER_TON_MAX':
                            result.energyCostPerTonMax = obj.Value;
                            break;
                        case 'ENERGY_COST_PER_TON_MIN':
                            result.energyCostPerTonMin = obj.Value;
                            break;
                        case 'HEATS_COUNT':
                            result.heatsCount = obj.Value;
                            break;
                        case 'LIME':
                            result.lime = obj.Value;
                            break;
                        case 'LIME_COST_PER_TON':
                            result.limeCostPerTon = obj.Value;
                            break;
                        case 'LIME_COST_PER_TON_MAX':
                            result.limeCostPerTonMax = obj.Value;
                            break;
                        case 'LIME_COST_PER_TON_MIN':
                            result.limeCostPerTonMin = obj.Value;
                            break;
                        case 'NATURAL_GAS':
                            result.naturalGas = obj.Value;
                            break;
                        case 'NATURAL_GAS_COST_PER_TON':
                            result.naturalGasCostPerTon = obj.Value;
                            break;
                        case 'NATURAL_GAS_COST_PER_TON_MAX':
                            result.naturalGasCostPerTonMax = obj.Value;
                            break;
                        case 'NATURAL_GAS_COST_PER_TON_MIN':
                            result.naturalGasCostPerTonMin = obj.Value;
                            break;
                        case 'OXYGEN':
                            result.oxygen = obj.Value;
                            break;
                        case 'OXYGEN_COST_PER_TON':
                            result.oxygenCostPerTon = obj.Value;
                            break;
                        case 'OXYGEN_COST_PER_TON_MAX':
                            result.oxygenCostPerTonMax = obj.Value;
                            break;
                        case 'OXYGEN_COST_PER_TON_MIN':
                            result.oxygenCostPerTonMin = obj.Value;
                            break;
                        case 'SLAG_B3':
                            result.slagB3Ratio = obj.Value;
                            break;
                        case 'SLAG_FE2O3':
                            result.slagFe2O3 = obj.Value;
                            break;
                        case 'SLAG_HEATS_COUNT':
                            result.slagHeatsCount = obj.Value;
                            break;
                        case 'SLAG_HEATS_PERCENTAGE':
                            result.slagHeatsPercentage = obj.Value;
                            break;
                        case 'SLAG_HEATS_PERCENTAGE_MAX':
                            result.slagHeatsPercentageMax = obj.Value;
                            break;
                        case 'SLAG_HEATS_PERCENTAGE_MIN':
                            result.slagHeatsPercentageMin = obj.Value;
                            break;
                        case 'SLAG_MGO':
                            result.slagMgO = obj.Value;
                            break;
                        case 'STEEL_WEIGHT':
                            result.steelWeight = obj.Value;
                            break;
                        case 'TAP_TEMPERATURES_COUNT':
                            result.temperaturesCount = obj.Value;
                            break;
                        case 'TAP_TEMPERATURES_PERCENTAGE':
                            result.temperaturesPercentage = obj.Value;
                            break;
                        case 'TAP_TEMPERATURES_PERCENTAGE_MAX':
                            result.temperaturesPercentageMax = obj.Value;
                            break;
                        case 'TAP_TEMPERATURES_PERCENTAGE_MIN':
                            result.temperaturesPercentageMin = obj.Value;
                            break;
                        case 'TOTAL_COST_PER_TON':
                            result.totalCostPerTon = obj.Value;
                            break;
                        case 'TOTAL_COST_PER_TON_MAX':
                            result.totalCostPerTonMax = obj.Value;
                            break;
                        case 'TOTAL_COST_PER_TON_MIN':
                            result.totalCostPerTonMin = obj.Value;
                            break;
                        default:
                            break;
                    }
                });
            }

            return result;
        },
    });

    Screen.Collections.EafKpiWeekly = Base.Collections.Base.extend({
        model: Screen.Models.EafKpiWeeklyItem,
        comparator: function (a, b) {
            var valA = a.get('crewId'),
                valB = b.get('crewId');

            if (valA == 'ALL_CREWS') {
                return 1;
            }
            else if (valB == 'ALL_CREWS') {
                return -1;
            }
            else {
                return (valA < valB)
                            ? -1
                            : (valA > valB)
                                ? 1
                                : 0;
            }
        },

        fetch: function (options) {
            var that = this,
                opt = _.extend(
                    { error: function () { }, success: function () { }, },
                    options
                ),
                qp = new QueryParameters(),
                ttimestamp = this.transaction_timestamp = new Date().getTime();

            this.isFetching = true;

            qp.Add('@year', 'INT', opt.params.year);
            qp.Add('@week', 'INT', opt.params.week);
            qp.Add('@productTypeId', 'INT', opt.params.productTypeId);

            this.getData(_.extend(
                {},
                opt,
                {
                    params: qp,
                    success: function (resp) {
                        //checking transaction timestamp
                        if (ttimestamp != that.transaction_timestamp)
                            return;

                        if (that.parseResponse(resp, opt) == true) {
                            that.trigger('fetch', that, resp, options);

                            opt.success(that, resp);

                            ////decreasing page since we couldn't get any data on this page.
                            //if (newColl.length == 0 && method == 'add')
                            //    that.currentPage--;

                            that.isFetching = false;
                        }
                        else {
                            var msg = (resp.Message) ? resp.Message : 'SERVER_RESPONSE_NOT_VALID';

                            opt.error(that, msg);
                            console.error(new Error(msg).stack);
                        }
                    },
                }
            ));

            return this;
        },
        parseResponse: function (resp, opt) {
            if ((resp) && (resp.Table)) {
                var that = this,
                    newColl;

                newColl = _.map(_.groupBy(resp.Table, 'CrewId'), function (obj, key) {
                    return that.model.prototype.parse(obj);
                });

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

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

                return true;
            }

            return false;
        },
    });

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