//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/jquery.floatThead/jquery.floatThead",
  'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',
  'js/jquery.timepicker/jquery.timepicker',
  //'js/typeahead.extended/typeahead.extended',
  'backgrid/infinator',
  'backgrid/time-cell', //Depends on the time jquery.timepicker
  'js/bootstrap-input-spinner/bootstrap-input-spinner',
  'js/autocomplete/backbone.autocomplete'
],

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

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

    ScrapUsage.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            itemId: null,
            items: null, 
            weights: null,
        },
        initialize: function () {
            this.attributes.items = new ScrapUsage.Collections.ScrapUsageRows();
        }, 
    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    ScrapUsage.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return "scrap-usage"; 
        } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
    }

    ScrapUsage.Models.ScrapUsageRow = Backbone.Model.extend({
        defaults: {
            id: null,
            heat: null,
            bucket: null,
            chargeNumber: null,
            scrapRecipe: null,
            chargeTimestamp: null,
            operator: null,
            furnace: null,
            crew: null,
            orderNumber: null,
            total: null,
            bucketTotalCost: null,
            recipeCost: null,
            shift: null,
            //dynamic fields
        }, 
    });

    ScrapUsage.Collections.ScrapUsageRows = Backbone.Collection.extend({
        model: ScrapUsage.Models.ScrapUsageRow,

        nextAddItems: [],
        remainingItems:[],
        pageSize: 50,

        initialize: function (opt) {
            this.options = _.extend({}, this.options, {
            });
        },
        comparator: function (a, b) {
            var aAttrs = a.toJSON(),
                bAttrs = b.toJSON(),
                aVal,
                bVal;


            //Sort depending if the row is the total row or not
            aVal = (aAttrs.heat + '').toUpperCase();
            bVal = (bAttrs.heat + '').toUpperCase();

            if (aVal != bVal) {
                if (aVal == 'TOTAL') return 1;
                else if (bVal == 'TOTAL') return -1;
            }


            //Sort by charge timestamp DESC
            aVal = new moment(aAttrs.chargeTimestamp, 'YYYY-MM-DD HH:mm:ss.SSS').toDate();
            bVal = new moment(bAttrs.chargeTimestamp, 'YYYY-MM-DD HH:mm:ss.SSS').toDate();
		
            if (aVal < bVal) return -1 * -1;
            else if (bVal < aVal) return 1 * -1;


            //Return equals
            return 0
        }, 
        fetch: function (opt) {
            var options = {
                method: (opt.params && opt.params.reset) ? "set" : "add",
                async: true,
                callback: null,
            };

            options = _.extend(options, (opt) ? opt : {});
            
            if (options.params && options.params.reset) {   
                this.resetPagination(true);
                var that = this,
                    QP = new Core.Database.QueryParameters(),
                    items = [];


                if (opt.params.shiftNavigation) {
                    QP.Add("From", "DATETIME", opt.params.fromDate);
                    QP.Add("ShiftId", "INT", opt.params.shiftId == 'D' ? 1 : (opt.params.shiftId == 'N' ? 2 : null));
                    QP.Add("TimeZoneCode", "CHAR(10)", app.models.user.get('timezoneCode'));

                } else {
                    QP.Add("From", "DATETIME", opt.params.from);
                    QP.Add("To", "DATETIME", opt.params.to);
                    QP.Add("TimeZoneCode", "CHAR(10)", app.models.user.get('timezoneCode'));
                }

                Core.Json.CallProcedure(app.DatabaseNames.Scrapyard + ".SCRAP.GetCharges", QP, {
                    onSuccess: function (data) {
                        if (data && data.Table && data.Table[0]) {
                            var status = data.Table[0].Status;
                            if (status == "OK") {
                                var data = data.Table1;
                                for (var i = 0; i < data.length; i++) {
                                    var itemData = data[i];
                                    var item = {
                                        id: itemData.ChargeId,
                                        heat: itemData.Heat,
                                        bucket: itemData.Bucket,
                                        chargeNumber: itemData.ChargeNumber,
                                        scrapRecipe: itemData.ScrapRecipe,
                                        chargeTimestamp: itemData.ChargeTimestamp,
                                        operator: itemData.Operator,
                                        furnace: itemData.Furnace,
                                        crew: itemData.Crew,
                                        orderNumber: itemData.OrderNumber,
                                        total: itemData.Total,
                                        bucketTotalCost: itemData.BucketTotalCost,
                                        recipeCost: itemData.RecipeCost,
                                        shift: itemData.Shift,
                                    };

                                    var dynamicfields = _.omit(itemData, ['ChargeId', 'Heat', 'Bucket', 'ChargeNumber', 'ScrapRecipe', 'ChargeTimestamp', 'Operator', 'Furnace', 'Crew', 'OrderNumber', 'Total', 'BucketTotalCost', 'RecipeCost','Shift']);
                                    item = _.extend(item, dynamicfields);

                                    items.push(item);
                                }
                            }
                        }

                        that.reset();

                        var firstItems = _.first(items, that.pageSize);

                        that.remainingItems = _.difference(items, firstItems);
                        that.nextAddItems = _.first(that.remainingItems, that.pageSize);
                        that.remainingItems = _.difference(that.remainingItems, that.nextAddItems);

                        that[options.method](firstItems, { from: "fetch" });

                        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) {
            this["add"](this.nextAddItems, { from: "fetch" });
            this.nextAddItems = _.first(this.remainingItems, this.pageSize);
            this.remainingItems = _.difference(this.remainingItems, this.nextAddItems);
        },
        resetPagination: function (force) {
            this.nextAddItems = [];
            this.remainingItems = [];
        },
    });

    ScrapUsage.Models.ScrapUsageDetailsRow = Backbone.Model.extend({
        defaults: {
            id: null,
            chargeId: null,
            layerOrder: null,
            scrapMaterialId: null,
            scrapMaterialName: null,
            weight: null,
        },

        parse: function (obj) {
            return {
                id: obj.Id,
                chargeId: obj.ChargeId,
                layerOrder: obj.LayerOrder,
                scrapMaterialId: obj.ScrapMaterialId,
                scrapMaterialName: obj.ScrapMaterialName,
                weight: obj.Weight,
            };
        },
    });

    ScrapUsage.Collections.ScrapUsageDetailsRows = Backbone.Collection.extend({
        model: ScrapUsage.Models.ScrapUsageDetailsRow,

        transaction_timestamp: null,

        fetch: function (opt) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                ttimestamp = this.transaction_timestamp = new Date().getTime(),
                options = opt ? _.clone(opt) : { async: true };

            qp.Add('@chargeId', 'INT', opt.params.chargeId);


            Core.Json.CallProcedure(
                app.DatabaseNames.Scrapyard + '.SCRAP.GetChargeDetails',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            //checking transaction timestamp
                            if (ttimestamp != that.transaction_timestamp)
                                return;

                            if ((resp) && (resp.Table)) {
                                var records = resp.Table,
                                    newColl;

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

                                //checking transaction timestamp
                                if (ttimestamp != that.transaction_timestamp)
                                    return;

                                that.set(newColl, { from: 'fetch' })
                                    .trigger('fetch', that, records);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error('Server response not valid.');
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: options.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
    });

    ScrapUsage.Views.Main = Backbone.Epoxy.View.extend({
        template: "scrap-usage"
        , id: "scrap-usage"
        , title: "ScrapUsage"
        //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
        , itemDetailsColl: 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 ScrapUsage.Models.Main({
            });

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

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

            this.model = model;

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


            this.itemDetailsColl = new ScrapUsage.Collections.ScrapUsageDetailsRows();
            var that = this;
            this.options.MYREFERENCES.subviews.subnavbarControls = new ScrapUsage.Views.SubnavBarControls({
                parent: this
                , model: new ScrapUsage.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,
                                    {
                                        start: new moment(params.from + " " + params.fromTime, 'YYYY-MM-DD HH:mm:ss').format('YYYYMMDDHHmmss'),
                                        end: new moment(params.to + " " + params.toTime, 'YYYY-MM-DD HH:mm:ss').format('YYYYMMDDHHmmss'),
                                    }
                                ),
                                false
                            ),
                            { trigger: false, }
                        );
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    this._refresh({
                        showLoading: true,

                    });
                    that.model.get("items").reset();

                }, this), 500)
            });

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

            this.bindEvents();
            //_.bindAll(this); //Comment bindall to prevent issues with epoxy
        },
        refresh: function (fixedParams) {
            if (fixedParams.start) {
                var start = new moment(fixedParams.start, 'YYYYMMDDHHmmss');
                fixedParams.from = start.format('YYYY-MM-DD');
                fixedParams.fromTime = start.format('HH:mm:ss');
            }
            if (fixedParams.end) {
                var end = new moment(fixedParams.end, 'YYYYMMDDHHmmss');
                fixedParams.to = end.format('YYYY-MM-DD');
                fixedParams.toTime = end.format('HH:mm:ss');
            }

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

            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: "id",
                            label: app.translate(that, "id"),
                            editable: false,
                            sortable: false,
                            renderable: false, 
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "heat",
                            label: app.translate(that, "heat_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "bucket",
                            label: app.translate(that, "bucket_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "chargeNumber",
                            label: app.translate(that, "chargeNumber_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "scrapRecipe",
                            label: app.translate(that, "scrapRecipe_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "chargeTimestamp",
                            label: app.translate(that, "chargeTimestamp_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "operator",
                            label: app.translate(that, "operator_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "furnace",
                            label: app.translate(that, "furnace_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },

                        {
                            name: "shift",
                            label: app.translate(that, "shift_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "crew",
                            label: app.translate(that, "crew_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "orderNumber",
                            label: app.translate(that, "orderNumber_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "bucketTotalCost",
                            label: app.translate(that, "bucketTotalCost_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                className: 'numeric-cell align-right-cell no-max-cell',
                                maxProp: 'recipeCost',

                                update: function () {
                                    var value = this.model.get(this.column.get('name')),
                                        max = this.model.get(this.maxProp);

                                    if (max != null && value > max) {
                                        var invMsg = app.translate([that, app], 'value_higher_than_recipe', [max]);

                                        this.$el.attr('title', invMsg)
                                            .addClass('maxRecipe-reached');
                                    } else {
                                        this.$el.attr('title', invMsg)
                                            .removeClass('maxRecipe-reached');
                                    }
                                },
                            }),
                        },
                        {
                            name: "recipeCost",
                            label: app.translate(that, "recipeCost_label"),
                            editable: false,
                            sortable: false,
                            renderable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "total",
                            label: app.translate(that, "total_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                    ];



                    // Initialize a new Grid instance
                    var items_grid;
                    items_grid  = that.options.grids.itemsGrid = new Backgrid.Grid({
                        className: "backgrid table table-hover scrap-usage-backgrid",
                        columns: columns,
                        collection: that.model.get("items"),
                        row: Backgrid.Row.extend({
                            highlightColor: "#ffee33",
                            events: function () {
                                return {
                                    'click': this.click,
                                };
                            },
                            click: function (e) {
                                try {
                                    this.model.trigger('backgrid:rowclick', this.model);
                                }
                                catch (Error) { console.error(Error.stack); }
                            },
                            render: function () {
                                Backgrid.Row.prototype.render.apply(this, arguments);

                                if (this.model.get('bucketTotalCost') > this.model.get('recipeCost')) {
                                    this.$el.attr('title', app.translate(that, "bucket_over_recipe"));
                                    this.$el.addClass('bucket-over-recipe');
                                } else {
                                    this.$el.removeClass('bucket-over-recipe');
                                }

                                return this;
                            }
                        }),
                        footer: Backgrid.Extension.Infinator.extend({
                            scrollToTop: false,
                        }),

                    });

                    //var container = that.$el.find(".items-grid-container");
                    ////container.find(".scrap-usage-backgrid").floatThead('destroy');

                    //container.empty();

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

                    //container.find(".scrap-usage-backgrid").floatThead({
                    //    scrollingTop: function () {
                    //        try {
                    //            return $(".fixed-subnavbar").height() + ($(".fixed-subnavbar").height() / 3);
                    //        } catch (error) { return 111; }
                    //    },
                    //    zIndex: 1000,
                    //    useAbsolutePositioning: false,
                    //});

                    items_grid = that.options.grids.itemGrid = new Backgrid.Grid({
                        className: "backgrid table table-hover",
                        columns: [
                            {
                                name: "id",
                                label: app.translate(that, "id"),
                                editable: false,
                                sortable: false,
                                renderable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "heat",
                                label: app.translate(that, "heat_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "bucket",
                                label: app.translate(that, "bucket_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "chargeNumber",
                                label: app.translate(that, "chargeNumber_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "scrapRecipe",
                                label: app.translate(that, "scrapRecipe_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "chargeTimestamp",
                                label: app.translate(that, "chargeTimestamp_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "operator",
                                label: app.translate(that, "operator_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "furnace",
                                label: app.translate(that, "furnace_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "crew",
                                label: app.translate(that, "crew_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "orderNumber",
                                label: app.translate(that, "orderNumber_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                }),
                            },
                            {
                                name: "total",
                                label: app.translate(that, "total_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    orderSeparator: '',
                                    className: "string-cell align-center-cell",
                                })
                            },
                            {
                                name: "bucketTotalCost",
                                label: app.translate(that, "bucketTotalCost_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.IntegerCell.extend({
                                    className: 'integer-cell align-right-cell no-max-cell'
                                })
                            },
                        ],
                        collection: that.itemColl,
                    });

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

                    items_grid = that.options.grids.itemDetailsGrid = new Backgrid.Grid({
                        className: "backgrid table table-hover",
                        columns: [
                            {
                                name: "layerOrder",
                                label: app.translate(that, "layerOrder_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.IntegerCell.extend({
                                    className: "integer-cell align-center-cell",
                                }),
                            },
                            {
                                name: "scrapMaterialName",
                                label: app.translate(that, "scrapMaterialName_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.StringCell.extend({
                                    className: "string-cell align-center-cell",
                                }),
                            },
                            {
                                name: "weight",
                                label: app.translate(that, "weight_label"),
                                editable: false,
                                sortable: false,
                                cell: Backgrid.NumberCell.extend({
                                    className: "numeric-cell align-center-cell",
                                }),
                            },
                        ],
                        collection: that.itemDetailsColl,
                    });

                    that.$el.find(".item-details-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.start) {
                        var start = new moment(fixedParams.start, 'YYYYMMDDHHmmss');
                        fixedParams.from = start.format('YYYY-MM-DD');
                        fixedParams.fromTime = start.format('HH:mm:ss');
                    }
                    if (fixedParams.end) {
                        var end = new moment(fixedParams.end, 'YYYYMMDDHHmmss');
                        fixedParams.to = end.format('YYYY-MM-DD');
                        fixedParams.toTime = end.format('HH:mm:ss');
                    }

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

                    //that._startAutoRefresh({ showLoading: true, refresh: true });
                    that._refresh({
                        showLoading: true,
                    });
                }, true, customPath);
            }, customPath, "main_template");
        },

        show_backgrid: function (){
            var container = this.$el.find(".items-grid-container");
            container.empty();

            container.append(this.options.grids.itemsGrid.render().el);

            var table = container.find(".scrap-usage-backgrid")
            table.floatThead({
                scrollingTop: function () {
                    try {
                        return $(".fixed-subnavbar").height() + ($("header").height()/2);
                    } catch (error) { return 111; }
                },
                zIndex: 500,
                useAbsolutePositioning: false,
            });

        }

        , refreshItemDetails: function (options) {
            var opt = _.extend({}, options, { params: {}, });

            this.model.set({
                hasItemData: false,
                isLoadingItemData: true,
            });


            var that = this,
                modelAttrs = this.model.toJSON();

            var itemId = (opt.params.id)
                                ? opt.params.id
                                : (modelAttrs.itemId)
                                    ? modelAttrs.itemId
                                    : null;


            this.itemColl.set([
                this.model.get('items').get(itemId),
            ]);


            this.itemDetailsColl.fetch({
                params: {
                    chargeId: itemId,
                },
                success: function () {
                    try {
                        that.model.set('isLoadingItemData', false);
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                },
                error: function (model, resp, opt) {
                    try {
                        that.model.set('isLoadingItemData', false);
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                }
            });
        }

        , _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 () {
                    if (that.options.MYREFERENCES.autoRefresh.enabled == true) {
                        that.options.MYREFERENCES.autoRefresh.toid = setTimeout(that._autoRefresh, 5000);
                    }
                }, 
            }));
        }

        , _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") + " " +
                    this.options.MYREFERENCES.subviews.subnavbarControls.model.get("fromTime"),
                    "YYYY-MM-DD HH:mm:ss"); 
                var to = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("to") + " " +
                    this.options.MYREFERENCES.subviews.subnavbarControls.model.get("toTime"),
                    "YYYY-MM-DD HH:mm:ss");

                var shiftId = this.options.MYREFERENCES.subviews.subnavbarControls.model.get("shiftId");
                var shiftNavigation = this.options.MYREFERENCES.subviews.subnavbarControls.model.get("shiftNavigation");


                this.model.get("items").fetch({
                    params: {
                        from: from.format("YYYY-MM-DD HH:mm:ss"),
                        to: to.format("YYYY-MM-DD HH:mm:ss"),
                        reset: true,
                        refresh: true,
                        shiftNavigation: shiftNavigation,
                        shiftId: shiftId,
                        fromDate: this.options.MYREFERENCES.subviews.subnavbarControls.model.get("from"),
                    },
                    callback: function (a, r) {
                        fetched = true;
                        that.addRemoveMaterialColumns(); 
                        that.show_backgrid();
                        that.showLoading(false);
                        if (opt && opt.callback && _.isFunction(opt.callback))
                            opt.callback.call(that, that);
                    },
                    refresh: (opt && opt.refresh) ? true : false,
                    set: true, 
                });

                

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

        , addRemoveMaterialColumns: function () {
            var that = this; 
            var items = this.model.get("items");
            var columns = that.options.grids.itemsGrid.columns;
            this.rowItems = [];

            

            var colsToDelete = [];
            var colsToAdd = []; 

            if (items.length > 0) {

                for (var i = 0; i < that.model.get('items').models.length; i++) {
                    this.rowItems.push(that.model.get('items').models[i].attributes);
                }

                var first = items.at(0); 
                var attrs = _.keys(first.attributes); 

                colsToAdd = _.filter(attrs, function (t) {
                    return columns.where({ name: t }).length == 0; 
                });

                colsToDelete = columns.filter(function (t) {
                    return _.indexOf(attrs, t.get("name")) == -1; 
                }); 

            } else {
                var default_keys = _.keys(ScrapUsage.Models.ScrapUsageRow.prototype.defaults); 
                colsToDelete = columns.filter(function (t) {
                    return _.indexOf(default_keys, t.get("name")) == -1; 
                }); 
                //colsToDelete = _.omit(columns, _.keys(ScrapUsage.Models.ScrapUsageRow.defaults));
            }

            _.each(colsToAdd, function(t) {
                if (t.indexOf('_max') == -1) {
                    that.options.grids.itemsGrid.insertColumn({
                        name: t,
                        label: app.translate(that, t),
                        editable: false,
                        sortable: false,
                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.IntegerCell).extend({
                            className: 'integer-cell align-center-cell',
                            maxProp: t + '_max' ,
                            invalidMaxMessage: function(value, limit, includeLimit) {
                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                            },
                        }),
                
                    }); 
                } 
            });

            _.each(colsToDelete, function (t) {
                that.options.grids.itemsGrid.removeColumn(t); 
            });
            //inserting total row
            if (items.length > 0) {
                var totalRow = {
                    heat: 'Total',
                    total: items.reduce(function (memo, value) { return memo + value.get("total"); }, 0),
                    bucketTotalCost: items.reduce(function (memo, value) { return memo + value.get("bucketTotalCost"); }, 0),
                    recipeCost: Infinity,
                };

                _.each(colsToAdd, function (t) {
                    //if column contains _max , remove of string with slice.
                    if (t.indexOf('_max') != -1) {
                        var str = t;
                        var t = str.slice(0, (str.length - 4));
                    }
                    if (!totalRow[t])
                        totalRow[t] = items.reduce(function (memo, value) { return memo + value.get(t); }, 0);

                });

                that.options.grids.itemsGrid.insertRow(totalRow);
            }

            //that.options.grids.itemsGrid.insertColumn({
            //    name: "TIRE WIRE",
            //    label: app.translate(that, "TIRE WIRE"),
            //    editable: false,
            //    sortable: false,
            //    cell: Backgrid.StringCell.extend({
            //        orderSeparator: '',
            //        className: "string-cell align-center-cell",
            //    })
            //});
        }

        , exportToExcel: function () {
            var that = this,
                itemId = this.model.get('itemId');

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

            if (itemId == null) {
                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") + " " +
                                    this.options.MYREFERENCES.subviews.subnavbarControls.model.get("fromTime"),
                                    "YYYY-MM-DD HH:mm:ss");
                var to = new moment(this.options.MYREFERENCES.subviews.subnavbarControls.model.get("to") + " " +
                    this.options.MYREFERENCES.subviews.subnavbarControls.model.get("toTime"),
                    "YYYY-MM-DD HH:mm:ss");



                var shiftId = this.options.MYREFERENCES.subviews.subnavbarControls.model.get("shiftId");
                var shiftNavigation = this.options.MYREFERENCES.subviews.subnavbarControls.model.get("shiftNavigation");
                var fromDate = this.options.MYREFERENCES.subviews.subnavbarControls.model.get("from");


                var QP = new QueryParameters();

                if (shiftNavigation) {
                    QP.Add("From", "DATETIME", fromDate);
                    QP.Add("ShiftId", "INT", shiftId == 'D' ? 1 : (shiftId == 'N' ? 2 : null));
                    QP.Add("TimeZoneCode", "CHAR(10)", app.models.user.get('timezoneCode'));

                } else {
                    var params = [
                        { Name: '@From', Type: 'DATETIME', Value: from.format("YYYY-MM-DD HH:mm:ss"), },
                        { Name: '@To', Type: 'DATETIME', Value: to.format("YYYY-MM-DD HH:mm:ss"), },
                        { Name: '@TimeZoneCode', Type: 'CHAR(10)', Value: app.models.user.get('timezoneCode'), },
                    ];

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

                var cellsData = [
                    { Column: "A", Value: "Heat" },
                    { Column: "B", Value: "Bucket" },
                    { Column: "C", Value: "Charge Number" },
                    { Column: "D", Value: "Scrap Recipe" },
                    { Column: "E", Value: "Charge Timestamp" },
                    { Column: "F", Value: "Operator" },
                    { Column: "G", Value: "Furnace" },
                    { Column: "H", Value: "Crew" },
                    { Column: "I", Value: "Order Number" },
                    { Column: "J", Value: "Bucket Total Cost" },
                    { Column: "K", Value: "Total" },
                ];

                var SQLCellsData = [
                    { ExcelColumnName: 'A', SQLDataColumnName: 'Heat', DataType: 'String' },
                    { ExcelColumnName: 'B', SQLDataColumnName: 'Bucket', DataType: 'String' },
                    { ExcelColumnName: 'C', SQLDataColumnName: 'ChargeNumber', DataType: 'String' },
                    { ExcelColumnName: 'D', SQLDataColumnName: 'ScrapRecipe', DataType: 'String' },
                    { ExcelColumnName: 'E', SQLDataColumnName: 'ChargeTimestamp', DataType: 'String' },
                    { ExcelColumnName: 'F', SQLDataColumnName: 'Operator', DataType: 'String' },
                    { ExcelColumnName: 'G', SQLDataColumnName: 'Furnace', DataType: 'String' },
                    { ExcelColumnName: 'H', SQLDataColumnName: 'Crew', DataType: 'String' },
                    { ExcelColumnName: 'I', SQLDataColumnName: 'OrderNumber', DataType: 'String' },
                    { ExcelColumnName: 'J', SQLDataColumnName: 'BucketTotalCost', DataType: 'Float' },
                    { ExcelColumnName: 'K', SQLDataColumnName: 'Total', DataType: 'Float' },
                ];

                var items = this.model.get("items");

                if (items.length > 0) {
                    var first = items.at(0);
                    var attrs = _.keys(first.attributes);
                    var default_keys = _.keys(ScrapUsage.Models.ScrapUsageRow.prototype.defaults);
                    var dynamicFields = _.filter(attrs, function (t) {
                        return _.indexOf(default_keys, t) == -1;
                    });

                    var dict = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

                    _.each(dynamicFields, function (t) {
                        var col = ((cellsData.length / dict.length) >= 1 ? dict[(Math.floor(cellsData.length / dict.length)) - 1] : "") + dict[cellsData.length % dict.length];
                        cellsData.push({
                            Column: col, Value: t
                        });

                        SQLCellsData.push({
                            ExcelColumnName: col, SQLDataColumnName: t, DataType: 'Float'
                        });
                    });
                }

                Core.Export.Excel({
                    Data: [
                        {
                            SheetName: 'Data',
                            RowsData: [{
                                CellsData: cellsData
                            }],
                            StartRowIndex: 1,
                        },
                        {
                            SheetName: 'Data',
                            RowsData: [],
                            StartRowIndex: 2,
                            DataSourceName: 'data',
                            DataSourceTableIndex: 1,
                            SQLCellsData: SQLCellsData
                        }
                    ],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'ScrapUsage',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.Scrapyard + '.SCRAP.GetCharges',
                                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);
                });
            }
            else {
                var item = this.model.get('items').get(itemId).toJSON();

                var QP = new QueryParameters();

                QP.Add("@chargeId", "INT", itemId);

                Core.Export.Excel({
                    Data: [
                        {
                            SheetName: 'Data',
                            RowsData: [{
                                CellsData: [
                                    { Column: "A", Value: "Heat" },
                                    { Column: "B", Value: "Bucket" },
                                    { Column: "C", Value: "Charge Number" },
                                    { Column: "D", Value: "Scrap Recipe" },
                                    { Column: "E", Value: "Charge Timestamp" },
                                    { Column: "F", Value: "Operator" },
                                    { Column: "G", Value: "Furnace" },
                                    { Column: "H", Value: "Crew" },
                                    { Column: "I", Value: "Order Number" },
                                    { Column: "J", Value: "Total" },
                                ],
                            }],
                            StartRowIndex: 1,
                        },
                        {
                            SheetName: 'Data',
                            RowsData: [],
                            StartRowIndex: 2,
                            DataSourceName: 'data',
                            DataSourceTableIndex: 1,
                            SQLCellsData: [
                                { ExcelColumnName: 'A', SQLDataColumnName: 'HeatNumber', DataType: 'String' },
                                { ExcelColumnName: 'B', SQLDataColumnName: 'Bucket', DataType: 'String' },
                                { ExcelColumnName: 'C', SQLDataColumnName: 'ChargeNumber', DataType: 'String' },
                                { ExcelColumnName: 'D', SQLDataColumnName: 'ScrapRecipe', DataType: 'String' },
                                { ExcelColumnName: 'E', SQLDataColumnName: 'ChargeTimestamp', DataType: 'String' },
                                { ExcelColumnName: 'F', SQLDataColumnName: 'Operator', DataType: 'String' },
                                { ExcelColumnName: 'G', SQLDataColumnName: 'Furnace', DataType: 'String' },
                                { ExcelColumnName: 'H', SQLDataColumnName: 'Crew', DataType: 'String' },
                                { ExcelColumnName: 'I', SQLDataColumnName: 'OrderNumber', DataType: 'String' },
                                { ExcelColumnName: 'J', SQLDataColumnName: 'TotWeight', DataType: 'Float' },

                            ]
                        },
                        //{
                        //    SheetName: 'Data',
                        //    RowsData: [{
                        //        CellsData: [
                        //            { Column: "A", Value: item.heat },
                        //            { Column: "B", Value: item.bucket },
                        //            { Column: "C", Value: item.chargeNumber },
                        //            { Column: "D", Value: item.scrapRecipe },
                        //            { Column: "E", Value: item.chargeTimestamp },
                        //            { Column: "F", Value: item.operator },
                        //            { Column: "G", Value: item.furnace },
                        //            { Column: "H", Value: item.crew },
                        //            { Column: "I", Value: item.orderNumber },
                        //            { Column: "J", Value: item.total },
                        //        ],
                        //    }],
                        //    StartRowIndex: 2,
                        //},
                        {
                            SheetName: 'Data',
                            RowsData: [{
                                CellsData: [
                                    { Column: "A", Value: "Order" },
                                    { Column: "B", Value: "Material" },
                                    { Column: "C", Value: "Weight" },
                                ],
                            }],
                            StartRowIndex: 4,
                        },
                        {
                            SheetName: 'Data',
                            RowsData: [],
                            StartRowIndex: 5,
                            DataSourceName: 'data',
                            DataSourceTableIndex: 0,
                            SQLCellsData: [
                                { ExcelColumnName: 'A', SQLDataColumnName: 'LayerOrder', DataType: 'String' },
                                { ExcelColumnName: 'B', SQLDataColumnName: 'ScrapMaterialName', DataType: 'String' },
                                { ExcelColumnName: 'C', SQLDataColumnName: 'Weight', DataType: 'Float' },
                            ]
                        }
                    ],
                    ConnectionStringName: 'APP',
                    ExportMethod:3,
                    FileName: 'ScrapUsageDetails',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.Scrapyard + '.SCRAP.GetChargeDetails',
                                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({ 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 () {
            this._startAutoRefresh(); 
        }


        , items_backgrid_rowclick: function (model) {
            try {
                this.model.set('itemId', model.get('id'));
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }
        , model_change_itemId: function (model, value, opt) {
            try {
                var params = this.model.toJSON();

                this.refreshItemDetails({
                    params: _.extend(
                        {},
                        params,
                        {}
                    ),
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }
    });

    ScrapUsage.Models.SubnavBarControls = Backbone.Epoxy.Model.extend({
        defaults: {
            from: null,
            to: null,
            fromTime: null,
            toTime: null,

            shiftNavigation: false,
            shiftId: 'D',
        },
        computeds: {
        }, 
        initialize: function () {
            var toDate = new Date(); 
            var fromDate = new Date(toDate);
            fromDate.setDate(toDate.getDate() - 1);

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

    //subview for the subnavbar controls
    ScrapUsage.Views.SubnavBarControls = Backbone.Epoxy.View.extend({
        id: "scrap-usage-subnavbar-controls"
        , title: ""
        , template: "scrap-usage"
        , 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',
            'click #searchViewBtn': 'searchViewBtn_click',
            'click #shiftViewBtn': 'shiftViewBtn_click',
            'click #backNavBtn': 'backNavBtn_click',
            'click #forwardNavBtn': 'forwardNavBtn_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/";

            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.$el.find('#fromTimePicker').timepicker({
                        showMeridian: false,
                        secondStep: 1,
                        minuteStep: 1,
                        showSeconds: true,
                    });
                    that.$el.find('#toTimePicker').timepicker({
                        showMeridian: false,
                        secondStep: 1,
                        minuteStep: 1,
                        showSeconds: true,
                    });

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

        , searchViewBtn_click: function () {
           var currentDate = this.model.get('from');

            this.model.set({
                shiftNavigation: false,
                to: new moment(currentDate, 'YYYY-MM-DD').add(1, 'day').format('YYYY-MM-DD'),
            })
            this.refreshClicked();
        }
        , shiftViewBtn_click: function () {
            this.model.set({
                shiftNavigation: true,
            })
            this.refreshClicked();
        }


        , backNavBtn_click: function () {
            var currentShift = this.model.get('shiftId'),
                currentDate = this.model.get('from');


            if (currentShift == 'N') this.model.set({ shiftId: 'D' });
            else {
                this.model.set({
                    shiftId: 'N',
                    from: new moment(currentDate, 'YYYY-MM-DD').subtract(1, 'day').format('YYYY-MM-DD'),

                });

            }
            this.refreshClicked();
        }
        , forwardNavBtn_click: function () {
            var currentShift = this.model.get('shiftId'),
                currentDate = this.model.get('from');

            if (currentShift == 'D') this.model.set({ shiftId: 'N' });
            else {
                this.model.set({
                    shiftId: 'D',
                    from: new moment(currentDate, 'YYYY-MM-DD').add(1, 'day').format('YYYY-MM-DD'),

                });

            }
            this.refreshClicked();
        }


        , 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:fromTime change:to change:toTime", 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 ScrapUsage;

});

