//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([
    'app',
    'js/templates-loader',
    'backbone',
    'moment',
    'modules/modal2',
    'modules/modal-sulpher-print/modal-sulpher-print',
    'components/ag-grid/ag-grid-module',
    'js/jquery.contextMenu/jquery.contextMenu',
],
    function (app, T, Backbone, moment, Modal, SulpherPrintModal, AgGridModule) {

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

        });

        function getColumnDefs(that) {
            var t = function (key) { return app.translate([that, app], key); };
            function w(n) { return { width: n, resizable: true }; }
            return [
                _.extend({ field: 'HeatNameColumn', headerName: t('Heat'), pinned: 'left', cellClassRules: { 'warning': '!data.HeatId', 'heat-reassigned': 'data.CasterHeatName === "UNK"', 'heat-row': 'true' }, cellRenderer: function(params) { if (!params.value) return ''; return '<span class="heat-link" style="color: #007bff; cursor: pointer; text-decoration: underline;">' + params.value + '</span>'; } }, w(98)),
                _.extend({ field: 'MeltOrder', headerName: t('Melt Order') }, w(142)),
                _.extend({ field: 'GradeName', headerName: t('Grade') }, w(137)),
                _.extend({ field: 'Product', headerName: t('Product') }, w(65)),
                _.extend({ field: 'CasterCode', headerName: t('Caster') }, w(60)),
                _.extend({ field: 'Start', headerName: 'Start', fieldType: 'Datetime', format: 'MM/DD/YY HH:mm' }, w(50)),
                _.extend({ field: 'CrewId', headerName: t('Crew') }, w(50)),
                _.extend({ field: 'IsQuickShroud', headerName: 'Quick\nShroud', headerClass: 'header-two-lines' }, w(62)),
                _.extend({ field: 'NonFreeOpen', headerName: 'Non Free\nOpen', headerClass: 'header-two-lines' }, w(50)),
                _.extend({ field: 'Rods', headerName: t('Rods') }, w(50)),
                _.extend({ field: 'Shift', headerName: t('Shift') }, w(50)),
                { headerName: 'Ladle Times', children: [
                    _.extend({ field: 'LadleWaitTime', headerName: t('Wait'), fieldType: 'Seconds', cellClassRules: { 'warning': 'data.LadleWaitTimeStatus === "WARNING"' } }, w(67)),
                    _.extend({ field: 'LadleOpeningTime', headerName: t('Opening'), fieldType: 'Seconds', cellClassRules: { 'warning': 'data.LadleOpeningTimeStatus === "WARNING"' } }, w(72)),
                    _.extend({ field: 'LadleOpenTime', headerName: t('Open'), fieldType: 'Seconds' }, w(67))
                ]},
                { headerName: 'Tundish', children: [
                    _.extend({ field: 'TundishNumber', headerName: t('Num') }, w(48)),
                    _.extend({ field: 'MinTundishTemperature', headerName: 'Min\nTemp', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 1 }, w(67)),
                    _.extend({ field: 'AverageTundishTemperature', headerName: 'Avg\nTemp', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 1 }, w(67)),
                    _.extend({ field: 'MaxTundishTemperature', headerName: 'Max\nTemp', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 1 }, w(67)),
                    _.extend({ field: 'MinTundishWeight', headerName: 'Min\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 1, cellClassRules: { 'warning': 'data.MinTundishWeightStatus === "WARNING"' } }, w(63)),
                    _.extend({ field: 'AverageTundishWeight', headerName: 'Avg\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 1 }, w(63))
                ]},
                _.extend({ field: 'ProcessedWeight', headerName: 'Proc\nWeight', headerClass: 'header-two-lines', fieldType: 'Float', decimals: 1 }, w(70)),
                { headerName: 'Cast Duration', children: [
                    _.extend({ field: 'S1CastDuration', headerName: t('S1'), fieldType: 'Seconds' }, w(70)),
                    _.extend({ field: 'S2CastDuration', headerName: t('S2'), fieldType: 'Seconds' }, w(70)),
                    _.extend({ field: 'S3CastDuration', headerName: t('S3'), fieldType: 'Seconds' }, w(70)),
                    _.extend({ field: 'S4CastDuration', headerName: t('S4'), fieldType: 'Seconds' }, w(70))
                ]},
                { headerName: 'Average Speed', children: [
                    _.extend({ field: 'S1AverageSpeed', headerName: t('S1'), fieldType: 'Float', decimals: 2 }, w(70)),
                    _.extend({ field: 'S2AverageSpeed', headerName: t('S2'), fieldType: 'Float', decimals: 2 }, w(70)),
                    _.extend({ field: 'S3AverageSpeed', headerName: t('S3'), fieldType: 'Float', decimals: 2 }, w(70)),
                    _.extend({ field: 'S4AverageSpeed', headerName: t('S4'), fieldType: 'Float', decimals: 2 }, w(70))
                ]},
                { headerName: 'Casted Length', children: [
                    _.extend({ field: 'S1CastedLength', headerName: t('S1') }, w(70)),
                    _.extend({ field: 'S2CastedLength', headerName: t('S2') }, w(70)),
                    _.extend({ field: 'S3CastedLength', headerName: t('S3') }, w(70)),
                    _.extend({ field: 'S4CastedLength', headerName: t('S4') }, w(70))
                ]},
                { headerName: 'Mold Number', children: [
                    _.extend({ field: 'S1MoldNumber', headerName: t('S1') }, w(62)),
                    _.extend({ field: 'S2MoldNumber', headerName: t('S2') }, w(62)),
                    _.extend({ field: 'S3MoldNumber', headerName: t('S3') }, w(62)),
                    _.extend({ field: 'S4MoldNumber', headerName: t('S4') }, w(62))
                ]},
                { headerName: 'Products', children: [
                    _.extend({ field: 'S1Products', headerName: t('S1') }, w(45)),
                    _.extend({ field: 'S2Products', headerName: t('S2') }, w(45)),
                    _.extend({ field: 'S3Products', headerName: t('S3') }, w(45)),
                    _.extend({ field: 'S4Products', headerName: t('S4') }, w(45))
                ]},
                { headerName: 'Products Weight', children: [
                    _.extend({ field: 'S1ProductsWeight', headerName: t('S1') }, w(52)),
                    _.extend({ field: 'S2ProductsWeight', headerName: t('S2') }, w(52)),
                    _.extend({ field: 'S3ProductsWeight', headerName: t('S3') }, w(52)),
                    _.extend({ field: 'S4ProductsWeight', headerName: t('S4') }, w(52))
                ]},
                _.extend({ colId: 'actions', headerName: 'Actions', pinned: 'right', fieldType: 'edit', suppressCellSelection: true }, w(85))
            ];
        }

        var CustomAgGridModule = AgGridModule.extend({
            initialize: function (options) {
                this.mainView = options.mainView;
                this.columnDefs = options.columnDefs || [];
                options.columnDefs = this.columnDefs;
                var gridOpts = options.gridOptions || {};
                gridOpts.getContextMenuItems = this.getContextMenuItems.bind(this);
                gridOpts.getRowClass = this.getRowClass.bind(this);
                options.gridOptions = gridOpts;
                AgGridModule.prototype.initialize.call(this, options);
            },
            getRowClass: function (params) {
                if (!params.data) return '';
                if (!params.data.HeatId) return 'warning heat-row';
                if (params.data.CasterHeatName === 'UNK') return 'heat-reassigned heat-row';
                return 'heat-row';
            },
            getContextMenuItems: function (params) {
                var self = this;
                var mainView = this.mainView;
                if (!mainView || !params || !params.node) return AgGridModule.prototype.getContextMenuItems.call(this, params);
                var model = params.node.data;
                mainView.model.set({ rowModel: model, showAssignOption: model.HeatId === null, index: params.node.rowIndex });
                var showAssign = model.HeatId === null;
                var casterCode = mainView.model.get('casterCode');
                var canNonFreeOpen = (casterCode === '2' || casterCode === 2);
                return [
                    { name: 'Go To Heat Report', icon: 'fa-bar-chart', action: function () { mainView.model.set({ contextMenuOption: 1 }); mainView.contextMenuOptionPressed(); } },
                    { name: 'Go To Products Report', icon: 'fa-align-justify', action: function () { mainView.model.set({ contextMenuOption: 2 }); mainView.contextMenuOptionPressed(); } },
                    'separator',
                    { name: 'Assign Heat', icon: 'edit', disabled: !showAssign, action: function () { mainView.model.set({ contextMenuOption: 3 }); mainView.contextMenuOptionPressed(); } },
                    'separator',
                    { name: 'Unassign Heat', icon: 'edit', disabled: showAssign, action: function () { mainView.model.set({ contextMenuOption: 4 }); mainView.contextMenuOptionPressed(); } },
                    'separator',
                    { name: 'Quick Shroud | Non Free Open', icon: 'fa-arrow-down', disabled: !canNonFreeOpen, action: function () { mainView.model.set({ contextMenuOption: 5 }); mainView.contextMenuOptionPressed(); } },
                    'separator',
                    'copy',
                    { name: 'Copy Selected with Headers', action: function () { self.copySelectedToClipboard(true); } },
                    'separator',
                    { name: 'Export All to Excel', action: function () { self.exportToExcel(false); } },
                    { name: 'Export Selected to Excel', action: function () { self.exportToExcel(true); } }
                ];
            },
            onCellClicked: function (params) {
                if (params.column && params.column.colDef.field === 'HeatNameColumn' && params.value && params.data) {
                    var heatName = params.data.HeatName;
                    if (heatName) {
                        app.router.navigate(
                            app.router.resolveURL(
                                'caster-heat-report',
                                {
                                    heatName: heatName,
                                },
                                false
                            ),
                            { trigger: true }
                        );
                        return;
                    }
                }
                if (params.column && params.column.colDef.colId === 'actions' && params.data && this.options.onEditClick) {
                    this.options.onEditClick(params.data);
                }
                AgGridModule.prototype.onCellClicked.call(this, params);
            }
        });

        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,
                    'click #calendarStartBtn': this.calendarStartBtn_click,
                    'click #calendarEndBtn': this.calendarEndBtn_click,
                };
            },
            calendarStartBtn_click: function () {
                $('#dateStartTbx').datepicker('show');
            },
            calendarEndBtn_click: function () {
                $('#dateEndTbx').datepicker('show');
            },
            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.agGridModule && this.agGridModule.showLoadingOverlay) {
                    this.agGridModule.showLoadingOverlay();
                }

                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/pages/caster/' + this.template + '/';

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

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

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

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


                                that.agGridModule = new CustomAgGridModule({
                                    columnDefs: getColumnDefs(that),
                                    mainView: that,
                                    rowData: [],
                                    fileName: 'CAS-Production',
                                    onEditClick: function (data) { that.actionOnRow(data, 'EDIT_DETAILS'); }
                                });
                                that.agGridModule.render();
                                that.$el.find('.processes-grid-container').empty().append(that.agGridModule.$el);

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

                                that.append(thatContainer, that.$el);


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

                                if (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 after grid is ready so showLoadingOverlay() has gridApi
                                var params = that.model.toJSON();
                                that.agGridModule.gridReadyPromise.then(function () {
                                    that._refresh({
                                        reset: true,
                                        params: _.extend(
                                            {},
                                            params,
                                            {}
                                        ),
                                    });
                                });


                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            removeHighlightRow: function () {
                if (this.agGridModule && this.agGridModule.getGridApi()) {
                    this.agGridModule.getGridApi().deselectAll();
                }
            },

            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.agGridModule) {
                                that.agGridModule.setRowDataAsCollection(that.itemsColl);
                                that.agGridModule.hideOverlay();
                            }
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            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: 'LadleWaitTimeMin' },
                                { Column: 'N', Value: 'LadleOpeningTimeMin' },
                                { Column: 'O', Value: 'LadleOpenTimeMin' },
                                { 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: 'LadleWaitTimeMin', DataType: 'String' },
                            { ExcelColumnName: 'N', SQLDataColumnName: 'LadleOpeningTimeMin', DataType: 'String' },
                            { ExcelColumnName: 'O', SQLDataColumnName: 'LadleOpenTimeMin', 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);
                                    }
                                    that.trigger('fetch', that, []);
                                }
                                that.isFetching = false;
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); that.trigger('fetch', that, []); that.isFetching = false; }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                            that.trigger('fetch', that, []);
                            that.isFetching = false;
                        },
                        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/pages/caster/' + 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/pages/caster/' + 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;
    });