//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",
  "modules/modal2", 
  "backgrid",
  "moment",
  "modules/furnace/furnace",
  'modules/modal-change-melt-order/modal-change-melt-order',

  'backgrid/moment-cell',
  'backgrid/select-integer-cell',
  'backgrid/duration-cell',
  'backgrid/infinator',
  'js/backgrid-0.3.5/extensions/valid-limit-cell/backgrid-valid-limit-cell',
  'backgrid/grouped-columns',
  'js/typeahead.extended/typeahead.extended'
],

   function (app, T, Modal, Backgrid, moment, Furnace, ModalChangeMeltOrder) {
    //replace all "Screen" with your view's name.
    var Screen = { Models: {}, Views: {}, Collections: {} };

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            positions: [],

            isLoading: true,
            hasData: false,
            sortType: null,
        },
        computeds: {
            hasPositions: {
                deps: ['positions'], 
                get: function (positions) {
                    return positions.length != 0;
                }, 
            },
        },

        fetchPositions: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();
                        
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadlePositions",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Name, }; });

                                that.set("positions", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        removeHeat: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters();


            qp.Add('@HeatNumber', 'CHAR(10)', params.HeatNumber);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.RemoveHeat",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var data = resp.Table[0];
                                app.views.topMessages.showMessage(data.Result, { stay: 5 * 1000, });
                            
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

        },
        clearLadle: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters();
            qp.Add('@LadleId', 'int', params.ladle);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.ClearLadleWeb",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var data = resp.Table[0];
                                app.views.topMessages.showMessage(`The Ladle ${params.ladle} was cleared`, { stay: 5 * 1000, });

                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );
        }
    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return "ladles-dashboard";
        } catch (Error) { }
    };

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: "ladles-dashboard",
        id: "ladles-dashboard",
        title: "Ladles Dashboard",
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        isCacheable: false,
        events: function () {
            return {
            };
        },

        autoRefresh: null,
        bindingSources: null,
        grids: null,
        items: null,
        subviews: null,

        templates: null,

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

            var that = this;

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

            this.templates = {
                splitHeatModal: null,
                changePositionModal: null,
                changeMeltOrderModal: null,
                changeHeatWeightsModal: null,
                assignHeatModal: null,
                returnLadleModal: null,
                reladleModal: null,
                createHeatModal: null,
                fixLadleModal:null,
                changeHeatStatusModal: null,
                assignLadleModal: null,
            };

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

            this.items = new Screen.Collections.Items();

            this.grids = {};

            this.bindingSources = {};

            this.listeners = {};

            this.bindEvents();
        },

        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.items, 'fetch', this.collection_fetch);
        },        
        _refresh: function (opt) {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshItemsColl(_.extend(
                {},
                opt,
                {
                    params: {}
                })
            );

            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 currentModal exists, hide it and erase it.
            if (this.currentModal) {
                this.currentModal.hide();
                this.currentModal = null;
            }

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

            this._refresh(_.extend(
                {},
                params,
                {
                    reset: true,
                    params: _.extend(
                        {},
                        params,
                        {}
                    ),
                }
            ));
        },
        refreshItemsColl: function (options) {
            try {
                var that = this,
                    modelAttrs = this.model.toJSON(),
                    opt = _.extend({}, { params: {}, refresh: true, }, options);

                //var agentId = ()
                //                ? opt.params.agentId
                //                : (modelAttrs.agentId)
                //                    ? modelAttrs.agentId
                //                    : null;

                if (opt.reset == true) {
                    this.model.set({
                        isLoading: true,
                    });
                }

                //Parameter details:
                // > Parameter 'reset' is used to reload only the first page of records and
                // show the 'Loading' poster.
                // > Parameter 'refresh' is uset to reload all the currently loaded records
                // without showing the 'Loading' poster.
                this.items.fetch({
                    params: {
                        sortType: (modelAttrs.sortType) ? modelAttrs.sortType : null
                        //agentId: opt.params.agentId,
                        //showRunning: opt.params.showRunning,
                        //showPaused: opt.params.showPaused,
                        //showStopped: opt.params.showStopped,
                        //showNew: opt.params.showNew,
                        //search: opt.params.search,
                        //onlyEnabledAgents: 1,
                    },
                    refresh: opt.refresh,
                    reset: opt.reset,
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        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;
                            //start: before the view is visible, but the template was already loaded (not instanced nor appended)

                            //end:

                            //CREATE AN OBJECT AND SET A PROPERTY CALLED EDITABLE THAT I WILL USE IN ASPX WITH HANDLEBARS TO ENABLE OR DISABLE A SECTION
                            // ALSO I CREATE AN OBJECT CALLED PERMISSIONS, THAT I WILL USE AS MUCH IN ASPX AS IN JS
                            var ctx = {
                                editable: (($.inArray("AdminUserRole", app.models.user.get("roles")) != -1
                                    || $.inArray("SupervisorUserRole", app.models.user.get("roles")) != -1) ? true : false),
                                permissions: {
                                    edit: (($.inArray("scrapyard_recipes_item_edit", app.models.user.get("roles")) != -1) ? true : null),
                                    download_all: (($.inArray("scrapyard_recipes_download_all", app.models.user.get("roles")) != -1) ? true : null),
                                    download_recipe: (($.inArray("scrapyard_recipes_download", app.models.user.get("roles")) != -1) ? true : null),
                                },
                            };

                            //SEND CTX TO ASPX SO I CAN MANIPULATE WITH HANDLEBARS
                            that.$el.html(tmp(_.extend({}, ctx, (that.model) ? that.model.toJSON() : {})));
                            that.applyBindings();
                            ////loading the view and appeding it to the views's $el.
                            //that.$el.html(tmp());
                            //that.applyBindings();

                            that.bindViewScopedEvents();
                            
                            //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.templates.splitHeatModal = Handlebars.compile(that.$el.find('#split_heat_modal_template').html());
                            that.templates.changePositionModal = Handlebars.compile(that.$el.find('#change_position_modal_template').html());
                            that.templates.changeMeltOrderModal = Handlebars.compile(that.$el.find('#change_melt_order_modal_template').html());
                            that.templates.changeHeatWeightsModal = Handlebars.compile(that.$el.find('#change_heat_weights_modal_template').html());
                            that.templates.assignHeatModal = Handlebars.compile(that.$el.find('#assign_heat_to_ladle_modal_template').html());
                            that.templates.returnLadleModal = Handlebars.compile(that.$el.find('#return_ladle_modal_template').html());
                            that.templates.reladleModal = Handlebars.compile(that.$el.find('#reladle_modal_template').html());
                            that.templates.createHeatModal = Handlebars.compile(that.$el.find('#create_heat_modal_template').html());
                            that.templates.fixLadleModal = Handlebars.compile(that.$el.find('#fix_ladle_modal_template').html());
                            that.templates.changeHeatStatusModal = Handlebars.compile(that.$el.find('#change_heat_status_modal_template').html());
                            that.templates.assignLadleModal = Handlebars.compile(that.$el.find('#assign_ladle_modal_template').html());

                            var customRow = Backgrid.Row.extend({
                                initialize: function () {
                                    Backgrid.Row.prototype.initialize.apply(this, arguments);

                                    this.bindEvents();
                                },
                                render: function () {
                                    Backgrid.Row.prototype.render.apply(this, arguments);

                                    if (this.model.get('isLoading')) {
                                        this.$el.addClass('locked-row');
                                    } else {
                                        this.$el.removeClass('locked-row');
                                    }

                                    return this;
                                },
                                bindEvents: function () {
                                    this.listenTo(this.model, 'change:isLoading', this.model_change_isLoading);
                                },
                                model_change_isLoading: function () {
                                    try{
                                        this.render();
                                    } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                },
                            });

                            var grid = that.grids.items = new Backgrid.Grid({
                                header: Backgrid.Extension.GroupedHeader.extend({
                                    columnLayout:
                                    [
                                        {
                                            name: 'positionId',
                                        },
                                        {
                                            name: 'ladle',
                                        },
                                        {
                                            name: 'since',
                                        },
                                        {
                                            name: 'heat',
                                        },
                                        {
                                            name: 'status',
                                        },
                                        {
                                            name: 'meltOrder',
                                        },
                                        {
                                            name: 'grade',
                                        },
										{
											name: 'temp'
										},
										{
											name: 'chem'
										},
                                        {
                                            name: app.translate(that, 'weight_col_label'),
                                            children: [
                                                {
                                                    name: 'net'
                                                },
                                                {
                                                    name: 'tare'
                                                },
                                                {
                                                    name: 'slag'
                                                },
                                            ],
                                        },
                                    ],
                                }),
                                className: 'backgrid table table-hover',
                                row: customRow,
                                columns: [
                                    {
                                        name: 'positionId',
                                        label: app.translate([that, app], 'position_col_label'),
                                        editable: false,
                                        sortable: true,
                                        cell: Backgrid.Extension.SelectIntegerCell.extend({
                                            optionValues: _.map(that.model.get('positions'), function (obj) { return [obj.label, obj.value, ]; }),
                                            className: 'select-cell align-center-cell positionId',
                                        }),
                                        //cell: Backgrid.StringCell.extend({
                                        //    orderSeparator: '',
                                        //    className: 'string-cell align-center-cell position',
                                        //}),
                                    },
                                    {
                                        name: 'ladle',
                                        label: app.translate([that, app], 'ladle_col_label'),
                                        editable: false,
                                        sortable: true,
                                        cell: Backgrid.NumberCell.extend({
                                            decimals: 0,
                                            className: 'numeric-cell align-center-cell ladle',
                                        }),
                                    },
                                    {
                                        name: 'since',
                                        label: app.translate([that, app], 'since_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell since',
                                        }),
                                    },
                                    {
                                        name: 'heat',
                                        label: app.translate([that, app], 'heat_col_label'),
                                        editable: false,
                                        sortable: true,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell heat',
                                        }),
                                    },
                                    {
                                        name: 'status',
                                        label: app.translate([that, app], 'status_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell status',
                                        }),
                                    },
                                    {
                                        name: 'meltOrder',
                                        label: app.translate([that, app], 'melt_order_col_label'),
                                        editable: false,
                                        sortable: true,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell meltOrder',
                                        }),
                                    },
                                    {
                                        name: 'grade',
                                        label: app.translate([that, app], 'grade_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell grade',
                                        }),
                                    },
									  {
                                        name: 'temp',
                                        label: app.translate([that, app], 'temp_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'numeric-cell align-center-cell temp',
                                        }),
                                    },
                                    {
                                        name: 'chem',
                                        label: app.translate([that, app], 'chem_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'numeric-cell align-center-cell chem',
                                        }),
                                    },
                                    {
                                        name: 'net',
                                        label: app.translate([that, app], 'net_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            decimals: 2,
                                            className: 'numeric-cell align-center-cell net',
                                        }),
                                    },
                                    {
                                        name: 'tare',
                                        label: app.translate([that, app], 'tare_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            decimals: 2,
                                            className: 'numeric-cell align-center-cell tare',
                                        }),
                                    },
                                    {
                                        name: 'slag',
                                        label: app.translate([that, app], 'slag_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            decimals: 2,
                                            className: 'numeric-cell align-center-cell slag',
                                        }),
                                    },
                                    {
                                        name: 'heatsOnLining',
                                        label: app.translate([that, app], 'heatsOnLining_col_label'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            decimals: 0,
                                            className: 'numeric-cell align-center-cell slag',
                                        }),
                                    },
                                  
                                  
                                    {
                                        name: "options",
                                        label: "",
                                        sortable: false,
                                        editable: false,
                                        //renderable: (_.isBoolean(ctx.editable)) ? ctx.editable : false,
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: "optionstd",
                                        }),
                                        cell: Backgrid.Cell.extend({
                                            template: Handlebars.compile(that.$el.find('#actions_cell_template').html()),
                                            className: 'actions-cell',
                                            events: {
                                                'click .btn-cell-action': 'cellActionClick',

                                                "click .btn-dropdown-config-option": "configure_dropdown_config_opt_click",
                                                //"click .btn-dropdown-action-option": "configure_dropdown_action_opt_click",

                                                "show.bs.dropdown .btn-group": "btnGroup_show",
                                                "hide.bs.dropdown .btn-group": "btnGroup_hide",
                                            },

                                            initialize: function () {
                                                Backgrid.Cell.prototype.initialize.apply(this, arguments);

                                                ////creating new locked attr on column
                                                //this.model.set("locked", false);

                                                //this.locksChanged();

                                                //_.bindAll(this);

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

                                                if (this.model.get("editing")) {
                                                    this.render_newRow();
                                                } else {
                                                    this.render_actions();
                                                }

                                                this.delegateEvents();
                                                return this;
                                            },
                                            render_newRow: function () {
                                                this.$el.find('[data-toggle="tooltip"]').tooltip();

                                                return this;
                                            },
                                            render_actions: function () {
                                                this.$el.find("[data-toggle=popover]").popover();

                                                //this.$el.find(".dropdown-menu").on("s", function (event) {
                                                //    alert('A');
                                                //});

                                                //this.$el.find(".dropdown-menu").on("hide.bs.dropdown", function (event) {
                                                //    alert('B');
                                                //});

                                                //if (!ctx.editable) {
                                                //  this.$el.find(".configure-source-btn").attr("disabled", true);
                                                //}

                                                this.checkAnyOptions();
                                                return this;
                                            },
                                            bindEvents: function () {
                                                this.listenTo(this.model, 'change:editing change:isLoading', this.checkMode);
                                            },
                                            /////////////////////////////////////////////////////////////////////////////////////
                                            checkMode: function () {
                                                try {
                                                    this.render();
                                                } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                            cellActionClick: function (e) {
                                                try {
                                                    var target = $(e.target);
                                                    var actionData = target.closest('[data-cell-action]').data('cell-action');
                                                    if (actionData) {
                                                        that.actionOnRow(this.model, actionData);
                                                    }
                                                }
                                                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                            /////////////////////////////////////////////////////////////////////////////////////
                                            btnGroup_show: function(e){
                                                try {
                                                    that.stopAutoRefresh();
                                                    //If there's an error, this line prevents 
                                                    this.startAutoRefreshTimeoutId = setTimeout(function () { that.startAutoRefresh(); }, 60 * 1000);
                                                }
                                                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                            btnGroup_hide: function (e) {
                                                try {
                                                    clearTimeout(this.startAutoRefreshTimeoutId);
                                                    that.startAutoRefresh();
                                                }
                                                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                            checkAnyOptions: function () {
                                                var actionSourceBtn = this.$el.find(".action-source-btn");
                                                if (this.$el.find(".action-source-dropdown").find("li").length > 0) {
                                                    actionSourceBtn.attr("disabled", false);
                                                } else {
                                                    actionSourceBtn.attr("disabled", true);
                                                }
                                            },
                                            configure_dropdown_config_opt_click: function (e) {
                                                try {
                                                    e.preventDefault();
                                                    if (!$(e.target).hasClass("disabled-link")) {
                                                        that.runOption(this.model, { option: $(e.target).data("option") });
                                                    }
                                                } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                        }),
                                    },
                                ],
                                collection: that.items,
                                body: Backgrid.Body.extend({
                                    //Override with an empty function to do the sort on the server.
                                    sort: function () { },
                                }),
                                header: Backgrid.Header.extend({
                                    initialize: function (options) {
                                        Backgrid.Header.prototype.initialize.apply(this, arguments);

                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                    collection_backgrid_sort: function (column, direction) {
                                        var sortType = column.get('name').toUpperCase();

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

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

                                        column.set("direction", direction);

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

                                        var params = that.model.toJSON();

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

                                            }
                                        ));
                                    },
                                }),
                            });
                            that.$el.find('.items-grid-container').append(grid.render().el);

                            //end
                            //appending view to the main container 

                            var fixedParams = _.extend({}, viewParams);

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

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

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

                            //Call first refresh.
                            that.startAutoRefresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },

        meltOrderPopup: function (m) {
            var that = this;
            var model = m.toJSON();
            var meltOrderNumber = model.meltOrder.split('.')[0];
            data = {
                GradeName: model.grade
                , HeatNumber: model.heat
                , LadleID: model.ladle ? model.ladle.toString() : ''
                , MaterialSize: model.dim
                , MeltOrderNumber: meltOrderNumber

                , FromMeltOrder: model.meltOrder
                , FromGradeName: model.grade
                , FromMaterialSize: model.dim
            };
            this.ChangeMOModal = new ModalChangeMeltOrder.Views.ModalChangeMeltOrder({
                parent: this,
                data: data,
                bus: null,
            });

            this.listenTo(that.ChangeMOModal, 'close', function () {
                try {
                    that.ChangeMOModal = null;

                    this.pauseTimer = false;
                    that.refresh();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            });
            try {
                if ($('.modal.in').length == 0) { //Check again if there is another modal of any kind displayed to prevent issues.
                    this.pauseTimer = true;
                    that.ChangeMOModal.show();
                }
                else {
                    that.ChangeMOModal.close();
                    that.ChangeMOModal = null;

                    this.pauseTimer = false;
                    that.refresh();
                }
            }
            catch (e) {
                if (that.ChangeMOModal != null) {
                    that.ChangeMOModal.close();
                    that.ChangeMOModal = null;

                    this.pauseTimer = false;
                    that.refresh();
                }
                app.views.topMessages.showMessage(app.translate([that, app], 'MODAL_DISPLAY_ERROR'), { stay: 5 * 1000, });
                console.error((e.stack) ? e.stack : new Error(e).stack);
            }

        },
        runOption: function (model, data) {
            try {
                //var row = model.attributes; 
                var that = this;
                //var type = row.systemType;
                //var typeClass = row.systemTypeClass;
                var menu_option = (data && data.option) ? data.option : null;
                
                switch (menu_option.toUpperCase()) {
                    case "OPT-SPLIT-HEAT":
                        this.splitHeat(model);
                        break;
                    case "OPT-CHANGE-POSITION":
                        this.changeLadlePosition(model);
                        break;
                    //IF optChangePosition IS FALSE, SHOW WARNING MODAL.
                    case "OPT-CHANGE-POSITION-WARNING":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "warning_modal_confirm_title"),
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.changeLadlePosition(model);
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;

                    case "OPT-CHANGE-MELT-ORDER":
                        //this.changeMeltOrder(model);
                        this.meltOrderPopup(model);
                        break;
                     //IF optAssignMeltOrder IS FALSE, SHOW WARNING MODAL.
                    case "OPT-CHANGE-MELT-ORDER-WARNING":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "warning_modal_confirm_title"),
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.changeMeltOrder(model);
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;

                    case "OPT-CHANGE-HEAT-WEIGHTS":
                        this.changeHeatWeights(model);
                        break;
                    //IF optChangeWeights IS FALSE, SHOW WARNING MODAL.
                    case "OPT-CHANGE-HEAT-WEIGHTS-WARNING":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "warning_modal_confirm_title"),
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.changeHeatWeights(model);
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;
                    
                    case "OPT-ASSIGN-HEAT":
                        this.assignHeat(model);
                        break;
                    case "OPT-CHANGE-HEAT-STATUS":
                        this.changeHeatStatus(model);
                        break;
                    case "OPT-CHANGE-HEAT-STATUS-WARNING":
                        break;
                    case "OPT-ASSIGN-LADLE":
                        this.assignLadle(model);
                        break;
                    case "OPT-ASSIGN-LADLE-WARNING":
                        break;
                    case "OPT-ASSIGN-HEAT-WARNING":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "warning_modal_confirm_title"),
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.assignHeat(model);
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;

                    case "OPT-RETURN-LADLE":
                        this.returnLadle(model);
                        break;
                    case "OPT-RETURN-LADLE-WARNING":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "warning_modal_confirm_title"),
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.returnLadle(model);
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;

                    case "OPT-RELADLE":
                        this.reladle(model);
                        break;
                    case "OPT-RELADLE-WARNING":
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "warning_modal_confirm_title"),
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.reladle(model);
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;
                    case "OPT-REMOVE-HEAT":
                        var { heat } = model.toJSON();
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: `The Heat ${heat} will be removed`,
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.model.removeHeat({
                                    HeatNumber: heat
                                });
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;
                    case "OPT-FIX-LADLE":
                        this.fixLadle(model);                     

                        break;
                    case "OPT-CREATE-HEAT":   
                        this.createHeat(model);

                        break;
                    case "OPT-CLEAR-LADLE":
                        var { ladle } = model.toJSON();
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: `The Ladle ${ladle} will be cleared`,
                            message: app.translate([this, app], "warning_modal_confirm_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.model.clearLadle({
                                    ladle: ladle
                                });
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;
                }
                
            }catch(Error){}
        },

        collection_fetch: function (coll, resp) {
            try {
                this.model.set({
                    hasData: (this.items.length > 0),
                    isLoading: false,
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        createHeat: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.CreateHeatModal({
                    model: new Screen.Models.CreateHeatModal({
                        heat: '',
                    }),
                    template: this.templates.createHeatModal,
                    i18n: this.options.i18n[this.template],
                });

                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 {
                            var { data } = output;
                            if (output.result == 'SUCCESS') {
                                app.views.topMessages.showMessage(app.translate([that, app], data.Result), { 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); }
        },

        splitHeat: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.SplitHeatModal({
                    model: new Screen.Models.SplitHeatModal({
                        ladle: attrs.ladle,
                        heat: attrs.heat,
                        curPositionId: attrs.positionId,
                        position: attrs.position,
                    }),
                    template: this.templates.splitHeatModal,
                    i18n: this.options.i18n[this.template],
                });

                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(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); }
        },
        changeLadlePosition: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.ChangePositionModal({
                    model: new Screen.Models.ChangePositionModal({
                        ladle: attrs.ladle,
                        heat: attrs.heat,
                        curPositionId: attrs.positionId,
                        position: attrs.position,
                    }),
                    template: this.templates.changePositionModal,
                    i18n: this.options.i18n[this.template],
                });

                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, });
                            }
                        }
                        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); }
        },
        changeMeltOrder: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.ChangeMeltOrderModal({
                    model: new Screen.Models.ChangeMeltOrderModal({
                        heat: attrs.heat,
                        curMeltOrder: attrs.meltOrder,
                        curGrade: attrs.grade,
                        curDim: attrs.dim,
                    }),
                    template: this.templates.changeMeltOrderModal,
                    i18n: this.options.i18n[this.template],
                });

                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, });
                            }
                        }
                        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); }
        },
        changeHeatWeights: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();
                this.currentModal = new Screen.Views.ChangeHeatWeightsModal({
                    model: new Screen.Models.ChangeHeatWeightsModal({
                        heat: attrs.heat,
                        tare: attrs.tare,
                        alloy: attrs.alloy,
                        net: attrs.net,
                    }),
                    template: this.templates.changeHeatWeightsModal,
                    i18n: this.options.i18n[this.template],
                });

                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, });
                            }
                        }
                        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); }
        },
        assignHeat: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.AssignHeatModal({
                    model: new Screen.Models.AssignHeatModal({
                        ladle: attrs.ladle,
                        heat: attrs.heat,
                    }),
                    template: this.templates.assignHeatModal,
                    i18n: this.options.i18n[this.template],
                });

                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, });
                            }
                        }
                        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); }
        },
        changeHeatStatus: function (model) {
            try {
                var that = this,
                    attrs = model.toJSON();

                this.currentModal = new Screen.Views.ChangeHeatStatusModal({
                    model: new Screen.Models.ChangeHeatStatusModal({
                        heat: attrs.heat,
                        status: attrs.status,
                    }),
                    template: this.templates.changeHeatStatusModal,
                    i18n: this.options.i18n[this.template],
                });

                this.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) { 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); }
        },
        assignLadle: function (model) {
            try {
                var that = this,
                    attrs = model.toJSON();

                this.currentModal = new Screen.Views.AssignLadleModal({
                    model: new Screen.Models.AssignLadleModal({
                        heat: attrs.heat,
                    }),
                    template: this.templates.assignLadleModal,
                    i18n: this.options.i18n[this.template],
                });

                this.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) { 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); }
        },
        returnLadle: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.ReturnLadleModal({
                    model: new Screen.Models.ReturnLadleModal({
                        heat: attrs.heat,
                        ladle: attrs.ladle,
                        position: attrs.position,
                    }),
                    template: this.templates.returnLadleModal,
                    i18n: this.options.i18n[this.template],
                });

                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, });
                            }
                        }
                        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); }
        },
        reladle: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();

                this.currentModal = new Screen.Views.ReladleModal({
                    model: new Screen.Models.ReladleModal({
                        ladle: attrs.ladle,
                        position: attrs.position,
                        heat: attrs.heat,
                    }),
                    template: this.templates.reladleModal,
                    i18n: this.options.i18n[this.template],
                });

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

        fixLadle: function (model) {
            try {
                var that = this
                    , attrs = model.toJSON();
                this.currentModal = new Screen.Views.FixLadleModal({
                    model: new Screen.Models.FixLadleModal({
                        currentLadle: `Ladle ${attrs.ladle}`,
                        heat: attrs.heat,
                    }),
                    template: this.templates.fixLadleModal,
                    i18n: this.options.i18n[this.template],
                });

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

        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 () {
            //TODO - Put this in events object.
            var that = this;

            this.listeners['beforeunload'] = _.bind(that.window_beforeUnload, that);
            $(window).on('beforeunload', this.listeners['beforeunload']);
        },
        close: function () {
            this.options.state = app.view_states.closed;

            //If currentModal exists, hide it and erase it.
            if (this.currentModal) {
                this.currentModal.hide();
                this.currentModal = null;
            }

            this.stopAutoRefresh();
            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.close();
            });
        },
        hide: function () {
            this.options.state = app.view_states.hidden;

            this.hideSubviews();
            this.stopAutoRefresh();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        remove: function () {
            this.removeBindings();
            this.$el.remove();
            this.stopListening();
            return this;
        },
        reRender: function () {
            this.startAutoRefresh();
        },
        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();
            });
        },
        startAutoRefresh: function () {
            try {
                if (this.autoRefresh.enabled !== true) {
                    var that = this;

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

                    this.autoRefresh.enabled = true;

                    //use a timeout to execute the first refresh to return the handle to the start function caller.
                    //So when the caller finish it will do the first refresh.
                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        1
                    );
                }
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
        unbindViewScopedEvents: function () {
            $(window).off('beforeunload', this.listeners['beforeunload']);

            this.stopAutoRefresh();
        },
        window_beforeUnload: function (e) {
            try {
                if (this.currentModal) {
                    this.currentModal.hide();
                }
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
    });

    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        defaults: {
            positionId: null,
            ladle: null,
            since:null,
            heat: null,
            status:null,
            meltOrder: null,
            dim: null,
            grade: null,
            net: null,
            tare: null,
            slag: null,
            temp: null,
            chem: null,
            alloy: null,

            optChangePosition: null,
            optAssignHeat: null,
            optChangeWeights: null,
            optReturnLadle: null,
            optReLadle: null,
            optAssignMeltOrder: null,
            optSplitHeat: null,
            optRemoveHeat: null,
            optCreateHeat: null,
            optFixLadle: null,
            optClearLadle: null,
            optChangeHeatStatus: null,
            optAssignLadle: null,
            isLoading: false,

            heatsOnLining:null,
        },
        parse: function (obj) {
            return {
                positionId: obj.PositionId,
                position: obj.Position,
                ladle: obj.Ladle,
                since: obj.Since,
                heat: obj.HeatNumber,
                status:obj.Status,
                meltOrder: obj.MeltOrder,
                dim: obj.Dim,
                grade: obj.GradeName,
                net: obj.NetWeight,
                tare: obj.TareWeight,
                slag: obj.SlagWeight,
                temp: obj.LastTemperature,
                chem: obj.LastChemistry,
                alloy: obj.AlloyWeight ? obj.AlloyWeight : '-',

                optChangePosition: obj.Option_ChangePosition,
                optAssignHeat: obj.Option_AssignHeat,
                optChangeWeights: obj.Option_ChangeWeights,
                optReturnLadle: obj.Option_ReturnLadle,
                optReLadle: obj.Option_ReLadle,
                optAssignMeltOrder: obj.Option_AssignMeltOrder,
                optSplitHeat: obj.Option_SplitHeat,
                heatsOnLining: obj.HeatsOnLining,                
		        optRemoveHeat : obj.Option_RemoveHeat,
                optCreateHeat: obj.Option_CreateHeat,
                optFixLadle: obj.Option_FixLadle,
                optClearLadle:obj.Option_ClearLadle,
                optChangeHeatStatus: obj.Option_ChangeHeatStatus,
                optAssignLadle: obj.Option_AssignLadle,

            };
        },
    });

    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.Item,

        fixedParameters: [],
        isFetching: false,
        currentPage: 1,
        pageSize: 50,
        transaction_timestamp: null,

        fetch: function (opt) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                ttimestamp = this.transaction_timestamp = new Date().getTime(),
                options = opt ? _.clone(opt) : {};

            //qp.Add('@onlyActives', 'BIT', false);

            if (options.refresh) {
                //this.resetPagination(true);

                this.fixedParameters = [
                    { Name: '@sortType', Type: 'VARCHAR', Value: options.params.sortType, },
                ];
            }

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

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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.GetLadleDashboard',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            //checking transaction timestamp
                            if (ttimestamp != that.transaction_timestamp)
                                return;
                            
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table,
                                    newColl;

                                newColl = _.map(records, that.model.prototype.parse);

                                var method = ((options.refresh) || ((options.reset))) ? 'set' : 'add';

                                //checking transaction timestamp
                                if (ttimestamp != that.transaction_timestamp)
                                    return;

                                var editingItems = _.where(that.toJSON(), { isNew: true });
                                [].push.apply(newColl, editingItems);

                                that[method](newColl, { from: 'fetch' })
                                    .trigger('fetch', that, records);

                                //decreasing page since we couldn't get any data on this page.
                                if (newColl.length == 0 && method == 'add')
                                    that.currentPage--;

                                that.isFetching = false;
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error('Server response not valid.');
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: options.async,
                    Secured: 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);
        //    }
        //},
    });

       //--------------------------------------//
       //------------ SPLIT HEAT --------------//
       //--------------------------------------//
       Screen.Models.SplitHeatModal = Backbone.Epoxy.Model.extend({
           defaults: {
               message: null,

               ladle: null,
               toLadle: 1,
               heat: null,

               ladles: [],
               comments: '',
               errorMsg: "",
               processing: false,

               weight: null,
           },
           computeds: {
               hasLadles: {
                   deps: ['ladles'],
                   get: function (ladles) {
                       return ladles.length != 0;
                   },
               },
           },
           fetchLadles: function () {
               var that = this,
                   qp = new Core.Database.QueryParameters();

               qp.Add('@onlyAvailableLadles', 'BIT', 0);

               Core.Json.CallProcedure(
                   app.DatabaseNames.MES + ".LAD.GetLadles",
                   qp,
                   {
                       onSuccess: function (resp) {
                           try {
                               if ((resp) && (resp.Table)) {
                                   var records = resp.Table;

                                   var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });
                                
                                   that.set("ladles", newItems);
                               }
                               else {
                                   if ((resp) && (resp.Message))
                                       console.error(resp.Message);
                                   else
                                       console.error("Server response not valid.");
                               }
                           }
                           catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                       },
                       onFailure: function (resp) {
                           console.error(resp);
                       },
                       Secured: true,
                       Async: false,
                   },
                   app.ConnectionStrings.app
               );

               return this;
           },
   
           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 + '.LAD.SplitHeat',
                   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);
                           }
                           catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                       },
                       Async: opt.async,
                       Secured: true,
                   },
                   app.ConnectionStrings.app
               );
           },
       });
       Screen.Views.SplitHeatModal = Modal.Views.SimpleModal.extend({
           className: Modal.Views.SimpleModal.prototype.className + ' split-heat-modal',

           i18n: null,

           initialize: function (options) {
               _.extend(this, options);

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

               this.model.fetchLadles();

               this.bindEvents();

               return this;
           },
           bindEvents: function () {
               Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
           },

           save: function () {
               var that = this,
                   attrs = this.model.toJSON();
               if (attrs.processing == false) {
                   this.model.set('processing', true);

                   try {
                       this.model.save({
                           params: [
                               { Name: '@LadleID1', Type: 'INT', Value: attrs.ladle, },
                               { Name: '@LadleID2', Type: 'INT', Value: attrs.toLadle, },
                               { Name: '@Weight', Type: 'FLOAT', Value: attrs.weight, },
                               { Name: '@Comments', Type: 'VARCHAR', Value: attrs.comments, },
                           ],
                           success: function (model, resp) {
                               try {
                                   that.model.set('processing', false);

                                   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(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;
                   }
               }
           },
           show: function () {
               if (!this.isRendered) {
                   this.render();
               }
               else {
                   this.$el.modal({
                       keyboard: false,
                       backdrop: 'static',
                   });
               }

               return this;
           },
           hide: function () {
               //if (this.innerModal)
               //    this.innerModal.hide();

               var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
               return result;
           },

           acceptBtn_click: function (e) {
               try {
                   this.save();
               }
               catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
           },
       });




       //--------------------------------------//
       //------------ CREATE HEAT --------------//
       //--------------------------------------//

    Screen.Views.CreateHeatModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' create-heat-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.bindEvents();

            return this;
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        isValidHeat: function() {
            var heat = this.model.get('heat');
            var letter = heat.charAt(0)
            var isLetter = (/[a-zA-Z]/).test(letter);
            var numbers = heat.substring(1, 7);

            if (heat.length != 7) return false;      
            if (!isLetter) return false;
            if (isNaN(numbers)) return false;             

            return true;

        },
        save: function () {
            var that = this,
                attrs = this.model.toJSON();
            var isValid = that.isValidHeat();

            this.model.set({
                isValid: isValid
            });

            if (!isValid) return;

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                            { Name: '@HeatNumber', Type: 'CHAR(10)', Value: attrs.heat, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                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(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;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    Screen.Models.CreateHeatModal = Backbone.Epoxy.Model.extend({
           defaults: {
               message: null,
               errorMsg: "",
               processing: false,
               isValid: true,
           },
           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 + '.LAD.CreateHeat',
                   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);
                           }
                           catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                       },
                       Async: opt.async,
                       Secured: true,
                   },
                   app.ConnectionStrings.app
               );
           },
       });

       //--------------------------------------------------//
       //------------ CHANGE LADLE POSITION --------------//
       //--------------------------------------------------//
    Screen.Models.ChangePositionModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            position: null,
            curPositionId: null,
            newPositionId: null,

            positions: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasPositions: {
                deps: ['positions'],
                get: function (positions) {
                    return positions.length != 0;
                },
            },
        },
        fetchPositions: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailablePositions', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadlePositions",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Name, }; });

                                that.set("positions", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

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


            qp.Add('@GodMode', 'BIT', true);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.ChangeLadlePositionWeb',
                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);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ChangePositionModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' change-position-modal',
        
        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchPositions();
            
            this.bindEvents();

            return this;
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        
        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: '@ladlePositionId', Type: 'INT', Value: attrs.newPositionId, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                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(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;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },
        
        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });


       //--------------------------------------------------//
       //------------ CHANGE MELT ORDER --------------//
       //--------------------------------------------------//
    Screen.Models.ChangeMeltOrderModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            heat: null,
            curMeltOrder: null,
            curGrade: null,
            curDim: null,
            newMeltOrder: null,
            newGrade: null,
            newDim: null,
            meltOrderSequence: '1',
            comments: '',

            meltOrders: [],
            grades: [],
            dims: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasMeltOrders: {
                deps: ['meltOrders'],
                get: function (meltOrders) {
                    return meltOrders.length != 0;
                },
            },
        },
        fetchMeltOrders: function () {
            var that = this;
            
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetMeltOrders",
                null,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var meltOrders = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });
                                var grades = _.map(records, function (obj) { return { value: obj.Id, label: obj.Grade, }; });
                                var dims = _.map(records, function (obj) { return { value: obj.Id, label: obj.Dim, }; });

                                that.set("meltOrders", meltOrders);
                                that.set("grades", grades);
                                that.set("dims", dims);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        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 + '.LAD.AssignMeltOrderToHeatWeb',
                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);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ChangeMeltOrderModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' change-melt-order-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchMeltOrders();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #changeMeltOrderSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
            this.listenTo(this.model, "change:newMeltOrder", this.model_change_newMeltOrder);
        },

        model_change_newMeltOrder: function () {
            var that = this;

            this.model.set('newGrade', (_.find(this.model.get('grades'), function (grade) { return grade.value == that.model.get('newMeltOrder'); })).label);
            this.model.set('newDim', (_.find(this.model.get('dims'), function (dim) { return dim.value == that.model.get('newMeltOrder'); })).label);
        },

        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                                { Name: '@heatNumber', Type: 'VARCHAR', Value: attrs.heat, },
                                { Name: '@meltOrderNumber', Type: 'VARCHAR', Value: attrs.newMeltOrder, },
                               // { Name: '@meltOrderSequence', Type: 'INT', Value: parseInt(attrs.meltOrderSequence), },
                                { Name: '@comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                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(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;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    //--------------------------------------------------//
    //------------ CHANGE WEIGHT --------------//
    //--------------------------------------------------//
    Screen.Models.ChangeHeatWeightsModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            heat: null,
            gross: null,
            tare: null,
            slag: null,
            skull: null,
            lid: null,

            errorMsg: "",
            processing: false,
        },
        computeds: {
        },
        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 + '.LAD.UpsertHeatTareAndGrossWeightsWeb',
                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);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ChangeHeatWeightsModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' change-heat-weights-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #changeHeatWeightsSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        
        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                            { Name: '@HeatNumber', Type: 'VARCHAR', Value: attrs.heat, },
                            { Name: '@NetWeight', Type: 'FLOAT', Value: attrs.net, },
                            { Name: '@TareWeight', Type: 'FLOAT', Value: attrs.tare, },    
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                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(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;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    //--------------------------------------------------//
    //------------ ASSIGN HEAT --------------//
    //--------------------------------------------------//
    Screen.Models.AssignHeatModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            newHeat: null,
            
            heats: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasHeats: {
                deps: ['heats'],
                get: function (heats) {
                    return heats.length != 0;
                },
            },
        },
        fetchHeats: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailableHeats', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetHeats",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });

                                that.set("heats", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        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 + '.LAD.AssignHeatToLadleWeb',
                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);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });
    Screen.Views.AssignHeatModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' assign-heat-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchHeats();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #assignHeatToLadleSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },

        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: '@heatNumber', Type: 'VARCHAR', Value: attrs.newHeat, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                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(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;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    //--------------------------------------------------//
    //------------ CHANGE HEAT STATUS --------------//
    //--------------------------------------------------//
    Screen.Models.ChangeHeatStatusModal = Backbone.Epoxy.Model.extend({
        defaults: {
            heat: null,
            status: null,
            heatStatuses: [],
            newHeatStatusId: null,
            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasHeatStatuses: {
                deps: ['heatStatuses'],
                get: function (heatStatuses) {
                    return heatStatuses.length != 0;
                },
            },
        },
        fetchHeatStatuses: function () {
            var that = this;
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetCatHeatStatus",
                new Core.Database.QueryParameters(),
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;
                                var newItems = _.map(records, function (obj) { return { value: obj.HeatStatusID, label: obj.Name, }; });
                                that.set("heatStatuses", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) { console.error(resp); },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );
            return this;
        },
        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 + '.LAD.ChangeHeatStatusWeb',
                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); }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });
    Screen.Views.ChangeHeatStatusModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' change-heat-status-modal',
        i18n: null,
        initialize: function (options) {
            _.extend(this, options);
            if (!this.model) this.model = new Screen.Models.ChangeHeatStatusModal();
            this.model.fetchHeatStatuses();
            this.bindEvents();
            return this;
        },
        events: function () {
            return { 'click #changeHeatStatusSaveBtn': this.acceptBtn_click };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        save: function () {
            var that = this, attrs = this.model.toJSON();
            if (attrs.processing == false) {
                this.model.set('processing', true);
                try {
                    this.model.save({
                        params: [
                            { Name: '@HeatNumber', Type: 'VARCHAR', Value: attrs.heat },
                            { Name: '@HeatStatusID', Type: 'INT', Value: attrs.newHeatStatusId },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);
                                that.finish({ result: 'SUCCESS', data: resp });
                                that.hide();
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                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; }
            }
        },
        show: function () {
            if (!this.isRendered) this.render();
            else this.$el.modal({ keyboard: false, backdrop: 'static' });
            return this;
        },
        hide: function () {
            return Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
        },
        acceptBtn_click: function (e) {
            try { this.save(); }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    //--------------------------------------------------//
    //------------ ASSIGN LADLE (to heat) --------------//
    //--------------------------------------------------//
    Screen.Models.AssignLadleModal = Backbone.Epoxy.Model.extend({
        defaults: {
            heat: null,
            ladles: [],
            selectedLadleId: null,
            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasLadles: {
                deps: ['ladles'],
                get: function (ladles) { return ladles.length != 0; },
            },
        },
        fetchLadles: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();
            qp.Add('@onlyAvailableLadles', 'BIT', 1);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadles",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;
                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Name }; });
                                that.set("ladles", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message)) console.error(resp.Message);
                                else console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) { console.error(resp); },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );
            return this;
        },
        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 + '.LAD.AssignHeatToLadleWeb',
                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); }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });
    Screen.Views.AssignLadleModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' assign-ladle-modal',
        i18n: null,
        initialize: function (options) {
            _.extend(this, options);
            if (!this.model) this.model = new Screen.Models.AssignLadleModal();
            this.model.fetchLadles();
            this.bindEvents();
            return this;
        },
        events: function () {
            return { 'click #assignLadleSaveBtn': this.acceptBtn_click };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        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.selectedLadleId },
                            { Name: '@heatNumber', Type: 'VARCHAR', Value: attrs.heat },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);
                                that.finish({ result: 'SUCCESS', data: resp });
                                that.hide();
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        error: function (model, errorMsg) {
                            try {
                                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; }
            }
        },
        show: function () {
            if (!this.isRendered) this.render();
            else this.$el.modal({ keyboard: false, backdrop: 'static' });
            return this;
        },
        hide: function () {
            return Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
        },
        acceptBtn_click: function (e) {
            try { this.save(); }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    //--------------------------------------------------//
    //------------ FIX LADLE --------------//
    //--------------------------------------------------//
    Screen.Models.FixLadleModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,
            currentLadle: null,
            ladle: null,
            heat: null,

            ladles: [],
            newLadle: null,


            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasLadles: {
                deps: ['ladles'],
                get: function (ladles) {
                    return ladles.length != 0;
                },
            },
        },
        fetchLadles: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();
            qp.Add('@onlyAvailableLadles', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadles",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Name, }; });
                              
                                that.set("ladles", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        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 + '.LAD.FixLadleNumberOnHeatWeb',
                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);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
       });
    Screen.Views.FixLadleModal = Modal.Views.SimpleModal.extend({
           className: Modal.Views.SimpleModal.prototype.className + ' fix-ladle-modal',

           i18n: null,

           initialize: function (options) {
               _.extend(this, options);

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

               this.model.fetchLadles();

               this.bindEvents();

               return this;
           },
           events: function () {
               return {
                   'click #fixLadleSaveBtn': this.acceptBtn_click,
               };
           },
           bindEvents: function () {
               Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
           },

           save: function () {
               var that = this,
                   attrs = this.model.toJSON();

               if (attrs.processing == false) {
                   this.model.set('processing', true);

                   try {
                       this.model.save({
                           params: [
                               { Name: '@HeatNumber ', Type: 'VARCHAR', Value: attrs.heat, },
                               { Name: '@LadleID', Type: 'INT', Value: attrs.newLadle, },
                           ],

                           success: function (model, resp) {
                               try {
                                   that.model.set('processing', false);

                                   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(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;
                   }
               }
           },
           show: function () {
               if (!this.isRendered) {
                   this.render();
               }
               else {
                   this.$el.modal({
                       keyboard: false,
                       backdrop: 'static',
                   });
               }

               return this;
           },
           hide: function () {
               //if (this.innerModal)
               //    this.innerModal.hide();

               var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
               return result;
           },

           acceptBtn_click: function (e) {
               try {
                   this.save();
               }
               catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
           },
       });

    //--------------------------------------------------//
    //------------ RETURN LADLE --------------//
    //--------------------------------------------------//
    Screen.Models.ReturnLadleModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            position: null,
            newPosition: null,
            comments: '',

            positions: [],
            
            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasPositions: {
                deps: ['positions'],
                get: function (positions) {
                    return positions.length != 0;
                },
            },
        },
        fetchPositions: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailablePositions', 'BIT', 1);
            
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadlePositions",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Name, }; });

                                that.set("positions", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        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 + '.LAD.ReturnLadleWeb',
                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);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ReturnLadleModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' return-ladle-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchPositions();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #returnLadleSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        
        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: 'VARCHAR', Value: attrs.ladle, },
                                { Name: '@ladlePositionId', Type: 'VARCHAR', Value: attrs.newPosition, },
                                { Name: '@comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                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(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;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });

    //--------------------------------------------------//
    //------------ RELADLE  --------------//
    //--------------------------------------------------//
    Screen.Models.ReladleModal = Backbone.Epoxy.Model.extend({
        defaults: {
            message: null,

            ladle: null,
            heat: null,
            position: null,
            newLadle: null,
            comments: '',

            ladles: [],

            errorMsg: "",
            processing: false,
        },
        computeds: {
            hasLadles: {
                deps: ['ladles'],
                get: function (ladles) {
                    return ladles.length != 0;
                },
            },
        },
        fetchLadles: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@onlyAvailableLadles', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".LAD.GetLadles",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.Id, }; });

                                that.set("ladles", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        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 + '.LAD.ReladleWeb',
                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);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
    });

    Screen.Views.ReladleModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' reladle-modal',

        i18n: null,

        initialize: function (options) {
            _.extend(this, options);

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

            this.model.fetchLadles();

            this.bindEvents();

            return this;
        },
        events: function () {
            return {
                'click #reladleSaveBtn': this.acceptBtn_click,
            };
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
        },
        
        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.model.save({
                        params: [
                                { Name: '@oldLadleId', Type: 'VARCHAR', Value: attrs.ladle, },
                                { Name: '@newLadleId', Type: 'VARCHAR', Value: attrs.newLadle, },
                                { Name: '@comments', Type: 'VARCHAR', Value: attrs.comments, },
                        ],
                        success: function (model, resp) {
                            try {
                                that.model.set('processing', false);

                                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(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;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            //if (this.innerModal)
            //    this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
    });
    // Required, return the module for AMD compliance.
    return Screen;

});
