//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',
    'js/d3v4/d3.v4',
    "select2",
    "select2totree",
  'backgrid/grouped-columns',
  'js/jquery.clearsearch/jquery.clearsearch',
  'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',
  'backgrid/calendar-cell',
  'backgrid/moment-cell',
  'js/jquery.timepicker/jquery.timepicker',
    'backgrid/time-cell',
],
    function (app, T, Backgrid, moment, Modal, d3, select2, select2totree) {


    //replace all 'Screen' with your view's name.
    var Screen = {
        Models: {},
        Views: {},
        Collections: {},
    };

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {

            productionDate: new moment().format('MM/DD/YYYY'),

            shiftId: moment().hour() >= 9 && moment().hour()< 21 ?  'D' : 'N',
            crewId: 'C',
            shifts: [],        
            hasData: true,
            isLoading: false,
            tphValues: null,

            showCaster2Data: true,
            showCaster1Data: true,



            itemId: null,
            itemTitle: '',
            itemAssetId: null,
            itemStatusCodeId: null,
            itemLogEntryTypeId: 1,
            itemDate: new moment().format('MM/DD/YYYY'),
            itemTime: new moment().format('HH:mm'),
            itemAuthor: '',
            itemCrew: '',
            itemDescription: '',

            entryModel: {
                itemId: null,
                itemTitle: null,
                itemDate: null,
                itemTime: null,
                itemAuthor: null,
                itemCrew: null,
                itemDescription: null,
                itemAssetId: null,
                itemLogEntryTypeId: null,
                itemStatusCodeId: null,
                itemHeatName: null,
            },
            entryHasChanged: false,
            isModalOpen: false,



            isDropdownEquipmentOpened: false,
            isDropdownStatusOpened: false,
            isDropdownTypeOpened: false,
            isInsideTextarea: false,
            isInsideInputTitle: false,
            isInsideInputDate: false,
            isInsideInputTime: false,

            upsertedId: null,
            defaultProductionDate: new moment().format('MM/DD/YYYY'),
            currentProductionDate: new moment().format('MM/DD/YYYY'),
            currentShiftId: 'D',     

            leftListItems: null,
            rightListItems: null,

            firstTime: true,
        },
        initialize: function () {
            this.timelineCollection = new Screen.Collections.ItemsCollection();
            this.timelineCollectionSaved = new Screen.Collections.ItemsCollectionSaved();
            this.timelineCaster1Collection= new Screen.Collections.ItemsCollection();
            this.timelineCaster2Collection= new Screen.Collections.ItemsCollection();
        },
        computeds: {
            enableSaveChangesBtn: {
                deps: ['entryHasChanged', 'itemId'],
                get: function (hasChanged, itemId) {
                    if (itemId && hasChanged) return true;
                    else return false;
                },
            },
            enableForm: {
                deps: ['itemId'],
                get: function (itemId) {
                    if (itemId) return true;
                    else return false;
                },
            },
        },
        fetchData: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters();
            this.fixedParameters = [
                { Name: '@ProductionDate', Type: 'DATE', Value: new moment(params.productionDate, 'MM/DD/YYYY').format('YYYY-MM-DD'), },
                { Name: '@ShiftId', Type: 'CHAR', Value: params.shiftId },
                { Name: '@FirstTime', Type: 'BIT', Value: params.firstTime },
            ];
            _.each(this.fixedParameters, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });


            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LogBook.GetLogBookByShift',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp) {
                                that.timelineCollection.setDataColl(resp.Table);    
                                that.timelineCollectionSaved.setDataColl(resp.Table);  
                                that.timelineCaster1Collection.setDataColl(that.timelineCollection.filter(x => x.get('CasterName') == 'caster1'))
                                   // = new Screen.Collections.ItemsCollection(that.timelineCollection.filter(x => x.get('CasterName') == 'caster1'));
                                that.timelineCaster2Collection.setDataColl(that.timelineCollection.filter(x => x.get('CasterName') == 'caster2'));
                                    //= new Screen.Collections.ItemsCollection(that.timelineCollection.filter(x => x.get('CasterName') == 'caster2'));
                                that.set({ moreInfo: resp.Table1[0] });
                                that.set({
                                    currentProductionDate: new moment(resp.Table1[0].currentProductionDate, 'YYYY-MM-DD').format('MM/DD/YYYY'),
                                    currentShiftId: resp.Table1[0].currentShiftId,     
                                });
                                if (that.get('firstTime')) {
                                    that.set({
                                        productionDate: new moment(resp.Table1[0].currentProductionDate, 'YYYY-MM-DD').format('MM/DD/YYYY'),
                                        shiftId: resp.Table1[0].currentShiftId,    
                                    })
                                }
                                that.set({ firstTime: false });
                                that.trigger('fetch',resp);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(new Error(resp.Message).stack);
                                else
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);

                                that.set({
                                    isLoading: false,
                                    hasData: false
                                });
                            }
                        }
                        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;
        },
        fetchPickers: function (options) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                opt = _.extend({ async: true, }, options);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LogBook.GetLogBookByShiftCatalogs',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                _.each(resp.Table, function (obj) {
                                    var tableKey = 'Table' + obj.Index;
                                    switch (obj.Name) {
                                        case 'EQUIPMENT':
                                            newItems = [];
                                            that.set('equipment', _.map(resp[tableKey], function (obj) {
                                               
                                                return {
                                                    id: obj.Id,
                                                    parentId: obj.ParentId,
                                                    text: obj.Name,
                                                    eqp: [],
                                                };
                                            }));
                                            break;
                                       
                                        case 'TYPE':
                                            that.set('types', _.map(resp[tableKey], function (obj) {
                                                return {
                                                    id: obj.Id,
                                                    text: obj.Name,
                                                };
                                            }));
                                            break;
                                        case 'STATUS':
                                            that.set('status', _.map(resp[tableKey], function (obj) {
                                                return {
                                                    id: obj.Id,
                                                    text: obj.Name,
                                                };
                                            }));
                                            break;
                                        

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

            return this;
        },
        upsertItem: function (params) {
            try {
                var that = this;
                const {
                    id
                    , title
                    , statusId
                    , typeId
                    , date
                    , time
                    , description
                    , equipmentId
                    , assetId
                } = params;


                const formattedTime = new moment(time, 'h:mm A');
                const convertedTime = formattedTime.format('HH:mm:ss');
     
                const datetime = new moment(date + ' ' + convertedTime, 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
           
                item = [
                    { name: '@Id', type: 'INT', value: id },
                    { name: '@Title', type: 'VARCHAR', value: title },
                    { name: '@StatusCodeId', type: 'INT', value: statusId },
                    { name: '@LogEntryTypeId', type: 'INT', value: typeId },
                    { name: '@Datetime', type: 'DATETIME', value: datetime },
                    { name: '@Description', type: 'VARCHAR', value: description },
                    { name: '@AssetId', type: 'INT', value: assetId },
                    { name: '@EquipmentId', type: 'INT', value: equipmentId },
                    { name: '@LogBookTypeCode', type: 'CHAR(1)', value: 'T' },
                  
                ];
                var qp = new QueryParameters();

                for (var q in item) {
                    qp.Add(item[q].name, item[q].type, item[q].value);

                }
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LogBook.UpsertEntry',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    that.trigger('upserted', resp && resp.Table && resp.Table[0] ? resp.Table[0] : null);
                                    app.views.topMessages.showMessage('Log entry saved', { stay: 5000, });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },


        deleteItem: function (params) {
            try {
                var that = this;
                const { id } = params;

                item = [
                    { name: '@Id', type: 'INT', value: id },

                ];
                var qp = new QueryParameters();

                for (var q in item) {
                    qp.Add(item[q].name, item[q].type, item[q].value);
                    
                }
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LogBook.DeleteLogEntry',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    app.views.topMessages.showMessage('Log entry removed', { stay: 5000, });
                                    that.trigger('removed');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        console.error("Server response not valid.");
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
       

    });

    Screen.Collections.ItemsCollection = Backbone.Collection.extend({
        setDataColl: function (data) {
            var newColl,
                that = this;
            newColl = data;
            that.set(newColl).trigger('fetch', that, data);
        },
    });

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


    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'caster-log-book-by-shift'
        , id: 'caster-log-book-by-shift'
        , title: 'Caster Log Book By Shift'

        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a _refresh method to reset the view without erasing the DOM.
        , isCacheable: false
        , events: function () {
            return {
                'click #forwardNavBtn': this.forwardNavBtn_click,
                'click #backNavBtn': this.backNavBtn_click,
                'click #saveBtn': this.saveBtn_click,
                'click #deleteBtn': this.deleteBtn_click,
                'click #createNewEntryBtn': this.createNewEntry_click,
                'click #shift': this.shift_click,
                'click #redirectToHeatBtn': this.redirectToHeat_click,
            };
        }
        , bindings: 'data-bind'
        , timelineView: 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;
            this.model = new Screen.Models.Main();

            this.bindingSources = {
                timelineCollection: that.model.timelineCollection,
            };

            this.bindEvents();
        }
        , bindEvents: function () {
            this.listenTo(this.model, 'fetch', this.fetched);
            this.listenTo(this.model, 'change:entryModel', this.entry_changed);
            this.listenTo(this.model, 'change:itemTitle change:itemDescription change:itemDate change:itemTime change:itemAssetId change:itemLogEntryTypeId change:itemStatusCodeId', this.form_changed);
            this.listenTo(this.model, 'upserted', this.upserted);
            this.listenTo(this.model, 'removed', this.removed);
            this.listenTo(this.model, 'change:itemId', this.itemId_changed);
        }
        , redirectToHeat_click: function (e) {
            e.preventDefault();
            try {
                var heatName = this.model.get('itemHeatName');
                app.router.navigate(
                    app.router.resolveURL(
                        'caster-heat-report',
                        {
                            heatName: heatName,
                        },
                        false
                    ),
                    { trigger: true, }
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }

        , subscribeProductionDateChanges: function () {
            this.listenTo(this.model, 'change:productionDate', this.productionDate_changed);
        }

        , unsubscribeProductionDateChanges: function () {
            this.stopListening(this.model, 'change:productionDate', this.productionDate_changed);
        }
        , createNewEntry_click: function () {
            var that = this;
            const { equipment } = this.model.toJSON();
            this.setDefaultForm();
            this.CreateEntryModal = new Screen.Views.CreateEntryModal({
                parent: this,
                eqpData: that.convertEquipment(equipment),
                status: that.model.get('status'),
                types: that.model.get('types'),

            });
            this.CreateEntryModal.show();

        }
        , changeSelectedItem: function (item) {
            if (item) {
                this.model.set({
                    itemId: item.ID,
                    itemTitle: item.Title,
                    itemDate: new moment(item.Time).format('MM/DD/YYYY'),
                    itemTime: new moment(item.Time).format('h:mm A'),
                    itemAuthor: item.Author,
                    itemCrew: item.CrewID,
                    itemDescription: item.Description,
                    itemHeatName: item.HeatName,

                });
                //This is the way to set the value of a select2totree element
                $('#treeSelectContainer').val(item.AssetId).trigger('select2:select');
                var selectedOption = $('#treeSelectContainer').find('option:selected');
                var selectedLabel = selectedOption.text();
                $('.select2-selection__rendered').text(selectedLabel);




                $('#type').val(item.LogEntryTypeID);
                $('#type').select2().trigger('change');
                $('#status').val(item.StatusCodeId);
                $('#status').select2().trigger('change');


                this.model.set({
                    entryModel: {
                        itemId: item.ID,
                        itemTitle: item.Title,
                        itemDate: new moment(item.Time).format('MM/DD/YYYY'),
                        itemTime: new moment(item.Time).format('h:mm A'),
                        itemAuthor: item.Author,
                        itemCrew: item.CrewID,
                        itemDescription: item.Description,
                        itemAssetId: item.AssetId,
                        itemLogEntryTypeId: item.LogEntryTypeID,
                        itemStatusCodeId: item.StatusCodeId,
                        itemHeatName: item.HeatName,
                    }
                });
            }
            else {
                this.model.set({
                    entryModel: {
                        itemId: null,
                        itemTitle: null,
                        itemDate: null,
                        itemTime: null,
                        itemAuthor: null,
                        itemCrew: null,
                        itemDescription: null,
                        itemAssetId: null,
                        itemLogEntryTypeId: null,
                        itemStatusCodeId: null,
                        itemHeatName: null,
                    }
                });
            }


            if (item.HeatName) {
                titleContent = $('#title');
                if (titleContent.hasClass('title-input')) {
                    titleContent.removeClass('title-input');
                    titleContent.addClass("title-input-with-button");
                    $('.titleContainer')[0].insertAdjacentHTML('beforeend', '<button id="redirectToHeatBtn" class="btn btn-primary"><i class= "fa fa-share-square-o" ></i ></button>');
                }
                else {
                   
                }

            }
            else {
                titleContent = $('#title');
                if (titleContent.hasClass('title-input-with-button')) {
                    titleContent.removeClass("title-input-with-button");
                    titleContent.addClass("title-input");
                    $('.titleContainer')[0].removeChild($('.titleContainer')[0].lastChild)
                }
                
            }
            
        }
        , convertEquipment: function (rawEquipment, parentId = null) {
            var that = this;
            const result = [];
            _.each(rawEquipment, function (item) {
                if (item.parentId === parentId) {
                    const newItem = { id: item.id, text: item.text, inc: that.convertEquipment(rawEquipment, item.id) };
                    result.push(newItem);
                }
            });

            return result;
        }
        , renderSelectInputs: function () {

            var that = this;
            const { equipment } = this.model.toJSON();
            var eqpData = this.convertEquipment(equipment);

            const statusSelect = new Screen.Views.Select({
                el: '#status',
                data: that.model.get('status'),
            });
            const typeSelect = new Screen.Views.Select({
                el: '#type',
                data: that.model.get('types'),
            });
            const equipmentSelect = new Screen.Views.Select({
                el: '#treeSelectContainer',
                data: eqpData,
                selectType: 'tree',
            });

        }

        , saveBtn_click: function (e) {
            e.preventDefault();
            const id = this.model.get('itemId');
            const title = document.getElementById("title").value;
            const statusId = document.getElementById("status").value;
            const typeId = document.getElementById("type").value;
            const date = document.getElementById("dateForm").value;
            const time = document.getElementById("timeForm").value;
            const description = document.getElementById("description").value;
            const equipmentId = document.getElementById("treeSelectContainer").value;
            const assetId = document.getElementById("treeSelectContainer").value;


            this.model.upsertItem({
                id
                , title
                , statusId
                , typeId
                , date
                , time
                , description
                , equipmentId
                , assetId
            })
        }
        , deleteBtn_click: function (e) {
            e.preventDefault();
            var that = this;

            var modal = new Modal.Views.Main({
                focusOk: false,
                focusSelector: '#btn-continue',
                title: "Remove entry",
                message: "The current entry will be removed. Do you want to continue?",
                buttons_type: "CONTINUE-CANCEL",
            });
            this.listenToOnce(modal, "continue", function (modal) {

                that.model.deleteItem({
                    id: that.model.get('itemId'),
                })

                that.model.set({
                    entryHasChanged: false,
                    isModalOpen: false
                });
                that.setDefaultForm();
            });
            this.listenToOnce(modal, "cancel", function (modal) {
                that.model.set({ isModalOpen: false });
            });
            this.model.set({ isModalOpen: true });
            modal.show();


        }
        , forwardNavBtn_click: function () {
            this.UpdateNav(true);
        }
        , backNavBtn_click: function () {
            this.UpdateNav(false);
        }

      
              
        ,shift_click: function () {
            const currentShiftId = this.model.get('shiftId');

            this.model.set({
                shiftId: currentShiftId === 'N' ? 'D' : 'N',
            });
            this.updateURLandRefresh();

        },
        productionDate_changed: function () {
            this.updateURLandRefresh();
        },
        updateURLandRefresh: function () {
            this.UpdateURL();
            this.refresh();
        },
        itemId_changed: function () {
            if (this.model.get('itemId')) {
                $('#treeSelectContainer').prop('disabled', false).val(null).trigger('change');
                $('#type').prop('disabled', false).val(null).trigger('change');
                $('#status').prop('disabled', false).val(null).trigger('change');

            } else {

                $('#treeSelectContainer').prop('disabled', true).val(null).trigger('change');
                $('#type').prop('disabled', true).val(null).trigger('change');
                $('#status').prop('disabled', true).val(null).trigger('change');
            }
        },
        upserted: function (model) {
            this.setDefaultForm();
            this.model.set({ upsertedId: model.ID })
            var params = this.model.toJSON();


            this.model.fetchData({
                productionDate: params.productionDate,
                shiftId: params.shiftId,
                firstTime: params.firstTime,
            });
        },
        removed: function (model) {
            var params = this.model.toJSON();
            this.model.fetchData({
                productionDate: params.productionDate,
                shiftId: params.shiftId,
                firstTime: params.firstTime,
            });
        },
        form_changed: function (e) {
            var that = this;
            var keys = Object.keys(e.changed);
            var key = keys[0];

            const entryModel = this.model.get('entryModel');

            const newEntryModel = { ...entryModel };
            if (key !== 'itemId') {
                newEntryModel[key] = e.changed[key];
                this.model.set({
                    entryModel: newEntryModel
                })

            }
        },
        entry_changed: function (e) {
            var that = this;
            var currentModel = this.model.get('entryModel');
            var savedCollection = that.model.timelineCollectionSaved.toJSON();
            var savedModel = _.where(savedCollection, { itemId: currentModel.itemId })[0];
            

            if (currentModel && savedModel && currentModel.itemId === savedModel.itemId) {
                if (currentModel.itemTitle === savedModel.itemTitle
                    && currentModel.itemDescription === savedModel.itemDescription
                    && currentModel.itemDate === savedModel.itemDate
                    && currentModel.itemTime === savedModel.itemTime
                    && currentModel.itemAssetId === savedModel.itemAssetId
                    && currentModel.itemLogEntryTypeId === savedModel.itemLogEntryTypeId
                    && currentModel.itemStatusCodeId === savedModel.itemStatusCodeId
                ) {
                    this.model.set({ entryHasChanged: false });
                } else {
                    this.model.set({ entryHasChanged: true });
                }
            }
        },

        openModal: function () {
            var that = this;
            var modal = new Modal.Views.Main({
                focusOk: false,
                focusSelector: '#btn-continue',
                title: "Unsaved changes",
                message: "The current entry had changed. Do you want to continue and discard the changes?",
                buttons_type: "CONTINUE-CANCEL",
            });
            this.listenToOnce(modal, "continue", function (modal) {
                that.model.set({
                    entryHasChanged: false,
                    isModalOpen: false
                });
                that.setDefaultForm();
            });
            this.listenToOnce(modal, "cancel", function (modal) {
                that.model.set({ isModalOpen: false });
            });
            this.model.set({ isModalOpen: true });
            modal.show();


        },

        fetched: function (resp) {
            this.model.set({
                isLoading: false,
                hasData: (resp && resp.Table && resp.Table.length > 0) ? true : false,
            });

            let coll = this.model.timelineCollection;
            let upsertedId = this.model.get('upsertedId');
            this.model.get('upsertedId')
            if (upsertedId) {

                let model = coll.findWhere({ ID: upsertedId });
                let index = coll.indexOf(model);
                this.highlightItem(index)

                this.model.set({ upsertedId: null });
            }

            this.placeRightLiElements();
            this.bindHighlightEvents();
        },
        placeRightLiElements: function () {
            // Get the ul elements and li elements with class "right"
            const rightList = document.querySelector('#timeline-caster2');
            const rightItems = document.querySelectorAll('.caster2');
            
            // Move the li elements to the right ul element
            rightItems.forEach(item => {
                rightList.appendChild(item);
            });
        },

        
        subscribeTextareaDescriptionChanges: function () {
            var that = this;
            const textInput = document.getElementById('description');
            let inputContent = '';

            const debouncedInputChange = _.debounce(function () {
                let trimmedValue = textInput.value;
                const prevModel = that.model.get('entryModel');
                let newEntryModel = { ...prevModel };
                if (textInput.value === '') {
                    inputContent = '';
                    newEntryModel.itemDescription = inputContent;
                } else {
                    inputContent = trimmedValue;
                    newEntryModel.itemDescription = inputContent;
                }
                that.model.set({
                    entryModel: newEntryModel
                })
            }, 300);

            textInput.addEventListener('input', debouncedInputChange);

        },
        subscribeInputChanges: function () {
            var that = this;
            const textInput = document.getElementById('title');
            let inputContent = '';

            const debouncedInputChange = _.debounce(function () {
                let trimmedValue = textInput.value;
                const prevModel = that.model.get('entryModel');
                let newEntryModel = { ...prevModel };
                if (textInput.value === '') {
                    inputContent = '';
                    newEntryModel.itemTitle = inputContent;
                } else {
                    inputContent = trimmedValue;
                    newEntryModel.itemTitle = inputContent;
                }
                that.model.set({
                    entryModel: newEntryModel
                })
            }, 300);

            textInput.addEventListener('input', debouncedInputChange);

        },
        subscribeEquipmentChanges: function () {
            var that = this;
            $('#treeSelectContainer').on('change', function () {
                //var selectedOption1 = $(this).find('option:selected');
                //var selectedValue1 = selectedOption1.val();
                if (that.model.get('itemId')) {


                    var selectedOption = $(this).find('option:selected');
                    var selectedValue = selectedOption.val();

                    const entryModel = that.model.get('entryModel');
                    const newEntryModel = { ...entryModel };
                    const key = 'itemAssetId';

                    newEntryModel[key] = parseInt(selectedValue);
                    that.model.set({
                        entryModel: newEntryModel
                    })

                }
            });
            $('#treeSelectContainer').on('select2:opening', function () {
                that.model.set({ isDropdownEquipmentOpened: true });
            });

            $('#treeSelectContainer').on('select2:closing', function () {
                that.model.set({ isDropdownEquipmentOpened: false });
            });



        },
        subscribeTypeChanges: function () {
            var that = this;
            $('#type').on('change', function () {
                if (that.model.get('itemId')) {

                    var selectedOption = $(this).find('option:selected');
                    var selectedValue = selectedOption.val();

                    const entryModel = that.model.get('entryModel');
                    const newEntryModel = { ...entryModel };
                    const key = 'itemLogEntryTypeId';

                    newEntryModel[key] = parseInt(selectedValue);
                    that.model.set({
                        entryModel: newEntryModel
                    })


                }
            });

            $('#type').on('select2:opening', function () {
                that.model.set({ isDropdownTypeOpened: true });
            });

            $('#type').on('select2:closing', function () {
                that.model.set({ isDropdownTypeOpened: false });
            });
        },

        subscribeStatusChanges: function () {
            var that = this;
            $('#status').on('change', function () {
                if (that.model.get('itemId')) {


                    var selectedOption = $(this).find('option:selected');
                    var selectedValue = selectedOption.val();

                    const entryModel = that.model.get('entryModel');
                    const newEntryModel = { ...entryModel };
                    const key = 'itemStatusCodeId';

                    newEntryModel[key] = parseInt(selectedValue);
                    that.model.set({
                        entryModel: newEntryModel
                    })
                }
            });

            $('#status').on('select2:opening', function () {
                that.model.set({ isDropdownStatusOpened: true });
            });

            $('#status').on('select2:closing', function () {
                that.model.set({ isDropdownStatusOpened: false });
            });
        }       
        , bindHighlightEvents: function () {
            var that = this;
            const leftListItems  = document.querySelectorAll('.caster1-items-grid-container tr');
            const rightListItems = document.querySelectorAll('.caster2-items-grid-container tr');           


            let currentList = leftListItems; // Initially set the current list to the left list
            let selectedIndex = null; // Initially set the index of the highlighted element
            // Add click event listener to each td element in the left list
            leftListItems.forEach((td, index) => {
                td.addEventListener('click', () => {
                    currentList = leftListItems;
                    selectedIndex = index;
                    that.highlightItem(currentList, selectedIndex, 'caster1' );
                });
            });

            // Add click event listener to each li element in the right list
            rightListItems.forEach((td, index) => {
                td.addEventListener('click', () => {
                    currentList = rightListItems;
                    selectedIndex = index;
                    that.highlightItem(currentList, selectedIndex, 'caster2');
                });
            });

            // Keyboard navigation using arrow keys
            document.addEventListener('keydown', (e) => {
                const key = e.key;
                if (that.model.get('isInsideInputTime') || that.model.get('isInsideInputDate') || that.model.get('isDropdownStatusOpened') || that.model.get('isDropdownEquipmentOpened') || that.model.get('isDropdownTypeOpened') || that.model.get('isInsideTextarea') || that.model.get('isInsideInputTitle')) return;

                if (key === 'ArrowUp' && selectedIndex > 0) {
                    // Move selection up
                    selectedIndex--;
                    if (currentList === rightListItems) {
                        that.highlightItem(currentList, selectedIndex, leftListItems.length);
                    } else {
                        that.highlightItem(currentList, selectedIndex);
                    }
                } else if (key === 'ArrowDown' && selectedIndex < currentList.length - 1) {
                    // Move selection down
                    selectedIndex++;
                    if (currentList === rightListItems) {
                        that.highlightItem(currentList, selectedIndex, leftListItems.length);
                    } else {
                        that.highlightItem(currentList, selectedIndex);
                    }
                } else if (key === 'ArrowLeft') {
                    // Switch to the left list
                    if (currentList === rightListItems) {
                        currentList = leftListItems;
                        selectedIndex = Math.min(selectedIndex, currentList.length - 1);
                        that.highlightItem(currentList, selectedIndex);
                    }
                } else if (key === 'ArrowRight') {
                    // Switch to the right list
                    if (currentList === leftListItems) {
                        currentList = rightListItems;
                        selectedIndex = Math.min(selectedIndex, currentList.length - 1);
                        that.highlightItem(currentList, selectedIndex, leftListItems.length);
                    }
                }
            });
        }

        ,highlightItem: function(list, index ,casterName) {
            var that = this;
            const previousHighlighted = document.querySelector('.highlighted');
            if (previousHighlighted) {
                previousHighlighted.classList.remove('highlighted');
            }

            if (index !== null) {
                var selectedModel = null;
                if (casterName == 'caster1') {
                    selectedModel = that.model.timelineCaster1Collection.at(index-2);
                }
                else {
                    selectedModel = that.model.timelineCaster2Collection.at(index-2);
                } 
                
                if (selectedModel) {
                    that.changeSelectedItem(selectedModel.toJSON());
                    list[index].classList.add('highlighted');
                }
            }

        },        
        subscribeInputTimeChanges: function () {
            var that = this;
            // Event handler for textarea focus
            $('#timeForm').on('focus', function () {
                that.model.set({ isInsideInputTime: true });
            });

            // Event handler for textarea blur
            $('#timeForm').on('blur', function () {
                that.model.set({ isInsideInputTime: false });
            });

        },
        subscribeInputDateChanges: function () {
            var that = this;
            // Event handler for textarea focus
            $('#dateForm').on('focus', function () {
                that.model.set({ isInsideInputDate: true });
            });

            // Event handler for textarea blur
            $('#dateForm').on('blur', function () {
                that.model.set({ isInsideInputDate: false });
            });

        },
        subscribeInputTitleChanges: function () {
            var that = this;
            // Event handler for textarea focus
            $('#title').on('focus', function () {
                that.model.set({ isInsideInputTitle: true });
            });

            // Event handler for textarea blur
            $('#title').on('blur', function () {
                that.model.set({ isInsideInputTitle: false });
            });

        },
        subscribeTextareaChanges: function () {
            var that = this;
            // Event handler for textarea focus
            $('textarea').on('focus', function () {
                that.model.set({ isInsideTextarea: true });
            });

            // Event handler for textarea blur
            $('textarea').on('blur', function () {
                that.model.set({ isInsideTextarea: false });
            });

        }
        , render: function (container, viewParams) {
            var that = this;

            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;
            var flag = false;
            //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) {
                    //getInternationalizationData
                    if (!that.options.i18n) that.options.i18n = {};

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

                            that.timelineView = Screen.Views.Timeline.extend({
                                template: Handlebars.compile(that.$el.find('#TimelineViewTemplate').html()),
                            });

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


                            that.$el.find('.input-date').datepicker();
                            that.$el.find('#timeForm').timepicker({
                                showMeridian: true,
                                showSeconds: false,
                                //secondStep: 0,
                                minuteStep: 1,
                            });
                            // Load pickers synchronously
                            that.model.fetchPickers({ async: false });

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

                            if (fixedParams.productionDate && fixedParams.shiftId) {
                                fixedParams.productionDate = new moment(fixedParams.productionDate, 'YYYYMMDD').format('MM/DD/YYYY');
                                fixedParams.shiftId = fixedParams.shiftId;
                                that.model.set({ firstTime: false });
                            }
                            
                            that.model.set(fixedParams);
                            // refresh collection

                            that.renderSelectInputs();
                            that.subscribeEquipmentChanges();
                            that.subscribeTypeChanges();
                            that.subscribeStatusChanges();
                            that.subscribeTextareaChanges();
                            that.subscribeInputTitleChanges();
                            that.subscribeInputTimeChanges();
                            that.subscribeInputDateChanges();
                            that.subscribeInputChanges();
                            that.subscribeTextareaDescriptionChanges();
                            that.subscribeProductionDateChanges();
                            that.refresh();
                            that.buildGrid();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        }
    , buildGrid: function () {
        try {
            var that = this;
            var gridCaster1 = new Backgrid.Grid({
                className: 'backgrid table table-hover table-condensed',
                columns: [

                    {
                        name: 'Timestamp',
                        editable: false,
                        label: 'Timestamp',
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell ',
                        }),
                    },

                    {
                        name: 'Title',
                        editable: false,
                        label: 'Title',
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell ',
                        }),
                    },
                    {
                        name: 'Description',
                        editable: false,
                        label: 'Description',
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell ',
                        }),
                    }

                ],
                header: Backgrid.Extension.GroupedHeader.extend({
                    columnLayout:
                        [
                            {
                                name: 'Caster 1', children:
                                    [
                                        { name: 'Timestamp' }
                                        , { name: 'Title' }
                                        , { name: 'Description' }
                                    ]

                            },
                        ],
                    initialize: function (options) {
                        Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                    },
                    render: function () {
                        var that = this;
                        Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                        return this;
                    },
                }),
                collection: that.model.timelineCaster1Collection,
            });

            var gridCaster2 = new Backgrid.Grid({
                className: 'backgrid table table-hover table-condensed',
                columns: [

                    {
                        name: 'Timestamp',
                        editable: false,
                        label: 'Timestamp',
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell ',
                        }),
                    },

                    {
                        name: 'Title',
                        editable: false,
                        label: 'Title',
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell ',
                        }),
                    },
                    {
                        name: 'Description',
                        editable: false,
                        label: 'Description',
                        cell: Backgrid.StringCell.extend({
                            className: 'string-cell align-center-cell ',
                        }),
                    }

                ],
                header: Backgrid.Extension.GroupedHeader.extend({
                    columnLayout:
                        [
                            {
                                name: 'Caster 2', children:
                                    [
                                        { name: 'Timestamp' }
                                        , { name: 'Title' }
                                        , { name: 'Description' }
                                    ]

                            },
                        ],
                    initialize: function (options) {
                        Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                    },
                    render: function () {
                        var that = this;
                        Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                        return this;
                    },
                }),
                collection: that.model.timelineCaster2Collection,
            });
            that.$el.find('.caster1-items-grid-container').append(gridCaster1.render().el);
            that.$el.find('.caster2-items-grid-container').append(gridCaster2.render().el);

        }
        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
    }
    , refresh: function () {
        try {
            var params = this.model.toJSON();
            this.model.timelineCollection.reset();
            this.model.timelineCollectionSaved.reset();  
            this.setDefaultForm();
            this.model.set({
                isLoading: true,
                hasData: false,
            })
            // reload collections 
            this.model.fetchData({
                productionDate: params.productionDate,
                shiftId: params.shiftId,
                firstTime: params.firstTime,
            });

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

        const productionDate = this.model.get('productionDate');
        this.model.set({
            itemId: null,
            itemTitle: '',
            itemAssetId: 1,
            itemStatusCodeId: 1,
            itemLogEntryTypeId: 1,
            itemDate: productionDate,
            itemTime: new moment().format('h:mm A'),
            itemAuthor: '',
            itemCrew: '',
            itemDescription: '',
        });

        this.model.set({
            entryModel: {
                itemId: null,
                itemTitle: null,
                itemDate: null,
                itemTime: null,
                itemAuthor: null,
                itemCrew: null,
                itemDescription: null,
                itemAssetId: null,
                itemLogEntryTypeId: null,
                itemStatusCodeId: null,
            }
        });
        this.highlightItem(null);
    },
    UpdateNav: function (nav) {
        var that = this;
        var params = this.model.toJSON();
        if (!that.model.get('entryHasChanged')) {
            that.unsubscribeProductionDateChanges();
            if (nav && that.model.get('shiftId') === 'N')
                that.model.set('productionDate', new moment(params.productionDate, 'MM/DD/YYYY').add(1, 'day').format('MM/DD/YYYY'));

            if (!nav && this.model.get('shiftId') === 'D')
                that.model.set('productionDate', new moment(params.productionDate, 'MM/DD/YYYY').subtract(1, 'day').format('MM/DD/YYYY'));


            if (that.model.get('shiftId') === 'N') that.model.set('shiftId', 'D');
            else if (that.model.get('shiftId') === 'D') that.model.set('shiftId', 'N');

            that.updateURLandRefresh();

            that.subscribeProductionDateChanges();
        } else {
            if (($('.modal.in').length == 0) && !that.model.get('isModalOpen')) that.openModal();
        }
    }

    , UpdateURL: function () {
        try {
            var params = this.model.toJSON();
            app.router.navigate(
                app.router.resolveURL(
                    app.router.currentModule,
                    _.extend(
                        {},
                        params,
                        {
                            productionDate: new moment(params.productionDate, "MM/DD/YYYY").format("YYYYMMDD"),
                        }
                    ),
                    false
                ),
                { trigger: false, }
            );
        }
        catch (e) { console.error((e.stack) ? e.stack : new Error(e).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.remove();
        this.unbindViewScopedEvents();
        this.unbind();      
       
    }
    , show: function () {
        this.options.state = app.view_states.shown;

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

        this.$el.hide();
        this.unbind();
        this.stopListening();
    }
    , preRender: function () {
        app.models.subnavbar.set('subnavbar', false);
    }
    , reRender: function (viewParams) {
        try {
            this.refresh();
        } catch (Error) { }
    }


});




    Screen.Views.Timeline = Backbone.Epoxy.View.extend({
        tagName: 'li',
        className: 'box',
        initialize: function (opt) {
            this.model = opt.model;
            var descr = this.model.get('Description');
            var title = this.model.get('Title');
            this.model.set({
                TruncatedDescription: descr ? (descr.length > 60 ? descr.substring(0, 57) + "..." : descr) : '',
                TruncatedTitle: title ? (title.length > 25 ? title.substring(0, 22) + "..." : title) : '',
            });
            this.bindEvents();
            this.render();
        },
        bindEvents: function () {
        },
        render: function () {          
            var casterName = this.model.get('CasterName');
            this.$el.html(this.template(this.model.toJSON()));
            this.$el.addClass(casterName);
            return this;
        },
    });

    Screen.Views.Select = Backbone.Epoxy.View.extend({
        el: null,
        data: null,
        maximumSelectionLength: null,
        selectType: 'default', // default, tree

        initialize: function (opt) {
            this.el = opt.el;
            this.data = opt.data;
            this.maximumSelectionLength = opt.maximumSelectionLength ? opt.maximumSelectionLength : null;
            this.selectType = opt.selectType ? opt.selectType : 'default';

            this.render();
        },
        render: function () {
            var that = this;
            if (that.maximumSelectionLength) this.$el.attr("multiple", true);

            if (this.selectType === 'tree') {
                this.$el.select2ToTree({
                    treeData: {
                        dataArr: that.data,
                    },
                    expandSelectedItemParents: true,
                    maximumSelectionLength: that.maximumSelectionLength,

                });
                this.$el.select2ToTree({ expandSelectedItemParents: true });
                this.$el.prop('disabled', true).trigger('change');
            } else {
                this.$el.select2({
                    data: that.data
                });
                this.$el.prop('disabled', true).trigger('change');
            }
        },
    })

    Screen.Models.ItemsCollectionSaved = Backbone.Epoxy.Model.extend({
        parse: function (item) {
            var result = {
                itemId: item.ID,
                itemTitle: item.Title,
                itemDate: new moment(item.Time).format('MM/DD/YYYY'),
                itemTime: new moment(item.Time).format('h:mm A'),
                itemAuthor: item.Author,
                itemCrew: item.CrewID,
                itemDescription: item.Description,
                itemAssetId: item.AssetId,
                itemLogEntryTypeId: item.LogEntryTypeID,
                itemStatusCodeId: item.StatusCodeId,

            };
            return result;
        },
    });

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

    Screen.Models.CreateEntryModal = Backbone.Epoxy.Model.extend({
        defaults: {
            errorMsg: '',
            processing: false,

            itemTitle: '',
            itemAssetId: 1,
            itemStatusCodeId: 1,
            itemLogEntryTypeId: 1,  
            itemDate: new moment().format('MM/DD/YYYY'),
            itemTime: new moment().format('h:mm A'),            
            itemDescription: '',

        },
        computeds: {
            enableCreateEntryBtn: {
                deps: ['itemTitle', 'itemDescription'],
                get: function (title, description) {
                    if (title && title !== '' && description && description !== '') return true;
                    else return false;
                },
            },
        }

    });


    Screen.Views.CreateEntryModal = Backbone.Epoxy.View.extend({
        template: 'caster-log-book-by-shift',
        id: 'caster-log-book-by-shift-modal',
        className: "modal hide fade",
        //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.
        bindings: "data-bind",
        isCacheable: false,
        events: function () {
            return {
                "click #saveBtnModal": 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 #redirectToHeatBtn": this.redirectToHeat_click,
            };
        },

        container: null,
        content: null,
        disposed: false,
        isRendered: false,
        preventDispose: false,
        visible: false,


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

            this.parent = options.parent;
            parentModel = this.parent.model.toJSON();

            let now = new moment().format('h:mm A');
            let time = now.slice(0, -2);

            let currProductionDate = new moment(parentModel.moreInfo.currentProductionDate).format('MM/DD/YYYY');
            let currShiftId = parentModel.moreInfo.currentShiftId;

            var timeModal = null;
            if (parentModel.productionDate === currProductionDate && parentModel.shiftId === currShiftId) {            
                timeModal = moment().hour() >= 0 && moment().hour() < 12 ? time + 'AM' : time + 'PM';
            } else {
                timeModal = parentModel.shiftId === 'D' ? '09:01 AM' : '09:01 PM';
            }

            this.model.set({
                eqpData: options.eqpData,
                status: options.status,
                types: options.types,
                itemDate: new moment(parentModel.productionDate, 'MM/DD/YYYY').format('MM/DD/YYYY'),
                itemTime: new moment(timeModal,'h:mm A').format('h:mm A'),
            });

            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/caster-log-book-by-shift/';

            T.render.call(
                this,
                this.template,
                function (tmp) {
                    //getInternationalizationData
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.i18n[that.template] = i18nJED;
                            //loading the view and appeding it to the views's $el.
                            that.$el.html(tmp(that.model.toJSON()));
                            that.applyBindings();
                            that.$el.find('.input-date-modal').datepicker();
                            that.$el.find('#timeFormModal').timepicker({
                                showMeridian: true,
                                showSeconds: false,
                                //secondStep: 0,
                                minuteStep: 1,
                            });
                          
                            that.isRendered = true;

                            that.trigger("render");
                        },
                        true,
                        customPath
                    );


                }, customPath, "create_new_entry_modal");
        },

        subscribeTextareaDescriptionChanges: function () {
            var that = this;
            const textInput = document.getElementById('descriptionModal');
            let inputContent = '';

            const debouncedInputChange = _.debounce(function () {
                let trimmedValue = textInput.value;
                if (textInput.value === '') {
                    inputContent = '';
                    that.model.set({ itemDescription: inputContent });
                } else {
                    inputContent = trimmedValue;
                    that.model.set({ itemDescription: inputContent });
                }
            }, 300);

            textInput.addEventListener('input', debouncedInputChange);

        },
        subscribeInputChanges: function () {
            var that = this;
            const textInput = document.getElementById('titleModal');
            let inputContent = '';

            const debouncedInputChange = _.debounce(function () {
                let trimmedValue = textInput.value;
                const prevModel = that.model.get('entryModel');
                let newEntryModel = { ...prevModel };
                if (textInput.value === '') {
                    inputContent = '';
                    that.model.set({ itemTitle: inputContent });
                } else {
                    inputContent = trimmedValue;
                    that.model.set({ itemTitle: inputContent });
                }
                that.model.set({
                    entryModel: newEntryModel
                })
            }, 300);

            textInput.addEventListener('input', debouncedInputChange);

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

            //this.model.set({
            //    errorMsg: "",
            //    processing: true,
            //});

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

            return this;
        },

        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenToOnce(this, "render", this.view_render);
        },
        close: function () {

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

                    //Do not close the modal like we do with others to prevent a rerender every time that is displayed.
                    this.remove();
                    this.unbind();

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

        acceptBtn_click: function (e) {
            try {
                var attrs = this.model.toJSON();

                const title = document.getElementById("titleModal").value;
                const statusId = document.getElementById("statusModal").value;
                const typeId = document.getElementById("typeModal").value;
                const date = document.getElementById("dateFormModal").value;
                const time = document.getElementById("timeFormModal").value;
                const description = document.getElementById("descriptionModal").value;
                const equipmentId = document.getElementById("treeSelectContainerModal").value;
                const assetId = document.getElementById("treeSelectContainerModal").value;

                this.parent.model.upsertItem({
                    id : null
                    , title
                    , statusId
                    , typeId
                    , date
                    , time
                    , description
                    , equipmentId
                    , assetId
                })
                this.close();

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        form_submit: function (e) {
            try {
                e.preventDefault();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        modal_keypress: function (e) {
            try {
                var attrs = this.model.toJSON();

                //if (((e.which == 13) && (e.shiftKey == false))
                //    && (attrs.processing == false)) {
                //    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();
                this.renderForm();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        view_render: function () {
            try {
                this.show();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        renderForm: function () {
            var that = this;
            const equipmentSelect = new Screen.Views.Select({
                el: '#treeSelectContainerModal',
                data: that.model.get('eqpData'),
                selectType: 'tree',
            });
            const statusSelect = new Screen.Views.Select({
                el: '#statusModal',
                data: that.model.get('status'),
            });
            const typeSelect = new Screen.Views.Select({
                el: '#typeModal',
                data: that.model.get('types'),
            });

            $('#treeSelectContainerModal').prop('disabled', false).val(null).trigger('change');
            $('#typeModal').prop('disabled', false).val(null).trigger('change');
            $('#statusModal').prop('disabled', false).val(null).trigger('change');

            this.subscribeEquipmentChanges();
            this.subscribeTypeChanges();
            this.subscribeStatusChanges();
            this.subscribeInputChanges();
            this.subscribeTextareaDescriptionChanges();
        },
        subscribeEquipmentChanges: function () {
            var that = this;
            $('#treeSelectContainerModal').on('change', function () { 
                var selectedOption = $(this).find('option:selected');
                var selectedValue = selectedOption.val();
                that.model.set({
                    itemAssetId: selectedValue
                });
            });
        },
        subscribeTypeChanges: function () {
            var that = this;
            $('#typeModal').on('change', function () {
                var selectedOption = $(this).find('option:selected');
                var selectedValue = selectedOption.val();
                that.model.set({
                    itemLogEntryTypeId: selectedValue
                });
            });

        },
        subscribeStatusChanges: function () {
            var that = this;
            $('#statusModal').on('change', function () {
                var selectedOption = $(this).find('option:selected');
                var selectedValue = selectedOption.val();
                that.model.set({
                    itemStatusCodeId: selectedValue
                });

            });
        },

        redirectToHeat_click: function (e) {
            console.log(this);
            e.preventDefault();
        }

    });

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

});