//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/modal2',
    'modules/modal-sulpher-print/modal-sulpher-print',
    'backgrid/infinator',
    'backgrid/moment-cell',
    'backgrid/duration-cell',
    'backgrid/grouped-columns',

    "js/jquery.floatThead/jquery.floatThead",
    'js/jquery.contextMenu/jquery.contextMenu',
],
    function (app, T, Backgrid, moment,Modal, SulpherPrintModal) {

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                start: new moment().subtract(2, 'days').format('YYYY-MM-DD'),
                end: new moment().format('YYYY-MM-DD'),

                casterCode: 1,
                casters: [{ label: '1', value: 1 }, { label: '2', value: 2 }],

                crewId: null,
                crews: [{ label: 'A', value: 'A' }, { label: 'B', value: 'B' }, { label: 'C', value: 'C' }, { label: 'D', value: 'D' }],

                shiftId: null,
                shifts: [{ label: 'D', value: 1 }, { label: 'N', value: '2' }],

                hasData: false,
                isLoading: false,
                heatName: null,

                showAssignOption:true,
               // reassignHeatOption: false,
                rowModel: [],
                contextMenuOption:1,
                
                index: null,
                grid: [],
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },
            reassing: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@processId', Type: 'INT', Value: params.processId, },
                        { Name: '@heatId', Type: 'INT', Value: params.heatId, },
                    ];
                   // return 0;

                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });
                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.AssignCasterProcessMES',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Heat Assigned', { stay: 5000, });
                                        that.trigger('reassigned');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                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
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            unassing: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@processId', Type: 'INT', Value: params.processId, },
                    ];
                    // return 0;

                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.UnassignCasterProcessMES',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Heat Unassigned', { stay: 5000, });
                                        that.trigger('reassigned');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                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
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }

        });


        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-production',
            id: 'caster-production',
            title: 'Caster Production',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    "click .btn-export-to-excel": this.exportToExcel,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            itemsColl: null,
            subviews: null,
            viewParams: null,

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

                var that = this;

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

                this.grids = {};

                this.itemsColl = new Screen.Collections.Items();
             
                this.bindingSources = {};

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

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

                
                this.bus.on("freeOpenUpdated", this.onFreeOpenUpdated, this);

                this.bindEvents();
            },
            bindEvents: function () {
                this.listenTo(this.itemsColl, 'fetch', this.processes_ready)
                    .listenTo(this.model, 'reassigned', this.reassigned_ready);

            },
            reassigned_ready: function () {
                this.refreshBtn_click();
            },
            onModalUnassignBtn: function (processId) {
                this.model.reassing({
                    processId: processId,
                    heatId: null,
                })
            },

            onModalAcceptBtn: function (processId,heatId) {
                this.model.reassing({
                    processId: processId,
                    heatId: heatId,
                })
            },
            onFreeOpenUpdated: function(){
                this.refreshBtn_click();
            },
            _refresh: function (opt) {
                this.itemsColl.reset();

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

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

                this.refreshProcesses(opt);

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

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

                var fixedParams = _.extend({}, Screen.Models.Main.prototype.defaults, viewParams);

                if (viewParams.start)
                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.casterCode)
                    fixedParams.casterCode = (viewParams.casterCode != '-' && viewParams.casterCode != null) ? parseInt(viewParams.casterCode, 10) : null;
                if (viewParams.crewId)
                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                if (viewParams.shiftId)
                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;

                this.model.set(fixedParams);

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

            render: function (container, viewParams) {
                var that = this;

                this.viewParams = viewParams;

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

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

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

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

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

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


                                var columns = [
                                    {
                                        name: 'HeatNameColumn',
                                        label: app.translate([that, app], 'Heat'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: function(){
                                                var model = this.model.toJSON();
                                                if (!model.HeatId) return 'string-cell align-center-cell warning heat-row';
                                                else if (model.CasterHeatName == 'UNK') return 'string-cell align-center-cell heat-reassigned heat-row';
                                                else return 'string-cell align-center-cell heat-row';
                                            },
                                        }),                                       
                                    },                                  
                                    {
                                        name: 'MeltOrder',
                                        label: app.translate([that, app], 'Melt Order'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell start-row',
                                        }),
                                        editable: false,
                                    },

                                    {
                                        name: 'GradeName',
                                        label: app.translate([that, app], 'Grade'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell start-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Product',
                                        label: app.translate([that, app], 'Product'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell start-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'CasterCode',
                                        label: app.translate([that, app], 'Caster'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Start',
                                        label: 'Start',
                                        editable: false,
                                        cell: Backgrid.Extension.MomentCell.extend({
                                            className: 'momment-cell align-center-cell timestamp',
                                            modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                            displayFormat: 'MM/DD/YY HH:mm',
                                            initialize: function (options) {
                                                this.momentValue = new moment(options.model.get('Start')).format('YYYY-MM-DD HH:mm:ss') || null;
                                                Backgrid.Extension.MomentCell.prototype.initialize.apply(this, arguments);
                                            },
                                            render: function () {
                                                // Use this.momentValue to display the Moment value in your custom rendering logic
                                                // You can format and display it as needed.
                                                this.$el.html(this.formatter.fromRaw(this.momentValue, this.model));
                                                this.delegateEvents();
                                                return this;
                                            }
                                        }),
                                    },
                                    //{
                                    //    name: 'Start',
                                    //    label: app.translate([that, app], 'Start'),
                                    //    cell: Backgrid.StringCell.extend({
                                    //        className: 'string-cell align-center-cell start-row',
                                    //    }),
                                    //    editable: false,
                                    //},
                                    {
                                        name: 'CrewId',
                                        label: app.translate([that, app], 'Crew'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'IsQuickShroud',
                                        label: 'Quick Shroud',
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'NonFreeOpen',
                                        label: 'Non Free Open',
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Rods',
                                        label: app.translate([that, app], 'Rods'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    
                                    {
                                        name: 'Shift',
                                        label: app.translate([that, app], 'Shift'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'LadleWaitTime',
                                        label: app.translate([that, app], 'Wait'),
                                        cell: Backgrid.StringCell.extend({
                                            className: function () {
                                                if (this.model.get('LadleWaitTimeStatus') == 'WARNING') return 'string-cell align-center-cell warning ladle-times-row';
                                                else return 'string-cell align-center-cell ladle-times-row';
                                            },
                                            formatter: Backgrid.Extension.DurationFormatter.extend({
                                                displayFormat: 'm:s',
                                                modelFormat: 's',
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'LadleOpeningTime',
                                        label: app.translate([that, app], 'Opening'),
                                        cell: Backgrid.StringCell.extend({
                                            className: function () {
                                                if (this.model.get('LadleOpeningTimeStatus') == 'WARNING') return 'string-cell align-center-cell warning ladle-times-row';
                                                else return 'string-cell align-center-cell ladle-times-row';
                                            },
                                            formatter: Backgrid.Extension.DurationFormatter.extend({
                                                displayFormat: 'm:s',
                                                modelFormat: 's',
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'LadleOpenTime',
                                        label: app.translate([that, app], 'Open'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell ladle-times-row',
                                            formatter: Backgrid.Extension.DurationFormatter.extend({
                                                displayFormat: 'm:s',
                                                modelFormat: 's',
                                            }),
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'TundishNumber',
                                        label: app.translate([that, app], 'Num'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell shift-crew-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MinTundishTemperature',
                                        label: app.translate([that, app], 'Min Temper'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell tundish-rows',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'AverageTundishTemperature',
                                        label: app.translate([that, app], 'Avg Temper'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell tundish-rows',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MaxTundishTemperature',
                                        label: app.translate([that, app], 'Max Temper'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell tundish-rows',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'MinTundishWeight',
                                        label: app.translate([that, app], 'Min Weight'),
                                        cell: Backgrid.StringCell.extend({
                                            className: function () {
                                                if (this.model.get('MinTundishWeightStatus') == 'WARNING') return 'string-cell align-center-cell warning tundish-rows';
                                                else return 'string-cell align-center-cell tundish-rows';
                                            },
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'AverageTundishWeight',
                                        label: app.translate([that, app], 'Avg Weight'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell tundish-rows',
                                        }),
                                        editable: false,
                                    },

                                    {
                                        name: 'ProcessedWeight',
                                        label: app.translate([that, app], 'Proc Weight'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },

                                    { name: 'S1CastDuration', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', formatter: Backgrid.Extension.DurationFormatter.extend({ displayFormat: 'm:s', modelFormat: 's', }) }), editable: false, },
                                    { name: 'S2CastDuration', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', formatter: Backgrid.Extension.DurationFormatter.extend({ displayFormat: 'm:s', modelFormat: 's', }) }), editable: false, },
                                    { name: 'S3CastDuration', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', formatter: Backgrid.Extension.DurationFormatter.extend({ displayFormat: 'm:s', modelFormat: 's', }) }), editable: false, },
                                    { name: 'S4CastDuration', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', formatter: Backgrid.Extension.DurationFormatter.extend({ displayFormat: 'm:s', modelFormat: 's', }) }), editable: false, },

                                    { name: 'S1AverageSpeed', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S2AverageSpeed', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S3AverageSpeed', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S4AverageSpeed', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S1StrandLost', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S2StrandLost', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S3StrandLost', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S4StrandLost', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S1CastedLength', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S2CastedLength', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S3CastedLength', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S4CastedLength', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S1LubeRunningPercent', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S2LubeRunningPercent', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S3LubeRunningPercent', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    //{ name: 'S4LubeRunningPercent', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S1MoldNumber', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S2MoldNumber', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S3MoldNumber', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S4MoldNumber', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S1Products', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S2Products', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S3Products', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S4Products', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S1ProductsWeight', label: app.translate([that, app], 'S1'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S2ProductsWeight', label: app.translate([that, app], 'S2'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S3ProductsWeight', label: app.translate([that, app], 'S3'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },
                                    { name: 'S4ProductsWeight', label: app.translate([that, app], 'S4'), cell: Backgrid.StringCell.extend({ className: 'string-cell align-center-cell sx-rows', }), editable: false, },

                                ]


                                that.$el.find('.input-date').datepicker();
                                var grid = that.grids.production = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                { name: 'HeatName' },
                                                { name: 'Start' },
                                                { name: 'CrewId' },
                                                { name: 'Shift' },
                                                { name: 'IsQuickShroud' },
                                                { name: 'NonFreeOpen' },
                                                { name: 'CasterCode' },
                                                { name: 'Rods' },

                                                {
                                                    name: 'Ladle Times', children:
                                                        [
                                                            { name: 'LadleWaitTime' }
                                                            , { name: 'LadleOpeningTime' }
                                                            , { name: 'LadleOpenTime' }
                                                        ]
                                                },

                                                {
                                                    name: 'Tundish', children:
                                                        [
                                                            { name: 'TundishNumber' }
                                                            , { name: 'MinTundishTemperature' }
                                                            , { name: 'AverageTundishTemperature' }
                                                            , { name: 'MaxTundishTemperature' }
                                                            , { name: 'MinTundishWeight' }
                                                            , { name: 'AverageTundishWeight' }
                                                        ]
                                                },


                                                { name: 'ProcessedWeight' },
                                                {
                                                    name: 'Cast Duration', children:
                                                        [
                                                            { name: 'S1CastDuration' }
                                                            , { name: 'S2CastDuration' }
                                                            , { name: 'S3CastDuration' }
                                                            , { name: 'S4CastDuration' }
                                                        ]
                                                },

                                                {
                                                    name: 'Average Speed', children:
                                                        [
                                                            { name: 'S1AverageSpeed' }
                                                            , { name: 'S2AverageSpeed' }
                                                            , { name: 'S3AverageSpeed' }
                                                            , { name: 'S4AverageSpeed' }
                                                        ]
                                                },

                                                //{
                                                //    name: 'Strand Lost', children:
                                                //        [
                                                //            { name: 'S1StrandLost' }
                                                //            , { name: 'S2StrandLost' }
                                                //            , { name: 'S3StrandLost' }
                                                //            , { name: 'S4StrandLost' }
                                                //        ]
                                                //},
                                                {
                                                    name: 'Casted Length', children:
                                                        [
                                                            { name: 'S1CastedLength' }
                                                            , { name: 'S2CastedLength' }
                                                            , { name: 'S3CastedLength' }
                                                            , { name: 'S4CastedLength' }
                                                        ]
                                                },
                                                //{
                                                //    name: 'Lube Running Percent', children:
                                                //        [
                                                //            { name: 'S1LubeRunningPercent' }
                                                //            , { name: 'S2LubeRunningPercent' }
                                                //            , { name: 'S3LubeRunningPercent' }
                                                //            , { name: 'S4LubeRunningPercent' }
                                                //        ]
                                                //},
                                                //{
                                                //    name: 'Lube SP', children:
                                                //        [
                                                //            { name: 'S1LubeSP' }
                                                //            , { name: 'S2LubeSP' }
                                                //            , { name: 'S3LubeSP' }
                                                //            , { name: 'S4LubeSP' }
                                                //        ]
                                                //},
                                                {
                                                    name: 'Mold Number', children:
                                                        [
                                                            { name: 'S1MoldNumber' }
                                                            , { name: 'S2MoldNumber' }
                                                            , { name: 'S3MoldNumber' }
                                                            , { name: 'S4MoldNumber' }
                                                        ]
                                                },
                                                {
                                                    name: 'Products', children:
                                                        [
                                                            { name: 'S1Products' }
                                                            , { name: 'S2Products' }
                                                            , { name: 'S3Products' }
                                                            , { name: 'S4Products' }
                                                        ]
                                                },
                                                {
                                                    name: 'Products Weight', children:
                                                        [
                                                            { name: 'S1ProductsWeight' }
                                                            , { name: 'S2ProductsWeight' }
                                                            , { name: 'S3ProductsWeight' }
                                                            , { name: 'S4ProductsWeight' }
                                                        ]
                                                },

                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                            this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            _.each(this.columns.models, function (modelValue) {
                                                if (modelValue.get('toolTip')) that.$el.find('.' + modelValue.get('name')).attr('title', modelValue.get('toolTip'))
                                            });
                                            return this;
                                        },
                                        collection_backgrid_sort: function (column, direction) {
                                            var sortType = column.get('name').toUpperCase();

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

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

                                            column.set("direction", direction);

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

                                        },
                                    }),
                                    columns: columns,
                                    collection: that.itemsColl,

                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);

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

                                            that.model.set({ 
                                                rowModel: model,
                                                showAssignOption: model.HeatId === null ? true : false,
                                                index: newIndex,
                                            });
                                        },

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

                                });
                                that.model.set({ grid: grid });
                                //container.append(grid.render().el);
                                that.$el.find('.processes-grid-container').append(grid.render().el);

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

                                
                                $.contextMenu( 'destroy' );


                                $(function() {
                                    $.contextMenu({
                                        selector: '#caster-production .string-cell', 
                                        callback: function(key, options) {
                                            if (key === 'heat')  that.model.set({contextMenuOption:1});                                                        
                                            if (key === 'products')  that.model.set({contextMenuOption:2});
                                            if (key === 'assign') that.model.set({ contextMenuOption: 3 });
                                            if (key === 'unassign') that.model.set({ contextMenuOption: 4 });
                                            if (key === 'opt-non-free-open') that.model.set({ contextMenuOption: 5 });
                                            that.contextMenuOptionPressed();
                                        },
                                        items: {
                                            "heat": {name: "Go To Heat Report", icon: "fa-bar-chart"},
                                            "products": {name: "Go To Products Report", icon: "fa-align-justify"},                                                        
                                            "sep1": "---------",
                                            "assign": {
                                                name: "Assign Heat", 
                                                icon: "edit",                                                 
                                                disabled: function (key, opt) { 
                                                    return !that.model.get('showAssignOption')
                                                }
                                            }, 
                                            "sep2": "---------",
                                            "unassign": {
                                                name: "Unassign Heat",
                                                icon: "edit",
                                                disabled: function (key, opt) {
                                                    return that.model.get('showAssignOption')
                                                }
                                            },
                                            "sep3": "---------",    
                                            "opt-non-free-open": { 
                                                name: "Quick Shroud | Non Free Open ", 
                                                icon: "fa-arrow-down",
                                                disabled: function(key,opt){
                                                    var m = that.model.toJSON();
                                                    if (m.casterCode === '2')
                                                        return false;
                                                    else 
                                                        return true;
                                                }       
                                            }
                                        },
                                        events: {
                                            hide : function(options){
                                                that.removeHighlightRow();
                                            },
                                        }
                                    }); 
                                });


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

                                if (fixedParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (viewParams.casterCode)
                                    fixedParams.casterCode = (viewParams.casterCode != '-' && viewParams.casterCode != null) ? parseInt(viewParams.casterCode, 10) : null;
                                if (viewParams.crewId)
                                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                                if (viewParams.shiftId)
                                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;

                                that.model.set(fixedParams);

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

                                

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


                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            removeHighlightRow: function(){
                var previousIndex = this.model.get('index');
                var rowsView = this.model.get('grid').body.rows;
                rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");
            },

            contextMenuOptionPressed: function(){                
                var that = this;
                var model = this.model.get('rowModel');
                var contextMenuOption = this.model.get('contextMenuOption');               

                if (contextMenuOption === 3) {
                    if (model.CasterHeatName == 'UNK' && model.HeatName) {
                        that.openEditionModal(model, true);
                    } else if (model.CasterHeatName == 'UNK' && !model.HeatName) {
                        that.openEditionModal(model, false);
                    } else if (model.HeatId === null && model.CasterHeatName != 'UNK') {
                        that.openEditionModal(model, false);
                    } else {
                        //app.views.topMessages.showMessage("Option not available. The Heat is already Assigned", { stay: 5000, });
                    }
                } else if (contextMenuOption === 1) {
                    app.router.navigate(
                        app.router.resolveURL(
                            'caster-heat-report',
                            {
                                heatName: model.HeatName,
                            },
                            false
                        ),
                        { trigger: true, }
                    );
                }
                else if (contextMenuOption === 2) {
                    app.router.navigate(
                        app.router.resolveURL(
                            'caster-products',
                            {
                                start: new moment(that.model.get('start'), 'YYYY-MM-DD').format('YYYYMMDD'),
                                end: new moment(that.model.get('start'), 'YYYY-MM-DD').format('YYYYMMDD'),
                                casterCode: that.model.get('casterCode'),
                                strandId: '-',
                                crewId: '-',
                                shiftId: that.model.get('shiftId'),
                            },
                            false
                        ),
                        { trigger: true, }
                    );
                } else if (contextMenuOption === 4) {
                    message = 'The Heat ' + model.Name + ' will be unassigned. Do you want to continue?'
                    modal = new Modal.Views.Main({
                        focusOk: false,
                        focusSelector: '#btn-cancel',
                        title: 'Unassign Heat Confirmation: ' + model.Name,
                        message: message,
                        buttons_type: "CONTINUE-CANCEL",
                    });
                    this.listenToOnce(modal, "continue", function (modal) {
                        try {
                            that.model.unassing({
                                processId: model.id,
                            });
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    });
                    modal.show();


                } else if (contextMenuOption === 5) {
                        this.nonFreeOpen(model);
                        // this.model.set({ rowModel: null, runOptionTrigger: false });
                }
            },
            nonFreeOpen: function (model) {
                try {
                    var that = this
                        , attrs = model;
                    this.currentModal = new Screen.Views.NonFreeOpenModal({
                        model: new Screen.Models.NonFreeOpenModal({
                            ladle: attrs.Ladle,
                            heat: attrs.HeatName,
                            comments:  attrs.Comments,
                            rods:  attrs.Rods,
                            quickShroud: attrs.QuickShroud ? 'YES' : 'NO',        
                            isNonFreeOpen: attrs.IsNonFreeOpen ? true : false,
                            bus: that.bus,
                        }),
                    });

                    var fn_modal_shown_hidden = function () {
                        try {
                            //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                            //or it is not executed for some reason.
                            //clickedBtn.attr("disabled", false);
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    };

                    this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                        .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                        .listenToOnce(this.currentModal, 'finish', function (modal, output) {

                            try {
                                if (output.result == 'SUCCESS') {   
                                    app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });
                                
                                    that.refresh();

                                }
                            }
                            catch (e) {
                                if (that.autoRefresh.enabled == false)
                                    that.startAutoRefresh();
                                console.error((e.stack) ? e.stack : new Error(e).stack);
                            }     


                            // try {
                            //     if (output.result == 'SUCCESS') {
                            //         app.views.topMessages.showMessage(output.data.Message, { stay: 5 * 1000, });
                            //     }
                            // }
                            // catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        });;

                    this.currentModal.show();
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },
            processes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            if (that.itemsColl.length > 0) that.show_backgrid();
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            show_backgrid: function () {
                var container = this.$el.find(".processes-grid-container");
                container.empty();

                container.append(this.grids.production.render().el);

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

            },

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

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


                this.itemsColl.fetch({
                    start: attrs.start,
                    end: attrs.end,
                    crewId: (attrs.crewId == "") ? null : attrs.crewId,
                    shiftId: (attrs.shiftId == "") ? null : attrs.shiftId,
                    refresh: true,
                    casterCode: attrs.casterCode ? attrs.casterCode : null,
                });
            },
            actionOnRow: function (model, action) {
                try {
                    var that = this;
                    switch (action.toUpperCase()) {
                        case 'EDIT_DETAILS':
                            this.openEditionModal(model,false);
                            break;
                    }
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },

            openEditionModal: function (model,unassign) {
                var modal = new Screen.Views.AssignModal({
                    row: model,
                    bus: this.bus,
                    unassign: unassign,
                });
                modal.show();
            },

            exportToExcel: function () {
                var that = this,
                    params = this.model.toJSON();

                that.setExportButtonExporting(true);

                var params = [
                    { Name: '@start', Type: 'DATETIME', Value: params.start, },
                    { Name: '@end', Type: 'DATETIME', Value: params.end, },
                    { Name: '@crewId', Type: 'CHAR', Value: (params.crewId != '' && params.crewId != '-') ? params.crewId : null, },
                    { Name: '@shiftId', Type: 'INT', Value: (params.shiftId != '' && params.shiftId != '-') ? params.shiftId : null, },
                    { 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: 'CAS-Production',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.CAS.GetProcesses',
                                QueryParameters: QP,
                            },
                        },
                    ]
                };

                /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'ProductionDate' },
                                { Column: 'B', Value: 'Grade' },
                                { Column: 'C', Value: 'Shift' },
                                { Column: 'D', Value: 'Crew' },
                                { Column: 'E', Value: 'Rods'     },
                                { Column: 'F', Value: 'NonFreeOpen' },
                                { Column: 'G', Value: 'HeatName' },
                                { Column: 'H', Value: 'Sequence' },
                                { Column: 'I', Value: 'CasterCode' },
                                { Column: 'J', Value: 'GradeName' },
                                { Column: 'K', Value: 'Start' },
                                { Column: 'L', Value: 'End' },
                                { Column: 'M', Value: 'LadleWaitTime' },
                                { Column: 'N', Value: 'LadleOpeningTime' },
                                { Column: 'O', Value: 'LadleOpenTime' },
                                { Column: 'P', Value: 'TundishNumber' },
                                { Column: 'Q', Value: 'InitialWeight' },
                                { Column: 'R', Value: 'FinalWeight' },
                                { Column: 'S', Value: 'ProcessedWeight' },
                                { Column: 'T', Value: 'MinTundishTemperature' },
                                { Column: 'U', Value: 'AverageTundishTemperature' },
                                { Column: 'V', Value: 'MaxTundishTemperature' },
                                { Column: 'W', Value: 'MinTundishWeight' },
                                { Column: 'X', Value: 'AverageTundishWeight' },
                                { Column: 'Y', Value: 'MaxTundishWeight' },
                                { Column: 'Z', Value: 'S1AverageSpeed' },
                                { Column: 'AA', Value: 'S1StrandStarted' },
                                { Column: 'AB', Value: 'S1StrandLost' },
                                { Column: 'AC', Value: 'S1CastedLength' },
                                { Column: 'AD', Value: 'S1LubeMode' },
                                { Column: 'AE', Value: 'S1LubeRunningPercent' },
                                { Column: 'AF', Value: 'S1LubeSP' },
                                { Column: 'AG', Value: 'S1OscillatorMode' },
                                { Column: 'AH', Value: 'S1OscillatorStroke' },
                                { Column: 'AI', Value: 'S1OscillatorFrequency' },
                                { Column: 'AJ', Value: 'S1MoldWaterVolume' },
                                { Column: 'AK', Value: 'S1MoldWaterExtractedHeat' },
                                { Column: 'AL', Value: 'S1MoldNumber' },
                                { Column: 'AM', Value: 'S1Products' },
                                { Column: 'AN', Value: 'S1ProductsWeight' },
                                { Column: 'AO', Value: 'S2AverageSpeed' },
                                { Column: 'AP', Value: 'S2StrandStarted' },
                                { Column: 'AQ', Value: 'S2StrandLost' },
                                { Column: 'AR', Value: 'S2CastedLength' },
                                { Column: 'AS', Value: 'S2LubeMode' },
                                { Column: 'AT', Value: 'S2LubeRunningPercent' },
                                { Column: 'AU', Value: 'S2LubeSP' },
                                { Column: 'AV', Value: 'S2OscillatorMode' },
                                { Column: 'AW', Value: 'S2OscillatorStroke' },
                                { Column: 'AX', Value: 'S2OscillatorFrequency' },
                                { Column: 'AY', Value: 'S2MoldWaterVolume' },
                                { Column: 'AZ', Value: 'S2MoldWaterExtractedHeat' },
                                { Column: 'BA', Value: 'S2MoldNumber' },
                                { Column: 'BB', Value: 'S2Products' },
                                { Column: 'BC', Value: 'S2ProductsWeight' },
                                { Column: 'BD', Value: 'S3AverageSpeed' },
                                { Column: 'BE', Value: 'S3StrandStarted' },
                                { Column: 'BF', Value: 'S3StrandLost' },
                                { Column: 'BG', Value: 'S3CastedLength' },
                                { Column: 'BH', Value: 'S3LubeMode' },
                                { Column: 'BI', Value: 'S3LubeRunningPercent' },
                                { Column: 'BJ', Value: 'S3LubeSP' },
                                { Column: 'BK', Value: 'S3OscillatorMode' },
                                { Column: 'BL', Value: 'S3OscillatorStroke' },
                                { Column: 'BM', Value: 'S3OscillatorFrequency' },
                                { Column: 'BN', Value: 'S3MoldWaterVolume' },
                                { Column: 'BO', Value: 'S3MoldWaterExtractedHeat' },
                                { Column: 'BP', Value: 'S3MoldNumber' },
                                { Column: 'BQ', Value: 'S3Products' },
                                { Column: 'BR', Value: 'S3ProductsWeight' },
                                { Column: 'BS', Value: 'S4AverageSpeed' },
                                { Column: 'BT', Value: 'S4StrandStarted' },
                                { Column: 'BU', Value: 'S4StrandLost' },
                                { Column: 'BV', Value: 'S4CastedLength' },
                                { Column: 'BW', Value: 'S4LubeMode' },
                                { Column: 'BX', Value: 'S4LubeRunningPercent' },
                                { Column: 'BY', Value: 'S4LubeSP' },
                                { Column: 'BZ', Value: 'S4OscillatorMode' },
                                { Column: 'CA', Value: 'S4OscillatorStroke' },
                                { Column: 'CB', Value: 'S4OscillatorFrequency' },
                                { Column: 'CC', Value: 'S4MoldWaterVolume' },
                                { Column: 'CD', Value: 'S4MoldWaterExtractedHeat' },
                                { Column: 'CE', Value: 'S4MoldNumber' },
                                { Column: 'CF', Value: 'S4Products' },
                                { Column: 'CG', Value: 'S4ProductsWeight' },
                                { Column: 'CH', Value: 'IsQuickShroud' },
                            ],
                    }],
                    StartRowIndex: 1,
                });

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'ProductionDate', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'GradeName', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'Shift', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'CrewId', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'Rods'    , DataType: 'String' },
                            { ExcelColumnName: 'F', SQLDataColumnName: 'NonFreeOpen', DataType: 'String' },
                            { ExcelColumnName: 'G', SQLDataColumnName: 'HeatName', DataType: 'String' },
                            { ExcelColumnName: 'H', SQLDataColumnName: 'Sequence', DataType: 'String' },
                            { ExcelColumnName: 'I', SQLDataColumnName: 'CasterCode', DataType: 'String' },
                            { ExcelColumnName: 'J', SQLDataColumnName: 'GradeName', DataType: 'String' },
                            { ExcelColumnName: 'K', SQLDataColumnName: 'Start', DataType: 'String' },
                            { ExcelColumnName: 'L', SQLDataColumnName: 'End', DataType: 'String' },
                            { ExcelColumnName: 'M', SQLDataColumnName: 'LadleWaitTime', DataType: 'String' },
                            { ExcelColumnName: 'N', SQLDataColumnName: 'LadleOpeningTime', DataType: 'String' },
                            { ExcelColumnName: 'O', SQLDataColumnName: 'LadleOpenTime', DataType: 'String' },
                            { ExcelColumnName: 'P', SQLDataColumnName: 'TundishNumber', DataType: 'String' },
                            { ExcelColumnName: 'Q', SQLDataColumnName: 'InitialWeight', DataType: 'String' },
                            { ExcelColumnName: 'R', SQLDataColumnName: 'FinalWeight', DataType: 'String' },
                            { ExcelColumnName: 'S', SQLDataColumnName: 'ProcessedWeight', DataType: 'String' },
                            { ExcelColumnName: 'T', SQLDataColumnName: 'MinTundishTemperature', DataType: 'String' },
                            { ExcelColumnName: 'U', SQLDataColumnName: 'AverageTundishTemperature', DataType: 'String' },
                            { ExcelColumnName: 'V', SQLDataColumnName: 'MaxTundishTemperature', DataType: 'String' },
                            { ExcelColumnName: 'W', SQLDataColumnName: 'MinTundishWeight', DataType: 'String' },
                            { ExcelColumnName: 'X', SQLDataColumnName: 'AverageTundishWeight', DataType: 'String' },
                            { ExcelColumnName: 'Y', SQLDataColumnName: 'MaxTundishWeight', DataType: 'String' },
                            { ExcelColumnName: 'Z', SQLDataColumnName: 'S1AverageSpeed', DataType: 'String' },
                            { ExcelColumnName: 'AA', SQLDataColumnName: 'S1StrandStarted', DataType: 'String' },
                            { ExcelColumnName: 'AB', SQLDataColumnName: 'S1StrandLost', DataType: 'String' },
                            { ExcelColumnName: 'AC', SQLDataColumnName: 'S1CastedLength', DataType: 'String' },
                            { ExcelColumnName: 'AD', SQLDataColumnName: 'S1LubeMode', DataType: 'String' },
                            { ExcelColumnName: 'AE', SQLDataColumnName: 'S1LubeRunningPercent', DataType: 'String' },
                            { ExcelColumnName: 'AF', SQLDataColumnName: 'S1LubeSP', DataType: 'String' },
                            { ExcelColumnName: 'AG', SQLDataColumnName: 'S1OscillatorMode', DataType: 'String' },
                            { ExcelColumnName: 'AH', SQLDataColumnName: 'S1OscillatorStroke', DataType: 'String' },
                            { ExcelColumnName: 'AI', SQLDataColumnName: 'S1OscillatorFrequency', DataType: 'String' },
                            { ExcelColumnName: 'AJ', SQLDataColumnName: 'S1MoldWaterVolume', DataType: 'String' },
                            { ExcelColumnName: 'AK', SQLDataColumnName: 'S1MoldWaterExtractedHeat', DataType: 'String' },
                            { ExcelColumnName: 'AL', SQLDataColumnName: 'S1MoldNumber', DataType: 'String' },
                            { ExcelColumnName: 'AM', SQLDataColumnName: 'S1Products', DataType: 'String' },
                            { ExcelColumnName: 'AN', SQLDataColumnName: 'S1ProductsWeight', DataType: 'String' },
                            { ExcelColumnName: 'AO', SQLDataColumnName: 'S2AverageSpeed', DataType: 'String' },
                            { ExcelColumnName: 'AP', SQLDataColumnName: 'S2StrandStarted', DataType: 'String' },
                            { ExcelColumnName: 'AQ', SQLDataColumnName: 'S2StrandLost', DataType: 'String' },
                            { ExcelColumnName: 'AR', SQLDataColumnName: 'S2CastedLength', DataType: 'String' },
                            { ExcelColumnName: 'AS', SQLDataColumnName: 'S2LubeMode', DataType: 'String' },
                            { ExcelColumnName: 'AT', SQLDataColumnName: 'S2LubeRunningPercent', DataType: 'String' },
                            { ExcelColumnName: 'AU', SQLDataColumnName: 'S2LubeSP', DataType: 'String' },
                            { ExcelColumnName: 'AV', SQLDataColumnName: 'S2OscillatorMode', DataType: 'String' },
                            { ExcelColumnName: 'AW', SQLDataColumnName: 'S2OscillatorStroke', DataType: 'String' },
                            { ExcelColumnName: 'AX', SQLDataColumnName: 'S2OscillatorFrequency', DataType: 'String' },
                            { ExcelColumnName: 'AY', SQLDataColumnName: 'S2MoldWaterVolume', DataType: 'String' },
                            { ExcelColumnName: 'AZ', SQLDataColumnName: 'S2MoldWaterExtractedHeat', DataType: 'String' },
                            { ExcelColumnName: 'BA', SQLDataColumnName: 'S2MoldNumber', DataType: 'String' },
                            { ExcelColumnName: 'BB', SQLDataColumnName: 'S2Products', DataType: 'String' },
                            { ExcelColumnName: 'BC', SQLDataColumnName: 'S2ProductsWeight', DataType: 'String' },
                            { ExcelColumnName: 'BD', SQLDataColumnName: 'S3AverageSpeed', DataType: 'String' },
                            { ExcelColumnName: 'BE', SQLDataColumnName: 'S3StrandStarted', DataType: 'String' },
                            { ExcelColumnName: 'BF', SQLDataColumnName: 'S3StrandLost', DataType: 'String' },
                            { ExcelColumnName: 'BG', SQLDataColumnName: 'S3CastedLength', DataType: 'String' },
                            { ExcelColumnName: 'BH', SQLDataColumnName: 'S3LubeMode', DataType: 'String' },
                            { ExcelColumnName: 'BI', SQLDataColumnName: 'S3LubeRunningPercent', DataType: 'String' },
                            { ExcelColumnName: 'BJ', SQLDataColumnName: 'S3LubeSP', DataType: 'String' },
                            { ExcelColumnName: 'BK', SQLDataColumnName: 'S3OscillatorMode', DataType: 'String' },
                            { ExcelColumnName: 'BL', SQLDataColumnName: 'S3OscillatorStroke', DataType: 'String' },
                            { ExcelColumnName: 'BM', SQLDataColumnName: 'S3OscillatorFrequency', DataType: 'String' },
                            { ExcelColumnName: 'BN', SQLDataColumnName: 'S3MoldWaterVolume', DataType: 'String' },
                            { ExcelColumnName: 'BO', SQLDataColumnName: 'S3MoldWaterExtractedHeat', DataType: 'String' },
                            { ExcelColumnName: 'BP', SQLDataColumnName: 'S3MoldNumber', DataType: 'String' },
                            { ExcelColumnName: 'BQ', SQLDataColumnName: 'S3Products', DataType: 'String' },
                            { ExcelColumnName: 'BR', SQLDataColumnName: 'S3ProductsWeight', DataType: 'String' },
                            { ExcelColumnName: 'BS', SQLDataColumnName: 'S4AverageSpeed', DataType: 'String' },
                            { ExcelColumnName: 'BT', SQLDataColumnName: 'S4StrandStarted', DataType: 'String' },
                            { ExcelColumnName: 'BU', SQLDataColumnName: 'S4StrandLost', DataType: 'String' },
                            { ExcelColumnName: 'BV', SQLDataColumnName: 'S4CastedLength', DataType: 'String' },
                            { ExcelColumnName: 'BW', SQLDataColumnName: 'S4LubeMode', DataType: 'String' },
                            { ExcelColumnName: 'BX', SQLDataColumnName: 'S4LubeRunningPercent', DataType: 'String' },
                            { ExcelColumnName: 'BY', SQLDataColumnName: 'S4LubeSP', DataType: 'String' },
                            { ExcelColumnName: 'BZ', SQLDataColumnName: 'S4OscillatorMode', DataType: 'String' },
                            { ExcelColumnName: 'CA', SQLDataColumnName: 'S4OscillatorStroke', DataType: 'String' },
                            { ExcelColumnName: 'CB', SQLDataColumnName: 'S4OscillatorFrequency', DataType: 'String' },
                            { ExcelColumnName: 'CC', SQLDataColumnName: 'S4MoldWaterVolume', DataType: 'String' },
                            { ExcelColumnName: 'CD', SQLDataColumnName: 'S4MoldWaterExtractedHeat', DataType: 'String' },
                            { ExcelColumnName: 'CE', SQLDataColumnName: 'S4MoldNumber', DataType: 'String' },
                            { ExcelColumnName: 'CF', SQLDataColumnName: 'S4Products', DataType: 'String' },
                            { ExcelColumnName: 'CG', SQLDataColumnName: 'S4ProductsWeight', DataType: 'String' },
                            { ExcelColumnName: 'CH', SQLDataColumnName: 'IsQuickShroud', 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.setExportButtonExporting(false);
                    },
                    function (resp) {
                        that.model.refreshProcesses();
                        that.setExportButtonExporting(false);
                        console.error(resp);
                    }
                );
            },
            setExportButtonExporting: function (val) {
                var btn_export = this.$el.find('.btn-export-to-excel');
                var export_state = btn_export.find('.excel-export-state');
                var loading_state = btn_export.find('.loading-state');

                if (val) {
                    export_state.css('display', 'none', 'important');
                    loading_state.removeClass('hide');

                    btn_export.attr('disabled', true);
                } else {
                    loading_state.addClass('hide');
                    export_state.css('display', 'inline-block', 'important');

                    btn_export.attr('disabled', false);
                }
            },
            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    casterCode: (params.casterCode == null || params.casterCode == "") ? '-' : params.casterCode,
                                    crewId: (params.crewId == null || params.crewId == "") ? '-' : params.crewId,
                                    shiftId: (params.shiftId == null || params.shiftId == "") ? '-' : params.shiftId,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

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

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

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

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

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

                    this.options.onappend(this);
                }

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

                if (this.options.state == app.view_states.closed) {
                    //return without appending.
                    return;
                }
            },
            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 (viewParams) {
                try {
                    this.refresh(viewParams);
                } catch (Error) { }
            },
        });

        Screen.Collections.Items = Backbone.Collection.extend({
            isFetching: false,
            currentPage: 1,
            pageSize: 100,

            fixedParameters: [],

            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};
                if (options.refresh) {
                    this.resetPagination(true);
                    this.fixedParameters = [
                        { Name: '@Start', Type: 'DATETIME', Value: params.start, },
                        { Name: '@End', Type: 'DATETIME', Value: params.end, },
                        { Name: '@CrewId', Type: 'CHAR', Value: params.crewId != '-' ? params.crewId : null, },
                        { Name: '@ShiftId', Type: 'INT', Value: params.shiftId != '-' ? params.shiftId : null, },
                        { Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
                        { Name: '@CasterCode', Type: 'INT', Value: params.casterCode, },
                        
                    ];
                }
                this.isFetching = true;

                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

                if (!options.refresh) {
                    qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize + 1);
                    qp.Add('@rowsToFetch', 'INT', this.pageSize - 1);
                } else {
                    qp.Add('@fromRow', 'INT', 0);
                    qp.Add('@toRow', 'INT', this.currentPage * this.pageSize);
                    qp.Add('@rowsToFetch', 'INT', this.pageSize);
                }


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

                                if ((resp) && (resp.Table)) {
                                    newColl = resp.Table;
                                    var method = (options.refresh) ? 'set' : 'add';
                                    that[method](newColl);
                                    that.trigger('fetch', that, newColl);

                                    if (newColl.length == 0 && method == 'add')
                                        that.currentPage--;

                                    that.isFetching = false;


                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            getNextPage: function (options) {
                if (!this.isFetching) {
                    this.currentPage++;
                    options = (_.isObject(options)) ? options : {};
                    this.fetch(options);
                }
            },
            resetPagination: function (force) {
                if (!this.isFetching || force == true) {
                    this.currentPage = 1;
                } else {
                    _.delay(this.resetPagination, 100);
                }
            },

        });



        Screen.Collections.LastHeats = Backbone.Collection.extend({
            fetch: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();

                qp.Add('@processId', 'INT', params.processId);

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

                                if ((resp) && (resp.Table)) {
                                    newColl = resp.Table;
                                    that.set(newColl);
                                    that.trigger('fetch', that, newColl);

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

        });

        Screen.Models.AssignModal = Backbone.Epoxy.Model.extend({
            defaults: {
                errorMsg: '',
                processing: true,
                title: '',
                hasData: false,
                isLoading: true,
                index: null,

                selectedHeatId: null,
                currentProcessId: null,
                show_unassign_btn: false,
            },
        });

        Screen.Views.AssignModal = Backbone.Epoxy.View.extend({
            template: "caster-production",
            id: "assign-heats",
            className: "modal modal-assign-heats hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "click #unassignBtn": this.unassignBtn_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: [],
            lastHeatsColl: [],
            grid: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.AssignModal();
                }
                this.row = options.row;
                this.model.set({
                    currentProcessId: this.row.id,
                    show_unassign_btn: options.unassign,
                    title: " Assign Caster Process Starting on " + this.row.Start + " on Caster " + this.row.CasterCode,
                });
           
                
                this.lastHeatsColl = new Screen.Collections.LastHeats();

                this.lastHeatsColl.fetch({
                    processId: this.row.id
                });

                this.bus = options.bus;

                this.bindEvents();

                return this;
            },

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

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

                        var columns = [
                            {
                                name: 'HeatName',
                                label: 'Heat',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },
                            {
                                name: 'EndTap',
                                label: 'End Tap',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },
                            {
                                name: 'GradeName',
                                label: 'Grade',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },

                            {
                                name: 'MaterialSize',
                                label: 'Mold Size',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },


                        ];
                        var grid = new Backgrid.Grid({
                            className: 'backgrid table table-hover table-condensed',
                            collection: that.lastHeatsColl,
                            columns: columns,
                            row: Backgrid.Row.extend({
                                initialize: function (options) {
                                    Backgrid.Row.prototype.initialize.apply(this, arguments);

                                },
                                events: {
                                    click: 'click',
                                },

                                click: function (e) {
                                    try {
                                        var previousIndex = that.model.get('index');

                                        if (!this.$el.hasClass("selectedItem")) {
                                            this.$el.addClass("selectedItem");
                                            that.model.set({ selectedHeatId: this.model.get('HeatId') });
                                        }
                                        var rowsView = that.grid.body.rows;
                                        var newIndex = _.indexOf(rowsView, this);

                                        if (previousIndex != null && previousIndex != newIndex) rowsView[previousIndex].$el.removeClass("selectedItem");

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

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

                        that.grid = grid;
                        that.$el.find('.last-heats-grid-container').append(grid.render().el);

                        that.isRendered = true;

                      

                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "assign_heats_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);
                this.listenTo(this.lastHeatsColl, 'fetch', this.lastHeats_ready);

            },
           
            lastHeats_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData: (that.lastHeatsColl.length > 0),
                                processing: false,
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            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 {
                    this.bus.trigger("modalAcceptBtn", this.model.get('currentProcessId'), this.model.get('selectedHeatId'));

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

            unassignBtn_click: function () {
                try {
                    //this.bus.trigger("modalUnassignBtn", this.model.get('currentProcessId'));
                    app.views.topMessages.showMessage('Method disabled', { stay: 5000, });
                    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); }
            },

        });


        //--------------------------------------//
        //------------ NON FREE OPEN --------------//
        //--------------------------------------//
        Screen.Models.NonFreeOpenModal = Backbone.Epoxy.Model.extend({
            defaults: {
                message: null,

                ladle: null,
                heat: null,
                rods: 0,
                quickShroudOptions: [{value:'YES',label:'YES'},{value:'NO',label:'NO'}],   
                quickShroud: 'YES',        
                isNonFreeOpen: false,
                comments: '',
                errorMsg: "",
                processing: false,


            },
            save: function (options) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    opt = _.extend({
                        async: true,
                    }, options);

                _.each(opt.params, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.DeclareNonFreeOpen',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table) && (resp.Table.length > 0)) {
                                    if (opt.success)
                                        opt.success(that, resp.Table[0]);
                                }
                                else {
                                    
                                    var errorMsg = ((resp) && (resp.Message))
                                        ? resp.Message
                                        : 'SERVER_RESPONSE_NOT_valid';
                                    console.error(errorMsg);


                                    if (opt.error)
                                        opt.error(that, errorMsg);
                                }
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        onError: function (errorMsg) {
                            try {
                                if (opt.error)
                                    opt.error(that, errorMsg);
                                
                                    app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Async: opt.async,
                        Secured: true,
                    },
                    app.ConnectionStrings.app
                );
            },
        });
        Screen.Views.NonFreeOpenModal = Backbone.Epoxy.View.extend({
            template: "caster-production",
            id: "non_free_open_modal_template_caster_production",
            className: "modal modal-non-free-open hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.save,
                    "click #cancelBtn": this.cancelBtn_click,
                    "click #unassignBtn": this.unassignBtn_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,
            initialize: function (options) {
                _.extend(this, options);
               if (!this.model)
                this.model = new Screen.Models.NonFreeOpenModal();            
                this.bus = options.model.toJSON().bus;

                this.bindEvents();

                return this;
            },
            
            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);              
            },
           
            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);

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

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

                return this;
            },

            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 () {
            },
            save: function () {
                var that = this,
                    attrs = this.model.toJSON();
                if (attrs.processing == false) {
                    this.model.set('processing', true);
                
                    try {
                        this.model.save({
                            params: [
                                { Name: '@LadleId', Type: 'INT', Value: attrs.ladle, },
                                { Name: '@PositionId', Type: 'INT', Value: attrs.curPositionId, },
                                { Name: '@Rods', Type: 'INT', Value: attrs.rods, },
                                { Name: '@HeatName', Type: 'VARCHAR', Value: attrs.heat, },
                                { Name: '@QuickShroud', Type: 'BIT', Value: attrs.quickShroud === 'YES' ? 1 : 0, },
                                { Name: '@isNonFreeOpen', Type: 'BIT', Value: attrs.isNonFreeOpen, },                            
                                { Name: '@Comments', Type: 'VARCHAR', Value: attrs.comments, },
                            ],
                            success: function (model, resp) {
                                try {
                                    that.model.set('processing', false);
                                    app.views.topMessages.showMessage('Rods and Quick Shroud updated', { stay: 5000, });    
                                    // that.finish({ result: 'SUCCESS', data: resp });

                                    that.hide();
                                    //setTimeout(_.bind(that.hide, that), 1500);
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            error: function (model, errorMsg) {
                                try {
                                  
                                    app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    // app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                finally {
                                    that.model.set('processing', false);
                                }
                            },
                        });
                    }
                    catch (e) {
                        this.model.set('processing', false);
                        throw e;
                    }
                }
                that.bus.trigger("freeOpenUpdated")
            },

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