//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/base/base',
   'backgrid',
   'moment',
   'modules/eaf-process/eaf-process',

  'backgrid/computed-cell',
  'backgrid/duration-cell',
  'backgrid/infinator',
  'backgrid/moment-cell',
  'js/backgrid-0.3.5/extensions/valid-limit-cell/backgrid-valid-limit-cell',
  'js/typeahead.extended/typeahead.extended',
],
function (app, T, Base, Backgrid, moment, EafProcess, Modal) {

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


    Screen.Models.ChemistrySamples = Backbone.Epoxy.Model.extend({
        defaults: {
            heatName: null,
            gradeName: null,
            timestamp: null,
            eafSamplesCount: null,
            lfSamplesCount: null,
            casterSamplesCount: null,
            licoSamplesCount: null,
            slagSamplesCount: null,
            vtdSamplesCount: null,
            slagEAFSamplesCount : null,
            slagLFSamplesCount  : null,
        },
        parse: function (obj) {
            return {
                heatName: obj.HeatName,
                gradeName: obj.GradeName,
                timestamp: obj.TimestampString,
                eafSamplesCount: obj.EafSamplesCount,
                lfSamplesCount: obj.LfSamplesCount,
                casterSamplesCount: obj.CasterSamplesCount,
                licoSamplesCount: obj.LicoSamplesCount,
                slagSamplesCount: obj.SlagSamplesCount,
                vtdSamplesCount: obj.VtdSamplesCount,
                slagEAFSamplesCount: obj.SlagEAFSamplesCount,
                slagLFSamplesCount : obj.SlagLFSamplesCount,
            };
        },
    });


    Screen.Collections.ChemistrySamples = Backbone.Collection.extend({
        model: Screen.Models.ChemistrySamples,
        comparator: 'heatName',
        fetch: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@start', 'DATETIME', params.start);
            qp.Add('@end', 'DATETIME', params.end);
            qp.Add('@heatId', 'INT', params.heatId);
            qp.Add('@onlyMissing', 'BIT', params.onlyMissing);

            qp.Add('@eaf', 'BIT', params.eafChecked);
            qp.Add('@eafSlag', 'BIT', params.eafSlagChecked);
            qp.Add('@lf', 'BIT', params.lfChecked);
            qp.Add('@lfSlag', 'BIT', params.lfSlagChecked);
            qp.Add('@lico', 'BIT', params.licoChecked);
            qp.Add('@vtd', 'BIT', params.vtdChecked);
            qp.Add('@caster', 'BIT', params.casterChecked);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAB.GetChemistriesSummary",
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && (resp.Table)) {
                                var newColl = _.map(resp.Table, that.model.prototype.parse);

                                that.set(newColl);
                                that.trigger('fetch', that, newColl);
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    console.error(new Error(resp.Message).stack);
                                    app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                }
                                else {
                                    app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                }
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: true,
                },
                app.ConnectionStrings.app
            );
            return this;
        },

    });


    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            start: new moment().format('YYYY-MM-DD'),
            end: new moment().format('YYYY-MM-DD'),
            onlyMissing: false,
            heatId: -1, //To get current eafProcess.
            filterGroup: 'DATE',

            navigating: false,
            search: '',

            hasData: false,
            isLoading: false,

            eafChecked: true,
            eafSlagChecked: true,
            lfChecked: true,
            lfSlagChecked: true,
            licoChecked: true,
            vtdChecked: true,
            casterChecked: true,
        },
        computeds: {
            start$: {
                deps: ['start'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            end$: {
                deps: ['end'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
        },
    });

    Screen.Models.Item = Base.Models.Base.extend({
        defaults: {
            heatName: null,
            gradeName: null,
            timestamp: null,
            eafSamplesCount: null,
            lfSamplesCount: null,
            casterSamplesCount: null,
            licoSamplesCount: null,
            slagSamplesCount: null,
            vtdSamplesCount: null,

        },

        procedures: {
            get: app.DatabaseNames.MES + ".LAB.GetChemistriesSummary",
        },

        parse: function (obj) {
            return {
                heatName: obj.HeatName,
                gradeName: obj.GradeName,
                timestamp: obj.TimestampString,
                eafSamplesCount: obj.EafSamplesCount,
                lfSamplesCount: obj.LfSamplesCount,
                casterSamplesCount: obj.CasterSamplesCount,
                licoSamplesCount: obj.LicoSamplesCount,
                slagSamplesCount: obj.SlagSamplesCount,
                vtdSamplesCount: obj.VtdSamplesCount,
            };
        },
    });


    var superRef, superProto, classRef;

    superRef = Base.Collections.Base;
    superProto = superRef.prototype;

    Screen.Collections.Items = classRef = superRef.extend({
        model: Screen.Models.Item,
        comparator: 'heatName',
    });




    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'chemistry-summary',
        id: 'chemistry-summary',
        title: 'Chemistry Summary',
        events: function () {
            return {
                'click #getPreviousItemBtn': this.getPreviousItemBtn_click,
                'click #getNextItemBtn': this.getNextItemBtn_click,
                'click #refreshBtn': this.refreshBtn_click,
                'click #showSearchItemsBtn': this.showSearchItemsBtn_click,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,

        items: null,
        subviews: null,
        viewParams: null,
        templates: null,
        eafProcess: null,
        items: null,
        searchTbx: null,

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

            var that = this;

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

            this.eafProcess = new EafProcess.Models.EafProcess();

            this.bindingSources = {
                eafProcess: this.eafProcess,
            };

            //this.items = new (Screen.Collections.Items.extend({ pageSize: 50, }))();
            this.itemsChemistrySamples = new Screen.Collections.ChemistrySamples();

            this.bindingSources = {};

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

            this.templates = {
                samplesCountCell:
                '{{#if noSample}} <div class= "no-samples-bullet" title="No samples" > <i class="fa fa-times"></i></div>  {{/if}} {{#if oneSample}} <div class="one-samples-bullet" title="{{samplesCount}} samples"><i class="fa fa-check"></i></div> {{/if}} {{#if twoSample}}  <div class="two-samples-bullet" title="{{samplesCount}} samples"><i class="fa fa-check"></i></div> {{/if}}',
            };
            this.bindEvents();
        },
        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.eafProcess, 'change:heatName', this.eafProcess_change_heatName)
                .listenTo(this.model, 'change:heatId', this.model_change_heatId)
                .listenTo(this, 'NextProcessReady', this.nextProcess_ready);
        },

        nextProcess_ready: function () {
            this._refresh();
        },
        _refresh: function (opt) {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshHeat(opt);
            this.refreshItems(opt);
            

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

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },

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

            this.eafProcess.fetch(_.extend(opt, {
                params: {
                    id: (attrs.heatId != -1) ? null : -1,
                    heatId: (attrs.heatId != -1) ? attrs.heatId : null,
                    timezoneCode: app.models.user.get('timezoneCode'),
                },
                //success: function () {
                //    that.model.set({
                //        isLoadingProcess: false,
                //        navigating: false,
                //    });
                //},
                //error: function () {
                //    that.model.set({
                //        isLoadingProcess: false,
                //        navigating: false,
                //    });
                //},
            }));
        },
        refresh: function (viewParams) {
            var fixedParams = _.extend({}, viewParams);

            if (viewParams.onlyMissing == 'true') {
                fixedParams.onlyMissing = true;
            } else {
                fixedParams.onlyMissing = false;
            }

            if ((viewParams.heatId != null) && (viewParams.heatId != '-')) {
                fixedParams.heatId = parseInt(fixedParams.heatId);
                fixedParams.start = this.model.get('start');
                fixedParams.end = this.model.get('end');
                fixedParams.filterGroup = 'HEAT';
            } 
            else {
                if (viewParams.start)
                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                fixedParams.heatId = this.model.get('heatId');
                fixedParams.filterGroup = 'DATE';
            }

            
            //||
            //if (viewParams.onlyMissing) { 
            //    viewParams.onlyMissing = (fixedParams.onlyMissing.toLowerCase() == "true");
           

            this.model.set(fixedParams);

            this._refresh({
                reset: true,
                params: _.extend(
                    {},
                    fixedParams,
                    {}
                ),
            });
        },
        
        render: function (container, viewParams) {
            var that = this;

            this.viewParams = viewParams;

            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/custom-screens/' + this.template + '/';

            T.render.call(
                this,
                this.template,
                function (tmp) {
                    if (!that.options.i18n) that.options.i18n = {};

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

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

                            that.applyBindings();

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

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


                            that.searchTbx = that.$el.find("#searchTbx").typeaheadExtended({
                                items: Infinity,
                                minLength: 0,
                                source: _.bind(that.getSearchControlSource, that),
                                updater: function (item) {
                                    var match;
                                    try {
                                        match = that.selectItemFromSearchComboItem(item);
                                    }
                                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                    finally {
                                        if (match)
                                            return match.heatName;
                                        else
                                            return item;
                                    }
                                }
                            });



                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'heatName',
                                        label: app.translate([that, app], 'items_heat_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell heatName',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'gradeName',
                                        label: app.translate([that, app], 'items_grade_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell gradeName',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'timestamp',
                                        label: app.translate([that, app], 'process_end_col'),
                                        cell: Backgrid.Extension.MomentCell.extend({
                                            className: 'momment-cell align-center-cell timestamp',
                                            modelFormat: 'YYYY-MM-DD HH:mm:ss.SSS',
                                            displayFormat: app.translate([that, app], 'MM/DD/YYYY') + ' HH:mm',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'eafSamplesCount',
                                        label: app.translate([that, app], 'items_eaf_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Screen.Views.SamplesCountCell.extend({
                                            className: 'string-cell align-center eafSamplesCount',
                                            template: Handlebars.compile(that.templates.samplesCountCell),
                                        })
                                    },
                                    {
                                        name: 'slagEAFSamplesCount',
                                        label: app.translate([that, app], 'items_slag_eaf_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Screen.Views.SamplesCountCell.extend({
                                            className: 'string-cell align-center slagSamplesCount',
                                            template: Handlebars.compile(that.templates.samplesCountCell),
                                        })
                                    },
                                    {
                                        name: 'lfSamplesCount',
                                        label: app.translate([that, app], 'items_lf_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Screen.Views.SamplesCountCell.extend({
                                            className: 'string-cell align-center lfSamplesCount',
                                            template: Handlebars.compile(that.templates.samplesCountCell),
                                        })
                                    },
                                    {
                                        name: 'slagLFSamplesCount',
                                        label: app.translate([that, app], 'items_slag_lf_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Screen.Views.SamplesCountCell.extend({
                                            className: 'string-cell align-center slagSamplesCount',
                                            template: Handlebars.compile(that.templates.samplesCountCell),
                                        })
                                    },

                                    {
                                        name: 'licoSamplesCount',
                                        label: app.translate([that, app], 'items_lico_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Screen.Views.SamplesCountCell.extend({
                                            className: 'string-cell align-center licoSamplesCount',
                                            template: Handlebars.compile(that.templates.samplesCountCell),
                                        })
                                    },
                                    {
                                        name: 'vtdSamplesCount',
                                        label: app.translate([that, app], 'items_vtd_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Screen.Views.SamplesCountCell.extend({
                                            className: 'string-cell align-center vtdSamplesCount',
                                            template: Handlebars.compile(that.templates.samplesCountCell),
                                        })
                                    },
                                    {
                                        name: 'casterSamplesCount',
                                        label: app.translate([that, app], 'items_caster_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Screen.Views.SamplesCountCell.extend({
                                            className: 'string-cell align-center casterSamplesCount',
                                            template: Handlebars.compile(that.templates.samplesCountCell),
                                        })
                                    },
                                    //{
                                    //    name: 'slagSamplesCount',
                                    //    label: app.translate([that, app], 'items_slag_col'),
                                    //    editable: false,
                                    //    sortable: false,
                                    //    cell: Screen.Views.SamplesCountCell.extend({
                                    //        className: 'string-cell align-center slagSamplesCount',
                                    //        template: Handlebars.compile(that.templates.samplesCountCell),
                                    //    })
                                    //}, 
                                ],
                                //collection: that.items,
                                collection: that.itemsChemistrySamples,
                                footer: Backgrid.Extension.Infinator.extend({
                                    scrollToTop: false,
                                }),
                                row: Backgrid.Row.extend({
                                    events: function () {
                                        return {
                                            'click': this.click,
                                        };
                                    },
                                    /*click: function (e) {
                                        try {
                                            this.model.trigger('backgrid:rowclick', this.model);
                                        }
                                        catch (Error) { console.error(Error.stack); }
                                    }*/
                                })
                            });
                            that.$el.find('.items-grid-container').append(grid.render().el);


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


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

                            if (!isNaN(parseInt(fixedParams.heatId))) {
                                if (viewParams.heatId)
                                    fixedParams.heatId = parseInt(fixedParams.heatId);
                                fixedParams.start = that.model.get('start');
                                fixedParams.end = that.model.get('end');
                                fixedParams.filterGroup = 'HEAT';
                            } else {
                                if (viewParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (viewParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                fixedParams.heatId = that.model.get('heatId');
                                fixedParams.filterGroup = 'DATE';
                            }
                            
                            if (fixedParams.onlyMissing)
                                fixedParams.onlyMissing = (fixedParams.onlyMissing.toLowerCase() == 'true');

                            that.model.set(fixedParams);

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

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

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

        getNextProcess: function (next) {
            var that = this;

            this.model.set('navigating', true);


            this.eafProcess.getNextProcess({
                params: {
                    next: next,
                },
                success: function (model, nextProcess) {
                    try {
                        if ((nextProcess) && (nextProcess.heatId)) {
                            that.model.set({
                                heatId: nextProcess.heatId,
                                navigating: false,
                            });
                        }
                        else {
                            that.model.set('navigating', false);

                            if (next)
                                app.views.topMessages.showMessage(app.translate([that, app], 'no_next_process'), { stay: 5 * 1000, });
                            else
                                app.views.topMessages.showMessage(app.translate([that, app], 'no_previous_process'), { stay: 5 * 1000, });
                        }
                        that.trigger('NextProcessReady');
                    }
                    catch (error) {
                        console.error((error.stack) ? error.stack : new Error(error).stack);

                        that.model.set('navigating', false);
                    }
                },
                error: function () {
                    that.model.set('navigating', false);
                },
            });
        },
            
        getSearchControlSource: function (query, process) {
            var that = this,
                opt = {
                    params: {
                        //furnaceCode: this.model.get('furnaceCode'),
                    },
                };

            if (query)
                opt.params.search = query;

            EafProcess.Collections.EafProcesses.fetch(_.extend(
                opt,
                {
                    success: function (records) {
                        try {
                            that.searchItems = {};

                            if (records) {
                                var items = [];

                                _.each(records, function (obj) {
                                    var legend = obj.heatName;

                                    that.searchItems[legend] = obj;

                                    items.push(legend);
                                });
                            }

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

        selectItemFromSearchComboItem: function (value) {
            var item = this.searchItems[value];

            if (item)
                this.model.set('heatId', item.heatId);

            return item;
        },

        eafProcess_change_heatName: function (model, value, opt) {
            try {
                this.model.set('search', this.eafProcess.get('heatName'));
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        getNextItemBtn_click: function (e) {
            try {
                this.getNextProcess(true);
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        getPreviousItemBtn_click: function (e) {
            try {
                this.getNextProcess(false);
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        model_change_heatId: function (model, value, opt) {
            try {
                this.refreshHeat();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        searchTbx_keypress: function (e) {
            try {
                var keyCode = e.which || e.keyCode;

                if (keyCode == 13) {
                    var search = this.model.get('search');

                    if (search) {
                        var item = this.selectItemFromSearchComboItem(search);

                        if (!item) {
                            item = _.findWhere(this.searchItems, { heatName: search, });

                            if (item)
                                this.model.set('heatId', item.heatId);
                            else
                                app.views.topMessages.showMessage(app.translate([this, app], 'no_match'), { stay: 5 * 1000, });
                        }
                    }
                }
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },

        showSearchItemsBtn_click: function (e) {
            try {
                if ((this.searchItems) && (this.searchItems.length > 0))
                    this.searchTbx.typeaheadExtended('show');
                else
                    this.searchTbx.typeaheadExtended('lookup');
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },




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

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

            //this.items.fetch(_.extend(opt, {
            //    params: {
            //        start: (attrs.filterGroup == 'DATE' ) ? attrs.start : null,
            //        end: (attrs.filterGroup == 'DATE' ) ? new moment(attrs.end, 'YYYY-MM-DD').add('days', 1).format('YYYY-MM-DD') : null,
            //        heatId: (attrs.filterGroup == 'HEAT') ? parseInt(attrs.heatId) : null,
            //        onlyMissing: attrs.onlyMissing
            //    },
            //}));


            this.itemsChemistrySamples.fetch({
                start: (attrs.filterGroup == 'DATE') ? attrs.start : null,
                end: (attrs.filterGroup == 'DATE') ? new moment(attrs.end, 'YYYY-MM-DD').add('days', 1).format('YYYY-MM-DD') : null,
                heatId: (attrs.filterGroup == 'HEAT') ? parseInt(attrs.heatId) : null,
                onlyMissing: attrs.onlyMissing,
                eafChecked: attrs.eafChecked,
                eafSlagChecked: attrs.eafSlagChecked,
                lfChecked: attrs.lfChecked,
                lfSlagChecked: attrs.lfSlagChecked,
                licoChecked: attrs.licoChecked,
                vtdChecked: attrs.vtdChecked,
                casterChecked: attrs.casterChecked,
            });
        },

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

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

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

                var filterGroups = [];
                
                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            (params.filterGroup == 'HEAT')
                                ? 
                                  {
                                      start: '-',
                                      end: '-',
                                      heatId: params.heatId,
                                  }
                                    
                                :
                                  {
                                      start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                      end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                                      heatId: '-',
                                  },
                            {}
                        ),
                        false
                    ),
                    { trigger: false, }
                );


                var refreshParams = {};

                if (params.filterGroup == 'DATE') {
                    refreshParams = {
                        start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                        end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                        heatId: null,
                    };
                } else {
                    refreshParams = {
                        start: null,
                        end: null,
                        heatId: params.heatId,
                    };
                }

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

                window.scrollTo(0, 0);
            }
            catch (Error) { console.error(Error.stack); }
        },

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

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

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

                this.options.onappend(this);
            }

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

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

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

            this.stopAutoRefresh();

            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.close();
            });
        },
        show: function () {
            this.options.state = app.view_states.shown;

            this.showSubviews();
            this.bindEvents();
            this.$el.show();
        },
        showSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.show();
            });
        },
        hide: function () {
            this.options.state = app.view_states.hidden;

            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.set("subnavbar", false);
        },
        reRender: function (viewParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },
        startAutoRefresh: function () {
            try {
                if (this.autoRefresh.enabled !== true) {
                    var that = this;

                    if (this.autoRefresh.toid != null) {
                        clearTimeout(this.autoRefresh.toid);
                        this.autoRefresh.toid = null;
                    }

                    this.autoRefresh.enabled = true;

                    //use a timeout to execute the first refresh to return the handle to the start function caller.
                    //So when the caller finish it will do the first refresh.
                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        1
                    );
                }
            } catch (Error) { console.error(Error.stack); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
    });

    Screen.Views.SamplesCountCell = Backgrid.Cell.extend({
        render: function () {
            this.$el.empty();

            var model = this.model,
                colName = this.column.get('name');
            var value = model.get(colName);

            this.$el.html(
                this.template({
                    hasSamples: (value > 0),
                    samplesCount: value,
                    noSample:  (value == 0) ? true : false,
                    oneSample: (value == 1) ? true : false,
                    twoSample: (value == 2) ? true : false,
                })
            );
            this.delegateEvents();

            return this;
        }, 
    })

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

