//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) {

    function isNull(val1, val2) {
        return (val1) ? val1 : val2;
    }

    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,

            hasData: false,
            isLoading: false,

            //Filters Data
            //crewId: -1,
            furnaceCode: -1,
            productTypeId: -1,

            timestampGroupBy: 'WEEK',
            othersGroupBy: ['CREW',],

            //crews: [],
            furnaces: [],
            productTypes: [],

            showFurnacesSelect: true,
            //showCrewsSelect: true,
            showProductTypesSelect: true,
        },
        initialize: function (a, b) {
            _.extend(this, this.options);

            this.attributes.cuberows = new Screen.Collections.CubeRows(null, {
                parent: this,
            });

            
            //this.fetchCrews();
            this.fetchFurnaces();
            this.fetchProductType();
        },
        computeds: {
            groupBy: {
                deps: ['othersGroupBy', 'timestampGroupBy',],
                get: function (othersGroupBy, timestampGroupBy) {
                    return [].concat(
                        othersGroupBy,
                        [timestampGroupBy]
                    );
                },
            },
            //crewId$: {
            //    deps: ['crewId',],
            //    get: function (value) {
            //        return value;
            //    },
            //    set: function (value) {
            //        var result = { crewId: value, };

            //        if (value != -1) {
            //            var groups = _.clone(this.get('othersGroupBy')),
            //                groupValue = 'CREW';

            //            if (_.indexOf(groups, groupValue) == -1)
            //                groups.push(groupValue);

            //            result.othersGroupBy = groups;
            //        }

            //        return result;
            //    }
            //},
            furnaceCode$: {
                deps: ['furnaceCode',],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    var result = { furnaceCode: value, };

                    if (value != -1) {
                        var groups = _.clone(this.get('othersGroupBy')),
                            groupValue = 'FURNACE';

                        if (_.indexOf(groups, groupValue) == -1)
                            groups.push(groupValue);

                        result.othersGroupBy = groups;
                    }

                    return result;
                }
            },
            productTypeId$: {
                deps: ['productTypeId',],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    var result = { productTypeId: value, };

                    if (value != -1) {
                        var groups = _.clone(this.get('othersGroupBy')),
                            groupValue = 'PRODUCTTYPE';

                        if (_.indexOf(groups, groupValue) == -1)
                            groups.push(groupValue);

                        result.othersGroupBy = groups;
                    }

                    return result;
                }
            },
            //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');
            //    },
            //},
        },
        //fetchCrews: function () {
        //    var that = this;
        //    var customPath = "/app/custom-screens/kpi-weekly/";
        //    $.ajax(app.foldersRoot + customPath + "cube-api/cube-api.aspx", {
        //        type: 'POST',
        //        data: {
        //            action: 'FILTER',
        //            name: 'Crews',
        //        },
        //        dataType: "json",
        //        success: function (data) {
        //            if (data) {
        //                data = _.where(data, { LEVEL_UNIQUE_NAME: '[Crews].[Id].[Id]' });
        //                that.set({
        //                    crews: (_.map(data, function (m) {
        //                        return {
        //                            key: m['MEMBER_NAME'], 
        //                            value: m['MEMBER_UNIQUE_NAME'] , //m["MEMBER_UNIQUE_NAME"],
        //                            label: m["MEMBER_KEY"],
        //                        };
        //                    })),
        //                });
        //            }
        //        }
        //    });
        //},
        fetchFurnaces: function () {
            var that = this;
            var customPath = "/app/custom-screens/kpi-weekly/";
            $.ajax(app.foldersRoot + customPath + "cube-api/cube-api.aspx", {
                type: 'POST',
                data: {
                    action: 'FILTER',
                    name: 'Furnaces',
                },
                dataType: "json",
                success: function (data) {
                    if (data) {
                        that.set({
                            furnaces: (_.map(data, function (m) {
                                return {
                                    key: m["MEMBER_KEY"], 
                                    value: m["MEMBER_UNIQUE_NAME"],
                                    label: m["MEMBER_NAME"],
                                };
                            })),
                        });
                    }
                }
            });
        },
        fetchProductType: function () {
            var that = this;
            var customPath = "/app/custom-screens/kpi-weekly/";
            $.ajax(app.foldersRoot + customPath + "cube-api/cube-api.aspx", {
                type: 'POST',
                data: {
                    action: 'FILTER',
                    name: 'Product Types',
                },
                dataType: "json",
                success: function (data) {
                    if (data) {
                        that.set({
                            productTypes: (_.map(data, function (m) {
                                return {
                                    key: m['MEMBER_KEY'], 
                                    value: m["MEMBER_UNIQUE_NAME"],
                                    label: m["MEMBER_NAME"],
                                };
                            })),
                        });
                    }
                }
            });
        },
        
    });    

    Screen.Models.CubeRows = Backbone.Model.extend({
        defaults: {
            //dimensions
            year: null,
            month: null,
            date: null,
            crewId: null,
            furnaceCode: null,
            productTypeId: null,

            //measures
            slagB3ratio: null,
            slagF2O3: null,
            slagMgO: null,
            carbon: null,
            lime: null,
            naturalGas: null,
            steelWeight: null,
            energy: null,

            //measures count
            crewsCount: null,
            furnacesCount: null,
            ProductTypesCount: null,
            slagSamplesCount: null,
            slagHeatsCount: null,
            heatsCount: null,

            //measures per tonelade
            carbonPerTon: null,
            tapTemperaturesPerTon: null,
            energyPerTon: null,
            naturalGasPerTon: null,
            totalCostPerTon: null,
            limePerTon: null,

            //measures percentage
            slagHeatsPercentage: null,
            tapTemperatures: null,
            tapTemperaturesPercentage: null,

            //measures min & max
            slagHeatsPercentageMin: null,
            slagHeatsPercentageMax: null,
            temperaturesPercentageMin: null,
            temperaturesPercentageMax: null,
            carbonCostPerTonMin: null,
            carbonCostPerTonMax: null,
            energyCostPerTonMin: null,
            energyCostPerTonMax: null,
            limeCostPerTonMin: null,
            limeCostPerTonMax: null,
            naturalGasCostPerTonMin: null,
            naturalGasCostPerTonMax: null,
            oxygenCostPerTonMin: null,
            oxygenCostPerTonMax: null,
            totalCostPerTonMin: null,
            totalCostPerTonMax: null,
            
        },
    });

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

        fixedParams: {},
        isFetching: false,
        currentPage: 1,
        pageSize: 50,

        initialize: function (a, b, c) {
           _.extend(this, this.options);
        },
        fetch: function (params) {
            var that = this;

            var ttimestamp = this.transaction_timestamp = new Date().getTime(),
                options = {
                    params: {},
                    callback: null,
                    refresh: false,
                    set: false,
                };

            options = _.extend(options, params);

            this.isFetching = true;

            if (options.refresh) {
                this.resetPagination(true);

                this.fixedParameters = {
                    groupBy: options.groupBy,
                    filterBy: options.filterBy,
                };
            }

            if (!options.refresh && !options.set) {
                fromRow = (this.currentPage - 1) * this.pageSize;
                rowsToFetch = this.pageSize;
            } else {
                fromRow = 0;
                rowsToFetch = this.currentPage * this.pageSize;
            }

            var customPath = "/app/custom-screens/kpi-weekly/";
            $.ajax(app.foldersRoot + customPath + "cube-api/cube-api.aspx", {
                type: 'POST',
                data: {
                    groupby: JSON.stringify(that.fixedParameters.groupBy),
                    filterby: JSON.stringify(that.fixedParameters.filterBy),
                    rowsStartIndex: fromRow,
                    rowsCount: rowsToFetch,
                },
                dataType: "json",
                success: function (data) {
                    if (data && data.Status != "FAILED") {
                        var items = [];

                        for (var i = 0; i < data.length; i++) {
                            var itemData = data[i];
                            var itemDataN = {};

                                _.each(itemData, function (value, key) {
                                    key = key.replace("[Measures].", "").replace(".[MEMBER_CAPTION]", "");
                                    key = key.split("[").join("").split("]").join("").split(" ").join("");
                                    itemDataN[key] = value;
                                });
                                itemData = itemDataN;
                            

                            var item = {
                                //dimensions
                                //year: itemData["Time.Year.Year"],
                                //month: itemData["Time.Month.Month"],
                                //date: itemData["Time.Date.Date"],
                                time: (itemData["Time.Year.Year"])
                                    ? itemData["Time.Year.Year"] :
                                    //? moment(itemData["Time.Year.Year"], 'YYYY-MM-DD HH:mm:ss.SSS').format('YYYY') :
                                    (itemData["Time.Month.Month"])
                                        ? itemData["Time.Month.Month"] :
                                        //? moment(itemData["Time.Month.Month"], 'YYYY-MM-DD HH:mm:ss.SSS').format('YYYY-MM') :
                                        (itemData["Time.Week.Week"])
                                            ? itemData["Time.Week.Week"] :
                                            //? moment(itemData["Time.Week.Week"], 'YYYY-MM-DD HH:mm:ss.SSS').format('YYYY-MM-DD') :
                                            itemData["Time.Date.Date"],

                                furnaceCode: itemData["Furnaces.Code.Code"],
                                crewId: isNull(itemData["Crews.Id.Id"], 'All') ,
                                productTypeId: (itemData["ProductTypes.Id.Id"])
                                    ? app.translate(app, itemData["ProductTypes.Id.Id"])
                                    : null,

                                //measures
                                steelWeight: itemData["SteelWeightAvg"],
                                energy: itemData["EnergyAvg"] * 1000,
                                slagB3ratio: itemData["SlagB3ratioAvg"],
                                slagFe2O3: itemData["SlagFe2O3Avg"],
                                slagMgO: itemData["SlagMgOAvg"],
                                carbon: itemData["CarbonAvg"],
                                tapTemperature: itemData["TapTemperature"],
                                lime: itemData["LimeAvg"],
                                naturalGas: itemData["NaturalGasAvg"],
                                oxygen: itemData["OxygenAvg"],

                                //measures count
                                heatsCount: itemData["HeatsCount"],
                                slagSamplesCount: itemData["SlagSamplesCount"],
                                slagHeatsCount: itemData["SlagHeatsCount"],
                                tapTemperaturesCount: itemData["TapTemperaturesCount"],

                                //measures per tonelade
                                energyPerTon: itemData["EnergyPerTonAvg"],
                                carbonPerTon: itemData["CarbonPerTonAvg"],
                                limePerTon: itemData["LimePerTonAvg"],
                                naturalGasPerTon: itemData["NaturalGasPerTonAvg"],
                                oxygenPerTon: itemData["OxygenPerTonAvg"],
                                totalCostPerTon: itemData["TotalCostPerTonAvg"],

                                //measures percentage
                                slagHeatsPercentage: itemData["SlagHeatsPercentage"], 
                                tapTemperaturesPercentage: itemData["TapTemperaturesPercentage"],

                                //measures min and max for specific product
                                slagHeatsPercentageMin: (itemData["ProductTypes.Id.Id"] )
                                                        ? itemData['SlagHeatsPercentageMin']
                                                        : itemData['SlagHeatsPercentageMinAll'] ,

                                slagHeatsPercentageMax: (itemData["ProductTypes.Id.Id"])
                                                        ? itemData['SlagHeatsPercentageMax']
                                                        : itemData['SlagHeatsPercentageMaxAll'],

                                carbonPerTonMin:    (itemData["ProductTypes.Id.Id"])
                                                    ? itemData['CarbonPerTonMin']
                                                    : itemData['CarbonPerTonMinAll'],

                                carbonPerTonMax:(itemData["ProductTypes.Id.Id"])
                                                ? itemData['CarbonPerTonMax']
                                                : itemData['CarbonPerTonMaxAll'],

                                oxygenPerTonMin:(itemData["ProductTypes.Id.Id"])
                                                ? itemData['OxygenPerTonMin']
                                                : itemData['OxygenPerTonMinAll'],

                                oxygenPerTonMax:(itemData["ProductTypes.Id.Id"])
                                                ? itemData['OxygenPerTonMax'] 
                                                : itemData['OxygenPerTonMaxAll'],

                                energyPerTonMin:(itemData["ProductTypes.Id.Id"])
                                                ? itemData['EnergyPerTonMin']
                                                : itemData['EnergyPerTonMinAll'],

                                energyPerTonMax:(itemData["ProductTypes.Id.Id"])
                                                ? itemData['EnergyPerTonMax']
                                                : itemData['EnergyPerTonMaxAll'],

                                limePerTonMin:(itemData["ProductTypes.Id.Id"]) 
                                              ? itemData['LimePerTonMin']
                                              : itemData['LimePerTonMinAll'] ,

                                limePerTonMax: (itemData["ProductTypes.Id.Id"])
                                               ? itemData['LimePerTonMax']
                                               : itemData['LimePerTonMaxAll'],

                                naturalGasPerTonMin: (itemData["ProductTypes.Id.Id"])
                                                     ? itemData['NaturalGasPerTonMin']
                                                     : itemData['NaturalGasPerTonMinAll'],

                                naturalGasPerTonMax: (itemData["ProductTypes.Id.Id"])
                                                     ? itemData['NaturalGasPerTonMax']
                                                     : itemData['NaturalGasPerTonMaxAll'] ,

                                tapTemperaturesPercentageMin: (itemData["ProductTypes.Id.Id"])
                                                              ? itemData['TapTemperaturesPercentageMin']
                                                              : itemData['TapTemperaturesPercentageMinAll'],

                                tapTemperaturesPercentageMax: (itemData["ProductTypes.Id.Id"])
                                                              ? itemData['TapTemperaturesPercentageMax']
                                                              : itemData['TapTemperaturesPercentageMaxAll'],

                                totalCostPerTonMin: (itemData["ProductTypes.Id.Id"])
                                                    ? itemData['TotalCostPerTonMin']
                                                    : itemData['TotalCostPerTonMinAll'],

                                totalCostPerTonMax: (itemData["ProductTypes.Id.Id"])
                                                    ? itemData['TotalCostPerTonMax']
                                                    : itemData['TotalCostPerTonMax'],

                            };

                            //var already = _.findWhere(items, { year: item.year, month: item.month, date: item.date, shift: item.shift, thicknessType: item.thicknessType, inputWidthType: item.inputWidthType }); 

                            //avoid empty rows
                            //var valid = _.every(_.values(_.omit(item, 'year', 'month', 'date', 'shift', 'thicknessType', 'inputWidthType')), function (t) {
                            //    return _.isNumber(t); 
                            //}); 

                            //if (!already && valid) items.push(item);
                            items.push(item);
                        }


                        if (ttimestamp == that.transaction_timestamp) {
                            var method = (options.set) ? 'set' : 'add';
                            method = (options.method) ? options.method : method;

                            that[method](items, { from: "fetch" });

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

                            that.isFetching = false;

                            //if (options && options.callback && _.isFunction(options.callback))
                            //    options.callback.call(that, that, data);
                        }
                    }

                    if (options.callback != null && _.isFunction(options.callback))
                        options.callback.call(this, that, data);
                },
                error: function (e) {
                    if (options && options.callback && _.isFunction(options.callback))
                        options.callback.call(that, that, data);
                    console.log("Failed when trying to get data from cube-api");
                }
            });
        },
        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },
    });

    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,
                "click .btn-export-to-excel": this.exportToExcel,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,

        lfCostItems: null,
        lfSuperHeatItems: null,
        lfUsageItems: null,

        subviews: null,
        viewParams: null,

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

            var that = this;

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

            this.eafKpiWeeklyColl = new Screen.Collections.EafKpiWeekly();
            this.lfCostItems = new Backbone.Collection();
            this.lfSuperHeatItems = new Backbone.Collection();
            this.lfUsageItems = new Backbone.Collection();

            this.bindingSources = {};

            this.grids = {};

            this.firstTime = true;


            //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);
            //this.listenTo(this.model, "change:crewId", this.filtersChanged);
            //this.listenTo(this.model, "change:furnaceCode", this.filtersChanged);
            //this.listenTo(this.model, "change:productTypeId", this.filtersChanged);
        },
        _refresh: function (opt) {
            var that = this;
            //console.log('autorefresh: ' + new Date().toString()); 
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            _.extend(opt, {
                groupBy: this.model.get("groupBy"),
                filterBy: {},
            });

            var snbe = this.$el.find('.subnavbar');

            var anyFilters = false;

            var dateStart = new moment().set({ 'year': this.model.get('year'), 'week': this.model.get('week'), 'day': 'mon' }).format('YYYY-MM-DD');
            var dateEnd = new moment().set({ 'year': this.model.get('year'), 'week': this.model.get('week'), 'day': 'mon' }).add(1,'week').format('YYYY-MM-DD');
            opt.filterBy['[Times].[Week]'] = {
                Type: 'DATE',
                Values: [dateStart, dateEnd],
                Name: "week",
            };
            snbe.find("[data-cube-filter]").each(function (i, e) {
                anyFilters = true;
                var elem = $(e);
                var type = elem.data("cube-filter").toUpperCase();
                var name = elem.data("cube-filter-name");
                var propName = elem.data("cube-filter-prop-name");
                var query = elem.data("cube-filter-query");

                var values = [];
                    values = [that.model.get(propName)];
                if (values[0] != -1) {
                    opt.filterBy[query] = {
                        Type: (type) ? type : 'DEFAULT',
                        Values: values,
                        Name: name,
                    };
                }
            });

            if (anyFilters) {

                this.model.get("cuberows").fetch(_.extend(opt, {
                    refresh: true,
                    set: true,
                    callback: function (a, b) {
                        //that.grayResults(false);
                        if (b.Status == "FAILED") {
                            //that.grayResults(true);
                            app.views.topMessages.showMessage(app.translate(that, b.Message + "_MESSAGE"));
                        }
                    },
                }));
            }

            //this.refreshItems(opt, {
            //    groupBy: this.model.get('groupBy'),
            //    filterBy: {},
            //});

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

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refresh: function (viewParams) {
            var that = this;
            var fixedParams = _.extend({}, viewParams);

            //if (fixedParams.crewId) {
            //    fixedParams.crewId = ((fixedParams.crewId != '-') || (fixedParams.crewId != '-1'))
            //        ? (fixedParams.crewId.indexOf('[Id]') != -1)
            //            ? fixedParams.crewId
            //            : '[Crews].[Id].&[' + fixedParams.crewId + ']'
            //        : -1;
            //}
            if (fixedParams.furnaceCode) {
                fixedParams.furnaceCode = ((fixedParams.furnaceCode != '-') || (fixedParams.furnaceCode != '-1'))
                    ? (fixedParams.furnaceCode.indexOf('[Code]') != -1)
                        ? fixedParams.furnaceCode
                        : '[Furnaces].[Code].&[' + fixedParams.furnaceCode + ']'
                    : -1;
            }
            if (fixedParams.productTypeId) {
                fixedParams.productTypeId = (fixedParams.productTypeId != '-')
                    ? (fixedParams.productTypeId.indexOf('[Id]') != -1)
                        ? fixedParams.productTypeId
                        : '[Product Types].[Id].&[' + fixedParams.productTypeId + ']'
                    : -1;   
            }

            this.model.set(fixedParams);


            

            this._refresh({
                reset: true,
                params: _.extend(
                    {},
                    fixedParams
                )
            });
        },
        exportToExcel: function (e) {
            try {
                this.setExportButtonExporting(true);

                var that = this;
                var customPath = "/app/custom-screens/kpi-weekly/";
                var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                    chari = 0,
                    chari2 = 0,
                    chari3 = 0,
                    chari4 = 0,
                    chari5 = 0,
                    chari6 = 0,
                    chari7 = 0,
                    chari8 = 0;

                var snbe = this.$el.find('.subnavbar');

                var opt = {
                    groupBy: this.model.get("groupBy"),
                    filterBy: {},
                };


                var dateStart = new moment().set({ 'year': this.model.get('year'), 'week': this.model.get('week'), 'day': 'mon' }).format('YYYY-MM-DD');
                var dateEnd = new moment().set({ 'year': this.model.get('year'), 'week': this.model.get('week'), 'day': 'mon' }).add(1, 'week').format('YYYY-MM-DD');
                opt.filterBy['[Times].[Week]'] = {
                    Type: 'DATE',
                    Values: [dateStart, dateEnd],
                    Name: "week",
                };

                var anyFilters = false;
                snbe.find("[data-cube-filter]").each(function (i, e) {
                    anyFilters = true;
                    var elem = $(e);
                    var type = elem.data("cube-filter").toUpperCase();
                    var name = elem.data("cube-filter-name");
                    var propName = elem.data("cube-filter-prop-name");
                    var query = elem.data("cube-filter-query");

                    var values = [];
                    values = [that.model.get(propName)];
                    if (values[0] != -1) {
                        opt.filterBy[query] = {
                            Type: (type) ? type : 'DEFAULT',
                            Values: values,
                            Name: name,
                        };
                    }
                });


                $.ajax(
                    app.foldersRoot + customPath + "cube-api/cube-api.aspx",
                    {
                        type: 'POST',
                        data: {
                            action: 'EXPORTEXCEL',

                            groupby: JSON.stringify(opt.groupBy),
                            filterby: JSON.stringify(opt.filterBy),
                            rowsStartIndex: 0,
                            rowsCount: 100000,

                            exportParams: JSON.stringify({
                                Data: [
                                    {
                                        SheetName: 'EAF Usage',
                                        RowsData: [{
                                            CellsData: [
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Week',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Shift',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Heats (#)',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Steel (tons)',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Energy (Kwh)',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Oxygen (scf)',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Gas (scf)',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Carbon (lbs)',
                                                },
                                                {
                                                    Column: chars[chari++],
                                                    Value: 'Lime (lbs)',
                                                },
                                                
                                            ]

                                        }],
                                        StartRowIndex: 1,
                                    },
                                    {
                                        SheetName: 'EAF Usage',
                                        RowsData: [],
                                        StartRowIndex: 2,
                                        DataSourceName: 'data',
                                        DataSourceTableIndex: 0,
                                        CubeCellsData: [
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Time].[Week].[Week].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Measures].[Heats Count]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Measures].[Steel Weight Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Measures].[Energy Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Measures].[Oxygen Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Measures].[Natural Gas Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Measures].[Carbon Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari2++],
                                                CubeDataColumnName: '[Measures].[Lime Avg]',
                                                DataType: 'String',
                                            },
                                        ],
                                    },
                                    {
                                        SheetName: 'EAF Cost Per Ton',
                                        RowsData: [{
                                            CellsData: [
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Week',
                                                },
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Shift',
                                                },
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Energy (USD)',
                                                },
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Oxygen (USD)',
                                                },
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Gas (USD)',
                                                },
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Carbon (USD)',
                                                },
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Lime (USD)',
                                                },
                                                {
                                                    Column: chars[chari3++],
                                                    Value: 'Total (USD)',
                                                },
                                            ]
                                        }],
                                        StartRowIndex: 1,
                                    },
                                    {
                                        SheetName: 'EAF Cost Per Ton',
                                        RowsData: [],
                                        StartRowIndex: 2,
                                        DataSourceName: 'data',
                                        DataSourceTableIndex: 0,
                                        CubeCellsData: [
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Time].[Week].[Week].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Measures].[Energy Per Ton Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Measures].[Oxygen Per Ton Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Measures].[Natural Gas Perton Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Measures].[Carbon Per Ton Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Measures].[Lime Per Ton Avg]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari4++],
                                                CubeDataColumnName: '[Measures].[Total Cost Per Ton Avg]',
                                                DataType: 'String',
                                            },
                                        ],
                                    },
                                    {
                                        SheetName: 'EAF Slag',
                                        RowsData: [{
                                            CellsData: [
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'Week',
                                                },
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'Shift',
                                                },
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'Heats (#)',
                                                },
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'Samples (#)',
                                                },
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'Samples (%)',
                                                },
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'Fe2O3',
                                                },
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'MgO',
                                                },
                                                {
                                                    Column: chars[chari5++],
                                                    Value: 'B3',
                                                },
                                            ]
                                        }],
                                        StartRowIndex: 1,
                                    },
                                    {
                                        SheetName: 'EAF Slag',
                                        RowsData: [],
                                        StartRowIndex: 2,
                                        DataSourceName: 'data',
                                        DataSourceTableIndex: 0,
                                        CubeCellsData: [
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Time].[Week].[Week].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Measures].[Heats Count]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Measures].[Slag Samples Count]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Measures].[Slag Heats Percentage]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Measures].[Slag Fe2O3]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Measures].[Slag Mg O]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari6++],
                                                CubeDataColumnName: '[Measures].[Slag B3ratio]',
                                                DataType: 'String',
                                            },
                                        ],
                                    },
                                    {
                                        SheetName: 'EAF Tap Temp',
                                        RowsData: [{
                                            CellsData: [
                                                {
                                                    Column: chars[chari7++],
                                                    Value: 'Week',
                                                },
                                                {
                                                    Column: chars[chari7++],
                                                    Value: 'Shift',
                                                },
                                                {
                                                    Column: chars[chari7++],
                                                    Value: 'T>3000 (#)',
                                                },
                                                {
                                                    Column: chars[chari7++],
                                                    Value: 'T>3000 (%)',
                                                },

                                            ]
                                        }],
                                        StartRowIndex: 1,
                                    },
                                    {
                                        SheetName: 'EAF Tap Temp',
                                        RowsData: [],
                                        StartRowIndex: 2,
                                        DataSourceName: 'data',
                                        DataSourceTableIndex: 0,
                                        CubeCellsData: [
                                            {
                                                ExcelColumnName: chars[chari8++],
                                                CubeDataColumnName: '[Time].[Week].[Week].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari8++],
                                                CubeDataColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari8++],
                                                CubeDataColumnName: '[Measures].[Tap Temperatures Count]',
                                                DataType: 'String',
                                            },
                                            {
                                                ExcelColumnName: chars[chari8++],
                                                CubeDataColumnName: '[Measures].[Tap Temperatures Percentage]',
                                                DataType: 'String',
                                            },
                                        ],
                                    },
                                ],
                                //ExportMethod: 1,
                                FileName: 'kpis weekly',
                                TemplateFileFullPath: 'kpi-weekly.xls',
                            }),
                        },
                        dataType: "json",
                        success: 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.setExportButtonExporting(false);
                        },
                        error: function (resp) {
                            that.setExportButtonExporting(false);
                            console.error(resp);
                        },
                    }
                );
            }
            catch (Error) { console.error(Error); }
        },
        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);
            }
        },
        //filtersChanged: _.debounce(function () {
        //    this.anyFilterChanged();
        //    //this.checkGroupBy();
        //}, 300)
        //, anyFilterChanged: function () {
        //    if (this.firstTime) {
        //        this.firstTime = false;
        //        var viewParams = this.model.toJSON();
        //        this.refresh(viewParams);
        //    } else {
        //        this.grayResults(true);
        //    }
        //},
        //grayResults: function (v) {
        //    var grid = this.$el.find(".items-grid-container");
        //    grid[(v) ? "addClass" : "removeClass"]("grayout");
        //    grid[(v) ? "removeClass" : "addClass"]("table-hover");
        //},
        //groupByChanged: _.debounce(function () {
        //    var that = this;
        //    this.anyFilterChanged();
        //}, 300),

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

            this.viewParams = viewParams;

            var thatContainer = (this.container) ? this.container : container;
            this.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.i18n) that.i18n = {};

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

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

                            that.applyBindings();

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

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


                            var grid = that.grids.EafCost = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_cost_crew_col'),
                                        cubeColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'energyPerTon',
                                        label: app.translate([that, app], 'eaf_cost_energy_col'),
                                        cubeColumnName: '[Measures].[Energy Per Ton Avg]',
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'energyPerTonMin',
                                            maxProp: 'energyPerTonMax',
                                            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: 'oxygenPerTon',
                                        label: app.translate([that, app], 'eaf_cost_oxygen_col'),
                                        cubeColumnName: '[Measures].[Oxygen Per Ton Avg]',
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'oxygenPerTonMin',
                                            maxProp: 'oxygenPerTonMax',
                                            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: 'naturalGasPerTon',
                                        label: app.translate([that, app], 'eaf_cost_natural_gas_col'),
                                        cubeColumnName: '[Measures].[Natural Gas Per Ton Avg]',
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'naturalGasPerTonMin',
                                            maxProp: 'naturalGasPerTonMax',
                                            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: 'carbonPerTon',
                                        label: app.translate([that, app], 'eaf_cost_carbon_col'),
                                        cubeColumnName: '[Measures].[Carbon Per Ton Avg]',
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'carbonPerTonMin',
                                            maxProp: 'carbonPerTonMax',
                                            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: 'limePerTon',
                                        label: app.translate([that, app], 'eaf_cost_lime_col'),
                                        cubeColumnName: '[Measures].[Lime Per Ton Avg]',
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'limePerTonMin',
                                            maxProp: 'limePerTonMax',
                                            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'),
                                        cubeColumnName: '[Measures].[Total Cost Per Ton Avg]',
                                        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.model.get('cuberows'),
                            });
                            that.$el.find('.eaf-cost-grid-container').append(that.grids.EafCost.render().el);

                            var grid = that.grids.EafSlag = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_slag_crew_col'),
                                        cubeColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                        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'),
                                        cubeColumnName: '[Measures].[Heats Count]',
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagSamplesCount',
                                        label: app.translate([that, app], 'eaf_slag_samples_count_col'),
                                        cubeColumnName: '[Measures].[Slag Samples Count]',
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'integer-cell align-center-cell',
					    decimals: 0,
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagHeatsPercentage',
                                        label: app.translate([that, app], 'eaf_slag_samples_percentage_col'),
                                        cubeColumnName: '[Measures].[Slag Heats Percentage]',
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).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)]);
                                            },
					    decimals: 2,
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'slagFe2O3',
                                        label: app.translate([that, app], 'eaf_slag_Fe2O3_col'),
                                        cubeColumnName: '[Measures].[Slag Fe 2O3 Avg]',
                                        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'),
                                        cubeColumnName: '[Measures].[Slag Mg O Avg]',
                                        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'),
                                        cubeColumnName: '[Measures].[Slag B3ratio Avg]',
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'numeric-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.model.get('cuberows'),
                            });
                            that.$el.find('.eaf-slag-grid-container').append(that.grids.EafSlag.render().el);

                            var grid = that.grids.EafTapTemp = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_tap_temp_crew_col'),
                                        cubeColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                            formatter: Backgrid.Extension.I18CellFormatter.extend({
                                                i18n: app,
                                                i18nSources: [that, app],
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'tapTemperaturesCount',
                                        label: app.translate([that, app], 'eaf_tap_temp_temperatures_count_col'),
                                        cubeColumnName: '[Measures].[Tap Temperatures Count]',
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'tapTemperaturesPercentage',
                                        label: app.translate([that, app], 'eaf_tap_temp_temperatures_percentage_col'),
                                        cubeColumnName: '[Measures].[Tap Temperatures Percentage]',
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                            className: 'integer-cell align-center-cell',
                                            minProp: 'tapTemperaturesPercentageMin',
                                            maxProp: 'tapTemperaturesPercentageMax',
                                            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)]);
                                            },
					    decimals: 2,
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.model.get('cuberows'),
                            });
                            that.$el.find('.eaf-tap-temp-grid-container').append(that.grids.EafTapTemp.render().el);

                            var grid = that.grids.EafUsage = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'crewId',
                                        label: app.translate([that, app], 'eaf_usage_crew_col'),
                                        cubeColumnName: '[Crews].[Id].[Id].[MEMBER_CAPTION]',
                                        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'),
                                        cubeColumnName: '[Measures].[Heats Count]',
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'steelWeight',
                                        cubeColumnName: '[Measures].[Steel Weight Avg]',
                                        label: app.translate([that, app], 'eaf_usage_steel_weight_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'energy',
                                        cubeColumnName: '[Measures].[Energy Avg]',
                                        label: app.translate([that, app], 'eaf_usage_energy_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'oxygen',
                                        cubeColumnName: '[Measures].[Oxygen Avg]',
                                        label: app.translate([that, app], 'eaf_usage_oxygen_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'naturalGas',
                                        cubeColumnName: '[Measures].[Natural Gas Avg]',
                                        label: app.translate([that, app], 'eaf_usage_natural_gas_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'carbon',
                                        cubeColumnName: '[Measures].[Carbon Avg]',
                                        label: app.translate([that, app], 'eaf_usage_carbon_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'lime',
                                        cubeColumnName: '[Measures].[Lime Avg]',
                                        label: app.translate([that, app], 'eaf_usage_lime_col'),
                                        cell: Backgrid.IntegerCell.extend({
                                            className: 'integer-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                ],
                                collection: that.model.get('cuberows'),
                            });
                            that.$el.find('.eaf-usage-grid-container').append(that.grids.EafUsage.render().el);

                            var grid = that.grids.LmfCost = 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(that.grids.LmfCost.render().el);

                            var grid = that.grids.LmfSuperHeats = 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(that.grids.LmfSuperHeats.render().el);

                            var grid = that.grids.LmfUsage = 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(that.grids.LmfUsage.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.crewId) {
                            //    fixedParams.crewId = (fixedParams.crewId != '-') ? '[Crews].[Id].&[' + fixedParams.crewId + ']' : -1;
                                   
                            //}
                                
                            if (fixedParams.furnaceCode) {
                                fixedParams.furnaceCode = (fixedParams.furnaceCode != '-') ? '[Furnaces].[Code].&[' + fixedParams.furnaceCode + ']' : -1;
                            }
                                
                            if (fixedParams.productTypeId) {
                                fixedParams.productTypeId = (fixedParams.productTypeId != '-') ? '[Product Types].[Id].&[' + fixedParams.productTypeId + ']' : -1;
                            }
                                

                            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, );
        //    _.extend(opt.params, {
        //        year: attrs.year,
        //        week: attrs.week,
        //    });
                

        //    if ((opt.refresh == true) || (opt.reset == true))
        //        this.model.set('isLoading', true);
            
        //    this.eafKpiWeeklyColl.fetch(_.extend(opt));            
        //},

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

                var furnaceCode = _.findWhere(params.furnaces, {value: params.furnaceCode });
                //var crewId = _.findWhere(params.crews, { value: params.crewId });
                var productTypeId = _.findWhere(params.productTypes, { value: params.productTypeId });

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                year: params.year,
                                week: params.week,
                                //crewId: (params.crewId != -1) ? crewId.key : '-',
                                furnaceCode: (params.furnaceCode != -1) ? furnaceCode.key : '-',
                                productTypeId: (params.productTypeId != -1) ? productTypeId.key : '-',
                            }
                        ),
                        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.state == app.view_states.loading
                || this.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

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

                this.onappend(this);
            }

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

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

        },
        close: function () {
            this.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.state = app.view_states.shown;

            this.showSubviews();
            this.bindEvents();
            this.$el.show();
        },
        showSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.show();
            });
        },
        hide: function () {
            this.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,
            furnaceCode: 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,
                    furnaceCode: obj.furnaceCode,
                };

                _.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;


    //            return true;
    //        }

    //        return false;
    //    },
    });

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