//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',
  'moment',
  'modules/navigation-buttons/navigation-buttons',
  'backgrid/moment-cell',
  'js/autocomplete/backbone.autocomplete'

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

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

    
    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            furnaceCodes: [{ label: 'A', value: 1 }, { label: 'B', value: 2 }],
            furnaceCode: 1,

            //URL parameters

            heatName: '-',

            hasData_process: false,
            isLoading_process: false,

            heatId: null,
            direction: null,
            navigation: null,
            heatNames: [],
            enterPress: false,
        },
        computeds: {
            hasData: {
                deps: ['hasData_process'],
                get: function (process) {
                    return process;
                },
            },
            isLoading: {
                deps: ['isLoading_process'],
                get: function (process) {
                    return process;
                },
            },
        },
        initialize: function () {
            this.process = new Screen.Collections.Process();
            this.limits = new Screen.Collections.Process();
            this.limitsCompare = null;
        },
        fetchPickers: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters()
                async = null;

            if (params.async == null) async = true;
            else async = params.async


            qp.Add('@heatName', 'VARCHAR', params.heatName);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAB.GetChemistrySamplesCatalogs',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                that.set('heatNames', _.map(resp.Table, function (obj) {
                                    return {
                                        name: obj.Name,
                                        heatId: obj.HeatId,
                                        gradeName: obj.GradeName,
                                    };
                                }));

                                if (params.firstRefresh) {
                                    if (that.get('heatNames').length > 0) {
                                        var fromDb = that.get('heatNames')[0];
                                        if (fromDb) {
                                            that.set({
                                                heatId: fromDb.heatId,
                                                heatName: fromDb.name,
                                                gradeName: fromDb.gradeName,
                                            })
                                        }
                                    }
                                }

                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(new Error(resp.Message).stack);
                                else
                                    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: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },

        fetch: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();

            qp.Add('@heatId', 'INT', params.heatId);
            qp.Add('@direction', 'BIT', params.direction);
            qp.Add('@ladleFurnaceCode', 'INT', params.furnaceCode );
            qp.Add('@timeZoneCode', 'CHAR(10)', app.models.user.get('timezoneCode'));

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

                            if (resp && resp.Table) {
                                if (resp.Table2) that.limitsCompare = resp.Table2

                                if (resp.Table1) that.limits.setDataColl(resp.Table1);

                                if (resp.Table) that.process.setDataColl(resp.Table);
                              
                                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_process: false,
                                        isLoading_process: false,


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

                            }


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

            return this;

        },


        update: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@HeatId', 'INT', params.heatId);
            qp.Add('@TypeCode', 'VARCHAR(10)', params.typeCode);
            qp.Add('@SampleIdCode', 'VARCHAR(10)', params.sampleIdCode);
            qp.Add('@ElementCode', 'VARCHAR(10)', params.elementCode);
            qp.Add('@ElementCodeValue', 'VARCHAR(10)', params.elementCodeValue);
            qp.Add('@Timestamp', 'DATETIME', params.timestamp);
            qp.Add('@timeZoneCode', 'CHAR(10)', app.models.user.get('timezoneCode'));


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

                            if (resp && resp.Table) {
                                that.trigger('chemistry-updated');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.trigger('chemistry-updated');
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.trigger('chemistry-updated');
                                }

                            }


                        }
                        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 'manage-chemistries';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'manage-chemistries',
        id: 'manage-chemistries',
        title: 'Manage Chemistries',
        isCacheable: false,
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                'click #backNavBtn': this.backNavBtn_click,
                'click #forwardNavBtn': this.forwardNavBtn_click,
                'keyup #search': this.keyPressEventHandler,
                "click .btn-export-to-excel": this.exportToExcel,
            };
        },
        bindings: 'data-bind',
        subviews: null,
        viewParams: null,

        process: null,

        autoCompleteCollection: null,
        autocompleteView : 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.autoCompleteCollection = new Screen.Collections.HeatNames();

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

            this.bindingSources = {
                process: that.model.process,
            };


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

            this.bindEvents();

        },
        bindEvents: function () {
            this.listenTo(this.model.process, 'fetch', this.process_fetched);
            this.listenTo(this.model, 'fetch-nav-buttons', this.fetchnavbuttons);
            this.listenTo(this.model, 'change:heatName', this.updateHeatNameInURL);
            this.listenTo(this.model, 'change:heatNames', this.updateAutocomplete);
            this.listenTo(this.model.process, 'change', this.collection_changed);
            this.listenTo(this.model, 'chemistry-updated', this.chemistry_updated);

        },
        onModalAcceptBtn: function (params) {
            this.model.update({
                heatId: params.row.get('heatId'),
                typeCode: params.row.get('TypeCode'),
                sampleIdCode: params.row.get('SampleIdCode'),
                timestamp: params.datetime,
            });

        },
        chemistry_updated: function () {
            var params = this.model.toJSON();
            this.model.fetch({
                heatId: params.heatId ? params.heatId : null,
                furnaceCode: params.furnaceCode == '-' ? null : params.furnaceCode,
            });
        },
        collection_changed: function (m) {
            var key = Object.keys(m.changed);
            this.model.update({
                elementCode: key[0] == 'As' ? '[As]' : (key[0] == 'SampleIdCode' ? 'Sample' : key[0]),
                elementCodeValue: m.get(key[0]),
                heatId: m.get('heatId'),
                typeCode: m._previousAttributes.TypeCode,
                sampleIdCode: m._previousAttributes.SampleIdCode,
            });

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

            that.model.fetchPickers({
                heatName: urlParams.heatName,
                firstRefresh: true,
                async: false,
            })

            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());


                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'info', editable: false, label: app.translate([that, app], 'process_comments_col'),
                                        cell: Backgrid.Cell.extend({
                                            template: function () {
                                                var rowModel = this.model.toJSON();
                                                if (rowModel.comments!= '-') {
                                                    return Handlebars.compile(that.$el.find('#actions_cell_template').html())
                                                }
                                                else return _.template('<label class="text-center">-</label>');
                                            },
                                            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.delegateEvents();
                                                return this;
                                            },
                                            cellActionClick: function (e) {
                                                try {
                                                    var target = $(e.target);
                                                    var actionData = target.closest('[data-cell-action]').data('cell-action');                                                    
                                                    if (actionData) {
                                                        var modal = new Screen.Views.Modal({
                                                            model: this.model,
                                                            bus: that.bus,
                                                            showComments: true,
                                                        });
                                                        modal.show();
                                                    }
                                                }
                                                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                        }),
                                    },

                                    { name: 'localTimestamp', editable: false, label: app.translate([that, app], 'process_localTimestamp_col'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'TypeCode', editable: true, label: app.translate([that, app], 'process_type_code_col'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell', }), },
                                    { name: 'SampleIdCode', editable: true, label: app.translate([that, app], 'process_sample_id_col'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell', }), },
                                    { name: 'C',            editable: true, label: app.translate([that, app], 'process_c_col'), cell: Backgrid.StringCell.extend({ className: function ()                       { return that.warningElementCodeValue('C',      this.model.get('C'),            )}, }), },
                                    { name: 'Mn',           editable: true, label: app.translate([that, app], 'process_mn_col'),                   cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Mn',     this.model.get('Mn'),          )}, }), },
                                    { name: 'S',             editable: true, label: app.translate([that, app], 'process_s_col'),                   cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('S',      this.model.get('S'),           )}, }), },
                                    { name: 'P',             editable: true, label: app.translate([that, app], 'process_p_col'),                   cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('P',      this.model.get('P'),           )}, }), },
                                    { name: 'Si',                 editable: true, label: app.translate([that, app], 'process_si_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Si',     this.model.get('Si'),          )}, }), },
                                    { name: 'Cu',                 editable: true, label: app.translate([that, app], 'process_cu_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Cu',     this.model.get('Cu'),          )}, }), },
                                    { name: 'Ni',                 editable: true, label: app.translate([that, app], 'process_ni_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Ni',     this.model.get('Ni'),          )}, }), },
                                    { name: 'Cr',                 editable: true, label: app.translate([that, app], 'process_cr_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Cr',     this.model.get('Cr'),          )}, }), },
                                    { name: 'Mo',                 editable: true, label: app.translate([that, app], 'process_mo_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Mo',     this.model.get('Mo'),          )}, }), },
                                    { name: 'Sn',                 editable: true, label: app.translate([that, app], 'process_sn_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Sn',     this.model.get('Sn'),          )}, }), },
                                    { name: 'Nb',                 editable: true, label: app.translate([that, app], 'process_nb_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Nb',     this.model.get('Nb'),          )}, }), },
                                    { name: 'V',                 editable: true, label: app.translate([that, app], 'process_v_col'),               cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('V',      this.model.get('V'),           )}, }), },
                                    { name: 'N',                 editable: true, label: app.translate([that, app], 'process_n_col'),               cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('N',      this.model.get('N'),           )}, }), },
                                    { name: 'Al',                 editable: true, label: app.translate([that, app], 'process_al_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Al',     this.model.get('Al'),          )}, }), },
                                    { name: 'B',                 editable: true, label: app.translate([that, app], 'process_b_col'),               cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('B',      this.model.get('B'),           )}, }), },
                                    { name: 'Ca',                 editable: true, label: app.translate([that, app], 'process_ca_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Ca',     this.model.get('Ca'),          )}, }), },
                                    { name: 'Pb',                 editable: true, label: app.translate([that, app], 'process_pb_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Pb',     this.model.get('Pb'),          )}, }), },
                                    { name: 'Ti',                 editable: true, label: app.translate([that, app], 'process_ti_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Ti',     this.model.get('Ti'),          )}, }), },
                                    { name: 'Mn2S',                 editable: true, label: app.translate([that, app], 'process_mn2S_col'),         cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Mn2S',   this.model.get('Mn2S'),        )}, }), },
                                    { name: 'Liq',                 editable: true, label: app.translate([that, app], 'process_liq_col'),           cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Liq',    this.model.get('Liq'),         )}, }), },
                                    { name: 'CorrIdx',               editable: true, label: app.translate([that, app], 'process_corrIdx_col'),     cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('CorrIdx',this.model.get('CorrIdx'),     )}, }), },
                                    { name: 'CE',                 editable: true, label: app.translate([that, app], 'process_cE_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('CE',     this.model.get('CE'),          )}, }), },
                                    { name: 'FP',                 editable: true, label: app.translate([that, app], 'process_fP_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('FP',     this.model.get('FP'),          )}, }), },
                                    { name: 'Fe',                 editable: true, label: app.translate([that, app], 'process_fe_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Fe',     this.model.get('Fe'),          )}, }), },
                                    { name: 'Zn',                 editable: true, label: app.translate([that, app], 'process_zn_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Zn',     this.model.get('Zn'),          )}, }), },
                                    { name: 'Sb',                 editable: true, label: app.translate([that, app], 'process_sb_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Sb',     this.model.get('Sb'),          )}, }), },
                                    { name: 'As',                 editable: true, label: app.translate([that, app], 'process_as_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('As',     this.model.get('As'),          )}, }), },
                                    { name: 'Co',                 editable: true, label: app.translate([that, app], 'process_co_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Co',     this.model.get('Co'),          )}, }), },
                                    { name: 'Zr',                 editable: true, label: app.translate([that, app], 'process_zr_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Zr',     this.model.get('Zr'),          )}, }), },
                                    { name: 'W',                 editable: true, label: app.translate([that, app], 'process_w_col'),               cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('W',      this.model.get('W'),           )}, }), },
                                    { name: 'Ta',                 editable: true, label: app.translate([that, app], 'process_ta_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Ta',     this.model.get('Ta'),          )}, }), },
                                    { name: 'Bi',                 editable: true, label: app.translate([that, app], 'process_bi_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Bi',     this.model.get('Bi'),          )}, }), },
                                    { name: 'Se',                 editable: true, label: app.translate([that, app], 'process_se_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Se',     this.model.get('Se'),          )}, }), },
                                    { name: 'Te',                 editable: true, label: app.translate([that, app], 'process_te_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Te',     this.model.get('Te'),          )}, }), },
                                    { name: 'Mg',                 editable: true, label: app.translate([that, app], 'process_mg_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Mg',     this.model.get('Mg'),          )}, }), },
                                    { name: 'Cb',                 editable: true, label: app.translate([that, app], 'process_cb_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('Cb',     this.model.get('Cb'),          )}, }), },                 
                                    { name: 'E1',                editable: false, label: app.translate([that, app], 'process_e1_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('E1',     this.model.get('E1'),          )}, }), },
                                    { name: 'CE2',               editable: false, label: app.translate([that, app], 'process_cE2_col'),           cell: Backgrid.StringCell.extend({className: function ()      { return that.warningElementCodeValue('CE2',    this.model.get('CE2'),         )}, }), },
                                    { name: 'CE3',               editable: false, label: app.translate([that, app], 'process_cE3_col'),           cell: Backgrid.StringCell.extend({className: function ()      { return that.warningElementCodeValue('CE3',    this.model.get('CE3'),         )}, }), },
                                    { name: 'CE1',               editable: false, label: app.translate([that, app], 'process_cE1_col'),           cell: Backgrid.StringCell.extend({className: function ()      { return that.warningElementCodeValue('CE1',    this.model.get('CE1'),         )}, }), },
                                    { name: 'E8',                editable: false, label: app.translate([that, app], 'process_e8_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('E8',     this.model.get('E8'),          )}, }), },
                                    { name: 'PC',                editable: false, label: app.translate([that, app], 'process_pC_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('PC',     this.model.get('PC'),          )}, }), },
                                    { name: 'I',                 editable: false, label: app.translate([that, app], 'process_i_col'),               cell: Backgrid.StringCell.extend({className: function ()    { return that.warningElementCodeValue('I',      this.model.get('I'),           )}, }), },
                                    { name: 'S1',                editable: false, label: app.translate([that, app], 'process_s1_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('S1',     this.model.get('S1'),          )}, }), },
                                    { name: 'S2',                editable: false, label: app.translate([that, app], 'process_s2_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('S2',     this.model.get('S2'),          )}, }), },
                                    { name: 'S3',                editable: false, label: app.translate([that, app], 'process_s3_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('S3',     this.model.get('S3'),          )}, }), },
                                    { name: 'S4',                editable: false, label: app.translate([that, app], 'process_s4_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('S4',     this.model.get('S4'),          )}, }), },
                                    { name: 'S5',                editable: false, label: app.translate([that, app], 'process_s5_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('S5',     this.model.get('S5'),          )}, }), },
                                    { name: 'M2',                editable: false, label: app.translate([that, app], 'process_m2_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('M2',     this.model.get('M2'),          )}, }), },
                                    { name: 'C8',                editable: false, label: app.translate([that, app], 'process_c8_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('C8',     this.model.get('C8'),          )}, }), },
                                    { name: 'D1',                editable: false, label: app.translate([that, app], 'process_d1_col'),             cell: Backgrid.StringCell.extend({className: function ()     { return that.warningElementCodeValue('D1',     this.model.get('D1'),          )}, }), },
                                    { name: 'DI',                editable: false, label: app.translate([that, app], 'process_dI_col'),              cell: Backgrid.StringCell.extend({className: function ()    { return that.warningElementCodeValue('DI',     this.model.get('DI'),          )}, }), },
                                  
                                ],
                                collection: that.model.process,        
                                row: Backgrid.Row.extend({
                                    events: function () {
                                        return {
                                            'click': this.click,
                                        };
                                    },
                                    click: function (e) {
                                        try {

                                            if ($(e.target).hasClass("timestamp")) {
                                                var modal = new Screen.Views.Modal({
                                                    model: this.model,
                                                    bus: that.bus,
                                                    showComments: false,
                                                });
                                                modal.show();
                                            }
                                        }
                                        catch (Error) { console.error(Error.stack); }
                                    }
                                })
                            });
                            that.$el.find('.process-process-grid-container').append(grid.render().el);



                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    { name: 'info', editable: false, label: '', cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell info', }), },

                                    { name: 'localTimestamp', editable: false, label: '', cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'TypeCode', editable: false, label: '', cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'SampleIdCode', editable: false, label: '', cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'C', editable: false, label: app.translate([that, app], 'process_c_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Mn', editable: false, label: app.translate([that, app], 'process_mn_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'S', editable: false, label: app.translate([that, app], 'process_s_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'P', editable: false, label: app.translate([that, app], 'process_p_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Si', editable: false, label: app.translate([that, app], 'process_si_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Cu', editable: false, label: app.translate([that, app], 'process_cu_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Ni', editable: false, label: app.translate([that, app], 'process_ni_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Cr', editable: false, label: app.translate([that, app], 'process_cr_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Mo', editable: false, label: app.translate([that, app], 'process_mo_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Sn', editable: false, label: app.translate([that, app], 'process_sn_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Nb', editable: false, label: app.translate([that, app], 'process_nb_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'V', editable: false, label: app.translate([that, app], 'process_v_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'N', editable: false, label: app.translate([that, app], 'process_n_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Al', editable: false, label: app.translate([that, app], 'process_al_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'B', editable: false, label: app.translate([that, app], 'process_b_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Ca', editable: false, label: app.translate([that, app], 'process_ca_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Pb', editable: false, label: app.translate([that, app], 'process_pb_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Ti', editable: false, label: app.translate([that, app], 'process_ti_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Mn2S', editable: false, label: app.translate([that, app], 'process_mn2S_col'),               cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Liq', editable: false, label: app.translate([that, app], 'process_liq_col'),                 cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'CorrIdx', editable: false, label: app.translate([that, app], 'process_corrIdx_col'),         cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'CE', editable: false, label: app.translate([that, app], 'process_cE_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'FP', editable: false, label: app.translate([that, app], 'process_fP_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Fe', editable: false, label: app.translate([that, app], 'process_fe_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Zn', editable: false, label: app.translate([that, app], 'process_zn_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Sb', editable: false, label: app.translate([that, app], 'process_sb_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'As', editable: false, label: app.translate([that, app], 'process_as_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Co', editable: false, label: app.translate([that, app], 'process_co_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Zr', editable: false, label: app.translate([that, app], 'process_zr_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'W', editable: false, label: app.translate([that, app], 'process_w_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Ta', editable: false, label: app.translate([that, app], 'process_ta_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Bi', editable: false, label: app.translate([that, app], 'process_bi_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Se', editable: false, label: app.translate([that, app], 'process_se_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Te', editable: false, label: app.translate([that, app], 'process_te_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Mg', editable: false, label: app.translate([that, app], 'process_mg_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'Cb', editable: false, label: app.translate([that, app], 'process_cb_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                                                                                                                      
                                    { name: 'E1', editable: false, label: app.translate([that, app], 'process_e1_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'CE2', editable: false, label: app.translate([that, app], 'process_cE2_col'),                 cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'CE3', editable: false, label: app.translate([that, app], 'process_cE3_col'),                 cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'CE1', editable: false, label: app.translate([that, app], 'process_cE1_col'),                 cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'E8', editable: false, label: app.translate([that, app], 'process_e8_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'PC', editable: false, label: app.translate([that, app], 'process_pC_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'I', editable: false, label: app.translate([that, app], 'process_i_col'),                     cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'S1', editable: false, label: app.translate([that, app], 'process_s1_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'S2', editable: false, label: app.translate([that, app], 'process_s2_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'S3', editable: false, label: app.translate([that, app], 'process_s3_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'S4', editable: false, label: app.translate([that, app], 'process_s4_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'S5', editable: false, label: app.translate([that, app], 'process_s5_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'M2', editable: false, label: app.translate([that, app], 'process_m2_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'C8', editable: false, label: app.translate([that, app], 'process_c8_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'D1', editable: false, label: app.translate([that, app], 'process_d1_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                                    { name: 'DI', editable: false, label: app.translate([that, app], 'process_dI_col'),                   cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },

                                ],
                                collection: that.model.limits,
                            });
                            that.$el.find('.process-limits-grid-container').append(grid.render().el);

                            that.applyBindings();

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

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

                            //Autocomplete Heat Names
                            that.autoCompleteCollection.setDataColl(that.model.get('heatNames'));

                            that.autocompleteView = new AutoCompleteView({
                                input: $("#search"),
                                minKeywordLength: 4,
                                model: that.autoCompleteCollection,
                            }).render();

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

        warningElementCodeValue: function (element, value) {
            var that = this,
                min = null,
                max = null;
            var limits = _.findWhere(that.model.limitsCompare, { Code: element });

            if (limits) {
                min = limits.Min;
                max = limits.Max;
            }
            if (value == '-') value = null;

            if (!value)
                return 'string-cell align-center-cell';
            if (!min && !max)
                return 'string-cell align-center-cell ok';
            if (value && min && value < min)
                return 'string-cell align-center-cell warning';
            if (value && max && value > max)
                return 'string-cell align-center-cell danger';
            if (value && max && !min  && value <= max)
                return 'string-cell align-center-cell ok';
            if (value && min && !max && value >= min)
                return 'string-cell align-center-cell ok';
            if (value && min && max && value >= min && value <= max)
                return 'string-cell align-center-cell ok';


        },

        refresh: function () {
            var currentAutcompleteText = this.autocompleteView.getClickedValue();
            if (currentAutcompleteText) {
                if (currentAutcompleteText) this.setHeatId(currentAutcompleteText);
                this.model.set({
                    heatName: currentAutcompleteText,
                })
            }


            var params = this.model.toJSON();
            this.model.set({
                isLoading_process: true,
                hasData_process: false,
            });

            this.model.fetch({
                heatId: params.heatId ? params.heatId : null,
                direction: params.direction,
                furnaceCode: params.furnaceCode == '-' ? null : params.furnaceCode,
            });

            this.model.set({
                direction: null,
            });

        },
                
        keyPressEventHandler: function (e) {
            var keyword = $("#search").val();
            if (keyword.length == 3 && e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13 && e.keyCode != 27 && e.keyCode != 8) {
                this.model.fetchPickers({
                    heatName: keyword,
                })
            } else if (keyword.length >= 9 && e.keyCode == 13)
                this.setHeatId(keyword);
            

        },

        setHeatId: function (keyword) {
            var that = this,
                obj = null;

            obj = _.where(that.model.get('heatNames'), { name: keyword });
            that.model.set('heatId', obj[0].heatId);
            that.model.set('heatName', obj[0].name);
            
        },

        updateAutocomplete: function () {
            var that = this;
            this.autoCompleteCollection.setDataColl(that.model.get('heatNames'));
        },

        updateHeatNameInURL: function () {
            var params = this.model.toJSON();

            if (params.navigation) {
                this.UpdateURL();
            }

            this.model.set({
                navigation: false,
            });

        },


        backNavBtn_click: function () {
            this.model.set({
                direction: false,
                navigation: true,
            });
            this.refresh();
        },

        forwardNavBtn_click: function () {
            this.model.set({
                direction: true,
                navigation: true,
            });
            this.refresh();

        },
        fetchnavbuttons: function (resp) {
            this.NavigationButtonView.setDataColl(resp);
        },
        process_fetched: function () {
            try {
                var that = this
                    model = null;
                if (that.model.process.length > 0) {
                    model = that.model.process.at(0).toJSON();
                }
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_process: (that.model.process.length > 0),
                            isLoading_process: false,
                            heatId: that.model.process.length > 0 ? model.heatId : null,
                            heatName: that.model.process.length > 0 ? model.heatName : null,
                        });

                    },
                    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();
        },
        exportToExcel: function () {
            var that = this,
                params = this.model.toJSON();
            var params = [
                { Name: '@heatId', Type: 'INT', Value: params.heatId, },
                { Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
            ];
            var QP = new QueryParameters();

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


            var data = {
                Data: [],
                ConnectionStringName: 'APP',
                ExportMethod: 3,
                FileName: 'LAB-Manage-Chemistries',
                TemplateFileFullPath: 'generic.xls',
                SQLDataSources: [
                    {
                        Name: 'data',
                        DatabaseParameters: {
                            DBEngine: 'SQLSERVER',
                            Procedure: app.DatabaseNames.MES + '.LAB.GetManageChemistries',
                            QueryParameters: QP,
                        },
                    },
                ]
            };

            /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
            data.Data.push({
                SheetName: 'Data',
                RowsData: [{
                    CellsData:
                        [
                            { Column: 'A', Value: 'HeatName' },
                            { Column: 'B', Value: 'GradeName' },
                            { Column: 'C', Value: 'Timestamp' },
                            { Column: 'D', Value: 'TypeCode' },
                            { Column: 'E', Value: 'SampleIdCode' },

                            { Column: 'F',Value:'C'},
                            { Column: 'G',Value:'Mn'},
                            { Column: 'H',Value:'S'},
                            { Column: 'I',Value:'P'},
                            { Column: 'J',Value:'Si'},
                            { Column: 'K',Value:'Cu'},
                            { Column: 'L',Value:'Ni'},
                            { Column: 'M',Value:'Cr'},
                            { Column: 'N',Value:'Mo'},
                            { Column: 'O',Value:'Sn'},
                            { Column: 'P',Value:'Nb'},
                            { Column: 'Q',Value:'V'},
                            { Column: 'R',Value:'N'},
                            { Column: 'S',Value:'Al'},
                            { Column: 'T',Value:'B'},
                            { Column: 'U',Value:'Ca'},
                            { Column: 'V',Value:'Pb'},
                            { Column: 'W',Value:'Ti'},
                            { Column: 'X',Value:'Mn2S'},
                            { Column: 'Y',Value:'Liq'},
                            { Column: 'Z',Value:'CorrIdx'},
                            { Column: 'AA',Value:'CE'},
                            { Column: 'AB',Value:'FP'},
                            { Column: 'AC',Value:'Fe'},
                            { Column: 'AD',Value:'Zn'},
                            { Column: 'AE',Value:'Sb'},
                            { Column: 'AF',Value:'As'},
                            { Column: 'AG',Value:'Co'},
                            { Column: 'AH',Value:'Zr'},
                            { Column: 'AI',Value:'W'},
                            { Column: 'AJ',Value:'Ta'},
                            { Column: 'AK',Value:'Bi'},
                            { Column: 'AL',Value:'Se'},
                            { Column: 'AM',Value:'Te'},
                            { Column: 'AN',Value:'Mg'},
                            { Column: 'AO',Value:'Cb'},
                            { Column: 'AP',Value:'E1'},
                            { Column: 'AQ',Value:'CE2'},
                            { Column: 'AR',Value:'CE3'},
                            { Column: 'AS',Value:'CE1'},
                            { Column: 'AT',Value:'E8'},
                            { Column: 'AU',Value:'PC'},
                            { Column: 'AV',Value:'I'},
                            { Column: 'AW',Value:'S1'},
                            { Column: 'AX',Value:'S2'},
                            { Column: 'AY',Value:'S3'},
                            { Column: 'AZ',Value:'S4'},
                            { Column: 'BA',Value:'S5'},
                            { Column: 'BB',Value:'M2'},
                            { Column: 'BC',Value:'C8'},
                            { Column: 'BD',Value:'D1'},
                            { Column: 'BE',Value:'DI'},                              
                            { Column: 'BF',Value:'Info'},     

                        ],
                }],
                StartRowIndex: 1,
            });

            data.Data.push({
                SheetName: 'Data',
                RowsData: [],
                StartRowIndex: 2,
                DataSourceName: 'data',
                DataSourceTableIndex: 0,
                SQLCellsData:
                    [
                        { ExcelColumnName: 'A', SQLDataColumnName: 'HeatName', DataType: 'String' },
                        { ExcelColumnName: 'B', SQLDataColumnName: 'GradeName', DataType: 'String' },
                        { ExcelColumnName: 'C', SQLDataColumnName: 'LocalTimestamp', DataType: 'String' },
                        { ExcelColumnName: 'D', SQLDataColumnName: 'TypeCode', DataType: 'String' },
                        { ExcelColumnName: 'E', SQLDataColumnName: 'SampleIdCode', DataType: 'String' },
                        { ExcelColumnName: 'F', SQLDataColumnName: 'C', DataType: 'String'},
                        { ExcelColumnName: 'G', SQLDataColumnName: 'Mn', DataType: 'String' },
                        { ExcelColumnName: 'H', SQLDataColumnName: 'S', DataType: 'String' },
                        { ExcelColumnName: 'I', SQLDataColumnName: 'P', DataType: 'String' },
                        { ExcelColumnName: 'J', SQLDataColumnName: 'Si', DataType: 'String' },
                        { ExcelColumnName: 'K', SQLDataColumnName: 'Cu', DataType: 'String' },
                        { ExcelColumnName: 'L', SQLDataColumnName: 'Ni', DataType: 'String' },
                        { ExcelColumnName: 'M', SQLDataColumnName: 'Cr', DataType: 'String' },
                        { ExcelColumnName: 'N', SQLDataColumnName: 'Mo', DataType: 'String' },
                        { ExcelColumnName: 'O', SQLDataColumnName: 'Sn', DataType: 'String' },
                        { ExcelColumnName: 'P', SQLDataColumnName: 'Nb', DataType: 'String' },
                        { ExcelColumnName: 'Q', SQLDataColumnName: 'V', DataType: 'String' },
                        { ExcelColumnName: 'R', SQLDataColumnName: 'N', DataType: 'String' },
                        { ExcelColumnName: 'S', SQLDataColumnName: 'Al', DataType: 'String' },
                        { ExcelColumnName: 'T', SQLDataColumnName: 'B', DataType: 'String' },
                        { ExcelColumnName: 'U', SQLDataColumnName: 'Ca', DataType: 'String' },
                        { ExcelColumnName: 'V', SQLDataColumnName: 'Pb', DataType: 'String' },
                        { ExcelColumnName: 'W', SQLDataColumnName: 'Ti', DataType: 'String' },
                        { ExcelColumnName: 'X', SQLDataColumnName: 'Mn2S', DataType: 'String' },
                        { ExcelColumnName: 'Y', SQLDataColumnName: 'Liq', DataType: 'String' },
                        { ExcelColumnName: 'Z', SQLDataColumnName: 'CorrIdx', DataType: 'String' },
                        { ExcelColumnName: 'AA', SQLDataColumnName: 'CE', DataType: 'String' },
                        { ExcelColumnName: 'AB', SQLDataColumnName: 'FP', DataType: 'String' },
                        { ExcelColumnName: 'AC', SQLDataColumnName: 'Fe', DataType: 'String' },
                        { ExcelColumnName: 'AD', SQLDataColumnName: 'Zn', DataType: 'String' },
                        { ExcelColumnName: 'AE', SQLDataColumnName: 'Sb', DataType: 'String' },
                        { ExcelColumnName: 'AF', SQLDataColumnName: 'As', DataType: 'String' },
                        { ExcelColumnName: 'AG', SQLDataColumnName: 'Co', DataType: 'String' },
                        { ExcelColumnName: 'AH', SQLDataColumnName: 'Zr', DataType: 'String' },
                        { ExcelColumnName: 'AI', SQLDataColumnName: 'W', DataType: 'String'},
                        { ExcelColumnName: 'AJ', SQLDataColumnName: 'Ta', DataType: 'String' },
                        { ExcelColumnName: 'AK', SQLDataColumnName: 'Bi', DataType: 'String' },
                        { ExcelColumnName: 'AL', SQLDataColumnName: 'Se', DataType: 'String' },
                        { ExcelColumnName: 'AM', SQLDataColumnName: 'Te', DataType: 'String' },
                        { ExcelColumnName: 'AN', SQLDataColumnName: 'Mg', DataType: 'String' },
                        { ExcelColumnName: 'AO', SQLDataColumnName: 'Cb', DataType: 'String' },
                        { ExcelColumnName: 'AP', SQLDataColumnName: 'E1', DataType: 'String' },
                        { ExcelColumnName: 'AQ', SQLDataColumnName: 'CE2', DataType: 'String' },
                        { ExcelColumnName: 'AR', SQLDataColumnName: 'CE3', DataType: 'String' },
                        { ExcelColumnName: 'AS', SQLDataColumnName: 'CE1', DataType: 'String' },
                        { ExcelColumnName: 'AT', SQLDataColumnName: 'E8' , DataType: 'String'},
                        { ExcelColumnName: 'AU', SQLDataColumnName: 'PC', DataType: 'String'},
                        { ExcelColumnName: 'AV', SQLDataColumnName: 'I', DataType: 'String'},
                        { ExcelColumnName: 'AW', SQLDataColumnName: 'S1', DataType: 'String' },
                        { ExcelColumnName: 'AX', SQLDataColumnName: 'S2', DataType: 'String' },
                        { ExcelColumnName: 'AY', SQLDataColumnName: 'S3', DataType: 'String' },
                        { ExcelColumnName: 'AZ', SQLDataColumnName: 'S4', DataType: 'String' },
                        { ExcelColumnName: 'BA', SQLDataColumnName: 'S5', DataType: 'String' },
                        { ExcelColumnName: 'BB', SQLDataColumnName: 'M2', DataType: 'String' },
                        { ExcelColumnName: 'BC', SQLDataColumnName: 'C8', DataType: 'String' },
                        { ExcelColumnName: 'BD', SQLDataColumnName: 'D1', DataType: 'String' },
                        { ExcelColumnName: 'BE', SQLDataColumnName: 'DI', DataType: 'String' },
                        { ExcelColumnName: 'BF', SQLDataColumnName: 'Comments', DataType: 'String' },        

                    ],
            });


            data.Data.push({
                SheetName: 'Limits',
                RowsData: [{
                    CellsData:
                        [
                            { Column: 'A', Value: 'Code' },
                            { Column: 'B', Value: 'C' },
                            { Column: 'C', Value: 'Mn' },
                            { Column: 'D', Value: 'S' },
                            { Column: 'E', Value: 'P' },
                            { Column: 'F', Value: 'Si' },
                            { Column: 'G', Value: 'Cu' },
                            { Column: 'H', Value: 'Ni' },
                            { Column: 'I', Value: 'Cr' },
                            { Column: 'J', Value: 'Mo' },
                            { Column: 'K', Value: 'Sn' },
                            { Column: 'L', Value: 'Nb' },
                            { Column: 'M', Value: 'V' },
                            { Column: 'N', Value: 'N' },
                            { Column: 'O', Value: 'Al' },
                            { Column: 'P', Value: 'B' },
                            { Column: 'Q', Value: 'Ca' },
                            { Column: 'R', Value: 'Pb' },
                            { Column: 'S', Value: 'Ti' },
                            { Column: 'T', Value: 'Mn2S' },
                            { Column: 'U', Value: 'Liq' },
                            { Column: 'V', Value: 'CorrIdx' },
                            { Column: 'W', Value: 'CE' },
                            { Column: 'X', Value: 'FP' },
                            { Column: 'Y', Value: 'Fe' },
                            { Column: 'Z', Value: 'Zn' },
                            { Column: 'AA', Value: 'Sb' },
                            { Column: 'AB', Value: 'As' },
                            { Column: 'AC', Value: 'Co' },
                            { Column: 'AD', Value: 'Zr' },
                            { Column: 'AE', Value: 'W' },
                            { Column: 'AF', Value: 'Ta' },
                            { Column: 'AG', Value: 'Bi' },
                            { Column: 'AH', Value: 'Se' },
                            { Column: 'AI', Value: 'Te' },
                            { Column: 'AJ', Value: 'Mg' },
                            { Column: 'AK', Value: 'Cb' },
                            { Column: 'AL', Value: 'E1' },
                            { Column: 'AM', Value: 'CE2' },
                            { Column: 'AN', Value: 'CE3' },
                            { Column: 'AO', Value: 'CE1' },
                            { Column: 'AP', Value: 'E8' },
                            { Column: 'AQ', Value: 'PC' },
                            { Column: 'AR', Value: 'I' },
                            { Column: 'AS', Value: 'S1' },
                            { Column: 'AT', Value: 'S2' },
                            { Column: 'AU', Value: 'S3' },
                            { Column: 'AV', Value: 'S4' },
                            { Column: 'AW', Value: 'S5' },
                            { Column: 'AX', Value: 'M2' },
                            { Column: 'AY', Value: 'C8' },
                            { Column: 'AZ', Value: 'D1' },
                            { Column: 'BA', Value: 'DI' },     


                        ],
                }],
                StartRowIndex: 8,
            });

            data.Data.push({
                SheetName: 'Limits',
                RowsData: [],
                StartRowIndex: 9,
                DataSourceName: 'data',
                DataSourceTableIndex: 1,
                SQLCellsData:
                    [
                        { ExcelColumnName: 'A', SQLDataColumnName: 'SampleIdCode', DataType: 'String'},
                        { ExcelColumnName: 'B', SQLDataColumnName: 'C', DataType: 'String'},
                        { ExcelColumnName: 'C', SQLDataColumnName: 'Mn', DataType: 'String' },
                        { ExcelColumnName: 'D', SQLDataColumnName: 'S', DataType: 'String' },
                        { ExcelColumnName: 'E', SQLDataColumnName: 'P', DataType: 'String' },
                        { ExcelColumnName: 'F', SQLDataColumnName: 'Si', DataType: 'String' },
                        { ExcelColumnName: 'G', SQLDataColumnName: 'Cu', DataType: 'String' },
                        { ExcelColumnName: 'H', SQLDataColumnName: 'Ni', DataType: 'String' },
                        { ExcelColumnName: 'I', SQLDataColumnName: 'Cr', DataType: 'String' },
                        { ExcelColumnName: 'J', SQLDataColumnName: 'Mo', DataType: 'String' },
                        { ExcelColumnName: 'K', SQLDataColumnName: 'Sn', DataType: 'String' },
                        { ExcelColumnName: 'L', SQLDataColumnName: 'Nb', DataType: 'String' },
                        { ExcelColumnName: 'M', SQLDataColumnName: 'V', DataType: 'String' },
                        { ExcelColumnName: 'N', SQLDataColumnName: 'N', DataType: 'String' },
                        { ExcelColumnName: 'O', SQLDataColumnName: 'Al', DataType: 'String' },
                        { ExcelColumnName: 'P', SQLDataColumnName: 'B', DataType: 'String' },
                        { ExcelColumnName: 'Q', SQLDataColumnName: 'Ca', DataType: 'String' },
                        { ExcelColumnName: 'R', SQLDataColumnName: 'Pb', DataType: 'String' },
                        { ExcelColumnName: 'S', SQLDataColumnName: 'Ti', DataType: 'String' },
                        { ExcelColumnName: 'T', SQLDataColumnName: 'Mn2S', DataType: 'String' },
                        { ExcelColumnName: 'U', SQLDataColumnName: 'Liq', DataType: 'String' },
                        { ExcelColumnName: 'V', SQLDataColumnName: 'CorrIdx', DataType: 'String' },
                        { ExcelColumnName: 'W', SQLDataColumnName: 'CE', DataType: 'String' },
                        { ExcelColumnName: 'X', SQLDataColumnName: 'FP', DataType: 'String' },
                        { ExcelColumnName: 'Y', SQLDataColumnName: 'Fe', DataType: 'String' },
                        { ExcelColumnName: 'Z', SQLDataColumnName: 'Zn', DataType: 'String' },
                        { ExcelColumnName: 'AA', SQLDataColumnName: 'Sb', DataType: 'String' },
                        { ExcelColumnName: 'AB', SQLDataColumnName: 'As', DataType: 'String' },
                        { ExcelColumnName: 'AC', SQLDataColumnName: 'Co', DataType: 'String' },
                        { ExcelColumnName: 'AD', SQLDataColumnName: 'Zr', DataType: 'String' },
                        { ExcelColumnName: 'AE', SQLDataColumnName: 'W', DataType: 'String' },
                        { ExcelColumnName: 'AF', SQLDataColumnName: 'Ta', DataType: 'String' },
                        { ExcelColumnName: 'AG', SQLDataColumnName: 'Bi', DataType: 'String' },
                        { ExcelColumnName: 'AH', SQLDataColumnName: 'Se', DataType: 'String' },
                        { ExcelColumnName: 'AI', SQLDataColumnName: 'Te', DataType: 'String' },
                        { ExcelColumnName: 'AJ', SQLDataColumnName: 'Mg', DataType: 'String' },
                        { ExcelColumnName: 'AK', SQLDataColumnName: 'Cb', DataType: 'String' },
                        { ExcelColumnName: 'AL', SQLDataColumnName: 'E1', DataType: 'String' },
                        { ExcelColumnName: 'AM', SQLDataColumnName: 'CE2', DataType: 'String' },
                        { ExcelColumnName: 'AN', SQLDataColumnName: 'CE3', DataType: 'String' },
                        { ExcelColumnName: 'AO', SQLDataColumnName: 'CE1', DataType: 'String' },
                        { ExcelColumnName: 'AP', SQLDataColumnName: 'E8', DataType: 'String' },
                        { ExcelColumnName: 'AQ', SQLDataColumnName: 'PC', DataType: 'String' },
                        { ExcelColumnName: 'AR', SQLDataColumnName: 'I', DataType: 'String' },
                        { ExcelColumnName: 'AS', SQLDataColumnName: 'S1', DataType: 'String' },
                        { ExcelColumnName: 'AT', SQLDataColumnName: 'S2', DataType: 'String' },
                        { ExcelColumnName: 'AU', SQLDataColumnName: 'S3', DataType: 'String' },
                        { ExcelColumnName: 'AV', SQLDataColumnName: 'S4', DataType: 'String' },
                        { ExcelColumnName: 'AW', SQLDataColumnName: 'S5', DataType: 'String' },
                        { ExcelColumnName: 'AX', SQLDataColumnName: 'M2', DataType: 'String' },
                        { ExcelColumnName: 'AY', SQLDataColumnName: 'C8', DataType: 'String' },
                        { ExcelColumnName: 'AZ', SQLDataColumnName: 'D1', DataType: 'String' },
                        { ExcelColumnName: 'BA', SQLDataColumnName: 'DI', DataType: 'String' },     

                        
                    ],
            });



            Core.Export.Excel(
                data,
                function (resp) {
                    try {
                        if ((resp) && (resp.Success == true) && (resp.Data)) {
                            location.href = app.foldersRoot + '/excel/' + resp.Data;

                        }
                        else {
                            if ((resp) && (resp.Message))
                                console.error(resp.Message);
                            else
                                console.error('Server response not valid.');
                        }
                    }
                    catch (Error) { console.error(Error); }
                    that.model.setExportButtonExporting(false);
                },
                function (resp) {
                    that.model.refreshProcesses();
                    that.model.setExportButtonExporting(false);
                    console.error(resp);
                }
            );
        },
        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.Process = Backbone.Epoxy.Model.extend({
        defaults: {
            info: '-',
            Al :                        null,
            As :                        null,
            B :                         null,
            Bi :                        null,
            C :                         null,
            C8 :                        null,
            CE :                        null,
            CE1 :                       null,
            CE2 :                       null,
            CE3 :                       null,
            Ca :                        null,
            Cb :                        null,
            Co:                         null,
            comments:                   null,
            CorrIdx:                    null,
            Cr :                        null,
            Cu :                        null,
            D1 :                        null,
            DI :                        null,
            E1 :                        null,
            E8 :                        null,
            FP :                        null,
            Fe :                        null,
            gradeId:                    null,
            gradeName:                  null,
            gradeVersionId:             null,
            heatId:                     null,
            heatName:                   null,
            heatNameSent:               null,
            I :                         null,
            Id :                        null,
            Liq:                        null,
            localTimestamp:             null,
            M2 :                        null,
            Mg :                        null,
            Mn :                        null,
            Mn2S :                      null,
            Mo :                        null,
            N :                         null,
            Nb :                        null,
            Ni :                        null,
            P :                         null,
            PC :                        null,
            Pb:                         null,
            processTimestamp:           null,
            S :                         null,
            S1 :                        null,
            S2 :                        null,
            S3 :                        null,
            S4 :                        null,
            S5:                         null,
            SampleIdCode:               null,
            Sb :                        null,
            Se :                        null,
            Si :                        null,
            Sn :                        null,
            Ta :                        null,
            Te :                        null,
            Ti:                         null,
            timestamp:                  null,
            TypeCode:                   null,
            V :                         null,
            W :                         null,
            Zn :                        null,
            Zr:                         null,
            location: null,
        },

        parse: function (obj) {
            var result = {
                Al :                                    obj.Al ?                             obj.Al.toFixed(4): '-',
                As :                                    obj.As ?                             obj.As.toFixed(4) :  '-',
                B :                                     obj.B ?                              obj.B.toFixed(4) :  '-',
                Bi :                                    obj.Bi ?                             obj.Bi.toFixed(4) :  '-',
                C :                                     obj.C ?                              obj.C.toFixed(4) :  '-',
                C8 :                                    obj.C8 ?                             obj.C8.toFixed(4) :  '-',
                CE :                                    obj.CE ?                             obj.CE.toFixed(4) :  '-',
                CE1 :                                   obj.CE1 ?                            obj.CE1.toFixed(4) :  '-',
                CE2 :                                   obj.CE2 ?                            obj.CE2.toFixed(4) :  '-',
                CE3 :                                   obj.CE3 ?                            obj.CE3.toFixed(4) :  '-',
                Ca :                                    obj.Ca ?                             obj.Ca.toFixed(4) :  '-',
                Cb :                                    obj.Cb ?                             obj.Cb.toFixed(4) :  '-',
                Co:                                    obj.Co ?                             obj.Co.toFixed(4) :  '-',
                comments:                              obj.Comments ?                       obj.Comments :  '-',
                CorrIdx:                               obj.CorrIdx ?                        obj.CorrIdx.toFixed(4) :  '-',
                Cr :                                    obj.Cr ?                             obj.Cr.toFixed(4) :  '-',
                Cu :                                    obj.Cu ?                             obj.Cu.toFixed(4) :  '-',
                D1 :                                    obj.D1 ?                             obj.D1.toFixed(4) :  '-',
                DI :                                    obj.DI ?                             obj.DI.toFixed(4) :  '-',
                E1 :                                    obj.E1 ?                             obj.E1.toFixed(4) :  '-',
                E8 :                                    obj.E8 ?                             obj.E8.toFixed(4) :  '-',
                FP :                                    obj.FP ?                             obj.FP.toFixed(4) :  '-',
                Fe :                                    obj.Fe ?                             obj.Fe.toFixed(4) :  '-',
                gradeId:                               obj.GradeId ?                        obj.GradeId :  '-',
                gradeName:                             obj.GradeName ?                      obj.GradeName :  '-',
                gradeVersionId:                        obj.GradeVersionId ?                 obj.GradeVersionId :  '-',
                heatId:                                obj.HeatId ?                         obj.HeatId :  '-',
                heatName:                              obj.HeatName ?                       obj.HeatName:  '-',
                heatNameSent:                          obj.HeatNameSent ?                   obj.HeatNameSent :  '-',
                I :                                      obj.I ?                              obj.I.toFixed(4) :  '-',
                Id :                                     obj.Id ?                             obj.Id.toFixed(4) :  '-',
                Liq:                                    obj.Liq ?                            obj.Liq.toFixed(4) :  '-',
                localTimestamp:                        obj.LocalTimestamp ?                 new moment(obj.LocalTimestamp).format('MM/DD/YY HH:mm'):  '-',
                M2 :                                       obj.M2 ?                             obj.M2.toFixed(4) :  '-',
                Mg :                                       obj.Mg ?                             obj.Mg.toFixed(4) :  '-',
                Mn :                                       obj.Mn ?                             obj.Mn.toFixed(4) :  '-',
                Mn2S :                                     obj.Mn2S ?                           obj.Mn2S.toFixed(4) :  '-',
                Mo :                                       obj.Mo ?                             obj.Mo.toFixed(4) :  '-',
                N :                                        obj.N ?                              obj.N.toFixed(4) :  '-',
                Nb :                                       obj.Nb ?                             obj.Nb.toFixed(4) :  '-',
                Ni :                                       obj.Ni ?                             obj.Ni.toFixed(4) :  '-',
                P :                                        obj.P ?                              obj.P.toFixed(4) :  '-',
                PC :                                       obj.PC ?                             obj.PC.toFixed(4) :  '-',
                Pb:                                       obj.Pb ?                             obj.Pb.toFixed(4) :  '-',
                processTimestamp:                      obj.ProcessTimestamp ?               obj.ProcessTimestamp:  '-',
                S :                                     obj.S ?                              obj.S.toFixed(4) :  '-',
                S1 :                                    obj.S1 ?                             obj.S1.toFixed(4) :  '-',
                S2 :                                    obj.S2 ?                             obj.S2.toFixed(4) :  '-',
                S3 :                                    obj.S3 ?                             obj.S3.toFixed(4) :  '-',
                S4 :                                    obj.S4 ?                             obj.S4.toFixed(4) :  '-',
                S5:                                    obj.S5 ?                             obj.S5.toFixed(4) :  '-',
                SampleIdCode:                          obj.SampleIdCode ?                   obj.SampleIdCode :  '-',
                Sb :                                    obj.Sb ?                             obj.Sb.toFixed(4) :  '-',
                Se :                                    obj.Se ?                             obj.Se.toFixed(4) :  '-',
                Si :                                    obj.Si ?                             obj.Si.toFixed(4) :  '-',
                Sn :                                    obj.Sn ?                             obj.Sn.toFixed(4) :  '-',
                Ta :                                    obj.Ta ?                             obj.Ta.toFixed(4) :  '-',
                Te :                                    obj.Te ?                             obj.Te.toFixed(4) :  '-',
                Ti:                                    obj.Ti ?                             obj.Ti.toFixed(4) :  '-',
                timestamp:                             obj.Timestamp ?                      obj.Timestamp :  '-',
                TypeCode:                              obj.TypeCode ?                       obj.TypeCode :  '-',
                location: (obj.TypeCode ? obj.TypeCode : '') + (obj.SampleIdCode ? (' - ' + obj.SampleIdCode) : ''),
                V :                                     obj.V ?                              obj.V.toFixed(4) :  '-',
                W :                                     obj.W ?                              obj.W.toFixed(4) :  '-',
                Zn :                                    obj.Zn ?                             obj.Zn.toFixed(4) :  '-',
                Zr:                                    obj.Zr ?                             obj.Zr.toFixed(4) :  '-',   



            };
            return result;
        }

    });
    Screen.Collections.Process = Backbone.Collection.extend({
        model: Screen.Models.Process,
        setDataColl: function (data) {
            var newColl,
                that = this;
            newColl = _.map(data, that.model.prototype.parse);
            that.set(newColl).trigger('fetch', that, data);
        },
    });


    Screen.Models.HeatName = Backbone.Model.extend({
        label: function () {
            return this.get("name");
        }
    });
    Screen.Collections.HeatNames = Backbone.Collection.extend({
        model: Screen.Models.HeatName,

        setDataColl: function (data) {
            var newColl,
                that = this;
            newColl = _.map(data, that.model.prototype.parse);
            that.set(newColl);
        },
    });

    Screen.Models.CommentsCollection = Backbone.Model.extend({
        defaults: {
            user: null,
            datetime: null,
            msg: null,
        },

        parse: function (obj) {
            var result = {
                user: obj.user ? obj.user : '-',
                datetime: obj.datetime ? new moment(obj.datetime).format('YYYY-MM-DD HH:mm:ss') : '-',
                msg: obj.msg ? obj.msg : '-',
            };
            return result;
        }
    });
    Screen.Collections.CommentsCollection = Backbone.Collection.extend({
        model: Screen.Models.CommentsCollection,
        comparator : -'datetime',
        setDataColl: function (data) {
            var newColl,
                that = this;
            newColl = _.map(data, that.model.prototype.parse);
            that.set(newColl);
        },
    });

    Screen.Models.ModalMain = Backbone.Epoxy.Model.extend({
        defaults: {
            errorMsg: '',
            processing: false,
            heatName: null,
            SampleIdCode: null,
            TypeCode: null,
            gradeName: null,
            currentDatetime: null,
            dateModal: null, //new moment().format('MM/DD/YYYY'),
            timeModal: null, //new moment().format('HH:mm:ss'),
            showComments: false,
            comments: null,
        },

    });

    Screen.Views.Modal = Backbone.Epoxy.View.extend({
        template: "manage-chemistries",
        id: "manage-chemistries",
        className: "modal hide fade",
        attributes: {
            'data-bind': "classes: { modalComments: showComments, } ",
        },
        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,
        row: [],
        commentsColl:[],
        initialize: function (options) {
            _.extend(this, options);

            this.row = options.model;
            this.model = new Screen.Models.ModalMain();
            this.model.set({
                dateModal: new moment().format('MM/DD/YYYY'),
                timeModal: new moment().format('HH:mm:ss'),
                gradeName: options.model.get('gradeName'),
                TypeCode: options.model.get('TypeCode'),
                currentDatetime: options.model.get('localTimestamp'),
                SampleIdCode: options.model.get('SampleIdCode'),
                heatName: options.model.get('heatName'),
                dateModal: new moment(options.model.get('localTimestamp')).format('MM/DD/YYYY'),
                timeModal: new moment(options.model.get('localTimestamp')).format('HH:mm'),
                showComments: options.showComments,
                comments: options.model.get('comments'),
            });
            this.bus = options.bus;

            this.commentsColl = new Screen.Collections.CommentsCollection();

            this.getCommentsCollection();

            this.bindEvents();

            return this;
        },

        getCommentsCollection() {
            var str = this.model.get('comments');
            var res = str.split("[");
            var mySubString = null;

            var aux = {},
                data = [],
                user = null,
                datetime = null,
                msg = null;
            _.each(res, function (obj, i) {
                if (i != 0) {
                    user = obj.substring(
                        obj.lastIndexOf("User : ") + 7,
                        obj.lastIndexOf("Datetime")
                    );
                    datetime = obj.substring(
                        obj.lastIndexOf("Datetime : ") + 11,
                        obj.lastIndexOf("Msg")
                    );
                    msg = obj.substring(
                        obj.lastIndexOf("Msg : ") + 6,
                        obj.lastIndexOf("]")
                    );
                    aux = {
                        user: user,
                        datetime: datetime,
                        msg: msg,
                    }
                    data.push(aux);
                }
                user = null;
                datetime = null;
                msg = null;
            });

            this.commentsColl.setDataColl(data);
        },

        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()));

                    var grid = new Backgrid.Grid({
                        className: 'backgrid table table-hover table-condensed',
                        columns: [
                            { name: 'user', editable: false, label: 'User', cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell info', }), },

                            { name: 'datetime', editable: false, label: 'Datetime', cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                            { name: 'msg', editable: false, label: 'Message', cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell timestamp', }), },
                          
                        ],
                        collection: that.commentsColl,
                    });
                    that.$el.find('.process-comments-grid-container').append(grid.render().el);


                    that.applyBindings();

                    that.isRendered = true;

                    that.$el.find('#dateModal').datepicker();
                    that.$el.find('#timeModal').timepicker({
                        showMeridian: false,
                        secondStep: 1,
                        minuteStep: 1,
                        //showSeconds: true,
                    });


                    that.trigger("render");
                    if (!that.model.get("equipmentsLength")) {
                        that.$el.find('#spares').attr("disabled", true);
                    }


                }, true, customPath);

            }, customPath, "modal");

        },
        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 () {
        },

        acceptBtn_click: function (e) {
            try {
                var modelAttrs = this.model.toJSON();
                var params = {
                    datetime: new moment(modelAttrs.dateModal, 'MM/DD/YYYY').format('YYYY-MM-DD') + ' ' + new moment(modelAttrs.timeModal, 'HH:mm:ss').format('HH:mm:ss'),
                    row: this.row,
                }
                this.bus.trigger("modalAcceptBtn", params);

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

    });

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

