//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/base/base',
   'backgrid',
   'modules/modal2',
   'moment',
   'modules/ladle-furnace',
    'modules/furnace/furnace',
    'modules/electrode-change-reason',
    'modules/supplier/supplier',

  'backgrid/computed-cell',
  'backgrid/duration-cell',
  'backgrid/infinator',
  'backgrid/moment-cell',
  'js/backgrid-0.3.5/extensions/valid-limit-cell/backgrid-valid-limit-cell',
  'js/typeahead.extended/typeahead.extended',
],
    function (app, T, Base, Backgrid, Modal, moment, LadleFurnace, Furnace, ElectrodeChangeReason, Supplier) {


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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            start: new moment().format('YYYY-MM-DD'),
            end: new moment().format('YYYY-MM-DD'),
            navigating: false,
            electrodeChangeReasonId: 0,
            electrodeChangeReasons: [],
            supplierId: 0,
            suppliers: [],
            reasons: [],
            crewId: 0,
            crews: [],
            equipmentCode: 0,
            areaCode: "0",
            lfLadleFurnaces: [],
            eafFurnaces: [],
            startDate: null,
            startTime: null,
            


            hasData: false,
            isLoading: false,
        },
        computeds: {
            start$: {
                deps: ['start'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            end$: {
                deps: ['end'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            hasCrews: {
                deps: ["crews"],
                get: function () {
                    return this.get("crews");
                },
            },
            hasReasons: {
                deps: ["reasons"],
                get: function () {
                    return this.get("reasons");
                },
            },        
            hasEquipments: {
                deps: ["equipments"],
                get: function () {
                    return this.get("equipments");
                },
            },
            equipments: {
                deps: ['areaCode', 'eafFurnaces', 'lfLadleFurnaces'],
                get: function (areaCode, eafFurnaces, lfLadleFurnaces) {
                    if (areaCode == 'EAF') {
                        return eafFurnaces;
                    } else if (areaCode == 'LF') {
                        return lfLadleFurnaces;
                    } else {
                        return areaCode = 'All';
                    }           
                },
            },
            
        },
        fetchReasons: function (params) {
            var that = this;

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.ELT.GetElectrodeChangeReasons',
                null,
                {
                    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('reasons', 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;
        },
        fetchCrews: function (params) {
            var that = this;

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.SYSTEM.GetCrews',
                null,
                {
                    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('crews', 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;
        },
    });

    Screen.Models.Item = Base.Models.Base.extend({
        defaults: {
            productionDate: null,
            timestampString: null,
            productionCrew: null,
            station: null,
            heatName: null,
            phaseCode: null,
            supplier: null,
            entryReasonType: null,
            size: null,
            tapSetting: null,
            chargeBuckets: null,
            energy: null,
            operatorsName: null,
            locationName: null,
            breakReason: null,
            scrapCraneOperator: null,
            breakLength: null,
            arcLength: null,
            numberSticks: null,
            comments: null,
            heatsName: null,
        },


        procedures: {
            get: app.DatabaseNames.MES + ".ELT.GetElectrodeConsumptions",
        },

        parse: function (obj) {
            return {
                productionDate: obj.ProductionDate,
                timestampString: obj.TimestampString,
                productionCrew: obj.ProductionCrew,
                station: obj.Station,
                heatName: obj.HeatName,
                phaseCode: obj.PhaseCode,
                supplier: obj.Supplier,
                entryReasonType: obj.EntryReasonType,
                size: obj.Size,
                tapSetting: obj.TapSetting,
                chargeBuckets: obj.ChargeBuckets,
                energy: obj.Energy,
                operatorsName: obj.OperatorsName,
                locationName: obj.LocationName,
                breakReason: obj.BreakReason,
                scrapCraneOperator: obj.ScrapCraneOperator,
                breakLength: obj.BreakLength,
                arcLength: obj.ArcLength,
                numberSticks: obj.NumberSticks,
                comments: obj.Comments,
                heatsName: obj.HeatsName,
            };
        },
    });


    var superRef, superProto, classRef;

    superRef = Base.Collections.Base;
    superProto = superRef.prototype;

    Screen.Collections.Items = classRef = superRef.extend({
        model: Screen.Models.Item,
        //comparator: 'heatName',
    });




    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'electrode-consumption',
        id: 'electrode-consumption',
        title: 'Electrode Consumption',
        events: function () {
            return {
                'click .btn-change-electrode': this.changeElectrodeBtn_click,
                'click #refreshBtn': this.refreshBtn_click,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,

        items: null,
        subviews: null,
        viewParams: null,
        templates: null,
        items: null,
        searchTbx: null,

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

            var that = this;

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

            this.items = new (Screen.Collections.Items.extend({ pageSize: 50, }))();

            this.bindingSources = {};

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

            this.model.fetchCrews();
            this.model.fetchReasons();


            LadleFurnace.Collections.LadleFurnaces.fetch({
                async: false,
                success: function (records) {
                    try {
                        that.model.set(
                            'lfLadleFurnaces',
                            _.map(records, function (obj) { return { value: obj.code, label: obj.name, }; })
                        );
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                },
            });

            Furnace.Collections.Furnaces.fetch({
                async: false,
                success: function (records) {
                    try {
                        that.model.set(
                            'eafFurnaces',
                            _.map(records, function (obj) { return { value: obj.code, label: obj.name, }; })
                        );
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                },
            });

            ElectrodeChangeReason.Collections.ElectrodeChangeReasons.fetch({
                async: false,
                success: function (records) {
                    try {
                        that.model.set('electrodeChangeReasons', _.map(records, function (obj) { return { value: obj.id, label: obj.name, }; }));
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                },
            });

            Supplier.Collections.Suppliers.fetch({
                async: false,
                success: function (records) {
                    try {
                        that.model.set('suppliers', _.map(records, function (obj) { return { value: obj.id, label: obj.name, }; }));
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                },
            });
            
        },
        //bindEvents: function () {
        //    this
        //        .listenTo(this.model, 'change:electrodeChangeReasonId', this.model_change_electrodeChangeReasonId)
        //        .listenTo(this.model, 'change:crewId', this.model_change_crewId)
        //        .listenTo(this.model, 'change:equipmentCode', this.model_change_equipmentCode);
        //    //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, 'backgrid:rowclick', this.items_backgrid_rowclick);**/
        //    this.listenTo(this.model, 'change:start change:end', this.model_change_pickers);
        //},
        _refresh: function (opt) {
            //console.log('autorefresh: ' + new Date().toString()); 
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshItems(opt);

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

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refreshItems: function (options) {
            var that = this,
                attrs = this.model.toJSON(),
                opt = _.extend({}, { params: {}, }, options);

            this.items.fetch(_.extend(opt, {
                params: {
                    electrodeChangeReasonId: ( attrs.electrodeChangeReasonId != 0 ) ? attrs.electrodeChangeReasonId : null,
                    crewId: ( attrs.crewId  != 0 ) ? attrs.crewId : null,
                    start: attrs.start ? attrs.start : null,
                    end: attrs.end ? new moment(attrs.end, 'YYYY-MM-DD').add('days', 1).format('YYYY-MM-DD') : null,
                    areaCode: ( attrs.areaCode != 0 ) ? attrs.areaCode : null,
                    equipmentCode: (attrs.equipmentCode != 0) ? attrs.equipmentCode : null,
                },
                success: function () {
                    that.model.set({
                        isLoadingProcess: false,
                        navigating: false,
                    });
                },
                error: function () {
                    that.model.set({
                        isLoadingProcess: false,
                        navigating: false,
                    });
                },
            }));
        },
        refresh: function (viewParams) {
            var fixedParams = _.extend({}, viewParams);

            if (viewParams.start)
                fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                
            
            if (viewParams.end)
                fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');


            this.model.set(fixedParams);

            this._refresh({
                reset: true,
                params: _.extend(
                    {},
                    fixedParams,
                    {}
                ),
            });
        },
        
        render: function (container, viewParams) {
            var that = this;
            
            this.viewParams = viewParams;

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

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

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

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

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

                            that.applyBindings();

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

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

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'timestampString',
                                        label: app.translate([that, app], 'date_ocurred_col'),
                                        cell: Backgrid.Extension.MomentCell.extend({
                                            className: 'momment-cell align-center-cell timestampString',
                                            modelFormat: 'YYYY-MM-DD HH:mm:ss.SSS',
                                            displayFormat: app.translate([that, app], 'MM/DD/YYYY HH:mm'),
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'productionDate',
                                        label: app.translate([that, app], 'production_date_col'),
                                        cell: Backgrid.Extension.MomentCell.extend({
                                            className: 'momment-cell align-center-cell productionDate',
                                            modelFormat: 'YYYY-MM-DD',
                                            displayFormat: app.translate([that, app], 'MM/DD/YYYY'),
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'productionCrew',
                                        label: app.translate([that, app], 'production_crew_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell productionCrew',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'station',
                                        label: app.translate([that, app], 'station_name_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell stationName',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'heatsName',
                                        label: app.translate([that, app], 'heat_name_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell heatName',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'phaseCode',
                                        label: app.translate([that, app], 'phase_type_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell phaseType',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'supplier',
                                        label: app.translate([that, app], 'supplier_name_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell supplierName',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'entryReasonType',
                                        label: app.translate([that, app], 'entry_reason_type_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell entryReasonType',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'size',
                                        label: app.translate([that, app], 'size_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell size',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'tapSetting',
                                        label: app.translate([that, app], 'tap_setting_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell tapSetting',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'chargeBuckets',
                                        label: app.translate([that, app], 'charge_buckets_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell chargeBuckets',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'energy',
                                        label: app.translate([that, app], 'mwh_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell mwh',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'operatorsName',
                                        label: app.translate([that, app], 'furnace_operator_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell furnaceOperator',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'locationName',
                                        label: app.translate([that, app], 'location_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell location',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'breakReason',
                                        label: app.translate([that, app], 'break_reason_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell breakReason',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'scrapCraneOperator',
                                        label: app.translate([that, app], 'scrap_crane_operator_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell scrapCraneOperator',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'breakLength',
                                        label: app.translate([that, app], 'break_length_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell breakLength',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'arcLength',
                                        label: app.translate([that, app], 'arc_length_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell arcLength',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'comments',
                                        label: app.translate([that, app], 'comments_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell comments',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'numberSticks',
                                        label: app.translate([that, app], 'number_sticks_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell numberSticks',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                    {
                                        name: 'heatName',
                                        label: app.translate([that, app], 'heats_name_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell heatsName',
                                        }),
                                        editable: false,
                                        sortable: false,
                                    },
                                ],
                                collection: that.items,
                                footer: Backgrid.Extension.Infinator.extend({
                                    scrollToTop: false,
                                }),
                                row: Backgrid.Row.extend({
                                    events: function () {
                                        return {
                                            'click': this.click,
                                        };
                                    },
                                    /*click: function (e) {
                                        try {
                                            this.model.trigger('backgrid:rowclick', this.model);
                                        }
                                        catch (Error) { console.error(Error.stack); }
                                    }*/
                                })
                            });
                            that.$el.find('.items-grid-container').append(grid.render().el);


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


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

                            if (fixedParams.start)
                                fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                            if (fixedParams.end)
                                fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');

                            that.model.set(fixedParams);

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

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

                            //that.startAutoRefresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },

        changeElectrodeBtn_click: function (e) {
            try {
                var that = this,
                    processAttrs = this.model.toJSON(),
                    phaseCode = $(e.currentTarget).data('phaseCode'),
                    electrodeRef;

                var modal = new Screen.Views.ElectrodeChangeModal({
                    model: new Screen.Models.ElectrodeChangeModal({
                        currentElectrodeHeatsCount: processAttrs['electrode' + electrodeRef + 'HeatsCount'],
                        currentElectrodeSupplier: processAttrs['electrode' + electrodeRef + 'Supplier'],
                        currentElectrodeWeight: processAttrs['electrode' + electrodeRef + 'Weight'],
                        electrodeChangeId: processAttrs['electrode' + electrodeRef + 'ChangeId'],
                        electrodeChangeReasons: this.model.get('electrodeChangeReasons'),
                        suppliers: this.model.get('suppliers'),
                        //equipments: [].concat(
                        //    _.map(this.model.get('eafFurnaces'), function (obj) { return { value: 'EAF-' + obj.value, label: obj.label, }; }),
                        //    _.map(this.model.get('lfLadleFurnaces'), function (obj) { return { value: 'LF-' + obj.value, label: obj.label, }; })
                        //),
                        equipments: _.map(this.model.get('eafFurnaces'), function (obj) { return { value: 'EAF-' + obj.value, label: obj.label, }; }),
                        //equipments: [].concat( this.model.get('eafFurnaces'),this.model.get('lfLadleFurnaces')),
                        //heatName: processAttrs.heatName,
                        heatName: this.model.get('heatName'),
                        phaseCode: this.model.get('phaseCode'),      
                        //areaCode: this.model.get('AreaCode'),
                        processId: processAttrs.id,
                        
                    }),
                    template: Handlebars.compile(this.$el.find('#electrode_change_modal_template').html()),
                });


                this.listenToOnce(modal, 'finish', function (modal, data) {
                    if (data.result == 'SUCCESS') {
                        var params = that.model.toJSON();

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

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

        
        refreshBtn_click: function (e) {
            try {
                var params = this.model.toJSON();

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );

                this._refresh({
                    reset: true,
                    params: _.extend(
                        params,
                        {}
                    ),
                });
                window.scrollTo(0, 0);
            }
            catch (Error) { console.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 () {
            var that = this;
        },
        unbindViewScopedEvents: function () {

        },
        close: function () {
            this.options.state = app.view_states.closed;

            this.stopAutoRefresh();

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

            this.showSubviews();
            this.bindEvents();
            this.$el.show();
        },
        showSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.show();
            });
        },
        hide: function () {
            this.options.state = app.view_states.hidden;

            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.set("subnavbar", false);
        },
        reRender: function (viewParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },
        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); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
    });


    Screen.Views.CreateHeatModal = Modal.Views.SimpleModal.extend({
        initialize: function (options) {
            _.extend(this, options);

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

            this.bindEvents();

           

            return this;
        },

        acceptBtn_click: function (e) {
            try {
                this.model.set({
                    errorMsg: '',
                    processing: true,
                });

                var that = this,
                    attrs = this.model.toJSON();


                this.rollset.remove(
                    function (model, id) {
                        try {
                            that.finish({ result: 'SUCCESS', });

                            that.hide();
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    function (model, errorMsg) {
                        try {
                            that.model.set({
                                errorMsg: app.translate([that.parent, app], errorMsg),
                                processing: false,
                            });
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    }
                );
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
    });

    Screen.Models.ElectrodeChangeModal = Backbone.Epoxy.Model.extend({
        defaults: {
            //heatName: null,
            processId: null,
            electrodeChangeId: null,
            phaseCode: null,
            equipmentCode$: null,
            newElectrodeChangeReasonId: null,
            newElectrodeSupplierId: null,

            heatName: null,
            heats: [],
            electrodeChangeReasons: [],
            suppliers: [],
            

            currentElectrodeHeatsCount: null,
            currentElectrodeSupplier: null,
            currentElectrodeWeight: null,

            newElectrodeComments: null,
            newElectrodeSize: null,
            newElectrodeSupplier: null,
            //newElectrodeWeight: null,
            

            processing: false,
        },
        computeds: {
            areaCode: {
                deps: ['equipmentCode$'],
                get: function (value) {
                    if (value == "EAF-1" || value == "EAF-2") {
                        return "EAF";
                    } 
                    //else if (value == 'LF-1' || value == 'LF-2') {
                    //    return 'LF';
                    //}
                }
            },
            equipmentCode: {
                deps: ['equipmentCode$'],
                get: function (value) {
                    if (value == "EAF-1" /*|| value == 'LF-1'*/) {
                        return "1";
                    } else if (value == 'EAF-2' /*|| value == 'LF-2'*/) {
                        return "2";
                    }
                }
            },

          
        //    startDate: {
        //        deps: ['start'],
        //        get: function (value) {
        //            return (value) ? new moment(value, 'YYYY-MM-DD HH:mm:ss.SSS').format('YYYY-MM-DD') : value;
        //        },
        //        set: function (value) {
        //            var dateObj = new moment(value, app.translate(app, 'MM/DD/YYYY'));

        //            if (dateObj.isValid()) {
        //                var time = this.get('startTime');

        //                return {
        //                    start: dateObj.format('YYYY-MM-DD')
        //                    + ' ' + ((time) ? time : '00:00:00'),
        //                };
        //            }

        //            return { start: null, };
        //        },
        //    },
        //    startTime: {
        //        deps: ['start'],
        //        get: function (value) {
        //            return (value) ? new moment(value, 'YYYY-MM-DD HH:mm:ss.SSS').format('HH:mm:ss') : value;
        //        },
        //        set: function (value) {
        //            if (('' + value).indexOf(':') != -1) {
        //                if (value) {
        //                    var date = this.get('startDate');

        //                    return {
        //                        start: ((date) ? date : new moment().format('YYYY-MM-DD'))
        //                        + ' ' + value,
        //                    };
        //                }

        //                return { start: null, };
        //            }
        //        },
        //    },
        },
        fetchHeats: function (params) {
            var that = this;

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetHeatsofAllAreas',
                null,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

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

                                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: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
    });

    Screen.Views.ElectrodeChangeModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' electrode-change-modal',

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

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

            this.bindEvents();

            this.model.fetchHeats();

            return this;
        },
        save: function () {
            try
            {
                var that = this,
                    attrs = this.model.toJSON({ computed: true});

                this.model.set('processing', true);

       
                var qp = new QueryParameters();
                //qp.Add('id', 'VARCHAR', attrs.electrodeChangeId);
                qp.Add('comments', 'VARCHAR', attrs.newElectrodeComments); 
                qp.Add('electrodeChangeReasonId', 'VARCHAR', (attrs.newElectrodeChangeReasonId != 0) ? attrs.newElectrodeChangeReasonId : null );
                qp.Add('size', 'VARCHAR', attrs.newElectrodeSize);
                qp.Add('supplier', 'VARCHAR', attrs.newElectrodeSupplierId);
                qp.Add('heatName', 'VARCHAR', attrs.heatName);
                qp.Add('areaCode', 'VARCHAR', attrs.areaCode);
                qp.Add('equipmentCode', 'VARCHAR', attrs.equipmentCode);
                qp.Add('phaseCode', 'VARCHAR', attrs.phaseCode);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.ELT.ChangeElectrodeManual',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && !resp.Message) {
                                    that.finish({ result: 'SUCCESS' });
                                    that.hide();
                                }
                                else {
                                    var msg = (resp.Message) ? resp.Message : 'SERVER_RESPONSE_NOT_VALID';

                                    console.error(new Error(msg).stack);
                                    app.views.topMessages.showMessage(app.translate([that, app], msg), { stay: 10000, });
                                }
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                        onError: function (msg) {
                            try {
                                console.error(new Error(msg).stack);

                                //Override msg variable to display a human message.
                                msg = 'SERVER_RESPONSE_NOT_VALID';

                                app.views.topMessages.showMessage(app.translate([that, app], msg), { stay: 10000, });
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                            finally {
                                that.model.set('processing', false);
                            }
                        },
                        Async: true,
                        Secured: true,
                    },
                    app.ConnectionStrings.app
                );
            }
            catch (error) {
                this.model.set('processing', false);

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


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

