<script>
        (function() {

            let numSectionsPendingInitialization = 0;

            function init() {
                $('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);

                });

                $('.edit-trigger')
                    .off('click.edit-trigger')
                    .on('click.edit-trigger', function() {
                        let editParent = $(this).closest('.note-section');
                        editParent.toggleClass('edit');
                        if(editParent.is('.edit')) {
                            editParent.siblings('.edit').removeClass('edit');
                            if(editParent.find('[autofocus]').length) {
                                editParent.find('[autofocus]').first().focus();
                            }
                        }
                        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;
                });

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

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

            }

            // 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);
        })();
    </script>
