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

  "modules/modal",

  "backgrid",

  "modules/dateTimeControl",
  "modules/dateControl",

  "moment",
  'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',
  'backgrid/infinator',
  'backgrid/calendar-cell',
  'backgrid/time-cell',
  'js/jquery.timepicker/jquery.timepicker',
  //'js/typeahead.extended/typeahead.extended',

  'backgrid/time-cell', //Depends on the time jquery.timepicker
],

function (app, T, Modal, Backgrid, DateTimeControl, DateControl, moment) {

    //replace all "ScrapUsage" with your view's name.
    var Screen = { Models: {}, Views: {}, Collections: {} }

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            from: new moment().format('YYYY-MM-DD'),
            to: new moment().format('YYYY-MM-DD'),
            time: '09:00:00',
            isLoading: false,
        },
        computeds: {
            from$: {
                deps: ['from'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { from: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            to$: {
                deps: ['to'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { to: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
        },
        initialize: function () {
            this.attributes.items = new Screen.Collections.ScrapUsageRows();
        }, 
    });

    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return "scrap-usage-summary"; 
        } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
    }

    Screen.Models.ScrapUsageRow = Backbone.Model.extend({
        defaults: {
            date: null,
            crew: null,
            shift: null,
            recipeCost: null,
            recipeTons: null,
            recipeCostPerTon: null,
            actualChargedTons: null,
            actualChargedCost: null,
            actualChargedCostPerTon: null,
            //dynamic fields
        }, 
    });

    Screen.Collections.ScrapUsageRows = Backbone.Collection.extend({
        model: Screen.Models.ScrapUsageRow,
        pageSize: 50,
        currentPage: 1,
        fixedParameters: [],
        isFetching: false,
        initialize: function (opt) {
            this.options = _.extend({}, this.options, {
            });
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },
        updateFixedParameters: function (params) {
            this.fixedParameters = [];

            for (var pName in params)
                this.fixedParameters.push({ name: pName, value: params[pName], type: 'VARCHAR', });
        },  
        fetch: function (opt) {
            var options = {
                async: true,
                callback: null,

            };

            options = _.extend(options, (opt) ? opt : {});

            var that = this,
                parentModel = this.options.parent,
                items = [],
                qp = new Core.Database.QueryParameters();

            this.isFetching = true;

            if (opt.reset)
                this.resetPagination(true);

            if ((opt.refresh) || (opt.reset))
                this.updateFixedParameters(opt.params);


            _.each(this.fixedParameters, function (qpParams) {
                qp.Add(qpParams.name, qpParams.type, qpParams.value);
            });

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

            Core.Json.CallProcedure(app.DatabaseNames.Scrapyard + ".SCRAP.GetScrapUsageSummary", qp, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        
                        var data = data.Table;
                        _.each(data, function (obj) {
                            var item = {
                                date: obj.Date,
                                shift: obj.Shift,
                                crew: obj.Crew,
                                recipeTons: obj.RecipeTons,
                                recipeCost: obj.RecipeCost,
                                recipeCostPerTon: obj.RecipeCostPerTon,
                                actualChargedTons: obj.ActualChargedTons,
                                actualChargedCost: obj.ActualChargedCost,
                                actualChargedCostPerTon: obj.ActualChargedCostPerTon,
                                deltaCostPerTon: obj.DeltaCostPerTon
                            };
                            items.push(item);
                        });

                        
                    }

                    var method = ((opt.refresh) || ((opt.reset))) ? 'set' : 'add';
                    that[method](items, { from: "fetch" });

                    that.isFetching = false;

                    if (options.callback != null && _.isFunction(options.callback)) {
                        options.callback.call(this, that);
                    }
                    
                        
                },
                Async: options.async,
                Secured: true,
            }, app.ConnectionStrings.app);

            return this;
        },
        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
    });


    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: "scrap-usage-summary"
        , id: "scrap-usage-summary"
        , title: "Scrap Usage Summary"
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        , isCacheable: false
        , bindings: 'data-bind'
        , events: {
        }

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

            if (this.options.viewParams) {
            }

            var model = new Screen.Models.Main({
            });

            this.options.MYREFERENCES = {
                subviews: {
                }
                , autoRefresh: {
                    enabled: false
                    , toid: null
                }
            };

            this.options.grids = {
                itemsGrid: null, 
            }; 

            this.model = model;

            this.itemColl = new Screen.Collections.ScrapUsageRows();

            this.options.MYREFERENCES.subviews.subnavbarControls = new Screen.Views.SubnavBarControls({
                parent: this
                , model: new Screen.Models.SubnavBarControls()
                , screenModel: this.model
                , container: app.views.subnavbar.getSectionContainer(1, 12)
                , onExportToExcel: _.bind(this.exportToExcel, this)
                , onRefresh: _.throttle(_.bind(function () {
                    try {
                        var params = this.options.MYREFERENCES.subviews.subnavbarControls.model.toJSON();
                        app.router.navigate(
                            app.router.resolveURL(
                                app.router.currentModule,
                                _.extend(
                                    {},
                                    params,
                                    {
                                        from: new moment(params.from,  'YYYY-MM-DD').format('YYYYMMDD'),
                                        to: new moment(params.to, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    }
                                ),
                                false
                            ),
                            { trigger: false, }
                        );
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    this._refresh({ showLoading: true });
                }, this), 500)
            });

            this.options.MYREFERENCES.subviews.subnavbarControls.render();

            this.bindEvents();
            //_.bindAll(this); //Comment bindall to prevent issues with epoxy
        },
        refresh: function (fixedParams) {
            if (fixedParams.from) {
                fixedParams.from = new moment(fixedParams.from, 'YYYYMMDD').format('YYYY-MM-DD');
            }
            if (fixedParams.to) {
                fixedParams.to = new moment(fixedParams.to, 'YYYYMMDD').format('YYYY-MM-DD');
            }

            this.options.MYREFERENCES.subviews.subnavbarControls.model.set(fixedParams);
        },
        render: function (container, viewParams) {
            var that = this;
            this.viewParams = viewParams;
            var thatContainer = (container != null && container != undefined) ? container : this.options.container;
            //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/scrapyard/scrap-usage-summary/";

            T.render.call(this, this.template, function (tmp) {
                //getInternationalizationData
                if (!that.options.i18n) that.options.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    //storing internationalization data
                    that.options.i18n[that.template] = i18nJED;
                    that.$el.html(tmp());

                    that.applyBindings();

                    var columns = [
                        {
                            name: "date",
                            label: app.translate(that, "date_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell timestamp-cell date-cell timestamp-date date',
                                formatter: Backgrid.Extension.DatetimeToDateFormatter.extend({
                                    columnName: 'date',
                                    displayFormat: app.translate([that, app], 'MM/DD/YYYY'),
                                    modelDateFormat: 'YYYY-MM-DD',
                                }),
                                editor: Backgrid.Extension.CalendarCellEditor.extend({
                                    dateFormat: 'mm/dd/yy',
                                    momentFormat: app.translate([that, app], 'mmddyyyy'),
                                }),
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'date'
                            }),
                        },
                        {
                            name: "shift",
                            label: app.translate(that, "shift_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell shift",
                            }),
                            headerCell: Backgrid.HeaderCell.extend({

                                className: 'shift'
                            }),
                        },

                        {
                            name: "recipeTons",
                            label: app.translate(that, "recipeTons_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                className: 'recipeTons align-right-cell'
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'recipeTons align-center-cell'
                            }),
                        },
                        {
                            name: "actualChargedTons",
                            label: app.translate(that, "actualChargedTons_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                className: 'actualChargedTons align-right-cell'
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'actualChargedTons '
                            }),
                        },
                        {
                            name: "recipeCost",
                            label: app.translate(that, "recipeCost_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                className: 'recipeCost align-right-cell'
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'recipeCost '
                            }),
                        },
                        {
                            name: "actualChargedCost",
                            label: app.translate(that, "actualChargedCost_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                                className: 'integer-cell align-right-cell no-max-cell actualChargedCost',
                                maxProp: 'recipeCost',
                                invalidMaxMessage: function (value, limit, includeLimit) {
                                    return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                },
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'actualChargedCost '
                            }),
                        },
                        {
                            name: "recipeCostPerTon",
                            label: app.translate(that, "recipeCostPerTon_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                className: 'recipeCostPerTon align-right-cell'
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'recipeCostPerTon '
                            }),
                        },
                        {
                            name: "actualChargedCostPerTon",
                            label: app.translate(that, "actualCostPerTon_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                className: 'number-cell align-right-cell no-max-cell actualChargedCostPerTon',
                                maxProp: 'recipeCostPerTon',

                                invalidMaxMessage: function (value, limit, includeLimit) {
                                    return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                },
                                decimals: 2,
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'actualChargedCostPerTon '
                            }),
                        },
                        {
                            name: "deltaCostPerTon",
                            label: app.translate(that, "deltaCostPerTon_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                className: 'deltaCostPerTon align-right-cell',
                                decimals: 2,
                            }),
                            headerCell: Backgrid.HeaderCell.extend({
                                className: 'deltaCostPerTon '
                            }),
                        },
                    ];

                    // Initialize a new Grid instance
                    var items_grid;
                    items_grid = that.options.grids.itemsGrid = new Backgrid.Grid({
                        //row: CustomRow, 
                        className: "backgrid table table-hover",
                        columns: columns,
                        collection: that.model.get("items"),
                        footer: Backgrid.Extension.Infinator.extend({
                            scrollToTop: false,
                        }),
                    });

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

                    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.from) {
                        fixedParams.from = new moment(fixedParams.from, 'YYYYMMDD').format('YYYY-MM-DD');
                    }
                    if (fixedParams.to) {
                        fixedParams.to = new moment(fixedParams.to, 'YYYYMMDD').format('YYYY-MM-DD');
                    }

                    that.options.MYREFERENCES.subviews.subnavbarControls.model.set(fixedParams);

                    //that._startAutoRefresh({ showLoading: true, refresh: true });
                    that._refresh({
                        showLoading: true,
                    });
                }, true, customPath);
            }, customPath, "main_template");
        }
        , _startAutoRefresh: function (opt) {
            try {
                if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                    clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                    this.options.MYREFERENCES.autoRefresh.toid = null;
                }

                this.options.MYREFERENCES.autoRefresh.enabled = true;

                this._autoRefresh(opt);
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }

        , _autoRefresh: function (opt) {
            var that = this; 
            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                this.options.MYREFERENCES.autoRefresh.toid = null;
            }

            this._refresh(_.extend({}, opt, {
                callback: function () {

                }, 
            }));
        }

        , _stopAutoRefresh: function () {
            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                this.options.MYREFERENCES.autoRefresh.toid = null;
            }
            this.options.MYREFERENCES.autoRefresh.enabled = false;
        }

        , _refresh: function (opt) {
            try {
                var that = this;
                var fetched = false; 

                if (opt && opt.showLoading) {
                    setTimeout(function () {
                        if (!fetched) that.showLoading(true);
                    }, 500);
                }

                var from = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("from"),
                    "YYYY-MM-DD"); 
                var to = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("to"),
                    "YYYY-MM-DD");

                this.model.get("items").fetch(
                    {
                        params: {
                            from: from.format("YYYY-MM-DD") + ' 09:00:00',
                            to: to.format("YYYY-MM-DD") + ' 09:00:00',
                        },
                        callback: function (a, r) {
                            fetched = true;
                            isFetching = false;
                            //that.addRemoveMaterialColumns(); 
                            that.showLoading(false);
                        },
                        reset: true,

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

        , exportToExcel: function () {
            var that = this;

            this.options.MYREFERENCES.subviews.subnavbarControls.setExportButtonExporting(true);

                var from = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("from"));
                var to = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("to"));

                var from = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("from"),
                                    "YYYY-MM-DD");
                var to = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("to"),
                    "YYYY-MM-DD");

                var params = [
                    { Name: '@from', Type: 'DATETIME', Value: from.format("YYYY-MM-DD"), },
                    { Name: '@to', Type: 'DATETIME', Value: to.format("YYYY-MM-DD"), },
                ];

                var QP = new QueryParameters();

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

                var cellsData = [
                    { Column: "A", Value: "Date" },
                    { Column: "B", Value: "Shift" },
                    { Column: "C", Value: "Recipe Weight (Tons)" },
                    { Column: "D", Value: "Actual Charged Weight (Tons)" },
                    { Column: "E", Value: "Recipe Cost (USD)" },
                    { Column: "F", Value: "Actual Charged Cost (USD)" },
                    { Column: "G", Value: "Recipe Cost Per Weight (USD / Tons)" },
                    { Column: "H", Value: "Actual Charged Cost Per Weight (USD / Tons)" },
                    { Column: "I", Value: "Delta Cost Per Weight (USD / Tons)" },
                ];

                var SQLCellsData = [
                    { ExcelColumnName: 'A', SQLDataColumnName: 'Date', DataType: 'String' },
                    { ExcelColumnName: 'B', SQLDataColumnName: 'Shift', DataType: 'String' },
                    { ExcelColumnName: 'C', SQLDataColumnName: 'RecipeTons', DataType: 'Float' },
                    { ExcelColumnName: 'D', SQLDataColumnName: 'ActualChargedTons', DataType: 'Float' },
                    { ExcelColumnName: 'E', SQLDataColumnName: 'RecipeCost', DataType: 'Float' },
                    { ExcelColumnName: 'F', SQLDataColumnName: 'ActualChargedCost', DataType: 'Float' },
                    { ExcelColumnName: 'G', SQLDataColumnName: 'RecipeCostPerTon', DataType: 'Float' },
                    { ExcelColumnName: 'H', SQLDataColumnName: 'ActualChargedCostPerTon', DataType: 'Float' },
                    { ExcelColumnName: 'I', SQLDataColumnName: 'DeltaCostPerTon', DataType: 'Float' },
                ];

                Core.Export.Excel({
                    Data: [
                        {
                            SheetName: 'Data',
                            RowsData: [{
                                CellsData: cellsData
                            }],
                            StartRowIndex: 1,
                        },
                        {
                            SheetName: 'Data',
                            RowsData: [],
                            StartRowIndex: 2,
                            DataSourceName: 'data',
                            DataSourceTableIndex: 0,
                            SQLCellsData: SQLCellsData
                        }
                    ],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'scrap-usage-summary',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.Scrapyard + '.SCRAP.GetScrapUsageSummary',
                                QueryParameters: QP,
                            },
                        },
                    ]
                }, function (resp) {
                    try {
                        if ((resp) && (resp.Success == true) && (resp.Data)) {
                            location.href = app.foldersRoot + '/excel/' + resp.Data;
                        }
                        else {
                            if ((resp) && (resp.Message))
                                console.error(resp.Message);
                            else
                                console.error('Server response not valid.');
                        }
                    }
                    catch (Error) { console.error(Error); }
                    that.options.MYREFERENCES.subviews.subnavbarControls.setExportButtonExporting(false);
                }, function (resp) {
                    that.options.MYREFERENCES.subviews.subnavbarControls.setExportButtonExporting(false);
                    console.error(resp);
                });

        }

        , showLoading: function (val) {
            var loadingPoster = this.$el.find(".loading-poster"); 
            var gridContainer = this.$el.find(".items-grid-container"); 
            
            if (val) {
                gridContainer.addClass("hide");
                loadingPoster.removeClass("hide");
            } else {
                loadingPoster.addClass("hide");
                gridContainer.removeClass("hide"); 
            }
        }

        , filtersChanged: _.debounce(function(){
            this._autoRefresh({ showLoading: true, refresh: true }); 
        }, 500)

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

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

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

                this.options.onappend(this);
            }

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

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        }

        , 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
            var that = this;
            this.listenTo(this.model.get('items'), 'backgrid:rowclick', this.items_backgrid_rowclick);
            this.listenTo(this.model, 'change:itemId', this.model_change_itemId);
            //this.listenTo(this.options.MYREFERENCES.subviews.subnavbarControls.model, "change:from", this.filtersChanged);
            //this.listenTo(this.options.MYREFERENCES.subviews.subnavbarControls.model, "change:to", this.filtersChanged);
        }

        , bindViewScopedEvents: function () {
            var that = this; 
        }

        , unbindViewScopedEvents: function () {
            this._stopAutoRefresh(); 
        }

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

            this.closeSubviews(); 
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        }

        , closeSubviews: function () {
            _.each(this.options.MYREFERENCES.subviews, function (sview) {
                sview.close();
            });
        }

        , show: function () {
            this.options.state = app.view_states.shown;

            this.showSubviews(); 
            this.bindEvents();
            this.$el.show();
        }

        , showSubviews: function () {
            _.each(this.options.MYREFERENCES.subviews, function (sview) {
                sview.show();
            });
        }

        , hide: function () {
            this.options.state = app.view_states.hidden;

            this.hideSubviews();
            this._stopAutoRefresh(); 

            this.$el.hide();
            this.unbind();
            this.stopListening();
        }

        , hideSubviews: function () {
            _.each(this.options.MYREFERENCES.subviews, function (sview) {
                sview.hide();
            });
        }

        , preRender: function () {
            app.models.subnavbar.setAll(false);
            app.models.subnavbar.set("subnavbar", true);
            app.models.subnavbar.set("sections", "12");
        }

        , reRender: function () {
        }

    });

    Screen.Models.SubnavBarControls = Backbone.Epoxy.Model.extend({
        defaults: {
            from: null,
            to: null,
        },
        computeds: {
        }, 
        initialize: function () {
            var toDate = new Date(); 
            var fromDate = new Date(toDate);
            fromDate.setDate(toDate.getDate() - 7);

            this.set({
                from: new moment(fromDate).format("YYYY-MM-DD"),
                to: new moment(toDate).format("YYYY-MM-DD"),
            }, { silent: true });
        },
        bindings: 'data-bind',
        bindingSources: {
            fromTime: this.fromTime
        }
    }); 

    //subview for the subnavbar controls
    Screen.Views.SubnavBarControls = Backbone.Epoxy.View.extend({
        id: "scrap-usage-subnavbar-controls"
        , title: ""
        , template: "scrap-usage-summary"
        , bindings: 'data-bind'
        , bindingSources: null

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

            _.extend(this, options);

            if (this.options.viewParams) {
            }

            this.options.MYREFERENCES = {};

            this.options.viewModels = {
                fromDateControl: new DateControl.Model({
                    date: this.model.get("from"),
                }),
                toDateControl: new DateControl.Model({
                    date: this.model.get("to"),
                }),
            };

            this.bindingSources = {
                screen: this.screenModel,
            };

            this.bindEvents();
            //_.bindAll(this);
        },

        events: {
            "click .btn-export-to-excel": 'exportToExcel',
            "click .btn-refresh": 'refreshClicked',
            "click .btn-back": 'backBtn_click',
        },

        render: function (container, onComplete) {
            var that = this;
            var thatContainer = (container) ? container : (this.options.container) ? this.options.container : null;
            var onViewComplete = (onComplete) ? onComplete : function () { };

            //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/scrapyard/scrap-usage-summary/";

            T.render.call(this, this.template, function (tmp) {
                if (!that.options.i18n) that.options.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    //storing internationalization data
                    that.options.i18n[that.template] = i18nJED;

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

                    that.applyBindings();

                    var dc = new DateControl.Views.Main({
                        model: that.options.viewModels.fromDateControl,
                    });
                    dc.render(that.$el.find(".from-date-control-container"));

                    var dc = new DateControl.Views.Main({ model: that.options.viewModels.toDateControl });
                    dc.render(that.$el.find(".to-date-control-container"));

                    that.append(thatContainer, that.$el);
                }, true, customPath);
            }, customPath, "subnavbar_controls");
        }

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

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

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

                this.options.onappend(this);
            }

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

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        }

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

        , exportToExcel: function () {
            if (_.isFunction(this.options.onExportToExcel)) {
                this.options.onExportToExcel.call(this);
            }
        }

        , refreshClicked: function () {
            if (_.isFunction(this.options.onRefresh)) {
                this.options.onRefresh.call(this);
            }
        }

        , refresh: function () {
            try {

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

        , 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.model, "change:from change:to ", this.model_changed_pickers);
            this.listenTo(this.options.viewModels.fromDateControl, "change:date", this.fromToModelChanged);
            this.listenTo(this.options.viewModels.toDateControl, "change:date", this.fromToModelChanged);
        }

        , fromToModelChanged: function (model, value, opt) {
            try {
                if (!opt) opt = {};

                if ((!opt.from) && (opt.from != 'model')) {
                    this.model.set(
                        {
                            from: new moment(this.options.viewModels.fromDateControl.get("date"), "YYYY-MM-DD HH:mm:ss.SSS").format("YYYY-MM-DD"),
                            to: new moment(this.options.viewModels.toDateControl.get("date"), "YYYY-MM-DD HH:mm:ss.SSS").format("YYYY-MM-DD"),
                        },
                        {
                            from: 'datepickers',
                        }
                    );
                }
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }

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

            this.remove();
            this.unbind();
        }

        , show: function () {
            this.options.state = app.view_states.shown;

            this.bindEvents();
            this.$el.show();
        }

        , hide: function () {
            this.options.state = app.view_states.hidden;

            this.$el.hide();
            this.unbind();
            this.stopListening();
        }

        , reRender: function () {
        }

        , backBtn_click: function (e) {
            try {
                this.screenModel.set('itemId', null);
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }

        , model_changed_pickers: function (model, value, opt) {
            try {
                if (!opt) opt = {};

                if ((!opt.from) && (opt.from != 'datepickers')) {
                    this.options.viewModels.fromDateControl.set("date", this.model.get("from"), { from: 'model' });
                    this.options.viewModels.toDateControl.set("date", this.model.get("to"), { from: 'model' });
                }
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }
    });

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

});

