//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',
    'chart',
    'moment',
    'chartjs-date-fns-adapter',
    'modules/navigation-buttons/navigation-buttons',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',
    'js/multiselect/virtual-select.min',
    'js/jquery.contextMenu/jquery.contextMenu',

],
    function (app, T, Backgrid, ChartJS, moment, ChartJsDateFnsAdapter, NavigationButton) {

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            hasData: true,
            isLoading: false,
            
            heatId: null,
            direction: null,

            heatName: null,
            heatNames: [],
            appendGrids: true,

            gridLog: null,
            types: [],
            typeId: '-',

            sources: [],
            sourceId: '-',
            searchText: '',
        },
        initialize: function () {
            this.itemsColl = new Screen.Collections.ItemsColl();
        },
        fetchNavigateHeat: function (params) {
            var qp = new Core.Database.QueryParameters();
            var that = this;
            qp.Add('@heatName', 'VARCHAR(10)', that.get('heatName'));
            qp.Add('@direction', 'SMALLINT', params.direction);
            qp.Add('@Asset', 'CHAR(3)', 'EAF');

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetNavigatedHeat',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp && resp.Table && resp.Table[0] && resp.Table[0].HeatName && resp.Table[0].HeatName !== '') {                    
                                that.set({
                                    heatName: resp.Table[0].HeatName,
                                    heatNames: [{
                                        value: resp.Table[0].HeatName,
                                        label: resp.Table[0].HeatName
                                    }],
                                });
                                that.trigger('heat-name-changed');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData: false,
                                        isLoading: false,
                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData: false,
                                        isLoading: false,
                                    });
                                }

                            }


                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );
        },
        fetchCatalogs: function () {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@HeatName', 'VARCHAR(10)', that.get('heatName'));
            qp.Add('@Asset', 'CHAR(3)', 'EAF');

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp && resp.Table) {
                                that.set({
                                    heatNames: resp.Table,
                                    heatName: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                });
                                that.trigger('catalogs-fetched');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData: false,
                                        isLoading: false,


                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData: false,
                                        isLoading: false,
                                    });
                                }

                            }


                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );
        },
        fetch: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@heatName', 'VARCHAR', that.get('heatName'));
            qp.Add('@source', 'VARCHAR', that.get('sourceId') === '-' ? null : that.get('sourceId'));
            qp.Add('@type', 'VARCHAR', that.get('typeId') === '-' ? null : that.get('typeId'));
            qp.Add('@searchText', 'VARCHAR', that.get('searchText') === '' ? null : that.get('searchText'));
            qp.Add('@timeZoneCode', 'CHAR(10)', app.models.user.get('timezoneCode'));

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetOnlineHeatReport',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if (resp && resp.Table) {
                                that.itemsColl.setDataColl(resp.Table);
                                
                                var types = _.map(resp.Table1, function (obj) {
                                    return {
                                        label: obj.Type,
                                        value: obj.Type
                                    }
                                });

                                var sources = _.map(resp.Table2, function (obj) {
                                    return {
                                        label: obj.Source,
                                        value: obj.Source
                                    }
                                });

                                that.set({ types: types, sources: sources });
                                if (resp.Table3) that.trigger('fetch-nav-buttons', resp.Table3);
                                
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData: false,
                                        isLoading: false,                                       

                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData: false,
                                        isLoading: false,                                       
                                    });
                                }

                            }


                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;

        },
    });

    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.refreshbtn
            return 'online-heat-report';
        } catch (Error) { }
        }

   

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'online-heat-report',
            id: 'online-heat-report',
            title: 'Online Heat Log',
            isCacheable: false,
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #backNavBtn': this.heatNavigationBtn_click,
                    'click #forwardNavBtn': this.heatNavigationBtn_click,
                    'click #addBtn': this.addBtn_click,
                    'keyup #search': this.search_changed,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,

            NavigationButtonView: null,

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

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

                this.NavigationButtonView = new NavigationButton.Views.Main();

                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);

                this.bindEvents();
                this.templates = {
                    replyCommentCell:
                        '{{#if noSample}} <div style="float:left;margin-right:5px;margin-left:3px"><i class="fa fa-reply"></i></div><div>{{cellValue}}</div> {{else}} {{cellValue}} {{/if}}'
                };

            },


            onModalAcceptBtn: function () {
                this.refresh();
            },
            bindEvents: function () {
                this.listenTo(this.model.itemsColl, 'fetch', this.process_fetched);               
                this.listenTo(this.model, 'fetch-nav-buttons', this.fetchnavbuttons);  

                this.listenTo(this.model, 'change:sourceId', this.refresh);
                this.listenTo(this.model, 'change:typeId', this.refresh);
                this.listenTo(this.model, 'change:searchText', _.debounce(this.refresh, 400)); 


                this.listenTo(this.model, 'heat-name-changed', this.heatNameChanged);

                
            },

            search_changed: function (e) {
                this.model.set({ searchText: e.target.value });
            },


            fetchnavbuttons: function (resp) {
                this.NavigationButtonView.setDataColl(resp);
            },
            heatNameChanged: function () {
                const value = this.model.get('heatName');
                const options = this.model.get('heatNames');
                document.querySelector('#heat-picker-multi-select').setOptions(options);
                document.querySelector('#heat-picker-multi-select').setValue(value);
                this.UpdateURL();
                this.refresh();
            },
           
            heatNavigationBtn_click: function (e) {
                const { id } = e.target;
                const direction = id === 'backNavBtn' ? -1 : 1;

                this.cleanPickers();
                this.model.fetchNavigateHeat({
                    direction
                });
            },

            cleanPickers: function () {

                //this.stopListening(this.model, 'heat-name-changed', this.heatNameChanged);
                this.model.set({
                    sourceId: '-',
                    typeId: '-',
                    searchText: '',
                });
                document.getElementById('search').value = '';
            },

            render: function (container, urlParams) {
                var that = this;
                var thatContainer = (this.options.container) ? this.options.container : container;
                this.options.container = thatContainer;

                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) {
                                that.options.i18n[that.template] = i18nJED;
                                that.$el.html(tmp());

                           
                                that.applyBindings();
                        
                                //rendering Navigation Buttons
                                that.NavigationButtonView.render(that.$el.find(".navigation-buttons"), null);


                                var gridLog = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed log-table',
                                    columns: [                                        
                                        {
                                            name: 'Datetime',
                                            label: app.translate([that, app], 'Datetime'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },
                                        {
                                            name: 'Source',
                                            label: app.translate([that, app], 'Source'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },  
                                        {
                                            name: 'Type',
                                            label: app.translate([that, app], 'Type'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },   
                                        {
                                            name: 'Description',
                                            label: app.translate([that, app], 'Description'),
                                            cell: Screen.Views.ReplyCommentCell.extend({
                                                className: 'string-cell align-left-cell',
                                                template: Handlebars.compile(that.templates.replyCommentCell),
                                            }),
                                            editable: false,
                                            sortable: false,
                                        },                                   
                                    ],
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);

                                            var isManual = this.model.toJSON().isManual;
                                            if (!isManual) this.$el.addClass('automatic-entries');
                                        },
                                        events: {
                                            contextmenu: 'onRightClick',
                                        },
                                        onRightClick: function (e) {
                                            e.preventDefault();
                                            var model = this.model.toJSON();
                                            
                                            var rowsView = that.model.get('gridLog').body.rows;
                                            var newIndex = _.indexOf(rowsView, this);
                                            this.$el.addClass("onRightClickSelectedRow");

                                            that.model.set({
                                                rowModel: model,
                                                index: newIndex,
                                            });
                                      
                                        },

                                    }),
                                    collection: that.model.itemsColl,

                                });
                                that.$el.find('.log-grid-container').append(gridLog.render().el);


                                that.model.set({ gridLog: gridLog });







                                $.contextMenu('destroy');

                                $(function (obj) {
                                    $.contextMenu({
                                        selector: '.log-table',
                                        callback: function (key, options) {
                                            that.model.set({ contextMenuOption: key });
                                            that.contextMenuOptionPressed();
                                        },
                                        items: {
                                            "opt-append-comment": {
                                                name: "Append Comment",
                                                icon: "fa-archive"                                               
                                            },
                                        },
                                        events: {
                                            hide: function (options) {
                                                that.removeHighlightRow();
                                            },
                                        }
                                    });
                                });



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

                                var fixedParams = _.extend({}, urlParams);
                                if (fixedParams && fixedParams.heatName && fixedParams.heatName.length === 7) {
                                    that.model.set(fixedParams);
                                } else {
                                    that.UpdateURL();
                                }
                                that.model.fetchCatalogs();

                                that.renderMultipicker();

                                that.refresh();

                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
           
            renderMultipicker: function () {
                var that = this;
                var heatNamesPicker = new VirtualSelect.init({
                    ele: '#heat-picker-multi-select',
                    options: that.model.get('heatNames'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select Heat',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearch,
                });
                var heat = that.model.get('heatName');
                document.querySelector('#heat-picker-multi-select').setOptions(that.model.get('heatNames'));
                document.querySelector('#heat-picker-multi-select').setValue(heat);
                document.querySelector('#heat-picker-multi-select').addEventListener('change', function () {
                    $('.vscomp-search-clear').click();
                    if (this.value === that.model.get('heatName')) {
                        return 0;
                    }
                    else {
                        var newHeatName = this.value;
                        if (newHeatName && newHeatName != '') {
                            that.model.set({
                                heatName: newHeatName
                            });
                            that.refresh();
                            that.UpdateURL();
                        }
                    }
                });

            },

            onSampleSelectServerSearch: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', searchValue);
                qp.Add('@SelectedHeatName', 'VARCHAR(10)', this.selectedValues[0]);
                qp.Add('@Asset', 'CHAR(3)', 'EAF');    

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                virtualSelect.setServerOptions(resp.Table);

                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },

            refresh: function () {
                this.model.set({
                    isLoading: true,
                    hasData: false,  
                });
                this.model.fetch();
            },

            fetchnavbuttons: function (resp) {
                this.NavigationButtonView.setDataColl(resp);
            },
            process_fetched: function (mainInfoColl) {
                try {
                    var that = this;
                    var coll = mainInfoColl.toJSON();
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData: true,
                                isLoading: false,
                                heatName: that.model.get('heatName'),
                            });

                        },
                        100
                    );

                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
         
            UpdateURL: function () {
                try {
                    var params = this.model.toJSON();

                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    heatName: params.heatName,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

        refreshBtn_click: function (e) {
            this.refresh();
            this.UpdateURL();

        },

        addBtn_click: function () {
            this.openAddCommentModal(null, false);
        },
        openAddCommentModal: function (datetime, isReply) {
            var attrs = this.model.toJSON();
            var modal = new Screen.Views.AddNewComment({
                heatName: attrs.heatName,
                datetime: datetime,
                isReply: isReply,
                bus: this.bus,
            });
            modal.show();
        },

        //-------------------------------------//
        //-------------------------------------//
        //-------------------------------------//
        //-------------------------------------//
        //-------------------------------------//
        //-------- CONTEXT MENU OPTIONS -------//
        //-------------------------------------//
        //-------------------------------------//
        //-------------------------------------//
        //-------------------------------------//
        //-------------------------------------//
        //-------------------------------------//
        contextMenuOptionPressed: function () {
            var that = this;
            rowModel = this.model.get('rowModel'),
                contextMenuOption = this.model.get('contextMenuOption');
            switch (contextMenuOption) {                
                case "opt-append-comment":
                    var utc = new moment(rowModel.DateTimeUTC).format('YYYY-MM-DD HH:mm:ss.sss');
                    that.openAddCommentModal(utc, true);
                    break;
              
            }
        },


        removeHighlightRow: function () {
            var previousIndex = this.model.get('index');
            var rowsView = this.model.get('gridLog').body.rows;

            if (rowsView && rowsView[previousIndex] && rowsView[previousIndex].$el)
                rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");


        },

        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.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 (urlParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },

    });


    Screen.Models.AddNewComment = Backbone.Epoxy.Model.extend({
        defaults: {
            comment: '',
            title: '',
            heatName: null,
            datetime: null,
            isReply: false,

        },
    });

    Screen.Views.AddNewComment = Backbone.Epoxy.View.extend({
        template: "online-heat-report",
        id: "add-new-comment",
        className: "modal modal-add-new-comment hide fade",
        bindings: "data-bind",
        isCacheable: true,
        events: function () {
            return {
                "click #acceptBtn": this.acceptBtn_click,
                "click #cancelBtn": this.cancelBtn_click,
                "submit form": this.form_submit,
                "keypress": this.modal_keypress,
                "show.bs.modal": this.modal_show,
                "shown.bs.modal": this.modal_shown,
                "hidden.bs.modal": this.modal_hidden,
            };
        },
        container: null,
        disposed: false,
        isRendered: false,
        preventDispose: false,
        visible: false,
        data: [],
        lastHeatsColl: [],
        grid: [],
        productId: null,
        initialize: function (options) {
            _.extend(this, options);
            if (!this.model) {
                this.model = new Screen.Models.AddNewComment();
            }

            this.model.set({
                heatName: options.heatName,
                title: `Heat ${options.heatName} - Add Comment`,
                datetime: options.datetime,
                isReply: options.isReply,
            })

            this.bus = options.bus;

            this.bindEvents();

            return this;
        },

        hide: function (preventDispose) {
            this.preventDispose = (preventDispose);

            this.$el.modal('hide');
        },
        render: function (container) {
            if (container)
                this.container = container;

            var that = this;
            var customPath = '/app/custom-screens/' + this.template + '/';
            T.render.call(this, this.template, function (tmp) {
                if (!that.i18n) that.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    that.i18n[that.template] = i18nJED;
                    that.$el.html(tmp(that.model.toJSON()));
                    that.applyBindings();
                    that.isRendered = true;
                    that.trigger("render");

                }, true, customPath);

            }, customPath, "add_new_comment_template");

        },



        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: true,
                    backdrop: 'both',
                });
            }

            return this;
        },

        bindEvents: function () {
            this.listenToOnce(this, "render", this.view_render);
        },

        close: function () {
            if (this.disposed == false) {
                if (this.visible == true) {
                    this.hide();
                }
                else {
                    this.trigger('close');

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

                    this.disposed = true;
                }
            }
        },
        preRender: function () {
            app.models.subnavbar.set("dateControl", false);
        },
        reRender: function () {
        },
        addNewComment: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters();

            this.fixedParameters = [
                { Name: '@heatName', Type: 'VARCHAR', Value: params.heatName, },
                { Name: '@comment', Type: 'VARCHAR', Value: params.comment, },
                { Name: '@datetime', Type: 'DATETIME', Value: params.datetime, },
                { Name: '@isReply', Type: 'BIT', Value: params.isReply, },
            ];
            _.each(this.fixedParameters, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.AddManualHeatComment',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && (resp.Table)) {
                                that.bus.trigger("modalAcceptBtn");
                                app.views.topMessages.showMessage(`${params.heatName} - New comment added`, { stay: 3000, });
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    console.error(new Error(resp.Message).stack);
                                    app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 3000, });
                                }
                                else {
                                    app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 3000, });
                                    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;
        },
        acceptBtn_click: function (e) {
            try {
                var model = this.model.toJSON();

                this.addNewComment({
                    heatName: model.heatName,
                    comment: model.comment,
                    isReply: model.isReply,
                    datetime: model.datetime,
                })
                this.close();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

        unassignBtn_click: function () {
            try {
                //this.bus.trigger("modalUnassignBtn", this.model.get('currentProcessId'));

                this.close();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

        form_submit: function (e) {
            try {
                e.preventDefault();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_hidden: function (e) {
            try {
                this.visible = false;

                if (!this.preventDispose)
                    this.close();
                else
                    this.preventDispose = false;
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_show: function (e) {
            try {
                this.visible = true;
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_shown: function (e) {
            try {
                this.$el.find(".autofocus").focus();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        view_render: function () {
            try {
                this.show();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });


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


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

            var model = this.model,
                colName = this.column.get('name');
            var attrs = this.model.toJSON();
            var value = model.get(colName);
            var cellValue = model.get(colName);
            var isReply = attrs.isReply;
            this.$el.html(
                this.template({
                    samplesCount: true,
                    cellValue: cellValue,
                    noSample: isReply,
                })
            );
            this.delegateEvents();

            return this;
        },
    })


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