//SCREEN-BOILERPLATE

//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
  // Application variable, always include it to have access to app methods.
  'app',

  //templates-loader: this loads templates async.
  'js/templates-loader',
    'backgrid',

    'modules/modal',
    'moment',
    'js/jquery.clearsearch/jquery.clearsearch',
    'js/multiselect/virtual-select.min',

    'backgrid/grouped-columns',
],

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

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

    Screen.Collections.Components = Backbone.Collection.extend({
        setDataColl: function (data) {
            this.set(data).trigger('fetch', this, data);
        },
    });

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            items: null,
            itemId: null,
            search: '',

            hasData: false,
            hasItemData: false,
            hasItemSpecData: false,
            isLoading: true,
            isLoadingItemData: false,
            isLoadingItemSpecData: false,
            heatNames: [],
            heatId: null,
            urlHeatName: null,
            start: new moment().format('YYYY-MM-DD'),
            locations: [],

            parts: [],
            allChanges: [],

            strand1PreviousData:[],
            strand2PreviousData:[],
            strand3PreviousData:[],
            strand4PreviousData: [],
            allPreviousData: [],
        },

        initialize: function () {
            this.strand1 = new Screen.Collections.Components();
            this.strand2 = new Screen.Collections.Components();
            this.strand3 = new Screen.Collections.Components();
            this.strand4 = new Screen.Collections.Components();
        },
        save: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            var array = [];
            _.each(that.get('allChanges'), function (obj) {
                array.push({ RootId: obj.currentModel.RootId, PartId: obj.currentModel.PartId, ComponentTypeId: obj.currentModel.ComponentTypeId });
            });

            console.log("array", array);
            qp.Add(
                'EquipmentChanges',
                'XML',
                app.jsonArrayToXml(
                    array,
                    [
                        'RootId',
                        'PartId',
                        'ComponentTypeId'
                    ]
                )
            );
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAS.ChangeCurrentEquipment',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp)) {
                            }
                            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: false,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;

        },
        fetch: function (opt) {
            var that = this,
                qp = new Core.Database.QueryParameters();
            var parts = [];

            var array = [];

            var currentParts = null;
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAS.GetCurrentEquipment',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                that.strand1.setDataColl(_.where(resp.Table, { StrandId: 1 }));
                                that.strand2.setDataColl(_.where(resp.Table, { StrandId: 2 }));
                                that.strand3.setDataColl(_.where(resp.Table, { StrandId: 3 }));
                                that.strand4.setDataColl(_.where(resp.Table, { StrandId: 4 }));
                                that.set({
                                    allPreviousData: resp.Table,
                                    strand1PreviousData:_.where(resp.Table, { StrandId: 1 }),
                                    strand2PreviousData:_.where(resp.Table, { StrandId: 2 }),
                                    strand3PreviousData:_.where(resp.Table, { StrandId: 3 }),
                                    strand4PreviousData:_.where(resp.Table, { StrandId: 4 }),
                                })
                                _.each(resp.Table1, function (obj, i) {
                                    currentParts = _.where(resp.Table2, { ComponentTypeId: obj.ComponentTypeId });
                                    array = [];
                                    _.each(currentParts, function (obj, i) {
                                        array[i] = [obj.Name, obj.Id];
                                    });
                                    parts[obj.ComponentTypeId] = array;
                                   
                                });
                                that.set({ parts: parts });
                                that.trigger('fetch', that, resp.Table);

                            }
                            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: false,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },  
    });

    //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.
    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return 'caster-equipments';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'caster-equipments',
        id: 'caster-equipments',
        title: 'Caster Equipments',
        //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,
        events: function () {
            return {                
                'click #cancelBtn': this.cancelBtn_click,
                'click #saveBtn': this.saveBtn_click,
                'click #refreshBtn': this.refreshBtn_click,
            };
        },
        autoRefresh: null,
        subviews: null,
        viewParams: null,

        item: null,
        parts: [],

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

            var that = this;

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

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



            this.bindEvents();
        },
        stopListeningPartChanges: function () {
            this.stopListening(this.model.strand1, 'change', this.strand_changed);
            this.stopListening(this.model.strand2, 'change', this.strand_changed);
            this.stopListening(this.model.strand3, 'change', this.strand_changed);
            this.stopListening(this.model.strand4, 'change', this.strand_changed);
        },

        startListeningPartChanges: function () {
            this.listenTo(this.model.strand1, 'change', this.strand_changed);
            this.listenTo(this.model.strand2, 'change', this.strand_changed);
            this.listenTo(this.model.strand3, 'change', this.strand_changed);
            this.listenTo(this.model.strand4, 'change', this.strand_changed);
        },

        bindEvents: function () {
            this.listenTo(this.model, 'fetch', this.data_fetch);
            this.listenTo(this.model.strand1, 'change', this.strand_changed);
            this.listenTo(this.model.strand2, 'change', this.strand_changed);
            this.listenTo(this.model.strand3, 'change', this.strand_changed);
            this.listenTo(this.model.strand4, 'change', this.strand_changed);
            this.listenTo(this.model.strand1, 'backgrid:edited', this.collection_backgrid_edited);
            this.listenTo(this.model.strand2, 'backgrid:edited', this.collection_backgrid_edited);
            this.listenTo(this.model.strand3, 'backgrid:edited', this.collection_backgrid_edited);
            this.listenTo(this.model.strand4, 'backgrid:edited', this.collection_backgrid_edited);
        },
        collection_backgrid_edited: function (model) {
            this.startListeningPartChanges();
        },

        resetModel: function (model) {     
            model.set({
                PartialHeats: 0,
                PartialTons: 0,
                PartialContact: 0,
                PartialLength: 0,
            });
        },

        removeItem: function (currentRowNumber) {
            var allChanges = this.model.get('allChanges');
            var indexOfObject = allChanges.findIndex(object => {
                return object.rn === currentRowNumber;
            });
            allChanges.splice(indexOfObject, 1);
            this.model.set({
                allChanges: allChanges,
            });

        },
        addItem: function (currentModel) {
            this.model.attributes.allChanges.push({
                rn: currentModel.rn
                , currentModel: currentModel
            });

        },
        checkValidChange: function (model) {
            var currentModel = model.toJSON();
            var currentRowNumber = currentModel.rn;
            var currentPartId = parseInt(currentModel.PartId);
            var previousModel = _.where(this.model.toJSON().allPreviousData, { rn: currentRowNumber })[0];
            var previousPartId = previousModel.PartId != null ? parseInt(previousModel.PartId) : null;
            var allChanges = this.model.get('allChanges');
            var rnAlreadyExists = [];
          
            if (previousPartId === null || currentPartId != previousPartId) {
                // CASE 1 --->  CURRENT MODEL !== PREVIOUS MODEL 

                // 1 - Check if the rn was already added to allChanges
                if (allChanges.length > 0) {
                    // If exists at least one change we need to check the mode of that change.
                    // 2 - check if the same rn was alread added to allChanges   
                    rnAlreadyExists = _.where(this.model.attributes.allChanges, { rn: currentRowNumber });
                 

                    if (rnAlreadyExists.length > 0) { 
                        this.removeItem(currentRowNumber);
                        this.addItem(currentModel);
                        this.resetModel(model);
                    } else {
                        this.addItem(currentModel);
                        this.resetModel(model);
                    }

                } else {
                    // CASE 2 ---> FIRST ROW INSERTED
                    this.addItem(currentModel);
                    this.resetModel(model);
                }              

            } else {
                // CASE 3 ---> CURRENT MODEL === PREVIOUS MODEL 
                // a - The backgrid detects a change even if the Part is the same.For that reason we need to check if the current model change is equal to the previous
                // b - If the previous is equal to the current also can be that the user returns to the previous values.

                // Return to the previous values
                model.set({
                    PartialHeats: previousModel.PartialHeats,
                    PartialTons: previousModel.PartialTons,
                    PartialContact: previousModel.PartialContact,
                    PartialLength: previousModel.PartialLength,
                });

                // Remove from allChanges array the change
                this.removeItem(currentRowNumber);

                return 0;
            }

        },

        checkValidChangeButton: function (model) {
            var currentModel = model.toJSON();
            var currentRowNumber = currentModel.rn;
            var currentPartId = parseInt(currentModel.PartId);
            var previousModel = _.where(this.model.toJSON().allPreviousData, { rn: currentRowNumber })[0];
            var previousPartId = previousModel.PartId != null ? parseInt(previousModel.PartId) : null;
            var allChanges = this.model.get('allChanges');
            var rnAlreadyExists = [];

            if (allChanges.length > 0) {
                // If exists at least one change we need to check the mode of that change.
                // 2 - check if the same rn was alread added to allChanges   
                rnAlreadyExists = _.where(this.model.attributes.allChanges, { rn: currentRowNumber });

                if (rnAlreadyExists.length > 0) {
                    return 0;
                } else {
                    this.addItem(currentModel);
                    this.resetModel(model);
                }

            } else {
                // CASE 2 ---> FIRST ROW INSERTED
                this.addItem(currentModel);
                this.resetModel(model);
            }

        },
        strand_changed: function (model) {
            this.stopListeningPartChanges();
            this.checkValidChange(model);
           
        },
        actionOnRow: function (model, action) {
            this.stopListeningPartChanges();
            this.checkValidChangeButton(model);
            this.startListeningPartChanges();
        },

        cancelBtn_click: function () {
            this.model.set({
                allChanges: [],
                hasData: false,
                isLoading: true,
            });
            this.model.fetch();
        },
        saveBtn_click: function () {
            this.model.save();
            this.model.set({
                allChanges: [],
                hasData: false,
                isLoading: true,
            });

            this.model.fetch();
        },
        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.fetchData();


                            var columns = [
                                {
                                    name: 'Component',
                                    label: 'Component',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                },
                                {
                                    name: 'PartId',
                                    label: 'Part',
                                    editable: true,
                                    sortable: false,
                                    cell: Backgrid.SelectCell.extend({
                                        optionValues: function () {
                                            var parts = that.model.toJSON().parts;
                                            var componentTypeId = this.model.toJSON().ComponentTypeId;
                                            if (parts[componentTypeId].length > 0) return parts[componentTypeId];
                                            else return that.locations;
                                        },
                                        className: function () {
                                            var parts = that.model.toJSON().parts;
                                            var componentTypeId = this.model.toJSON().ComponentTypeId;
                                            if (parts[componentTypeId].length > 0)
                                                return 'string-cell align-center-cell parts'
                                            else return 'string-cell align-center-cell hide';
                                        },
                                    })
                                },
                                {
                                    name: 'actions',
                                    label: 'Action',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.Cell.extend({
                                        template: Handlebars.compile(that.$el.find('#actions_cell_template_caster_equipment_no_type').html()),
                                        className: 'actions-cell',
                                        events: {
                                            'click .btn-cell-action': 'cellActionClick'
                                        },

                                        initialize: function () {
                                            Backgrid.Cell.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            this.$el.html(this.template());

                                            this.$el.find('[data-toggle="tooltip"]').tooltip();

                                            this.checkMode();

                                            return this;
                                        },
                                        checkMode: function () {
                                            var btnSave = this.$el.find('.btn-done');
                                            var parts = that.model.toJSON().parts;
                                            var componentTypeId = this.model.toJSON().ComponentTypeId;
                                            if (parts[componentTypeId].length > 0) {
                                                btnSave.addClass('hide');
                                            }
                                        },
                                        cellActionClick: function (e) {
                                            try {
                                                var target = $(e.target);
                                                var actionData = target.closest('[data-cell-action]').data('cell-action');
                                                if (actionData) {
                                                    that.actionOnRow(this.model, actionData);
                                                }
                                            }
                                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                        },
                                    }),
                                },
                                {
                                    name: 'PartialHeats',
                                    label: 'Heats',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            if (this.model.toJSON().PartialAlertStatusHeats === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().PartialAlertStatusHeats === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },
                                {
                                    name: 'PartialTons',
                                    label: 'Tons',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            if (this.model.toJSON().PartialAlertStatusTons === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().PartialAlertStatusTons === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },
                                {
                                    name: 'PartialContact',
                                    label: 'Time',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            if (this.model.toJSON().PartialAlertStatusContact === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().PartialAlertStatusContact === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },
                                {
                                    name: 'PartialLength',
                                    label: 'Length',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.IntegerCell.extend({
                                        orderSeparator: '',
                                        className: function () {
                                            if (this.model.toJSON().TotalAlertStatusLength === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().TotalAlertStatusLength === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },
                                {
                                    name: 'TotalHeats',
                                    label: 'Heats',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            if (this.model.toJSON().TotalAlertStatusHeats === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().TotalAlertStatusHeats === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },
                                {
                                    name: 'TotalTons',
                                    label: 'Tons',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            if (this.model.toJSON().TotalAlertStatusTons === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().TotalAlertStatusTons === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },
                                {
                                    name: 'TotalContact',
                                    label: 'Time',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.StringCell.extend({
                                        className: function () {
                                            if (this.model.toJSON().TotalAlertStatusContact === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().TotalAlertStatusContact === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },
                                {
                                    name: 'TotalLength',
                                    label: 'Length',
                                    editable: false,
                                    sortable: false,
                                    cell: Backgrid.IntegerCell.extend({
                                        orderSeparator: '',
                                        className: function () {
                                            if (this.model.toJSON().TotalAlertStatusLength === 'A') return 'string-cell align-center-cell danger';
                                            else if (this.model.toJSON().TotalAlertStatusLength === 'W') return 'string-cell align-center-cell warning';
                                            else return 'string-cell align-center-cell';
                                        }
                                    }),
                                },

                            ];

                            var header = Backgrid.Extension.GroupedHeader.extend({
                                columnLayout:
                                    [
                                        { name: 'Component' },
                                        { name: 'PartId' },
                                        { name: 'actions' },
                                        {
                                            name: 'Partial', children:
                                                [
                                                    { name: 'PartialHeats' }
                                                    , { name: 'PartialTons' }
                                                    , { name: 'PartialContact' }
                                                    , { name: 'PartialLength' }
                                                ]
                                        },
                                        {
                                            name: 'Total', children:
                                                [
                                                    { name: 'TotalHeats' }
                                                    , { name: 'TotalTons' }
                                                    , { name: 'TotalContact' }
                                                    , { name: 'TotalLength' }
                                                ]
                                        },
                                    ],
                                initialize: function (options) {
                                    Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                    this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                },
                                render: function () {
                                    var that = this;
                                    Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                    _.each(this.columns.models, function (modelValue) {
                                        if (modelValue.get('toolTip')) that.$el.find('.' + modelValue.get('name')).attr('title', modelValue.get('toolTip'))
                                    });
                                    return this;
                                },
                                collection_backgrid_sort: function (column, direction) {
                                    var sortType = column.get('name').toUpperCase();

                                    switch ((direction + '').toUpperCase()) {
                                        case 'ASCENDING':
                                            sortType += '-ASC';
                                            break;
                                        case 'DESCENDING':
                                            sortType += '-DESC';
                                            break;
                                        case 'NULL':
                                            sortType = null;
                                            break;
                                    }

                                    _.each(this.row.cells, function (obj) {
                                        obj.removeCellDirection();
                                    });

                                    column.set("direction", direction);

                                    that.model.set('sortType', sortType);

                                },
                            });

                            var gridStrand1 = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                header: header,
                                columns: columns,
                                collection: that.model.strand1,
                            });
                            that.$el.find('.items-grid-container-strand1').append(gridStrand1.render().el);

                            var gridStrand2 = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                header: header,
                                columns: columns,
                                collection: that.model.strand2,
                            });
                            that.$el.find('.items-grid-container-strand2').append(gridStrand2.render().el);

                            var gridStrand3 = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                header: header,
                                columns: columns,
                                collection: that.model.strand3,
                            });
                            that.$el.find('.items-grid-container-strand3').append(gridStrand3.render().el);

                            var gridStrand4 = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                header: header,
                                columns: columns,
                                collection: that.model.strand4,
                            });
                            that.$el.find('.items-grid-container-strand4').append(gridStrand4.render().el);                         


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


                            //Call first refresh.
                            that._refresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },
        fetchData: function () {
            var that = this;
            var array = [];
            array[0] = ['', ''];
            this.locations = array;
            this.refresh();
        },
      
        refreshBtn_click: function () {
            this.refresh();
        },
      
        data_fetch: function (coll, resp) {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData: true,
                            isLoading: false,
                        });

                    },
                    500
                );

            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
       
        _refresh: function (opt) {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.refresh();
            if (this.autoRefresh.enabled == true) {
                var that = this;

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refresh: function (viewParams) { 
            this.model.set({
                hasData: false,
                isLoading: true,
            });
            this.model.fetch();
        },


        // Common functions
        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;
            }
        },
        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) ? error.stack : new Error(error).stack); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
        bindViewScopedEvents: function () {
        },
        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.stopAutoRefresh();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.setAll(false);
            app.models.subnavbar.set('sections', '12');
            app.models.subnavbar.set('subnavbar', true);
        },
        reRender: function () {
            //this.startAutoRefresh();
        },
        
      
    });


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

});
