//SCREEN-BOILERPLATE
//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
  // Application variable, always include it to have access to app methods.
  'app',

  //templates-loader: this loads templates async.
  'js/templates-loader',
  'backgrid',
  'moment',
  'modules/navigation-buttons/navigation-buttons',
  'backgrid/moment-cell',
  'js/autocomplete/backbone.autocomplete'

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

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

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

            //URL parameters
            tankCode: 1,
            heatName: '-',
            treatmentNumber: '-',

            hasData_process: false,
            isLoading_process: false,
            hasData_probes: false,
            isLoading_probes: false,

            
            hasData_alloysDetails: false,
            isLoading_alloysDetails: false,


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

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


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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.VTD.GetProcessCatalogs',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                that.set('heatNames', _.map(resp.Table, function (obj) {
                                    return {
                                        name: obj.Name,
                                        treatment: obj.Treatment,
                                        processId: obj.ProcessId,
                                        heatId: obj.HeatId,
                                        VTDTankCode: obj.VTDTankCode,
                                    };
                                }));

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

                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(new Error(resp.Message).stack);
                                else
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: async,
                },
                app.ConnectionStrings.app
            );

            return this;
        },

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

            qp.Add('@processId', 'INT', params.processId);
            qp.Add('@direction', 'BIT', params.direction);
            qp.Add('@VTDTankCode', 'INT', params.tankCode );
            qp.Add('@timeZoneCode', 'CHAR(10)', app.models.user.get('timezoneCode'));


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

                            if (resp && resp.Table) {
                                if (resp.Table)  that.process.setDataModel(resp.Table);
                                if (resp.Table1) that.probesColl.setDataColl(resp.Table1);
                                if (resp.Table2) that.trigger('fetch-nav-buttons', resp.Table2);
                                if (resp.Table4 && resp.Table3) that.alloysDetailsColl.setDataColl(resp.Table4, resp.Table3);
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                        hasData_probes: false,
                                        isLoading_probes: false,
                                        hasData_alloysDetails: false,
                                        isLoading_alloysDetails: false,
                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                        hasData_probes: false,
                                        isLoading_probes: false,
                                        hasData_alloysDetails: false,
                                        isLoading_alloysDetails: false,
                                    });
                                }

                            }


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

            return this;

        },
    });

    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.refreshbtn
            return 'vtd-heat-report';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'vtd-heat-report',
        id: 'vtd-heat-report',
        title: 'VTD Heat Report',
        isCacheable: false,
        events: function () {
            return {
                'click .anchor-link-eaf': this.anchorLinkEAF_click,
                'click .anchor-link-lmf': this.anchorLinkLMF_click,
                'click #refreshBtn': this.refreshBtn_click,
                'click #backNavBtn': this.backNavBtn_click,
                'click #forwardNavBtn': this.forwardNavBtn_click,
                'keyup #search': this.keyPressEventHandler,
                'click #printBtn': this.printBtn_click,
            };
        },
        bindings: 'data-bind',
        subviews: null,
        viewParams: null,

        process: null,
        alloysTableView: null,

        autoCompleteCollection: null,
        autocompleteView : null,

        vtdChart: null,
        vtdChartPrint: null,

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

            var that = this;
            this.model = new Screen.Models.Main();
            this.autoCompleteCollection = new Screen.Collections.HeatNames();

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

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


            this.bindEvents();

        },
        bindEvents: function () {
            this.listenTo(this.model.process, 'fetch', this.process_fetched);
            this.listenTo(this.model.probesColl, 'fetch', this.probesColl_fetched);
            this.listenTo(this.model, 'fetch-nav-buttons', this.fetchnavbuttons);
            this.listenTo(this.model, 'change:heatName', this.updateHeatNameInURL);
            this.listenTo(this.model, 'change:heatNames', this.updateAutocomplete);
            this.listenTo(this.model, 'change:processId', this.processIdChanged);
            this.listenTo(this.model.alloysDetailsColl, 'fetch', this.alloysDetailsColl_fetched);


        },
        printBtn_click: function () {
            window.print();
            return false;
        },
        render: function (container, urlParams) {
            var that = this;
            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;

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

            var customPath = '/app/custom-screens/' + this.template + '/';

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

                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            that.options.i18n[that.template] = i18nJED;
                            that.$el.html(tmp());

                            
                            that.alloysTableView = Screen.Views.AlloysTable.extend({
                                template: Handlebars.compile(that.$el.find('#alloysTableViewTemplate').html()),
                            });

                            var probesColumns = [
                                {
                                    name: 'datetime',
                                    label: app.translate(that, 'item_datetime_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'temperature',
                                    label: app.translate(that, 'item_temperature_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'oxygen',
                                    label: app.translate(that, 'item_oxygen_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'hydrogen',
                                    label: app.translate(that, 'item_hydrogen_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell twenty-percent',
                                    }),
                                    editable: false,
                                },

                            ];

                            var probesGrid = new Backgrid.Grid({
                                className: 'grid-styles table',
                                collection: that.model.probesColl,
                                columns: probesColumns,
                            });

                            container.append(probesGrid.render().el);
                            that.$el.find('.probes-items-grid-container').append(probesGrid.render().el);


                            that.applyBindings();


                            that.vtdChart = new IndustrialChart(
                                that.$el.find('#vtdChartContainer')[0],
                                {
                                    View: {
                                        Title: app.translate([that, app], 'process_chart_title'),
                                        Header: false,
                                        DisplayScales: {
                                            value: false,
                                        },
                                        Resize: false,
                                        Configuration: {
                                            CursorValue: true,
                                        },
                                    },
                                    DatabaseParameters: {
                                        ConnectionStringName: app.ConnectionStrings.app,
                                        Procedure: app.DatabaseNames.MES + '.VTD.GetProcessChartData',
                                        Secured: true,
                                    },
                                }
                            );


                            that.vtdChartPrint = new IndustrialChart(
                                that.$el.find('#vtdChartContainerPrint')[0],
                                {
                                    View: {
                                        Title: app.translate([that, app], 'process_chart_title'),
                                        Header: false,
                                        DisplayScales: {
                                            value: false,
                                        },
                                        Resize: false,
                                        Configuration: {
                                            CursorValue: true,
                                        },
                                    },
                                    DatabaseParameters: {
                                        ConnectionStringName: app.ConnectionStrings.app,
                                        Procedure: app.DatabaseNames.MES + '.VTD.GetProcessChartData',
                                        Secured: true,
                                    },
                                }
                            );

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

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


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

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




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

        refresh: function () {
            var currentAutcompleteText = this.autocompleteView.getClickedValue();
            if (currentAutcompleteText && this.model.get('direction') == null) {
                if (currentAutcompleteText) this.setProcessId(currentAutcompleteText);
                this.model.set({
                    heatName: currentAutcompleteText,
                })
            }


            var params = this.model.toJSON();

            this.vtdChart.Clear();
            this.vtdChartPrint.Clear();

            this.model.set({
                isLoading_process: true,
                hasData_process: false,
                isLoading_probes: true,
                hasData_probes: false,
                
                isLoading_alloysDetails: true,
                hasData_alloysDetails: false,
                //isLoading_heatings: true,
                //hasData_heatings: false,
                //isLoading_alloysDetails: true,
                //hasData_alloysDetails: false,
            });


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


            this.fetchLFTrendingChart({
                processId: params.processId ? params.processId : null,
            });


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

        },
              alloysDetailsColl_fetched: function () {
            try {
                var that = this;
                if (that.model.alloysDetailsColl.length > 0)
                    this.spanAlloysTableRows();

                setTimeout(
                    function () {
                        that.model.set({
                            hasData_alloysDetails: (that.model.alloysDetailsColl.length > 0),
                            isLoading_alloysDetails: false,
                        });

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

        alloysNotBelongToProcess: function () {
            var that = this;
            var aTags = document.getElementsByClassName("spanrow1");
            var bachStart = null;
            var processEnd = new moment(that.model.process.get('endProcessLimit'), 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
            for (var i = 0; i < aTags.length; i++) {
                bachStart = new moment(aTags[i].textContent, 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
                found = aTags[i];
                if (moment(bachStart).isAfter(processEnd, 'second')) {
                    $(found).addClass('highlightRed');
                } else {
                    $(found).removeClass('highlightRed');
                }
            }
        },

        spanAlloysTableRows: function () {
            var that = this,
                coll = that.model.alloysDetailsColl.toJSON(),
                count = 1,
                prev = null,
                curr = null;


            var element = {},
                cart = [],
                rowDelete = null,
                firstrowSpan = null;


            var classes = [
                'spanrow1',
                'spanrow2',
                'spanrow3',
                'spanrow4',
            ]
            

            _.each(coll, function (obj, i) {
                element = {};
                curr = obj.additionBatchId;

                if (curr != prev) {
                    if (count > 1) {
                        element.additionBatchId = prev;
                        element.rowSpan = count;
                        element.startPos = i - count;
                        cart.push(element);
                    };
                    count = 1;
                } else {
                    count += 1;
                    repeatedAdditionBatchId = curr;
                }

                prev = curr;
                if (coll.length - 1 == i) {

                    if (count > 1) {
                        element.additionBatchId = prev;
                        element.rowSpan = count;
                        element.startPos = i + 1 - count;
                        cart.push(element);
                    }
                }
            });

            _.each(cart, function (obj) {
                _.each(classes, function (obj2) {
                    firstrowSpan = document.getElementsByClassName(obj2)[obj.startPos];
                    firstrowSpan.rowSpan = obj.rowSpan;

                })
            });


            _.each(cart, function (obj) {
                _.each(classes, function (obj2) {
                    for (var i = obj.startPos + 1; i < obj.startPos + obj.rowSpan; i++) {
                        rowDelete = document.getElementsByClassName(obj2)[i];
                        rowDelete.style.display = 'none';
                    }
                    //rowDelete = document.getElementsByClassName(obj2)[obj.startPos + 1];
                    //rowDelete.style.display = 'none';

                })
            });

        },
        processIdChanged: function () {
            var params = this.model.toJSON(),
                qp = new QueryParameters();

            qp.Add('id', 'INT', params.processId);
            if (this.vtdChart) {
                this.vtdChart.Clear();
                this.vtdChart.RefreshData(qp);
            }
            if (this.vtdChartPrint) {
                this.vtdChartPrint.Clear();
                this.vtdChartPrint.RefreshData(qp);
            }
        },

        fetchLFTrendingChart: function (params) {
            var qp = new QueryParameters();

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

            this.vtdChart.RefreshData(qp);
            this.vtdChartPrint.RefreshData(qp);
        },

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

        },

        setProcessId: function (keyword) {
            var that = this,
                res = null,
                obj = null,
                obj2 = null,
                processId = null;

            res = keyword.split("-");
            obj = _.where(that.model.get('heatNames'), { name: res[0] });
            if (obj)
                obj2 = _.where(obj, { treatment: parseInt(res[1]) });
            if (obj && obj2 && obj2[0] && obj2[0].processId) {
                processId = obj2[0].processId;
                if (processId) {
                    that.model.set('processId', processId);
                }
            } else {
                var value = $('#search').val().split('-');
                if (value && value[0] && value[1]) {
                    that.model.fetchPickers({
                        heatName: value[0],
                        treatment: value[1],
                        firstRefresh: true,
                        async: false,
                    })
                }
            }

        },

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

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

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

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

        },


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

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

        },
        fetchnavbuttons: function (resp) {
            this.NavigationButtonView.setDataColl(resp);
        },
        probesColl_fetched: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_probes: (that.model.probesColl.length > 0),
                            isLoading_probes: false,
                        });

                    },
                    100
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        process_fetched: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_process: that.model.process.get('id') ? true : false,
                            isLoading_process: false,
                            processId: that.model.process.get('id'),
                            //tankCode: that.model.process.get('tankCode'),
                            heatName: that.model.process.get('heatName') + '-' + that.model.process.get('treatment'),
                            treatmentNumber: that.model.process.get('treatment'),
                        });

                    },
                    100
                );
                if (this.model.get('changeVTD'))
                    this.model.set({ tankCode: that.model.process.get('tankCode'), });

                this.model.set({ changeVTD: false });

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

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

                var heatNameStr = params.heatName;
                var res = heatNameStr.split("-");
                var heat = res[0],
                    treat = res[1];
                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                heatName: heat,
                                treatmentNumber: treat,
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

        refreshBtn_click: function (e) {
            this.model.set({ changeVTD: true });
            this.refresh();
            this.UpdateURL();
        },

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

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

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

                this.options.onappend(this);
            }

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

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        bindViewScopedEvents: function () {
            var that = this;
        },
        unbindViewScopedEvents: function () {

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

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

            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.set("subnavbar", false);
        },
        reRender: function (urlParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },

    });

    Screen.Views.AlloysTable = Backbone.Epoxy.View.extend({
        tagName: 'tr',
        template: null,
        initialize: function () {
            this.render();
        },
        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },
    });

    Screen.Models.Process = Backbone.Epoxy.Model.extend({
        defaults: {
            argonLanceUsed: null,
            argonLanceVolume: null,
            argonVolume1: null,
            argonVolume2: null,
            arriveDatetime: null,
            comments: null,
            crewId: null,
            end: null,
            energy: null,
            heatId: null,
            id: null,
            operatorId: null,
            powerOn: null,
            productionDate: null,
            shiftId: null,
            shipDatetime: null,
            start: null,
            treatment: null,
            meltOrder: null,

            heatName: null,
            gradeName: null,
            initGradeName: null,
            ladleFurnaceName: null,
            ladleName: null,
            operatorName: null,

            preparationTime: null,
            heatingTime: null,
            lastStage: null,
            totalTreatmentTime: null,
            steelWeight: null,
            powerOff: null,

            totalSequenceTime: null,
            vacuumTime: null,
            argonTime1: null,
            argonTime2: null,
            argonBypassTime1: null,
            argonBypassTime2: null,
            minimumTorr: null,
            tankCode: null,
        },
        computeds: {
            tankLabel: {
                deps: ['tankCode'],
                get: function (code) {
                    if (code == 1) return '1'
                    else if (code == 2) return '2'
                },
            },
            shiftName: {
                deps: ['shiftId'],
                get: function (shift) {
                    if (shift == 1) return 'Day'
                    else if (shift == 2) return 'Night'
                },
            },
            productionDateAndShift: {
                deps: ['shiftId', 'productionDate'],
                get: function (shift, date) {
                    if (shift == 1) return date + ' - ' + 'Day'
                    else if (shift == 2) return date + ' - ' + 'Night'
                },
            },
        },
        setDataModel: function (model) {
            if (model && model[0]) {
                var obj = model[0];
                this.set({
                    id: obj.Id ? obj.Id : null,

                    heatId: obj.HeatId ? obj.HeatId : null,
                    heatName: obj.HeatName ? obj.HeatName : null,


                    treatment: obj.Treatment ? obj.Treatment : null,
                    meltOrder: obj.MeltOrder ? obj.MeltOrder : null,

                    productionDate: obj.ProductionDate ? new moment(obj.ProductionDate).format('MM/DD/YYYY') : null,
                    shiftId: obj.ShiftId ? obj.ShiftId : null,
                    crewId: obj.CrewId ? obj.CrewId : null,


                    start: obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : null,
                    end: obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : null,

                    shipDatetime: obj.ShipTimestamp ? new moment(obj.ShipTimestamp).format('HH:mm') : null,
                    arriveDatetime: obj.ArriveTimestamp ? new moment(obj.ArriveTimestamp).format('HH:mm') : null,

                    operatorId: obj.OperatorId ? obj.OperatorId : null,
                    operatorName: obj.OperatorName ? obj.OperatorName : null,

                    ladleFurnaceName: obj.ladleFurnaceName ? obj.LadleFurnaceName : null,
                    ladleName: obj.LadleName ? obj.LadleName : null,
                    gradeName: obj.GradeName ? obj.GradeName : null,
                    initGradeName: obj.InitGradeName ? obj.InitGradeName : null,

                    totalTreatmentTime: obj.TotalTreatmentTime ? obj.TotalTreatmentTime : null,
                    totalSequenceTime: obj.TotalSequenceTime ? obj.TotalSequenceTime : null,
                    vacuumTime: obj.VacuumTime ? obj.VacuumTime : null,

                    argonTime1: obj.ArgonTime1 ? obj.ArgonTime1 : null,
                    argonTime2: obj.ArgonTime2 ? obj.ArgonTime2 : null,
                    argonBypassTime1: obj.ArgonBypassTime1 ? obj.ArgonBypassTime1 : null,
                    argonBypassTime2: obj.ArgonBypassTime2 ? obj.ArgonBypassTime2 : null,

                    argonVolume1: obj.ArgonVolume1 ? obj.ArgonVolume1.toFixed(1) : null,
                    argonVolume2: obj.ArgonVolume2 ? obj.ArgonVolume2.toFixed(1) : null,

                    minimumTorr: obj.MinimumTorr ? obj.MinimumTorr.toFixed(1) : null,
                    tankCode: obj.VTDTankCode ? obj.VTDTankCode : null,
                    comments: obj.Comments ? obj.Comments : null,

                }).trigger('fetch', this, obj);

            }
            else this.trigger('fetch', this, model);
        },
    });



    Screen.Models.ProbesColl = Backbone.Epoxy.Model.extend({
        defaults: {
            datetime: null,
            oxygen: null,
            temperature: null,
            hydrogen: null,
        },

        parse: function (obj) {
            var result = {
                datetime: obj.Datetime ? new moment(obj.Datetime).format('DD/MM HH:mm') : null,
                oxygen: obj.O,
                temperature: obj.T,
                hydrogen: obj.H,
            };
            return result;
        }

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

    Screen.Models.HeatName = Backbone.Model.extend({
        label: function () {
            return this.get("name") + '-' + this.get("treatment");
        }
    });

    Screen.Collections.HeatNames = Backbone.Collection.extend({
        model: Screen.Models.HeatName,

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

    Screen.Models.AlloysDetailsColl = Backbone.Epoxy.Model.extend({
        defaults: {
            id: null,
            additionBatchId: null,
            weightSP: null,
            weightPV: null,
            materialName: null,
            sourceCode: null,
            batchStart: null,
            batchEnd: null,
            dumpStart: null,
            dumpEnd: null,
            parameter1: null,
        },

        parse: function (det, all) {
            var result = {
                id: det.ID ? det.ID : null,
                additionBatchId: det.AdditionBatchID ? det.AdditionBatchID : null,
                weightSP: det.WeightSP ? det.WeightSP : '',
                weightPV: det.WeightPV ? det.WeightPV : '',
                materialName: det.MaterialName ? det.MaterialName : null,                
                parameter1: det.Parameter1 ? det.Parameter1 : '',  
                sourceCode: _.where(all, { ID: det.AdditionBatchID })[0].SourceCode,
                start: new moment(_.where(all, { ID: det.AdditionBatchID })[0].BatchStart).format('YYYY-MM-DD HH:mm:ss'),
                batchStart: new moment(_.where(all, { ID: det.AdditionBatchID })[0].BatchStart).format('DD/MM/YYYY HH:mm:ss'),
                batchEnd: new moment(_.where(all, { ID: det.AdditionBatchID })[0].BatchEnd).format('DD/MM HH:mm'),  
                dumpStart: new moment(_.where(all, { ID: det.AdditionBatchID })[0].DumpStart).format('DD/MM HH:mm'),
                dumpEnd: new moment(_.where(all, { ID: det.AdditionBatchID })[0].DumpEnd).format('DD/MM HH:mm'),   
            };
            return result;
        }

    });
    Screen.Collections.AlloysDetailsColl = Backbone.Collection.extend({
        model: Screen.Models.AlloysDetailsColl,
        comparator: 'start',
        setDataColl: function (data,all) {
            var newColl,
                that = this;
            newColl = _.map(data, function (obj) { return that.model.prototype.parse(obj, all); });
            that.set(newColl).trigger('fetch', that, data);
        },
    });
    // Required, return the module for AMD compliance.
    return Screen;
});