<script>
    (function() {

        function initRTEs(_parent) {
            _parent.find('[note-rte]:not(.ql-container)').each(function() {

                let noteRTE = $(this);

                $(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).attr('data-field-name') ? $(this).attr('data-field-name') : 'free_text';

                var el = this;
                var existingContent = $(el).html();
                var quill = new Quill(el, {
                    theme: 'snow',
                    modules: stagQuillConfig
                });

                var toolbar = $(quill.container).prev('.ql-toolbar');

                // add button for new shortcut
                if(!noteRTE.is('[use-shortcuts]') || !noteRTE.attr('use-shortcuts')) {
                    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);
                }

                quill.root.innerHTML = existingContent;

                let setValue = function(delta, oldDelta, source) {
                    var content = quill.root.innerHTML;
                    let dataObject = {};
                    dataObject[fieldName] = content;
                    var dataValue = JSON.stringify(dataObject);
                    let pElem = $(el).closest('[visit-moe]');
                    if(!pElem.length) {
                        pElem = $(el).closest('form');
                    }
                    let v = pElem.find('input[name=data]').val();
                    if(!!v) {
                        try {
                            v = JSON.parse(v);
                            v[fieldName] = content;
                            v = JSON.stringify(v);
                        }
                        catch (e) {
                            v = JSON.stringify(dataObject);
                        }
                    }
                    else {
                        v = JSON.stringify(dataObject);
                    }
                    pElem.find('input[name=data]').val(v);
                }

                let onTextChange = function(delta, oldDelta, source) {
                    setValue(delta, oldDelta, source);
                    $(el).trigger('rich-text-input');
                }

                quill.on('text-change', onTextChange);

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

                // set value initially
                setValue();
            });
        }

        function init() {

            $(document)
                .off('input.auto-grow', '[visit-moe] form textarea')
                .on('input.auto-grow', '[visit-moe] form textarea', function() {
                    this.style.minHeight = "calc(1.5em + .5rem + 2px)";
                    this.style.height = "calc(1.5em + .5rem + 2px)";
                    this.style.height = (this.scrollHeight)+"px";
                });

            let parent = $('#note-rhs-segments-list');
            initRTEs(parent);
            initSegmentMoes(parent);
            initStagSuggest();

            // check and run all segment initializers
            /*try {
                if(window.segmentInitializers) {
                    for(let x in window.segmentInitializers) {
                        if(window.segmentInitializers.hasOwnProperty(x) && typeof window.segmentInitializers[x] === 'function') {
                            window.segmentInitializers[x].call(window);
                        }
                    }
                }
            }
            catch (e) {
                console.warn('Error running 1 or more segment initializers.')
            }*/
        }

        addMCInitializer('note-rhs-segments-list', init, '#note-rhs-segments-list');

    })();
</script>
