//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',

    'components/ag-grid/ag-grid-module',
    'components/modal-confirmation/modal-confirmation',
    'backgrid/infinator',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',

    "js/jquery.floatThead/jquery.floatThead",
    'js/jquery.contextMenu/jquery.contextMenu',
    "js/bootstrap-slider/bootstrap-slider.min"
],
    function (app, T, Backgrid, moment, Modal,  AgGridModule, ModalConfirmation) {

        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'),


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

                shiftId: '-',
                shifts: [{ label: 'D', value: 1 }, { label: 'N', value: 2 }],
                casterId: '-',
                casters: [{ label: '1', value: 1 }, { label: '2', value: 2 }],
                hasData: false,
                isLoading: false,
                isExcelExporting: false,
                grid: [],
                searchText: '',
                isPageLoading: false,
                onlyJustified: 0,
                showOnlyUndeclared: false
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },


        });

        var CustomAgGridModule = AgGridModule.extend({
            initialize: function (options) {
                this.bus = options.bus;
                this.itemsColl = options.delaysColl;
                this.columnDefs = [
                    { field: 'Start', headerName: 'Start', flex: 1, minWidth: 109, fieldType: 'Datetime', format: 'YYYY/MM/DD HH:mm' },
                    { field: 'End', headerName: 'End', flex: 1, minWidth: 109, fieldType: 'Datetime', format: 'YYYY/MM/DD HH:mm' },
                    {
                        headerName: 'Duration',
                        field: 'Duration',  // If you don't need a field for this column
                        cellRenderer: this.formatDurationRenderer.bind(this),  // Bind the method to `this`
                        minWidth: 50
                    },
                    //{ field: 'Duration', headerName: 'Duration', flex: 1, minWidth: 84 },
                    { field: 'AssetName', headerName: 'Caster', flex: 1, minWidth: 70 },
                    { field: 'DelayCodeName', headerName: 'Cause', flex: 1, minWidth: 70 },
                    { field: 'DelayCategoryName', headerName: 'Area', flex: 1, minWidth: 70 },
                    { field: 'Comments', headerName: 'Comments', flex: 1, minWidth: 70 },

                    // Column for Declare and Split buttons
                    {
                        headerName: 'Actions',
                        field: null,  // If you don't need a field for this column
                        cellRenderer: this.actionsCellRenderer.bind(this),  // Bind the method to `this`
                        minWidth: 50
                    }
                ];

                // Pass the columns to the options
                options.columnDefs = this.columnDefs;

                // Add getRowClass and getRowStyle to color undeclared delays
                if (!options.gridOptions) {
                    options.gridOptions = {};
                }
                options.gridOptions.getRowClass = this.getRowClass.bind(this);
                options.gridOptions.getRowStyle = this.getRowStyle.bind(this);

                // Initialize ag-Grid
                AgGridModule.prototype.initialize.call(this, options);
            },
            getRowClass: function(params) {
                // Color undeclared delays (when DelayCodeId is null or DelayCodeName is null/empty)
                if (params.data) {
                    var delayCodeId = params.data.DelayCodeId;
                    var delayCodeName = params.data.DelayCodeName;
                    
                    // Check if delay is undeclared (DelayCodeId is null/undefined or DelayCodeName is empty/null)
                    if (delayCodeId === null || delayCodeId === undefined || delayCodeId === '' ||
                        !delayCodeName || delayCodeName === '' || delayCodeName === null) {
                        return 'undeclared-delay-row';
                    }
                }
                return '';
            },
            getRowStyle: function(params) {
                // Color undeclared delays (when DelayCodeId is null or DelayCodeName is null/empty)
                if (params && params.data) {
                    var delayCodeId = params.data.DelayCodeId;
                    var delayCodeName = params.data.DelayCodeName;
                    
                    // Check if delay is undeclared (DelayCodeId is null/undefined or DelayCodeName is empty/null)
                    var isUndeclared = (delayCodeId === null || delayCodeId === undefined || delayCodeId === '' ||
                        !delayCodeName || delayCodeName === '' || delayCodeName === null);
                    
                    if (isUndeclared) {
                        return { backgroundColor: '#D0A4A4' };
                    }
                }
                return null;
            },
            formatDurationRenderer: function (d) {
                d = Number(d.data.Duration);
                var h = Math.floor(d / 3600);
                var m = Math.floor(d % 3600 / 60);
                var s = Math.floor(d % 3600 % 60);
                return ((h > 0 ? h + " h " : "") + m + " min " + ((s > 0) ? s + " seg" : ""));

            },

            actionsCellRenderer: function (params) {
                // Create the Justify button
                const justifyBtn = document.createElement('button');
                justifyBtn.className = 'MuiButtonBase-root MuiIconButton-root';
                justifyBtn.setAttribute('title', 'Justify');
                justifyBtn.style.display = 'inline-block';  // Ensure buttons are visible
                justifyBtn.style.minWidth = '30px';  // Ensure the button has enough width
                justifyBtn.style.minHeight = '24px'; // Ensure the button has enough height
                justifyBtn.style.marginRight = '10px';
                justifyBtn.innerHTML = `
                    <span class="MuiIconButton-label">
                        <svg class="MuiSvgIcon-root text-blue-500 MuiSvgIcon-fontSizeInherit" focusable="false" viewBox="0 0 24 24" aria-hidden="true" style="cursor: pointer;">
                            <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18zM18 14H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"></path>
                        </svg>
                    </span>`;

                // Create the Split button
                const splitBtn = document.createElement('button');
                splitBtn.className = 'MuiButtonBase-root MuiIconButton-root';
                splitBtn.setAttribute('title', 'Split');
                splitBtn.style.display = 'inline-block';  // Ensure buttons are visible
                splitBtn.style.minWidth = '30px';  // Ensure the button has enough width
                splitBtn.style.minHeight = '24px'; // Ensure the button has enough height
                splitBtn.style.marginRight = '10px';
                splitBtn.innerHTML = `
                    <span class="MuiIconButton-label">
                        <svg class="MuiSvgIcon-root text-blue-500 MuiSvgIcon-fontSizeInherit" focusable="false" viewBox="0 0 24 24" aria-hidden="true" style="cursor: pointer;">
                            <path d="M14 4l2.29 2.29-2.88 2.88 1.42 1.42 2.88-2.88L20 10V4zm-4 0H4v6l2.29-2.29 4.71 4.7V20h2v-8.41l-5.29-5.3z"></path>
                        </svg>
                    </span>`;


                // Create Delete Button 
                
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'MuiButtonBase-root MuiIconButton-root';
                deleteBtn.setAttribute('title', 'Delete');
                deleteBtn.style.display = 'inline-block';  // Ensure buttons are visible
                deleteBtn.style.minWidth = '30px';  // Ensure the button has enough width
                deleteBtn.style.minHeight = '24px'; // Ensure the button has enough height
                deleteBtn.innerHTML = `
                    <span class="MuiIconButton-label">
                       <svg class="MuiSvgIcon-root root text-blue-500 MuiSvgIcon-fontSizeInherit" focusable="false" aria-hidden="true" viewBox="0 0 24 24" style="cursor: pointer;">
                        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m5 11H7v-2h10z"></path>
                        </svg>
                    </span>`;
                if(!params.data.IsDelayManual) {
                    deleteBtn.disabled = true;
                    deleteBtn.style.opacity = '0.5';
                }
               
                

                justifyBtn.style.zIndex = '1000';  // Ensure it's above other elements
                splitBtn.style.zIndex = '1000';    // Ensure it's above other elements
                deleteBtn.style.zIndex = '1000';    // Ensure it's above other elements

                // Create a container for the buttons
                const container = document.createElement('div');
                container.className = 'flex justify-center';
                container.style.display = 'inline-block';  // Ensure container is visible
                container.style.minWidth = '70px';   // Ensure container width
                container.style.minHeight = '24px';  // Ensure container height
                container.appendChild(justifyBtn);
                container.appendChild(splitBtn);
                container.appendChild(deleteBtn);




                const rowData = params.data;

                // LISTENERS
                justifyBtn.addEventListener('click', function () {


                    var that = this;
                    var delayjustifymodal = new Screen.Views.JustifyDelay({
                        viewParams: {
                            rowData: {
                                id: rowData.DelayId,
                                model: rowData,
                            },
                        },
                        model: new Screen.Models.JustifyDelay({
                            id: rowData.DelayId,
                            start: rowData.Start,
                            end: rowData.End,
                            duration: rowData.Duration,
                            commentsDelay: rowData.Comments,
                            delayCodeId: rowData.DelayCodeId,
                            delayCategoryId: rowData.DelayCategoryId,
                            casterCode: rowData.AssetId / 1000 // to only get the caster Code

                        }),

                        bus: this.bus,
                    });
                    delayjustifymodal.show();
                }.bind(this));

                splitBtn.addEventListener('click', function () {


                    var that = this;
                    var delaysplitmodal = new Screen.Views.SplitDelay({
                        viewParams: {
                            rowData: {
                                id: rowData.DelayId,
                                model: rowData,
                            },
                        },
                        model: new Screen.Models.SplitDelay({
                            id: rowData.DelayId,
                            start: rowData.Start,
                            end: rowData.End,
                            duration: rowData.Duration,
                            commentsDelay1: rowData.Comments,
                            delayCodeId1: rowData.DelayCodeId,
                            delayCategoryId1: rowData.DelayCategoryId,
                            casterCode: rowData.AssetId / 1000, 
                        }),

                        bus: this.bus,
                    });
                    delaysplitmodal.show();
                }.bind(this));


                deleteBtn.addEventListener('click', function () {
                    var that = this;

                    var modalConfirmation = new ModalConfirmation.Views.ModalConfirmation({
                        model: new ModalConfirmation.Models.ModalConfirmation({
                            message: "Are you sure you want to delete delay Start: "+ rowData.Start+" and End: "+ rowData.End+ " from Caster: "+rowData.AssetId/1000+ " ?",
                                title: "Delete Delay Confirmation",
                                acceptBtnLabel: "DELETE",
                                cancelBtnLabel: "CANCEL",
                                action: "DELETE"
                        }),
                        bus: this.bus,
                    });
                    this.listenToOnce(modalConfirmation, "acceptBtn", function (modal) {
                        try {
                            that.deleteManualDelay(rowData);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    });
                    modalConfirmation.show();
                }.bind(this));

                // Return the container to be rendered
                return container;
            },
            deleteManualDelay: function(delayData) {
                var that = this;
                var QP = new Core.Database.QueryParameters();

                QP.Add("DelayId", "INT", delayData.DelayId);
                app.CallProcedure(app.DatabaseNames.MES + ".DEL.DeleteManualDelay", QP, {
                    onSuccess: function (data) {
                        that.bus.trigger('refreshGrid');
                        //that.hide();
                        app.views.topMessages.showMessage('Delay Deleted', { stay: 5000, });

                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,

                }, app.ConnectionStrings.app);

            }

        });


        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-delays-manager',
            id: 'caster-delays-manager',
            title: 'Caster Delays Manager',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    "click #exportExcelBtn": this.exportToExcel,
                    'click #calendarStartBtn': this.calendarStartBtn_click,
                    'click #calendarEndBtn': this.calendarEndBtn_click,
                    'click .new_delay_btn': this.newDelayBtn_click,


                };
            },
            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 () { };
                this.bus = _.extend({}, Backbone.Events);
                // Init AgGridModule:
                this.agGridModule = new CustomAgGridModule({
                    delaysColl: this.itemsColl,
                    bus: this.bus,
                    rowData: [],
                    onChange: this.handleGridChange.bind(this),
                    onRemove: this.handleGridRemove.bind(this),
                    fileName: 'caster-delays-manager'
                });


                var that = this;

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

                this.grids = {};

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

                this.bindingSources = {};

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


                this.bindEvents();

                this.bus.on("refreshGrid", this._refresh, this);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);
            },

            handleGridChange: function (event) {
                // This function will be called when a cell value changes
                // You can update your model or perform any other actions here
            },

            handleGridRemove: function () {
                // This function will be called when the grid is being removed/destroyed
                // Perform any cleanup or additional actions here
            },
            calendarStartBtn_click: function () {
                $('#dateStartTbx').datepicker('show');
            },
            calendarEndBtn_click: function () {
                $('#dateEndTbx').datepicker('show');
            },
            newDelayBtn_click: function() {
                var that = this;
                var modal = new Screen.Views.CreateDelay({
                    bus: this.bus,
                });
                modal.show();
            },

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


            },
            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
                    );
                }
            },
            render: function (container, viewParams) {
                var that = this;

                this.viewParams = viewParams;
                // Toggle should be off by default (show all delays)
                var defaultToUnjustified = false;

                // Initialize the loading state
                that.model.set({ isPageLoading: true });

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

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

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

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

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

                                that.applyBindings();

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

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

                                // Render the AgGridModule and append it to the container
                                that.agGridModule.render();
                                that.$el.find('.processes-grid-container').append(that.agGridModule.$el);

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

                                //Set model with view params here to prevent changes on the model when the view bindings are applied.
                                var fixedParams = _.extend({}, viewParams);
                                if (fixedParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (viewParams.furnaceCode)
                                    fixedParams.furnaceCode = (viewParams.furnaceCode != '-' && viewParams.furnaceCode != null) ? parseInt(viewParams.furnaceCode) : '-';
                                if (viewParams.crewId)
                                    fixedParams.crewId = (viewParams.crewId != '-' && viewParams.crewId != null) ? viewParams.crewId : '-';
                                if (viewParams.shiftId)
                                    fixedParams.shiftId = (viewParams.shiftId != '-' && viewParams.shiftId != null) ? parseInt(viewParams.shiftId) : '-';
                                if (viewParams.strandId)
                                    fixedParams.strandId = (viewParams.strandId != '-' && viewParams.strandId != null) ? parseInt(viewParams.strandId) : '-';

                                // Map showOnlyUndeclared to onlyUnjustified for backward compatibility
                                // If showOnlyUndeclared is set in viewParams, use it; otherwise use defaultToUnjustified
                                if (viewParams.showOnlyUndeclared !== undefined) {
                                    fixedParams.showOnlyUndeclared = viewParams.showOnlyUndeclared;
                                    fixedParams.onlyUnjustified = viewParams.showOnlyUndeclared ? 1 : 0;
                                } else {
                                    fixedParams.onlyUnjustified = defaultToUnjustified ? 1 : 0;
                                    fixedParams.showOnlyUndeclared = defaultToUnjustified;
                                }
                                that.model.set(fixedParams);

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

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

                                // Set loading state to false when everything is ready
                                that.model.set({ isPageLoading: false });


                            },
                            true,
                            customPath
                        );
                    },
                    customPath, "delays_report"
                );
            },
            showDelaySplitModal: function () {

            },
            processes_ready: function () {
                try {
                    var that = this;
                    const collectionData = that.itemsColl;
                    setTimeout(
                        function () {
                            that.agGridModule.setRowDataAsCollection(collectionData);
                            that.agGridModule.hideOverlay();
                            // Force refresh to apply row styles
                            if (that.agGridModule.getGridApi()) {
                                that.agGridModule.getGridApi().refreshCells({ force: true });
                            }
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                            if(that.viewParams.delayId){
                                that.openJustifyModalByParameter(that.viewParams.delayId);
                                that.viewParams.delayId = null
                            }
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            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);
                    that.agGridModule.showLoadingOverlay();  // Show loading overlay
                }

                // Map showOnlyUndeclared to onlyUnjustified for backward compatibility
                if (attrs.showOnlyUndeclared !== undefined) {
                    attrs.onlyUnjustified = attrs.showOnlyUndeclared ? 1 : 0;
                }

                this.itemsColl.fetch({
                    ...attrs,
                    refresh: true,
                });





            },
            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'),
                                    furnaceCode: (params.furnaceCode == null || params.furnaceCode == "") ? '-' : params.furnaceCode,
                                    crewId: (params.crewId == null || params.crewId == "") ? '-' : params.crewId,
                                    shiftId: (params.shiftId == null || params.shiftId == "") ? '-' : params.shiftId,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

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

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

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

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

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

                    this.options.onappend(this);
                }

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

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

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

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

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

                this.hideSubviews();

                this.$el.hide();
                this.unbind();
                this.stopListening();
            },
            hideSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.hide();
                });
            },
            preRender: function () {
                app.models.subnavbar.set("subnavbar", false);
            },
            reRender: function (viewParams) {
                try {
                    this.refresh(viewParams);
                } catch (Error) { }
            },
            openJustifyModalByParameter: function (delayId){
                var that = this;
                var delayModel = this.itemsColl.findWhere({ DelayId: parseInt(delayId) });

                if (!delayModel) {
                    console.warn("Delay not found in collection:", delayId);
                    return;
                }

                var formattedStart = moment(delayModel.get('Start')).format('YYYY/MM/DD HH:mm');
                var formattedEnd = moment(delayModel.get('End')).format('YYYY/MM/DD HH:mm');
            

                var delayjustifymodal = new Screen.Views.JustifyDelay({
                    viewParams: {
                        rowData: {
                            id: delayModel.get('DelayId'),
                            model: delayModel.toJSON(),
                        },
                    },
                    model: new Screen.Models.JustifyDelay({
                        id: delayModel.get('DelayId'),
                        start: formattedStart,
                        end: formattedEnd,
                        duration: delayModel.get('Duration'),
                        commentsDelay: delayModel.get('Comments'),
                        delayCodeId: delayModel.get('DelayCodeId'),
                        delayCategoryId: delayModel.get('DelayCategoryId'),
                        casterCode: delayModel.get('AssetId') / 1000, 
                    }),
                    bus: this.bus,
                });

                delayjustifymodal.show();
            }

        });

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

            fixedParameters: [],

            fetch: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                options = params ? _.clone(params) : {};
                if (options.refresh) {
                    this.resetPagination(true);
                    // Map showOnlyUndeclared to onlyUnjustified for the stored procedure
                    var onlyUnjustifiedValue = 0;
                    if (params.showOnlyUndeclared !== undefined) {
                        onlyUnjustifiedValue = params.showOnlyUndeclared ? 1 : 0;
                    } else if (params.onlyUnjustified !== undefined) {
                        onlyUnjustifiedValue = params.onlyUnjustified ? 1 : 0;
                    }
                    this.fixedParameters = [
                        { Name: '@StartDate', Type: 'DATE', Value: params.start },
                        { Name: '@EndDate', Type: 'DATE', Value: params.end },
                        { Name: '@AssetId', Type: 'INT', Value: (params.casterId * 1000) },
                        // Scope to the Casters area (AssetId 1) so EAF delays (3100/3200)
                        // never leak into the caster grid when no specific caster is selected.
                        { Name: '@DelayAreaAssetId', Type: 'INT', Value: 1 },
                        { Name: '@ShowOnlyUnjustified', Type: 'INT', Value: onlyUnjustifiedValue }
                    ];
                }

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


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

                                if ((resp) && (resp.Table)) {
                                    newColl = resp.Table;
                                    var method = (options.refresh) ? 'set' : 'add';
                                    that[method](newColl);
                                    that.trigger('fetch', that, newColl);

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

                                    that.isFetching = false;


                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            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);
                }
            },

        });

        Screen.Models.SplitDelay = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                start: null,
                end: null,
                duration: null,

                // Split durations
                split1_duration: null,
                split2_duration: null,

                // Calculated delay start and end times
                delay1Start: null,
                delay1End: null,
                delay2Start: null,
                delay2End: null,
                delayCategoryId1: 1,
                delayCategoryId2: 1,
                commentsDelay1: '',
                commentsDelay2: '',
                delayCategories: [],
                delayCodes: [],
                delayCodes1: [],
                delayCodes2: [],
                delayCodeId1: 1,
                delayCodeId2: 1,
                casterCode: null,

            },
            initialize: function () {

                this.fetchDelayCategories();
                this.fetchDelayCodes();
            },

            fetchDelayCategories: function () {
                var that = this;
                Core.Json.CallProcedure(app.DatabaseNames.MES + ".DEL.GetDelayCategories", null, {
                    onSuccess: function (data) {
                        if (data && data.Table) {
                            var items = data.Table;

                            that.set({
                                delayCategories: _.map(items, function (m) {
                                    return { value: m.DelayCategoryId, label: m.DelayCategoryName, assetId: m.AssetId / 1000 };
                                }),
                            });

                        }
                    },
                    Async: false,
                    Secured: true,
                }, app.ConnectionStrings.app);
            },
            fetchDelayCodes: function () {
                var that = this;
                var QP = new Core.Database.QueryParameters();
                QP.Add("DelayAreaAssetId", "INT", 1);   // Casters root: both casters' codes, never EAF
                Core.Json.CallProcedure(app.DatabaseNames.MES + ".DEL.GetDelayCodes", QP, {
                    onSuccess: function (data) {
                        if (data && data.Table) {
                            var items = data.Table;

                            that.set({
                                delayCodes: _.map(items, function (m) {
                                    return { value: m.DelayCodeId, label: m.DelayCodeName, parent: m.DelayCategoryId };
                                })
                            });
                        }
                    },
                    Async: false,
                    Secured: true,
                }, app.ConnectionStrings.app);
            },
        });


        Screen.Views.SplitDelay = Backbone.Epoxy.View.extend({
            template: "caster-delays-manager"
            , id: "caster-delays-manager-split"
            , title: ""
            , className: "modal hide fade modal-wider"
            , bindings: 'data-bind'
            //default not cacheable, change this if you want the view to be cacheable
            // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
            , isCacheable: true
            , initialize: function () {
                _.bindAll(this);

                this.options.MYREFERENCES = {
                    autoRefresh: {
                        enabled: true
                        , toid: null
                    },
                    rowData: null,
                };
                this.bus = this.options.bus;
                if (this.options.viewParams) {
                    this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
                }
                if (!this.model) {
                    this.model = new Screen.Models.SplitDelay();
                }

                this.options._isRendered = false;
                this.options.sliders = {};

                this.bindEvents();
                this.delegateEvents();
            },

            splitDelay: function () {
                var that = this;
                var QP = new Core.Database.QueryParameters();

                var model = this.model;

                var s1duration = this.model.get("split1_duration");
                var s2duration = this.model.get("split2_duration");

                if (s1duration > 0 && s2duration > 0) {
                    QP.Add("DelayId", "INT", model.get("id"));
                    QP.Add("SplitTime", "DATETIME", model.get("splitTime"));
                    QP.Add("DelayCodeId1", "INT", model.get("delayCodeId1"));
                    QP.Add("DelayCategoryId1", "INT", model.get("delayCategoryId1"));
                    QP.Add("Comments1", "VARCHAR", model.get("commentsDelay1"));
                    QP.Add("DelayCodeId2", "INT", model.get("delayCodeId2"));
                    QP.Add("DelayCategoryId2", "INT", model.get("delayCategoryId2"));
                    QP.Add("Comments2", "VARCHAR", model.get("commentsDelay2"));
                    app.CallProcedure(app.DatabaseNames.MES + ".DEL.SplitDelay", QP, {
                        onSuccess: function (data) {
                            that.bus.trigger('refreshGrid');
                            that.hide();
                            app.views.topMessages.showMessage('Delay Splitted', { stay: 5000, });

                        },
                        Secured: true,

                    }, app.ConnectionStrings.app);
                }
            },

            events: {
                'click .close, .btn-close': 'handleClose',
                'click .delay_split_modal_split_btn': 'splitDelay',

            },

            handleClose: function (event) {
                event.preventDefault();
                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },

            render: function (container) {
                var that = this;
                var customPath = "/app/pages/caster/caster-delays-manager/";

                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;

                        var startDate = new moment(that.model.get("start"));
                        var endDate = new moment(that.model.get("end"));

                        that.filterCodes1();
                        that.filterCodes2();

                        var ctx = {
                            start_date: startDate.format("YYYY-MM-DD"),
                            end_date: endDate.format("YYYY-MM-DD"),
                            start_time: startDate.format("HH:mm:ss"),
                            end_time: endDate.format("HH:mm:ss"),

                            // Delay start and end times for each split
                            delay1Start: that.model.get("delay1Start"),
                            delay1End: that.model.get("delay1End"),
                            delay2Start: that.model.get("delay2Start"),
                            delay2End: that.model.get("delay2End"),
                        };

                        that.$el.html(tmp(ctx));
                        that.applyBindings();
                        // Ensure events are re-bound after rendering
                        that.delegateEvents();

                        setTimeout(function () {
                            that.options.sliders.split = that.$el.find(".slider").slider({
                                formatter: function (value) {
                                    var start = new Date(startDate.toDate().getTime() + (parseInt(value, 10) * 1000));
                                    return "Split at: " + new moment(start).format("YYYY-MM-DD HH:mm:ss");
                                },
                                min: 0,
                                max: that.model.get("duration"),
                                step: 1,
                                value: parseInt(that.model.get("duration")) / 2,
                            }).data('slider');

                            that.$el.find(".slider").on("change", _.throttle(function () {
                                that.updateModelSplitDurations();
                            }, 100));

                            that.updateModelSplitDurations();

                        }, 500);

                        that.options._isRendered = true;

                    }, true, customPath);

                }, customPath, "delay_split_split_action_template");
            },
            updateModelSplitDurations: function () {
                var val = this.options.sliders.split.getValue();
                var duration = this.model.get("duration");

                this.model.set({
                    split1_duration: val,
                    split2_duration: duration - val,
                });

                var startDate = new moment(this.model.get("start"));
                var delay1End = startDate.clone().add(val, 'seconds');
                var delay2Start = delay1End.clone();
                var endDate = new moment(this.model.get("end"));

                this.model.set({
                    delay1Start: startDate.format("HH:mm:ss"),
                    delay1End: delay1End.format("HH:mm:ss"),
                    delay2Start: delay2Start.format("HH:mm:ss"),
                    delay2End: endDate.format("HH:mm:ss"),
                    splitTime: delay1End.format("YYYY-MM-DD HH:mm:ss")
                });
            },

            updateDelayTimesDisplay: function () {
                this.$el.find('#delay1-start')[0].value = this.model.get('delay1Start')
                this.$el.find('#delay1-end')[0].value = this.model.get('delay1End')
                this.$el.find("#delay2-start")[0].value = this.model.get("delay2Start");
                this.$el.find("#delay2-end")[0].value = this.model.get("delay2End");
            }


            , secondsToHHMMSS: function (d) {
                d = Number(d);
                var h = Math.floor(d / 3600);
                var m = Math.floor(d % 3600 / 60);
                var s = Math.floor(d % 3600 % 60);
                return ((h > 0 ? h + " h " : "") + m + " min " + ((s > 0) ? s + " seg" : ""));
            }

            , slideRight: function () {
                var val = this.options.sliders.split.getValue();
                this.options.sliders.split.setValue(val + 1, true, true);
            }
            , slideLeft: function () {
                var val = this.options.sliders.split.getValue();
                this.options.sliders.split.setValue(val - 1, true, true);
            }



            , refresh: function () {
                try {
                    console.log();
                } catch (Error) { }
            }

            , checkSplitsLength: function () {
                var s1duration = this.model.get("split1_duration");
                var s2duration = this.model.get("split2_duration");
                var splitBtn = this.$el.find("#delay_split_modal_split_btn");

                if (s1duration > 0 && s2duration > 0) splitBtn.prop("disabled", false);
                else splitBtn.prop("disabled", true);
            }

            , show: function () {

                if (!this.options._isRendered) {
                    this.render();
                    setTimeout(this.show, 100);
                    return;
                }

                var self = this,
                    $el = this.$el;

                //creating modal
                $el.modal({
                    keyboard: false
                    , backdrop: "static"
                });

                $backdrop = $('.modal-backdrop');

                $backdrop.one('click', function () {
                    if (self.options.content && self.options.content.trigger) {
                        self.options.content.trigger('cancel', self);
                    }

                    self.trigger('cancel');
                });

                $(document).one('keyup.dismiss.modal', function (e) {
                    e.which == 27 && self.trigger('cancel');

                    if (self.options.content && self.options.content.trigger) {
                        e.which == 27 && self.options.content.trigger('shown', self);
                    }
                });

                this.on('cancel', function () {
                    self.hide();
                });

                return this;

            }
            , hide: function (data) {
                var self = this,
                    $el = this.$el;

                $el.one('hidden', function onHidden(e) {
                    // Ignore events propagated from interior objects, like bootstrap tooltips
                    if (e.target !== e.currentTarget) {
                        return $el.one('hidden', onHidden);
                    }
                    self.newDelay = data;
                    if (self.options.content && self.options.content.trigger) {
                        self.options.content.trigger('hidden', self);
                    }

                    // self.trigger('hidden');
                    //self.trigger('delaySplitted', data);

                    self.close();
                });

                $el.modal('hide');
            },
            bindEvents: function () {
                this.listenTo(this.model, "change:split1_duration", this.checkSplitsLength);
                this.listenTo(this.model, "change:split2_duration", this.checkSplitsLength);
                this.listenTo(this.model, "change:delayCategoryId1", this.filterCodes1);
                this.listenTo(this.model, "change:delayCategoryId2", this.filterCodes2);

                // Listen to changes on delay start and end times
                this.listenTo(this.model, "change:delay1Start change:delay1End change:delay2Start change:delay2End", this.updateDelayTimesDisplay);
            }

            , close: function () {
                this.unbind();
            }

            , preRender: function () {
            }

            , reRender: function () {
            }
            , filterCodes1: function () {
                var that = this;
                that.model.set('delayCategories', that.model.get('delayCategories').filter(x => x.assetId == that.model.get('casterCode')))
                that.model.set('delayCodes1', that.model.get('delayCodes').filter(x => x.parent == that.model.get('delayCategoryId1')))
            }
            , filterCodes2: function () {
                var that = this;
                that.model.set('delayCodes2', that.model.get('delayCodes').filter(x => x.parent == that.model.get('delayCategoryId2')))
            }
        });

        // JUSTIFY DELAY


        Screen.Models.JustifyDelay = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                start: null,
                end: null,
                duration: null,
                durationinMin: null,

                // Split durations
                split1_duration: null,
                split2_duration: null,

                // Calculated delay start and end times

                delayCategoryId: 1,
                commentsDelay: '',
                delayCategories: [],
                delayCodes: [],
                delayCodeId: 1,
                delayCodes1: [],
                casterCode: null,

            },
            initialize: function () {

                this.fetchDelayCategories();
                this.fetchDelayCodes();
                this.set({ durationinMin: this.secondsToHHMMSS(this.attributes.duration) });
            },

            fetchDelayCategories: function () {
                var that = this;
                Core.Json.CallProcedure(app.DatabaseNames.MES + ".DEL.GetDelayCategories", null, {
                    onSuccess: function (data) {
                        if (data && data.Table) {
                            var items = data.Table;

                            that.set({
                                delayCategories: _.map(items, function (m) {
                                    return { value: m.DelayCategoryId, label: m.DelayCategoryName, assetId: m.AssetId / 1000};
                                }),
                            });


                        }
                    },
                    Async: false,
                    Secured: true,
                }, app.ConnectionStrings.app);
            },
            fetchDelayCodes: function () {
                var that = this;
                var QP = new Core.Database.QueryParameters();
                QP.Add("DelayAreaAssetId", "INT", 1);   // Casters root: both casters' codes, never EAF
                Core.Json.CallProcedure(app.DatabaseNames.MES + ".DEL.GetDelayCodes", QP, {
                    onSuccess: function (data) {
                        if (data && data.Table) {
                            var items = data.Table;

                            that.set({
                                delayCodes: _.map(items, function (m) {
                                    return { value: m.DelayCodeId, label: m.DelayCodeName, parent: m.DelayCategoryId };
                                })
                            });
                        }
                    },
                    Async: false,
                    Secured: true,
                }, app.ConnectionStrings.app);
            },
            secondsToHHMMSS: function (d) {
                d = Number(d);
                var h = Math.floor(d / 3600);
                var m = Math.floor(d % 3600 / 60);
                var s = Math.floor(d % 3600 % 60);
                return ((h > 0 ? h + " h " : "") + m + " min " + ((s > 0) ? s + " seg" : ""));
            }

        });


        Screen.Views.JustifyDelay = Backbone.Epoxy.View.extend({
            template: "caster-delays-manager"
            , id: "caster-delays-manager-justify"
            , title: ""
            , className: "modal hide fade modal-wider"
            , bindings: 'data-bind'
            //default not cacheable, change this if you want the view to be cacheable
            // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
            , isCacheable: true
            , initialize: function () {
                _.bindAll(this);

                this.options.MYREFERENCES = {
                    autoRefresh: {
                        enabled: true
                        , toid: null
                    },
                    rowData: null,
                };
                this.bus = this.options.bus;
                if (this.options.viewParams) {
                    this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
                }
                if (!this.model) {
                    this.model = new Screen.Models.JustifyDelay();
                }

                this.options._isRendered = false;
                this.options.sliders = {};

                this.bindEvents();
                this.delegateEvents();
            },

            justifyDelay: function () {
                var that = this;
                var QP = new Core.Database.QueryParameters();

                var model = this.model;



                QP.Add("DelayId", "INT", model.get("id"));
                QP.Add("DelayCodeId", "INT", model.get("delayCodeId"));
                QP.Add("DelayCategoryId", "INT", model.get("delayCategoryId"));
                QP.Add("Comments", "VARCHAR", model.get("commentsDelay"));
                app.CallProcedure(app.DatabaseNames.MES + ".DEL.JustifyDelay", QP, {
                    onSuccess: function (data) {
                        that.bus.trigger('refreshGrid');
                        that.hide();
                        app.views.topMessages.showMessage('Delay Declared', { stay: 5000, });

                    },
                    Secured: true,

                }, app.ConnectionStrings.app);

            },

            events: {
                'click .close, .btn-close': 'handleClose',
                'click #delay_justify_btn': 'justifyDelay',

            },

            handleClose: function (event) {
                event.preventDefault();
                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },

            render: function (container) {
                var that = this;
                var customPath = "/app/pages/caster/caster-delays-manager/";

                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;

                        var startDate = new moment(that.model.get("start"));
                        var endDate = new moment(that.model.get("end"));

                        that.filterCodes();

                        var ctx = {
                            start_date: startDate.format("YYYY-MM-DD"),
                            end_date: endDate.format("YYYY-MM-DD"),
                            start_time: startDate.format("HH:mm:ss"),
                            end_time: endDate.format("HH:mm:ss"),

                        };

                        that.$el.html(tmp(ctx));
                        that.applyBindings();
                        // Ensure events are re-bound after rendering
                        that.delegateEvents();



                        that.options._isRendered = true;

                    }, true, customPath);

                }, customPath, "justify_delay");
            }

            , refresh: function () {
                try {
                    console.log();
                } catch (Error) { }
            }

            , show: function () {

                if (!this.options._isRendered) {
                    this.render();
                    setTimeout(this.show, 100);
                    return;
                }

                var self = this,
                    $el = this.$el;

                //creating modal
                $el.modal({
                    keyboard: false
                    , backdrop: "static"
                });

                $backdrop = $('.modal-backdrop');

                $backdrop.one('click', function () {
                    if (self.options.content && self.options.content.trigger) {
                        self.options.content.trigger('cancel', self);
                    }

                    self.trigger('cancel');
                });

                $(document).one('keyup.dismiss.modal', function (e) {
                    e.which == 27 && self.trigger('cancel');

                    if (self.options.content && self.options.content.trigger) {
                        e.which == 27 && self.options.content.trigger('shown', self);
                    }
                });

                this.on('cancel', function () {
                    self.hide();
                });

                return this;

            }
            , hide: function (data) {
                var self = this,
                    $el = this.$el;

                $el.one('hidden', function onHidden(e) {
                    // Ignore events propagated from interior objects, like bootstrap tooltips
                    if (e.target !== e.currentTarget) {
                        return $el.one('hidden', onHidden);
                    }
                    self.newDelay = data;
                    if (self.options.content && self.options.content.trigger) {
                        self.options.content.trigger('hidden', self);
                    }

                    // self.trigger('hidden');
                    //self.trigger('delaySplitted', data);

                    self.close();
                });

                $el.modal('hide');
            },
            bindEvents: function () {

                this.listenTo(this.model, "change:delayCategoryId", this.filterCodes);

            }

            , close: function () {
                this.unbind();
            }

            , preRender: function () {
            }

            , reRender: function () {
            }
            , filterCodes: function () {
                var that = this;
                that.model.set('delayCategories', that.model.get('delayCategories').filter(x => x.assetId == that.model.get('casterCode')))
                that.model.set('delayCodes1', that.model.get('delayCodes').filter(x => x.parent == that.model.get('delayCategoryId')))
            }
        });


        // NEW DELAY


        Screen.Models.CreateDelay = Backbone.Epoxy.Model.extend({
            defaults: {
                id: null,
                start: null,
                end: null,
                duration: null,
                durationinMin: null,

                // Split durations
                split1_duration: null,
                split2_duration: null,

                // Calculated delay start and end times

                delayCategoryId: 1,
                commentsDelay: '',
                delayCategories: [],
                delayCategoriesCaster1: [],
                delayCategoriesCaster2: [],
                delayCodes: [],
                delayCodeId: 1,
                delayCodesToFilter: [],
                casterCodes: [{value: 1, label: "Caster 1", assetId: 1000}, {value: 2, label: "Caster 2", assetId: 2000}],
                casterCode: null
            },
            computeds: {
                durationinMin: {
                    deps: ["start", "end"],
                    get: function () {
                        const start = moment(this.get("start"), "YYYY-MM-DDTHH:mm");
                        const end = moment(this.get("end"), "YYYY-MM-DDTHH:mm");
                        
                        if (start.isValid() && end.isValid()) {
                            var seconds = end.diff(start, "seconds");
                            return this.secondsToHHMMSS(seconds);
                        }
                        return 0;
                    }
                },
                duration: {
                    deps: ["duration"],
                    get: function () {
                        
                        const start = moment(this.get("start"), "YYYY-MM-DDTHH:mm");
                        const end = moment(this.get("end"), "YYYY-MM-DDTHH:mm");
                        
                        if (start.isValid() && end.isValid()) {
                            return end.diff(start, "seconds");
                        }
                        return 0;
                    }
                }
            },
            initialize: function () {

                this.fetchDelayCategories();
                this.fetchDelayCodes();
                //this.set({ durationinMin: this.secondsToHHMMSS(this.attributes.duration) });
                const now = moment().format("YYYY-MM-DDTHH:mm");
                this.set({ start: now, end: now });
                this.on("change:start change:end", this.updateDurations, this);
            },

            fetchDelayCategories: function () {
                var that = this;
                Core.Json.CallProcedure(app.DatabaseNames.MES + ".DEL.GetDelayCategories", null, {
                    onSuccess: function (data) {
                        if (data && data.Table) {
                            var items = data.Table;

                            that.set({
                                delayCategories: _.map(items, function (m) {
                                    return { value: m.DelayCategoryId, label: m.DelayCategoryName, assetId: m.AssetId / 1000 };
                                }),
                                delayCategoriesCaster1: _.map(_.filter(items, function (m) {
                                    return m.AssetId === 1000;
                                }), function (m) {
                                    return { value: m.DelayCategoryId, label: m.DelayCategoryName, assetId: m.AssetId / 1000 };
                                }),
                                delayCategoriesCaster2: _.map(_.filter(items, function (m) {
                                    return m.AssetId === 2000;
                                }), function (m) {
                                    return { value: m.DelayCategoryId, label: m.DelayCategoryName, assetId: m.AssetId / 1000 };
                                }),
                            });


                        }
                    },
                    Async: false,
                    Secured: true,
                }, app.ConnectionStrings.app);
            },
            fetchDelayCodes: function () {
                var that = this;
                var QP = new Core.Database.QueryParameters();
                QP.Add("DelayAreaAssetId", "INT", 1);   // Casters root: both casters' codes, never EAF
                Core.Json.CallProcedure(app.DatabaseNames.MES + ".DEL.GetDelayCodes", QP, {
                    onSuccess: function (data) {
                        if (data && data.Table) {
                            var items = data.Table;

                            that.set({
                                delayCodes: _.map(items, function (m) {
                                    return { value: m.DelayCodeId, label: m.DelayCodeName, parent: m.DelayCategoryId };
                                }),
                                delayCodesToFilter: _.map(items, function (m) {
                                    return { value: m.DelayCodeId, label: m.DelayCodeName, parent: m.DelayCategoryId };
                                }),

                            });
                        }
                    },
                    Async: false,
                    Secured: true,
                }, app.ConnectionStrings.app);
            },
            secondsToHHMMSS: function (d) {
                d = Number(d);
                var h = Math.floor(d / 3600);
                var m = Math.floor(d % 3600 / 60);
                var s = Math.floor(d % 3600 % 60);
                return ((h > 0 ? h + " h " : "") + m + " min " + ((s > 0) ? s + " seg" : ""));
            },
            updateDurations: function () {
                // Trigger computed recalculation for duration and durationinMin
                this.trigger("change:duration");
                this.trigger("change:durationinMin");
            },

        });


        Screen.Views.CreateDelay = Backbone.Epoxy.View.extend({
            template: "caster-delays-manager"
            , id: "caster-delays-manager-create"
            , title: ""
            , className: "modal hide fade modal-wider"
            , bindings: 'data-bind'
            //default not cacheable, change this if you want the view to be cacheable
            // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
            , isCacheable: true
            , initialize: function () {
                _.bindAll(this);

                this.options.MYREFERENCES = {
                    autoRefresh: {
                        enabled: true
                        , toid: null
                    },
                    rowData: null,
                };
                this.bus = this.options.bus;
                if (this.options.viewParams) {
                    this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
                }
                if (!this.model) {
                    this.model = new Screen.Models.CreateDelay();
                }

                

                this.options._isRendered = false;
                this.options.sliders = {};

                this.bindEvents();
                this.delegateEvents();
            },

            createDelay: function () {
                var that = this;
                var QP = new Core.Database.QueryParameters();

                var model = this.model;



                QP.Add("DelayId", "INT", null);
                QP.Add("DelayCodeId", "INT", model.get("delayCodeId"));
                QP.Add("DelayCategoryId", "INT", model.get("delayCategoryId"));
                QP.Add("Comments", "VARCHAR", model.get("commentsDelay"));
                QP.Add("AssetId", "INT", 1000);
                QP.Add("Start", "DATETIME", model.get("start"));
                QP.Add("End", "DATETIME", model.get("end"));
                app.CallProcedure(app.DatabaseNames.MES + ".DEL.UpsertManualDelay", QP, {
                    onSuccess: function (data) {
                        that.bus.trigger('refreshGrid');
                        that.hide();
                        app.views.topMessages.showMessage('Delay created', { stay: 5000, });

                    },
                    Secured: true,

                }, app.ConnectionStrings.app);

            },

            events: {
                'click .close, .btn-close': 'handleClose',
                'click #new_delay_accept_btn': 'createDelay',

            },

            handleClose: function (event) {
                event.preventDefault();
                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },

            render: function (container) {
                var that = this;
                var customPath = "/app/pages/caster/caster-delays-manager/";

                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.filterCodes();

                        var ctx = {
                            start: that.model.get("start"),
                            end: that.model.get("end"),
                        };

                        that.$el.html(tmp(ctx));
                        that.applyBindings();
                        // Ensure events are re-bound after rendering
                        that.delegateEvents();



                        that.options._isRendered = true;

                    }, true, customPath);

                }, customPath, "new_delay");
            }

            , refresh: function () {
                try {
                    console.log();
                } catch (Error) { }
            }

            , show: function () {

                if (!this.options._isRendered) {
                    this.render();
                    setTimeout(this.show, 100);
                    return;
                }

                var self = this,
                    $el = this.$el;

                //creating modal
                $el.modal({
                    keyboard: false
                    , backdrop: "static"
                });

                $backdrop = $('.modal-backdrop');

                $backdrop.one('click', function () {
                    if (self.options.content && self.options.content.trigger) {
                        self.options.content.trigger('cancel', self);
                    }

                    self.trigger('cancel');
                });

                $(document).one('keyup.dismiss.modal', function (e) {
                    e.which == 27 && self.trigger('cancel');

                    if (self.options.content && self.options.content.trigger) {
                        e.which == 27 && self.options.content.trigger('shown', self);
                    }
                });

                this.on('cancel', function () {
                    self.hide();
                });

                return this;

            }
            , hide: function (data) {
                var self = this,
                    $el = this.$el;

                $el.one('hidden', function onHidden(e) {
                    // Ignore events propagated from interior objects, like bootstrap tooltips
                    if (e.target !== e.currentTarget) {
                        return $el.one('hidden', onHidden);
                    }
                    self.newDelay = data;
                    if (self.options.content && self.options.content.trigger) {
                        self.options.content.trigger('hidden', self);
                    }

                    // self.trigger('hidden');
                    //self.trigger('delaySplitted', data);

                    self.close();
                });

                $el.modal('hide');
            },
            bindEvents: function () {
                this.listenTo(this.model, "change:casterCode", this.filterCategories);
                this.listenTo(this.model, "change:delayCategoryId", this.filterCodes);
            }
            ,
            updateDuration: function () {
                var that = this;

            }

            , close: function () {
                this.unbind();
            }

            , preRender: function () {
            }

            , reRender: function () {
            }
            ,filterCategories: function () {
                var that = this;
                if(that.model.get('casterCode') == 1){
                    that.model.set('delayCategories', that.model.get('delayCategoriesCaster1'));
                    this.filterCodes();
                }
                else {
                    that.model.set('delayCategories', that.model.get('delayCategoriesCaster2'));
                    this.filterCodes();
                }
                
            }
            , filterCodes: function () {
                var that = this;
                    that.model.set('delayCodes', that.model.get('delayCodesToFilter').filter(x => x.parent == that.model.get('delayCategoryId')))
                
            }
        });

        return Screen;
    });