<script>
        (function() {

            let numSectionsPendingInitialization = 0;

            function init() {

                $(document)
                    .off('keydown.capture-print')
                    .on('keydown.capture-print', function(_e) {
                        if(_e.which === 80 && _e.ctrlKey) {
                            window.print(); // use "lhs" frame for printing, not "top"
                            return false;
                        }
                    });

                $(document)
                    .off('change.check-book-fu-appt', '.fu-appt-container [name="is_follow_up_needed"]')
                    .on('change.check-book-fu-appt', '.fu-appt-container [name="is_follow_up_needed"]', function() {
                        let parent = $(this).closest('.fu-appt-container');
                        let choice = +(parent.find('[name="is_follow_up_needed"]:checked').val());
                        if(choice) {
                            parent.find('.no-fu-memo-form').addClass('d-none');
                            openDynamicStagPopup(
                                '{{route('patients.view.calendar', ['patient' => $patient])}}?opUid={{$note->hcpPro ? $note->hcpPro->uid : ''}}&fromNoteUid={{$note->uid}}',
                                'patient-calendar-{{$patient->id}}',
                                'Book follow-up appointment for {{$patient->displayName()}}',
                                true,
                                'medium-large fit-height'
                            );
                        }
                        else {
                            parent.find('.no-fu-memo-form').removeClass('d-none');
                            parent.find('.no-fu-memo-form textarea').first().focus();
                        }
                    });

                $(document)
                    .off('click.cancel-fu-appt-form', '.fu-appt-container .cancel-fu-appt-form')
                    .on('click.cancel-fu-appt-form', '.fu-appt-container .cancel-fu-appt-form', function() {
                        let parent = $(this).closest('.fu-appt-container');
                        parent.find('.no-fu-memo-form').addClass('d-none');
                        parent.find('[name="is_follow_up_needed"]').prop('checked', false);
                        return false;
                    });

                $(document)
                    .off('click.update-fu-appt-status', '.fu-appt-container .update-fu-appt-status')
                    .on('click.update-fu-appt-status', '.fu-appt-container .update-fu-appt-status', function() {
                        let parent = $(this).closest('.fu-appt-container'),
                            choices = parent.find('.fu-appt-choices');
                        if(choices.is('.d-none')) {
                            choices.removeClass('d-none').addClass('d-block');
                        }
                        else {
                            choices.removeClass('d-block').addClass('d-none');
                        }
                        return false;
                    });

                // on note-section hover, highlight the according left-tree node(s)
                $(document)
                    .off('mouseenter', '.note-section')
                    .on('mouseenter', '.note-section', function(){
                        $('.note-tree-node').removeClass('hovered');
                        let target = $('.note-tree-node a[data-segment-uid="' + $(this).attr('data-segment-uid') + '"]');
                        target.parent().addClass('hovered');
                        target.parent().parents('.note-tree-node').addClass('hovered');
                        return false;
                    });

                $(document)
                    .off('mouseenter', '[data-non-segment-section]')
                    .on('mouseenter', '[data-non-segment-section]', function(){
                        $('.note-tree-node').removeClass('hovered');
                        let target = $('.note-tree-node a[data-non-segment-target="' + $(this).attr('data-non-segment-section') + '"]');
                        target.parent().addClass('hovered');
                        target.parent().parents('.note-tree-node').addClass('hovered');
                        return false;
                    });

                $(document)
                    .off('mouseleave', '.note-section')
                    .on('mouseleave', '.note-section', () => {
                        $('.note-tree-node').removeClass('hovered');
                        return false;
                    });

                // print note
                $(document)
                    .off('click.print', '.print-note')
                    .on('click.print', '.print-note', () => {
                        window.print();
                        return false;
                    });
                $('.print-note').removeClass('invisible');

                $('.note-method-select').change(function() {
                    let form = $(this).closest('form');
                    if(this.value === 'IN_CLINIC') {
                        form.find('.if-in-clinic').show();
                    }
                    else {
                        form.find('.if-in-clinic').hide();
                    }
                });

                $('.note-method-select').each(function() {
                    let form = $(this).closest('form');
                    if(this.value === 'IN_CLINIC') {
                        form.find('.if-in-clinic').show();
                    }
                    else {
                        form.find('.if-in-clinic').hide();
                    }
                });

                $('textarea[rte]').each(function() {

                    $(this).wrap(
                        $('<div class="border-left border-right rte-holder"/>')
                            .attr('data-shortcuts', '')
                    );

                    // give a unique id to this editor instance
                    var editorID = Math.ceil(Math.random() * 99999),
                        fieldName = this.name;

                    var ti = $('<input type="hidden" />')
                        .val(this.value)
                        .attr('name', this.name)
                        .insertBefore(this);
                    var ce = $('<div data-editor-id="' + editorID + '" data-field="' + this.name + '"/>')
                        .html(this.value)
                        .insertBefore(this);
                    $(this).remove();

                    var qe = new Quill('[data-editor-id="' + editorID + '"]', {
                        theme: 'snow',
                        modules: stagQuillConfig
                    });
                    var toolbar = $(qe.container).prev('.ql-toolbar');

                    // add button for new shortcut
                    var newSCButton = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
                        'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
                    toolbar.append(newSCButton);

                    qe.on('text-change', function() {
                        ti.val(qe.root.innerHTML);
                    });

                    $(qe.container)
                        .find('.ql-editor[contenteditable]')
                            .attr('data-field', fieldName)
                            .attr('data-editor-id', editorID)
                            .attr('with-shortcuts', 1);

                });

                $(document)
                    .off('click.edit-trigger', '.edit-trigger:not(.edit)')
                    .on('click.edit-trigger', '.edit-trigger:not(.edit)', function() {

                        if($('.note-section>.stag-popup:visible').length) return;

                        let editParent = $(this).closest('.note-section');

                        // TEMP: disable edit mode for medrisk_vigilance
                        // TODO: do this in the proper place
                        if(editParent.is('[data-segment-template-name="medrisk_vigilence"]')) return false;

                        // TEMP: show wizard for allergies, rx, dx, goals
                        if(editParent.is('[data-segment-template-name="plan_allergies"]') ||
                            editParent.is('[data-segment-template-name="intake_allergies"]') ||
                            editParent.is('[data-segment-template-name="allergies"]') ||
                            editParent.is('[data-segment-template-name="omega_allergies"]') ||
                            editParent.is('[data-segment-template-name="omega_plan_allergies"]')) {
                            $('.note-bottom-toolbar .allergies-center-trigger').trigger('click');
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="plan_problems"]') ||
                            editParent.is('[data-segment-template-name="intake_problems"]') ||
                            editParent.is('[data-segment-template-name="problems"]') ||
                            editParent.is('[data-segment-template-name="omega_problems"]') ||
                            editParent.is('[data-segment-template-name="omega_plan_problems"]')) {
                            $('.note-bottom-toolbar .problems-center-trigger').trigger('click');
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="plan_medications"]') ||
                            editParent.is('[data-segment-template-name="intake_medications"]') ||
                            editParent.is('[data-segment-template-name="medications"]') ||
                            editParent.is('[data-segment-template-name="omega_medications"]') ||
                            editParent.is('[data-segment-template-name="omega_plan_medications"]')) {
                            $('.note-bottom-toolbar .medications-center-trigger').trigger('click');
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="plan_goals"]') ||
                            editParent.is('[data-segment-template-name="intake_goals"]') ||
                            editParent.is('[data-segment-template-name="goals"]') ||
                            editParent.is('[data-segment-template-name="omega_goals"]') ||
                            editParent.is('[data-segment-template-name="omega_plan_goals"]')) {
                            $('.note-bottom-toolbar .goals-center-trigger').trigger('click');
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="plan_care_team"]') ||
                            editParent.is('[data-segment-template-name="intake_care_team"]') ||
                            editParent.is('[data-segment-template-name="care_team"]') ||
                            editParent.is('[data-segment-template-name="omega_care_team"]') ||
                            editParent.is('[data-segment-template-name="omega_plan_care_team"]')) {
                            $('.note-bottom-toolbar .careteam-center-trigger').trigger('click');
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="plan_supplements"]') ||
                            editParent.is('[data-segment-template-name="intake_supplements"]') ||
                            editParent.is('[data-segment-template-name="omega_supplements"]') ||
                            editParent.is('[data-segment-template-name="omega_plan_supplements"]')) {
                            $('.note-bottom-toolbar .supplements-center-trigger').trigger('click');
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="omega_history_past_medical"]')) {
                            openDynamicStagPopup('/note-segment-view-by-name/{{$note->uid}}/past_medical_history/edit',
                                'edit-univ_history_past_medical-container-{{$note->id}}',
                                'Past Medical History',
                                false,
                                "overflow-visible");
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="omega_history_family"]')) {
                            openDynamicStagPopup('/note-segment-view-by-name/{{$note->uid}}/history_family/edit',
                                'edit-univ_history_family-container-{{$note->id}}',
                                'Family History',
                                false,
                                "overflow-visible");
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="omega_history_social"]')) {
                            openDynamicStagPopup('/note-segment-view-by-name/{{$note->uid}}/history_social/edit',
                                'edit-univ_history_social-container-{{$note->id}}',
                                'Social History',
                                false,
                                "overflow-visible");
                            return false;
                        }
                        else if(editParent.is('[data-segment-template-name="omega_history_surgical"]')) {
                            openDynamicStagPopup('/note-segment-view-by-name/{{$note->uid}}/history_surgical/edit',
                                'edit-univ_history_surgical-container-{{$note->id}}',
                                'Surgical History',
                                false,
                                "overflow-visible");
                            return false;
                        }

                        // TEMP: open in popup if LS segment
                        if(editParent.is('[data-segment-template-name^="lifestyle_"]')) {
                            showStagPopup('segment-popup-' + editParent.attr('data-segment-template-name'), true);
                            return false;
                        }

                        if(editParent.is('[data-segment-template-name="plan_nutrition"]') ||
                            editParent.is('[data-segment-template-name="intake_nutrition"]') ||
                            editParent.is('[data-segment-template-name="nutrition"]')) {
                            openDynamicStagPopup('/nutrition-center/{{$note->client->uid}}/{{$note->uid}}',
                                'nutrition-center-{{$note->id}}',
                                '<img src="/img/nutrition-rx.png" class=""/> Nutrition Rx',
                                false,
                                "overflow-visible");
                            return false;
                        }

                        if(editParent.is('[data-segment-template-name="plan_exercise"]') ||
                            editParent.is('[data-segment-template-name="intake_exercise"]') ||
                            editParent.is('[data-segment-template-name="exercise"]')) {
                            openDynamicStagPopup('/exercise-center/{{$note->client->uid}}/{{$note->uid}}',
                                'exercise-center-{{$note->id}}',
                                '<img src="/img/exercise-rx.png" class=""/> Exercise Rx',
                                false,
                                "overflow-visible");
                            return false;
                        }

                        if(editParent.is('[data-segment-template-name="plan_behavior"]') ||
                            editParent.is('[data-segment-template-name="intake_behavior"]') ||
                            editParent.is('[data-segment-template-name="behavior"]')) {
                            openDynamicStagPopup('/behavior-center/{{$note->client->uid}}/{{$note->uid}}',
                                'behavior-center-{{$note->id}}',
                                '<img src="/img/behavior-rx.png" class=""/> Behavior Rx',
                                false,
                                "overflow-visible");
                            return false;
                        }
                        //ROS
                        <?php
                        $rosName = 'ros';
                        $rosSegment = $note->getSegmentByInternalName($rosName);
                        if(!$rosSegment) {
                            $rosName = 'omega_ros';
                            $rosSegment = $note->getSegmentByInternalName($rosName);
                        }
                        ?>
                        @if($rosSegment)
                        if(editParent.is('[data-segment-template-name="{{$rosName}}"]')) {
                            openDynamicStagPopup('/note-segment-view/{{$note->client->uid}}/{{$note->uid}}/{{$rosSegment->uid}}/{{$rosName}}/edit',
                                'init-ros-{{$note->id}}',
                                'Review of Systems',
                                false,
                                "overflow-visible");
                            return false;
                        }
                        @endif

                        //PE
                        <?php
                        $peName = 'omega_pe';
                        $peSegment = $note->getSegmentByInternalName($peName);
                        ?>
                        @if($peSegment)
                        if(editParent.is('[data-segment-template-name="{{$peName}}"]')) {
                            openDynamicStagPopup('/note-segment-view/{{$note->client->uid}}/{{$note->uid}}/{{$peSegment->uid}}/{{$peName}}/edit',
                                'init-pe-{{$note->id}}',
                                'Physical Exam',
                                false,
                                "overflow-visible");
                            return false;
                        }
                        @endif


                        // OPEN popup for if note-segment-view exists
                        if($('.' + editParent.attr('data-segment-template-name') + '-trigger').length) {
                            $('.' + editParent.attr('data-segment-template-name') + '-trigger').trigger('click');
                            return false;
                        }

                        if(editParent.is('.edit')) {
                            editParent.removeClass('edit');
                        }
                        else {
                            let docRoot = $('html');
                            let prevEffectiveTop = editParent.offset().top - docRoot.scrollTop();
                            $('.note-section.edit').removeClass('edit');
                            editParent.addClass('edit');
                            let newEffectiveTop = editParent.offset().top - docRoot.scrollTop();
                            if(newEffectiveTop < prevEffectiveTop) {
                                docRoot.scrollTop(docRoot.scrollTop() - (prevEffectiveTop - newEffectiveTop));
                            }
                            editParent.find('.ql-editor').first().focus();
                            editParent.trigger('edit-mode-activated');
                        }

                        let visitTreeLink = $('.note-tree-node a[data-segment-internal-name="' + editParent.attr('data-segment-template-name') + '"]');
                        if(visitTreeLink.length) {
                            $('.note-tree-node.active').removeClass('active');
                            visitTreeLink.closest('.note-tree-node').addClass('active');
                        }

                        // to force graph redraw
                        window.dispatchEvent(new Event('resize'));

                        return false;
                    });

                $('.note-templates-trigger')
                    .off('click.note-templates-trigger')
                    .on('click.note-templates-trigger', function() {
                        $('.note-templates-underlay').show();
                        let container = $(this).closest('.note-section').find('.note-template-container');
                        container.find('.note-template-children').hide();
                        container.find('.note-template-item.selected').removeClass('selected');
                        container.find('.note-template-item[prefix]').removeAttr('prefix');
                        container.find('input[type="checkbox"]').prop('checked', false);
                        container.find('.note-template-output-text').empty();
                        container.show();
                        loadTemplateSet(container.find('.note-template-set-chooser'));
                        loadExamTemplateSet(container.find('.note-exam-template-set-chooser'),
                            container.find('.note-exam-exam-chooser').val(),
                            container.find('.note-exam-template-set-chooser').val());
                        return false;
                    });

                $(document)
                    .off('click.note-templates-trigger-assessment', '.note-templates-trigger-assessment')
                    .on('click.note-templates-trigger-assessment', '.note-templates-trigger-assessment', function() {
                        $('.note-templates-underlay').show();
                        let container = $(this).closest('.note-section').find('.note-template-container');
                        container.find('.note-template-children').hide();
                        container.find('.note-template-item.selected').removeClass('selected');
                        container.find('.note-template-item[prefix]').removeAttr('prefix');
                        container.find('input[type="checkbox"]').prop('checked', false);
                        container.find('.note-template-output-text').empty();
                        container.attr('data-editor-id', $(this).attr('data-editor-id'));
                        container.show();
                        container.css({
                            left: ($(this).position().left - 140) + 'px',
                            top: ($(this).position().top + 22) + 'px',
                        });
                        loadTemplateSet(container.find('.note-template-set-chooser'));
                        loadExamTemplateSet(container.find('.note-exam-template-set-chooser'),
                            container.find('.note-exam-exam-chooser').val(),
                            container.find('.note-exam-template-set-chooser').val());
                        return false;
                    });

                $(document)
                    .off('click.note-templates-underlay', '.note-templates-underlay, .note-template-close-trigger')
                    .on('click.note-templates-underlay', '.note-templates-underlay, .note-template-close-trigger', function() {
                        $('.note-templates-underlay').hide();
                         $('.note-template-container').hide();
                    });

                $(document)
                    .off('click.note-template-label', '.note-template-item .label')
                    .on('click.note-template-label', '.note-template-item .label', function() {
                        let item = $(this).closest('.note-template-item');
                        let isChecked = $(this).find('>input[type="checkbox"]').prop('checked');
                        let hasChildren = !!item.find('>.note-template-children').length,
                            childrenShown = item.find('>.note-template-children:visible').length;

                        if(isChecked && hasChildren && !childrenShown) { // just show
                            $('.note-template-children').hide();
                            $(this).parents('.note-template-children').show();
                            item.find('>.note-template-children').show()
                                .find('>textarea,>input[type="number"],>input[type="date"]').first().focus();
                            return false;
                        }

                        $(this).find('>input[type="checkbox"]').prop('checked', !isChecked);
                        isChecked = !isChecked;
                        if(isChecked) {
                            item.addClass('selected');
                        }
                        else {
                            item.removeClass('selected');
                        }
                        $('.note-template-children').hide();
                        $(this).parents('.note-template-children').show();
                        if(isChecked) {
                            item.find('>.note-template-children')
                                .show()
                                .find('>textarea,>input[type="number"],>input[type="date"]')
                                .first().focus();
                        }

                        generateTemplateOutput();

                        return false;
                    });

                $(document)
                    .off('mousedown.note-templates-apply', '.note-template-apply-trigger')
                    .on('mousedown.note-templates-apply', '.note-template-apply-trigger', function() {
                        let templateContainer = $('.note-template-container:visible').first();
                        let result = $('.note-template-output-text:visible').first().html();
                        $('.note-templates-underlay').hide();
                        $('.note-template-container').hide();
                        let editor = null;
                        if($(this).closest('.assessment-detail-template').length) {
                            editor  = $('.ql-editor[data-editor-id="' + templateContainer.attr('data-editor-id') + '"]:visible').first();
                        }
                        else {
                            editor  = $('.ql-editor[contenteditable]:visible').first();
                        }
                        if(editor && editor.length) {
                            result = $.trim(editor.text() !== '' ? editor.html() : '') + result;
                            editor.html(result).focus();
                        }
                        return false;
                    });

                $(document)
                    .off('input paste change', '.note-template-item textarea, .note-template-item input[type="number"], .note-template-item input[type="date"]')
                    .on('input paste change', '.note-template-item textarea, .note-template-item input[type="number"], .note-template-item input[type="date"]', function() {
                        generateTemplateOutput();
                    });

                $(document)
                    .off('click.plus-trigger', '.note-template-item .plus-trigger')
                    .on('click.plus-trigger', '.note-template-item .plus-trigger', function() {
                        let item = $(this).closest('.note-template-item');
                        if(item.attr('prefix') === '(+)') {
                            item.removeAttr('prefix');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', false);
                            item.removeClass('selected');
                        }
                        else {
                            item.attr('prefix', '(+)');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', true);
                            item.addClass('selected');
                        }
                        generateTemplateOutput();
                        return false;
                    });

                $(document)
                    .off('click.minus-trigger', '.note-template-item .minus-trigger')
                    .on('click.minus-trigger', '.note-template-item .minus-trigger', function() {
                        let item = $(this).closest('.note-template-item');
                        if(item.attr('prefix') === '(-)') {
                            item.removeAttr('prefix');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', false);
                            item.removeClass('selected');
                        }
                        else {
                            item.attr('prefix', '(-)');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', true);
                            item.addClass('selected');
                        }
                        generateTemplateOutput();
                        return false;
                    });

                $(document)
                    .off('change.note-template-set-chooser', '.note-template-set-chooser')
                    .on('change.note-template-set-chooser', '.note-template-set-chooser', function() {
                        return loadTemplateSet($(this));
                    });

                $(document)
                    .off('change.note-exam-template-set-chooser', '.note-exam-template-set-chooser')
                    .on('change.note-exam-template-set-chooser', '.note-exam-template-set-chooser', function() {
                        $(this).closest('.note-template-container')
                            .find('.note-exam-exam-chooser')
                                .val($(this).find('option:selected').attr('exam'));
                        return loadExamTemplateSet($(this),
                            $(this).closest('.note-template-container').find('.note-exam-exam-chooser').first().val(),
                            $(this).val());
                    });

                $(document)
                    .off('change.note-exam-exam-chooser', '.note-exam-exam-chooser')
                    .on('change.note-exam-exam-chooser', '.note-exam-exam-chooser', function() {
                        return loadExamTemplateSet($(this),
                            $(this).val(),
                            $(this).closest('.note-template-container').find('.note-exam-template-set-chooser').first().val());
                    });

                $('.remove-section-trigger').click(function() {
                    $.post('/api/section/deactivate', {
                        uid: $(this).attr('data-uid'),
                        memo: 'Deactivated from note',
                    }, function(_data) {
                        if(_data) {
                            if(_data.success) {
                                fastReload();
                            }
                            else {
                                toastr.error(_data.message);
                            }
                        }
                        else {
                            toastr.error('Unable to remove section!');
                        }
                    }, 'json');
                    // $(this).closest('.note-section').removeClass('edit');
                    return false;
                });

                @if(!$note->visitTemplate)
                $(document)
                    .off('mousedown.enable-edit', '.note-section:not(.edit):not(.page-driven)')
                    .on('mousedown.enable-edit', '.note-section:not(.edit):not(.page-driven)', function(e) {
                        if($(this).closest('.note-signed-by-hcp').length) return;
                        e.stopPropagation();
                        e.preventDefault();
                        $(this).find('.edit-trigger').first().click();
                        return false;
                    });
                @endif

                $(document)
                    .off('keydown.collapse-active-segment')
                    .on('keydown.collapse-active-segment', function(e) {
                        if(e.which === 27) {
                            if(!isEventConsumed(e)) {
                                if($('.visit-segment.edit').length) {
                                    $('.visit-segment.edit').first().find('.edit-trigger').first().click();
                                    markEventAsConsumed(e);
                                    return false;
                                }
                            }
                            else {
                                // event already consumed!
                            }
                        }
                    });

                scrollToLatest();

                function __moveSection(_uid, _direction) {
                    $.post('/api/section/move' + _direction, {
                        uid: _uid
                    }, function(_data) {
                        if(_data && _data.success) {
                            fastReload();
                        }
                        else {
                            if(_data) {
                                toastr.error(_data.message);
                            }
                            else {
                                toastr.error('Unknown error while moving section');
                            }
                        }
                    }, 'json')
                }

                $('.move-up-trigger').click(function() {
                    __moveSection($(this).attr('data-uid'), 'Up');
                });

                $('.move-down-trigger').click(function() {
                    __moveSection($(this).attr('data-uid'), 'Down');
                });

                // refresh once ticket popup is closed
                /*$('body').off('stag-popup-closed')
                $('body').on('stag-popup-closed', function() {
                    if($('#note-single-header').length) {
                        fastReload();
                    }
                });*/
                // ticket-popup
                $(document)
                    .off('click', '.ticket-popup-trigger.note-dashboard-action')
                    .on('click', '.ticket-popup-trigger.note-dashboard-action', function() {
                        showMask();
                        window.noMc = true;
                        $.get(this.href, (_data) => {

                            if(!$('.ticket-popup').length) {
                                $('main.stag-content').append('<div class="stag-popup stag-popup-lg ticket-popup mcp-theme-1" stag-popup-key="ticket-popup"></div>');
                            }

                            $('.ticket-popup').html(_data);
                            showStagPopup('ticket-popup', true);
                            $('.ticket-popup .stag-popup.stag-slide').attr('close-all-with-self', 1);
                            runMCInitializer('patient-tickets'); // run specific mc initer
                            hideMask();
                        });
                        return false;
                    });

            }

            // scroll to latest created section
            function scrollToLatest() {
                window.setTimeout(function() {
                    let latestSectionTS = $('.latest-section-ts');
                    if(latestSectionTS.length) {
                        let latestSection = $('.note-section[data-ts="' + latestSectionTS.text() + '"]');
                        if(latestSection.length) {
                            latestSection[0].scrollIntoView({behavior: "smooth", block: "center"});
                            // latestSection.find('.edit-trigger').first().click();
                            console.log('DONE!');
                        }
                    }
                }, 100);
            }

            function loadTemplateSet(_chooser) {
                if(!_chooser.length || !_chooser.val()) return false;
                let container = _chooser.closest('.note-template-container');
                container.find('>.note-template-item').remove();
                container.find('.please-wait').remove();
                container.append('<p class="please-wait my-2 text-secondary text-center">Please wait ...</p>');
                $.get('/note-template-set/' + _chooser.attr('data-section') + '/' + _chooser.val(), function(_html) {
                    container.find('.please-wait').remove();
                    container.append(_html);
                });
                return false;
            }

            function loadExamTemplateSet(_chooser, _exam, _templateSet) {
                if(!_chooser.length || !_chooser.val()) return false;
                let container = _chooser.closest('.note-template-container');
                container.find('>.note-template-item').remove();
                container.find('.please-wait').remove();
                container.append('<p class="please-wait my-2 text-secondary text-center">Please wait ...</p>');
                $.get('/note-template-set/exam/' + _exam + '/' + _templateSet, function(_html) {
                    container.find('.please-wait').remove();
                    container.append(_html);
                });
                return false;
            }

            function generateOutputForNode(_node) {
                let template = (_node.attr('prefix') ? _node.attr('prefix') : '') + _node.attr('template'),
                    value = template;
                let hasChildText = !!_node.find('>.note-template-children>textarea,>.note-template-children>input[type="number"],>.note-template-children>input[type="date"]').length;
                let hasChildren = !!_node.find('>.note-template-children>.note-template-item').length;
                if(hasChildText) {
                    value = value.replace('{text}',
                        _node
                            .find('>.note-template-children')
                                .find('>textarea,>input[type="number"],>input[type="date"]').first().val());
                }
                else if(hasChildren) {
                    let values = [];
                    _node.find('>.note-template-children>.note-template-item.selected').each(function() {
                        values.push(generateOutputForNode($(this)));
                    });
                    let combined = '';
                    for (let i = 0; i < values.length; i++) {
                        combined += values[i];
                        if(values.length > 1 && i <= values.length - 2) {
                            if(i === values.length - 2) {
                                combined += ' and ';
                            }
                            else {
                                combined += ', ';
                            }
                        }
                    }
                    value = value.replace('{children}', ' ' + combined).replace('{text}', ' ' + combined);
                }
                return value;
            }

            function generateTemplateOutput() {
                let container = $('.note-template-container:visible').first();
                if(!container.length) return '';
                let lines = [];
                if(container.find('.note-template-set-chooser').length) {
                    lines.push('<b>' + container.find('.note-template-set-chooser').first().find('option:selected').text() + '</b>');
                }
                else if(container.find('.note-exam-template-set-chooser').length && container.find('.note-exam-exam-chooser').length) {
                    lines.push('<b>' +
                        container.find('.note-exam-template-set-chooser').first().find('option:selected').text() +
                        ': ' +
                        container.find('.note-exam-exam-chooser').first().find('option:selected').text() +
                        '</b>');
                }
                container.find('>.note-template-item.selected').each(function() {
                    lines.push('<p class="note-template-output-line">' + generateOutputForNode($(this)) + '</p>');
                });
                $('.note-template-output-text:visible').first().html(lines.join(''));
            }

            addMCInitializer('note-single', init, '#note-single-header');
        })();
    </script>
