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

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

    //templates-loader: this loads templates async.
    'js/templates-loader',
    'backgrid',
    'moment',

    'modules/modal2',
    'modules/modal-sulpher-print/modal-sulpher-print',
    'backgrid/infinator',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',

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

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

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

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

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

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


                strandId: null,
                //strands: [{ label: '1', value: 1 }, { label: '2', value: 2 }, { label: '3', value: 3 }, { label: '4', value: 4 }],

                hasData: false,
                isLoading: false,
                grid: [],
                searchText: '',
            },
            computeds: {
                strands: {
                    deps: ['casterCode'],
                    get: function (casterCode) {
                        const value = parseInt(casterCode);
                        if (value === 1) return [{ label: '1', value: 1 }, { label: '2', value: 2 }, { label: '3', value: 3 }, { label: '4', value: 4 }];
                        else if (value === 2) return [{ label: '5', value: 5 }, { label: '6', value: 6 }, { label: '8', value: 8 }, { label: '9', value: 9 }];
                        else return [{ label: '1', value: 1 }, { label: '2', value: 2 }, { label: '3', value: 3 }, { label: '4', value: 4 }, { label: '5', value: 5 }, { label: '6', value: 6 }, { label: '8', value: 8 }, { label: '9', value: 9 }];
                    },
                },
                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, };
                    },
                },
            },
            printTag: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                    { Name: '@Printer', Type: 'INT', Value: params.printer, },
                    { Name: '@ReasonPhraseId', Type: 'INT', Value: params.reasonPhraseId, },
                    { Name: '@Comments', Type: 'VARCHAR', Value: params.comments, },
                    { Name: '@Employee', Type: 'VARCHAR', Value: params.employee, },
                    { Name: '@IsColdLength',     Type: 'INT',     Value: (params.isColdLength === 1 ? 1 : 0) }

                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.UpsertTaggingCommand',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('Tagging in process...', { stay: 5000, });
                                    that.trigger('triggerFetch');
                                    //app.views.topMessages.showMessage(resp.Table[0].ProductMsg, { stay: 5000, });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            resendToL3: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });

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

                                if ((resp) && !(resp.Message)) {
                                    app.views.topMessages.showMessage('Resend Product to L3 in process...', { stay: 5000, });
                                    that.trigger('triggerFetch');
                                    //app.views.topMessages.showMessage(resp.Table[0].ProductMsg, { stay: 5000, });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
        });


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

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

                var that = this;

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

                this.grids = {};

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

                this.bindingSources = {};

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


                this.bindEvents();
                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);
            },
            onModalAcceptBtn: function () {
                this.refreshBtn_click();
            },
            bindEvents: function () {
                this.listenTo(this.itemsColl, 'backgrid:rowclick', this.processes_backgrid_rowclick)
                    .listenTo(this.itemsColl, 'fetch', this.processes_ready)
                    .listenTo(this.model, 'triggerFetch', this.refreshBtn_click);


            },
            getPermissions: function () {
                var write = $.inArray('casps_w', app.models.user.get('roles'));
                var ctx = {
                    write: write != -1 ? true : false,
                };
                return ctx.write;
            },
            removeHighlightRow: function () {
                var previousIndex = this.model.get('index');
                var rowsView = this.model.get('grid').body.rows;


                if (rowsView && rowsView[previousIndex] && rowsView[previousIndex].$el)
                    rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");


            },
            _refresh: function (opt) {
                this.itemsColl.reset();

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

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

                this.refreshProcesses(opt);

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

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

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

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

                this.model.set(fixedParams);

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

                this.viewParams = viewParams;

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

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

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

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

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

                                that.applyBindings();

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

                                that.$el.find('.input-date').datepicker();
                                var grid = that.grids.production = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    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); }
                                        }
                                    }),
                                    columns: [
                                        {
                                            name: 'ProductNumber',
                                            label: app.translate([that, app], 'Product Number'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'hasSulfur',
                                            label: app.translate([that, app], 'Sulfur Assigned'),
                                            cell: Backgrid.StringCell.extend({
                                                className: function () {
                                                    var hasSulfur = this.model.get('hasSulfur');
                                                    if (hasSulfur == 'Yes') {
                                                        return 'string-cell align-center-cell heat-row hasSulfurBG';
                                                    }
                                                    else {
                                                        return 'string-cell align-center-cell heat-row nonHasSulfurBG';
                                                    }

                                                    return 'string-cell align-center-cell heat-row';
                                                }

                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'CutStart',
                                            label: app.translate([that, app], 'Cut Time'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        //{
                                        //    name: 'HeatName',
                                        //    label: app.translate([that, app], 'Heat'),
                                        //    cell: Backgrid.StringCell.extend({
                                        //        className: 'string-cell align-center-cell heat-row',
                                        //    }),
                                        //    editable: false,
                                        //},
                                        {
                                            name: 'CasterCode',
                                            label: app.translate([that, app], 'Caster'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'StrandId',
                                            label: app.translate([that, app], 'Strand'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Sequence',
                                            label: app.translate([that, app], 'Sequence'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        //{
                                        //    name: 'ProductionDate',
                                        //    label: app.translate([that, app], 'Production Date'),
                                        //    cell: Backgrid.StringCell.extend({
                                        //        className: 'string-cell align-center-cell production-date-row',
                                        //    }),
                                        //    editable: false,
                                        //},
                                        {
                                            name: 'CrewId',
                                            label: app.translate([that, app], 'Crew'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Shift',
                                            label: app.translate([that, app], 'Shift'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        ////{
                                        ////    name: 'Destination',
                                        ////    label: app.translate([that, app], 'Destination'),
                                        ////    cell: Backgrid.StringCell.extend({
                                        ////        className: 'string-cell align-center-cell',
                                        ////    }),
                                        ////    editable: false,
                                        ////},
                                        {
                                            name: 'Weight',
                                            label: app.translate([that, app], 'Weight'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Length',
                                            label: app.translate([that, app], 'Length'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'MetLengthStart',
                                            label: app.translate([that, app], 'Met Length Start'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'MetLengthEnd',
                                            label: app.translate([that, app], 'Met Length End'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'SentToL3',
                                            label: app.translate([that, app], 'Sent To L3'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        //{
                                        //    name: 'CutEnd',
                                        //    label: app.translate([that, app], 'Cut End'),
                                        //    cell: Backgrid.StringCell.extend({
                                        //        className: 'string-cell align-center-cell datetime-row',
                                        //    }),
                                        //    editable: false,
                                        //},
                                        //{
                                        //    name: 'ShipTime',
                                        //    label: app.translate([that, app], 'Ship Time'),
                                        //    cell: Backgrid.StringCell.extend({
                                        //        className: 'string-cell align-center-cell datetime-row',
                                        //    }),
                                        //    editable: false,
                                        //},

                                    ],
                                    collection: that.itemsColl,
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        },
                                        events: {
                                            contextmenu: 'onRightClick',
                                        },
                                        onRightClick: function (e) {
                                            e.preventDefault();
                                            var model = this.model.toJSON();
                                            var write = that.getPermissions();
                                            if (write) {
                                                var rowsView = that.model.get('grid').body.rows;
                                                var newIndex = _.indexOf(rowsView, this);
                                                this.$el.addClass("onRightClickSelectedRow");

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

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

                                });


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



                                //
                                $.contextMenu('destroy');

                                const write = true;
                                if (write) {
                                    $(function (obj) {
                                        $.contextMenu({
                                            selector: '.production-table',
                                            callback: function (key, options) {
                                                that.model.set({ contextMenuOption: key });
                                                that.contextMenuOptionPressed();
                                            },
                                            items: {
                                                "opt-send-to-l3": {
                                                    name: "Send To L3",
                                                    icon: "fa-share-square",
                                                },
                                                separator1: {
                                                    "type": "cm_separator",
                                                },
                                                "opt-print-tag": {
                                                    name: "Print Tag",
                                                    icon: "fa-tag",
                                                },
                                                separator2: {
                                                    "type": "cm_separator",
                                                },
                                                "sulfur-print-rating": {
                                                    name: "Edit Sulfur Rating",
                                                    icon: "fa-pencil",
                                                },
                                                separator3: {
                                                    "type": "cm_separator",
                                                },
                                                "opt-edit-length": {
                                                    name: "Edit Length",
                                                    icon: "fa-pencil",
                                                },


                                            },
                                            events: {
                                                hide: function (options) {
                                                    that.pauseRealTime = false;
                                                    that.removeHighlightRow();
                                                },
                                                show: function () {
                                                    that.pauseRealTime = true;
                                                }
                                            }
                                        });
                                    });

                                }











                                //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');
                                if (viewParams.casterCode)
                                    fixedParams.casterCode = (viewParams.casterCode != '-' && viewParams.casterCode != null) ? parseInt(viewParams.casterCode, 10) : null;
                                if (viewParams.crewId)
                                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : null;
                                if (viewParams.shiftId)
                                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId, 10) : null;
                                if (viewParams.strandId)
                                    fixedParams.strandId = (viewParams.strandId != '-' && viewParams.strandId != null) ? parseInt(viewParams.strandId, 10) : null;

                                that.model.set(fixedParams);

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

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


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

                switch (contextMenuOption) {
                    case "opt-send-to-l3":
                        message = 'The product ' + rowModel.ProductNumber + ' will be sent to L3. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([this, app], "resend_item_modal_confirm_title"),
                            message: message,
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {

                                that.model.resendToL3({
                                    productId: rowModel.Id
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        break;
                    case "opt-print-tag":
                        var modal = new Screen.Views.PrintTagConfirmationModal({
                            data: rowModel,
                            bus: this.bus
                        });
                        modal.show();
                        break;
                    case "opt-print-tag-cas2":
                        message = 'The tag ' + rowModel.ProductNumber + ' will be printed with CAS 2 printer. Do you want to continue?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: 'Print Tag Confirmation',
                            message: message,
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.model.printTag({
                                    productId: rowModel.Id,
                                    printer: 2,
                                })
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        break;
                    //case "opt-reprint-tag":
                    //    message = 'The tag ' + rowModel.ProductNumber + ' will be printed. Do you want to continue?'
                    //    modal = new Modal.Views.Main({
                    //        focusOk: false,
                    //        focusSelector: '#btn-cancel',
                    //        title: 'Reprint Tag CAS 2 Confirmation',
                    //        message: message,
                    //        buttons_type: "CONTINUE-CANCEL",
                    //    });
                    //    this.listenToOnce(modal, "continue", function (modal) {
                    //        try {
                    //            that.model.printTag({
                    //                productId: rowModel.Id,
                    //                printer: rowModel.CasterCode,
                    //            })
                    //        }
                    //        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    //    });
                    //    modal.show();
                    //    break;
                    case "sulfur-print-rating":
                        var data = [];
                        data = {
                            ProductNumber: that.model.get('rowModel').ProductNumber,
                            HeatNumber: that.model.get('rowModel').HeatName,
                            Strand: that.model.get('rowModel').StrandId,
                            Cut: that.model.get('rowModel').Sequence,
                            Date: that.model.get('rowModel').CutStart,
                            Grade: that.model.get('rowModel').GradeName,
                            ProductId: that.model.get('rowModel').Id
                        };
                        modal = new SulpherPrintModal.Views.SulfurPrintRatings({
                            parent: this,
                            data: data,
                            rowModel: that.model.get('rowModel'),
                            bus: that.bus,
                        });
                        modal.show();
                        break;
                    
                    case "opt-edit-length":
                         var modal = new Screen.Views.EditLengthModal({
                            data: rowModel,   
                            bus: this.bus
                        });
                        modal.show();
                        break;
                }
            },
            processes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            if (that.itemsColl.length > 0) that.show_backgrid();
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            show_backgrid: function () {
                var container = this.$el.find(".processes-grid-container");
                container.empty();

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

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

            },
            search_keypress: function (e) {
                if (e.keyCode === 13) {
                    $('#search').blur();
                    this.refreshBtn_click();
                }
            },
            refreshProcesses: function (options) {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {}, });

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

                this.itemsColl.fetch({
                    start: attrs.start,
                    end: attrs.end,
                    crewId: (attrs.crewId == "") ? null : attrs.crewId,
                    shiftId: (attrs.shiftId == "") ? null : attrs.shiftId,
                    strandId: (attrs.strandId == "") ? null : attrs.strandId,
                    casterCode: attrs.casterCode === "1" || attrs.casterCode === "2" ? attrs.casterCode : null,
                    searchText: attrs.searchText,
                    refresh: true,
                });





            },

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

                var params = [
                    { Name: '@start', Type: 'DATETIME', Value: params.start, },
                    { Name: '@end', Type: 'DATETIME', Value: params.end, },
                    { Name: '@crewId', Type: 'CHAR', Value: (params.crewId != '' && params.crewId != '-') ? params.crewId : null, },
                    { Name: '@shiftId', Type: 'INT', Value: (params.shiftId != '' && params.shiftId != '-') ? params.shiftId : null, },
                    { Name: '@strandId', Type: 'INT', Value: (params.strandId != '' && params.strandId != '-') ? params.strandId : null, },
                    { Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
                ];
                var QP = new QueryParameters();

                _.each(params, function (qpParams) {
                    QP.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });


                var data = {
                    Data: [],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'CAS-Products',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.CAS.GetProducts',
                                QueryParameters: QP,
                            },
                        },
                    ]
                };

                /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'Datetime' },
                                { Column: 'B', Value: 'Strand' },
                                { Column: 'C', Value: 'Crew' },
                                { Column: 'D', Value: 'Shift' },
                                { Column: 'E', Value: 'Destination' },
                                { Column: 'F', Value: 'Weight' },
                                { Column: 'G', Value: 'Length' },
                                { Column: 'H', Value: 'Met Length Start' },
                                { Column: 'I', Value: 'Met Length End' },
                                { Column: 'J', Value: 'Cut Start' },
                                { Column: 'K', Value: 'Cut End' },
                                { Column: 'J', Value: 'Ship Time' },

                            ],
                    }],
                    StartRowIndex: 1,
                });

                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'Datetime', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'Strand', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'CrewId', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'Shift', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'Destination', DataType: 'String' },
                            { ExcelColumnName: 'F', SQLDataColumnName: 'Weight', DataType: 'String' },
                            { ExcelColumnName: 'G', SQLDataColumnName: 'Length', DataType: 'String' },
                            { ExcelColumnName: 'H', SQLDataColumnName: 'MetLengthStart', DataType: 'String' },
                            { ExcelColumnName: 'I', SQLDataColumnName: 'MetLengthEnd', DataType: 'String' },
                            { ExcelColumnName: 'J', SQLDataColumnName: 'CutStart', DataType: 'String' },
                            { ExcelColumnName: 'K', SQLDataColumnName: 'CutEnd', DataType: 'String' },
                            { ExcelColumnName: 'J', SQLDataColumnName: 'ShipTime', DataType: 'String' },
                        ],
                });

                Core.Export.Excel(
                    data,
                    function (resp) {
                        try {
                            if ((resp) && (resp.Success == true) && (resp.Data)) {
                                location.href = app.foldersRoot + '/excel/' + resp.Data;

                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error('Server response not valid.');
                            }
                        }
                        catch (Error) { console.error(Error); }
                        that.model.setExportButtonExporting(false);
                    },
                    function (resp) {
                        that.model.refreshProcesses();
                        that.model.setExportButtonExporting(false);
                        console.error(resp);
                    }
                );
            },
            processes_backgrid_rowclick: function (model) {
                try {
                    //app.router.navigate(
                    //    app.router.resolveURL(
                    //        'eaf-heat-report',
                    //        {
                    //            heatName: model.get('heatName'),
                    //        },
                    //        false
                    //    ),
                    //    { trigger: true, }
                    //);
                }
                catch (Error) { console.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'),
                                    casterCode: (params.casterCode == null || params.casterCode == "") ? '-' : params.casterCode,
                                    crewId: (params.crewId == null || params.crewId == "") ? '-' : params.crewId,
                                    shiftId: (params.shiftId == null || params.shiftId == "") ? '-' : params.shiftId,
                                    strandId: (params.strandId == null || params.strandId == "") ? '-' : params.strandId,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

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

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

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

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

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

                    this.options.onappend(this);
                }

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

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

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

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

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

                this.hideSubviews();

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

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

            fixedParameters: [],

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

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

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


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

                                if ((resp) && (resp.Table)) {
                                    //var newColl = _.map(resp.Table, that.model.prototype.parse);
                                    newColl = resp.Table;
                                    var method = (options.refresh) ? 'set' : 'add';

                                    that[method](newColl);
                                    that.trigger('fetch', that, newColl);

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

                                    that.isFetching = false;


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

        });


        //-------------------------------//
        //------ Print Tag Confirmation -------//
        //------------------------------//
        Screen.Models.PrintTagConfirmation = Backbone.Epoxy.Model.extend({
            defaults: {
                productNumber: null,
                printerId: 1,
                comments: '',
                rowModel: null,
                printers: [{ value: 1, label: 1 }, { value: 2, label: 2 }],
                reasonPhrases: null,
                employeeNumber: null,
                reasonPhraseId: 1,
                pieceLength: 0,
                printLengthMode: 'cold',
                coldConversionFactor: 1.012
            },
            initialize: function () {
                var reasonPhrases = this.fetchReasonPhrases();
                this.set('reasonPhrases', reasonPhrases);

            },
            fetchReasonPhrases: function () {
                var reasonPhrases = [];
                var qp = new Core.Database.QueryParameters();
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetTagPrintReasonPhrases',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if (resp.Table) {
                                    reasonPhrases = resp.Table.map(item => {
                                        return {
                                            value: item.ReasonPhraseId,
                                            label: item.Name
                                        };
                                    });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData: false,
                                            isLoading: false,

                                        });

                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                        that.set({
                                            hasData: false,
                                            isLoading: false,
                                        });
                                    }

                                }


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

                return reasonPhrases;
            }
        });
        Screen.Views.PrintTagConfirmationModal = Backbone.Epoxy.View.extend({
            template: "caster-products",
            id: "print-tag-confirmation",
            className: "modal modal-print-tag-confirmation hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                    "click #printLengthToggle label": "onPrintLengthToggleClick",
                    "change input[name='printLengthModeModal']": "onPrintLengthModeChange"

                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            data: null,
            lastHeatsColl: [],
            grid: [],
            productId: null,
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.PrintTagConfirmation();
                }
                var data = options.data;
                this.model.set({
                    productNumber: data.ProductNumber
                })
                this.model.set({
                    productId: data.Id
                })
                this.model.set({
                    pieceLength: data.Length
                })
                this.model.set({
                    originalPieceLength: data.Length
                })
                this.bus = options.bus;
                this.bindEvents();

                return this;
            },

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

                this.$el.modal('hide');
            },
            render: function (container) {
                if (container)
                    this.container = container;

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



                        that.isRendered = true;
                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "print_confirmation_modal");

            },



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

                return this;
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
                this.listenTo(this.model, "change:pieceLength", this.updateColdLength)
            },

            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');

                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },

           acceptBtn_click: function (e) {
  try {
    var that = this;
    var model = this.model.toJSON();
    var warningMessage = document.getElementById('warning');

    if (model.employeeNumber === null) {
      warningMessage.style.display = 'inline';
      e.preventDefault();
      return;
    } else {
      warningMessage.style.display = 'none';
    }

    // compute the length to send based on toggle
    var selectedLength;
    if (model.printLengthMode === 'cold') {
      // cold length = hot / factor
      selectedLength = (parseFloat(model.pieceLength) / parseFloat(model.coldConversionFactor));
    } else {
      // hot length as-is
      selectedLength = parseFloat(model.pieceLength);
    }

    // round to 2 decimals (optional)
    selectedLength = Math.round(selectedLength * 100) / 100;

    var isColdLength = (model.printLengthMode === 'cold') ? 1 : 0;
    this.printTag({
      productId: model.productId,
      printer: model.printerId,
      employee: model.employeeNumber,
      reasonPhraseId: model.reasonPhraseId,
      comments: model.comments,
      pieceLength: model.pieceLength,
      isColdLength: isColdLength

    });

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


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

                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                    { Name: '@Printer', Type: 'INT', Value: params.printer, },
                    { Name: '@ReasonPhraseId', Type: 'INT', Value: params.reasonPhraseId, },
                    { Name: '@Comments', Type: 'VARCHAR', Value: params.comments, },
                    { Name: '@Employee', Type: 'VARCHAR', Value: params.employee, },
                    { Name: '@Length', Type: 'FLOAT', Value: params.pieceLength, },
                    { Name: '@IsColdLength',     Type: 'INT',    Value: params.isColdLength }
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.UpsertTaggingCommand',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

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

            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_hidden: function (e) {
                try {
                    this.visible = false;

                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    //this.renderMultipicker();
                    this.show();
                    this.updateColdLength();
                    var mode = this.model.get('printLengthMode') || 'hot';
                    var $grp = this.$el.find("#printLengthToggle");
                    $grp.find("label").removeClass("active");
                    $grp.find("input[name='printLengthModeModal']").prop("checked", false);
                    $grp.find("input[value='"+mode+"']").prop("checked", true).closest("label").addClass("active");
                    this.syncPrintLengthToggleUI(mode);
                    $grp.find("input[name='printLengthModeModal']")
                    .prop("disabled", true)
                    .addClass("disabled");
                      $grp.find("label").css({
                        pointerEvents: "none",
                        opacity: 0.6,          
                        cursor: "default"
                    });
                    this.$el.find('#pieceLengthInput, #coldLengthInput')
                    .prop('disabled', true)
                    .addClass('disabled');


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

onPrintLengthToggleClick: function (e) {
  var $label = $(e.currentTarget);
  var $grp   = $label.closest("#printLengthToggle");
  var $input = $label.find("input[type='radio']");

  $grp.find("label").removeClass("active");
  $grp.find("input[type='radio']").prop("checked", false);

  $label.addClass("active");
  $input.prop("checked", true).trigger("change"); 
},
setInputsEnabled: function (mode) {
  var $hot  = this.$el.find('#pieceLengthInput');   // HOT input (editable when mode='hot')
  var $cold = this.$el.find('#coldLengthInput');    // COLD input (editable when mode='cold')

  if (mode === 'cold') {
    $hot.prop('disabled', true).addClass('disabled');
    $cold.prop('disabled', false).removeClass('disabled').focus();
  } else {
    $hot.prop('disabled', false).removeClass('disabled').focus();
    $cold.prop('disabled', true).addClass('disabled');
  }
},

syncPrintLengthToggleUI: function (mode) {
  var $grp  = this.$el.find("#printLengthToggle");
  var $hot  = $grp.find("input[value='hot']").closest("label");
  var $cold = $grp.find("input[value='cold']").closest("label");

  // reset button classes
  $grp.find("label").removeClass("active btn-hot-active btn-cold-active btn-inactive");
  $hot.addClass("btn-inactive");
  $cold.addClass("btn-inactive");

  if (mode === 'hot') {
    $hot.removeClass("btn-inactive").addClass("active btn-hot-active");
  } else {
    $cold.removeClass("btn-inactive").addClass("active btn-cold-active");
  }

  // field emphasis (optional but clear)
  var $hotInput  = this.$el.find('#pieceLengthInput');
  var $coldLabel = this.$el.find('#coldLengthLabel');
  $hotInput.removeClass('active-length-input');
  $coldLabel.removeClass('active-length-pill pill-blue pill-red');

  if (mode === 'hot') {
    $hotInput.addClass('active-length-input');
    $coldLabel.addClass('active-length-pill pill-red');   
  } else {
    $coldLabel.addClass('active-length-pill pill-blue');  
  }
},
updateColdLength: function () {
  var val = this.model.get('pieceLength');
  var $cold = this.$el.find('#coldLengthInput');
  if (!isNaN(val) && val !== null && val !== "") {
    var factor = parseFloat(this.model.get('coldConversionFactor') || 1.012);
    var cold = parseFloat(val) / factor;
    $cold.val(Math.round(cold * 100) / 100);
  } else {
    $cold.val('');
  }
},
onPrintLengthModeChange: function () {
  var mode = this.$el.find("input[name='printLengthModeModal']:checked").val(); // 'hot' | 'cold'
  this.model.set('printLengthMode', mode);
  this.syncPrintLengthToggleUI(mode);
},
        });

Screen.Models.EditLength = Backbone.Epoxy.Model.extend({
  defaults: {
    productId: null,
    productNumber: null,
    hotLength: null,                 
    coldConversionFactor: 1.012,
    editLengthMode: 'hot'        
  }
});

Screen.Views.EditLengthModal = Backbone.Epoxy.View.extend({
  template: "caster-products",
  id: "edit-length-modal",
  className: "modal modal-edit-length hide fade",
  bindings: "data-bind",
  isCacheable: true,
  events: function () {
    return {
      "click #saveEditLengthBtn": this.save_click,
      "hidden.bs.modal": this.modal_hidden,
      "click #savePrintEditLengthBtn": this.save_and_print_click,
      "click #editLengthToggle label": "onToggleClick",
      "change input[name='editLengthMode']": "onModeChange",
      "input #editHotInput":  this.handleHotChange,
      "input #editColdInput": this.handleColdChange
    };
  },

  initialize: function (options) {
    _.extend(this, options);
    if (!this.model) this.model = new Screen.Models.EditLength();

    // seed initial data
    var d = options.data || {};
    this.model.set({
      productId:     d.Id,
      productNumber: d.ProductNumber,
      hotLength:     d.Length,                 
      editLengthMode:'hot'
    });
     this.openPrintAfterSave = false;
    return this;
  },

  render: function (container) {
    if (container) this.container = container;

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

  afterRender: function () {
    // set initial values
    var hot = this.model.get('hotLength');
    this.$el.find('#editHotInput').val(hot != null ? hot : '');

    // compute initial cold
    this.updateColdFromHot();

    // init toggle ui
    var mode = this.model.get('editLengthMode') || 'hot';
    var $grp = this.$el.find("#editLengthToggle");
    $grp.find("label").removeClass("active");
    $grp.find("input[name='editLengthMode']").prop("checked", false);
    $grp.find("input[value='"+mode+"']").prop("checked", true)
        .closest("label").addClass("active");

    this.setInputsEnabled(mode);
    this.syncEditToggleUI(mode);

    // show
    this.$el.modal({ keyboard: true, backdrop: 'static' });
  },

  show: function () {
    if (!this.$el.children().length) this.render();
    else this.$el.modal({ keyboard: true, backdrop: 'static' });
    return this;
  },

  modal_hidden: function () { this.remove(); this.unbind(); },

  // --- Toggle / inputs logic ---
  onToggleClick: function (e) {
    var $label = $(e.currentTarget);
    var $grp   = $label.closest("#editLengthToggle");
    var $input = $label.find("input[type='radio']");
    $grp.find("label").removeClass("active");
    $grp.find("input[type='radio']").prop("checked", false);
    $label.addClass("active");
    $input.prop("checked", true).trigger("change");
  },

  onModeChange: function () {
    var mode = this.$el.find("input[name='editLengthMode']:checked").val();
    this.model.set('editLengthMode', mode);
    this.setInputsEnabled(mode);
    this.syncEditToggleUI(mode);
  },

  setInputsEnabled: function (mode) {
    var $hot  = this.$el.find('#editHotInput');
    var $cold = this.$el.find('#editColdInput');
    if (mode === 'cold') {
      $hot.prop('disabled', true).addClass('disabled');
      $cold.prop('disabled', false).removeClass('disabled').focus();
    } else {
      $hot.prop('disabled', false).removeClass('disabled').focus();
      $cold.prop('disabled', true).addClass('disabled');
    }
  },

  handleHotChange: function () {
    var raw = this.$el.find('#editHotInput').val();
    var hot = (raw === '' ? null : parseFloat(raw));
    if (isNaN(hot) || hot === null) {
      this.model.set('hotLength', null);
      this.$el.find('#editColdInput').val('');
      return;
    }
    this.model.set('hotLength', hot);
    this.updateColdFromHot();
  },

  handleColdChange: function () {
    var raw = this.$el.find('#editColdInput').val();
    var cold = (raw === '' ? null : parseFloat(raw));
    if (isNaN(cold) || cold === null) {
      // clear hot if cold invalid
      this.model.set('hotLength', null);
      this.$el.find('#editHotInput').val('');
      return;
    }
    var factor = parseFloat(this.model.get('coldConversionFactor') || 1.012);
    var hot = cold * factor;
    hot = Math.round(hot * 100) / 100;
    this.model.set('hotLength', hot);
    this.$el.find('#editHotInput').val(hot);
  },

  updateColdFromHot: function () {
    var hot = this.model.get('hotLength');
    var $cold = this.$el.find('#editColdInput');
    if (hot == null || isNaN(hot)) { $cold.val(''); return; }
    var factor = parseFloat(this.model.get('coldConversionFactor') || 1.012);
    var cold = hot / factor;
    cold = Math.round(cold * 100) / 100;
    $cold.val(cold);
  },

    save_click: function () {
        // plain save
        this.openPrintAfterSave = false;
        this._doSave();
    },

    save_and_print_click: function () {
    // save and then open print modal
    this.openPrintAfterSave = true;
    this._doSave();
  },
    _doSave: function () {
    var mode   = this.model.get('editLengthMode');    // 'hot' | 'cold'
    var isCold = (mode === 'cold') ? 1 : 0;

    var value = (isCold === 1)
      ? parseFloat(this.$el.find('#editColdInput').val())
      : parseFloat(this.$el.find('#editHotInput').val());

    if (isNaN(value)) {
      app.views.topMessages.showMessage('Please enter a valid length.', { stay: 3000 });
      return;
    }
    value = Math.round(value * 100) / 100;

    this.updateProductLength({
      productId: this.model.get('productId'),
      length: value,
      isColdLength: isCold
    });
  },

  syncEditToggleUI: function (mode) {
  var $grp  = this.$el.find("#editLengthToggle");
  var $hot  = $grp.find("input[value='hot']").closest("label");
  var $cold = $grp.find("input[value='cold']").closest("label");

  $grp.find("label").removeClass("active btn-hot-active btn-cold-active btn-inactive");

  $hot.addClass("btn-inactive");
  $cold.addClass("btn-inactive");

  if (mode === 'hot') {
    $hot.removeClass("btn-inactive").addClass("active btn-hot-active");
  } else {
    $cold.removeClass("btn-inactive").addClass("active btn-cold-active");
  }
},


updateProductLength: function (params) {
  var qp = new Core.Database.QueryParameters();
  [
    { Name: '@ProductId', Type: 'INT',   Value: params.productId },
    { Name: '@Length',    Type: 'FLOAT', Value: params.length }
  ].forEach(function(p){ qp.Add(p.Name, p.Type, p.Value); });

  var that = this;   // 👈 need this

  Core.Json.CallProcedure(
    app.DatabaseNames.MES + '.CAS.UpdateProductLength',
    qp,
    {
      onSuccess: function (resp) {
        app.views.topMessages.showMessage('Length updated.', { stay: 3000 });

        if (that.bus) that.bus.trigger('modalAcceptBtn');

        if (that.openPrintAfterSave) {
          that.openPrintModalAfterSave(params);
        }

        that.$el.modal('hide');
        that.remove();
        that.unbind();
      },
      onFailure: function (resp) {
        console.error(resp);
      },
      Secured: true,
      Async: true
    },
    app.ConnectionStrings.app
  );
},
 openPrintModalAfterSave: function (saveParams) {
  var hotLen        = this.model.get('hotLength');
  var productId     = this.model.get('productId');
  var productNumber = this.model.get('productNumber');

  if (isNaN(hotLen) || hotLen == null) {
    hotLen = saveParams.length; // fallback to what we just saved
  }

  // 👇 use the modal from THIS file
  var printModal = new Screen.Views.PrintTagConfirmationModal({
    data: {
      Id: productId,
      ProductNumber: productNumber,
      Length: hotLen
    },
    bus: this.bus // so parent can refresh
  });

  printModal.show();
},
});

        // Required, return the module for AMD compliance.
        return Screen;
    });