jQuery(document).ready(function ($) {
    function matchWord(source, target, task) {
        
        if (!source.length) {
            return;
        }
        var wIndex = source.data('index')
        var type = source.data('type');
        source.parent().find('.focus').removeClass('focus')
        if ($('.match-line').length) $('.match-line').remove();
        if ($('.parent-focus').length) $('.parent-focus').removeClass('parent-focus');
        if (target.length) {
            target.parent().addClass('parent-focus')
            target.parent().find('.focus').removeClass('focus')
            target.addClass('focus')
            source.addClass('focus')
            
            // If word is not visible, scroll to it.
            var curP = target.position().top
            var parent = target.parent()
            var parentHeight = parent.height()
            var elementViewHeight = parent[0].clientHeight;
            var elementScrollTop = parent[0].scrollTop;
            if (curP > parentHeight || curP < 0) {
                var scrollTop = curP + elementScrollTop - elementViewHeight / 3;
                parent.animate({
                    scrollTop: scrollTop
                }, 600, function () {
                    // Animation complete.
                    vectorSVG(`${task}-${wIndex}`, target.find('span.correct-text'), source, type)
                })
            }
            else {
                vectorSVG(`${task}-${wIndex}`, target.find('span.correct-text'), source, type)
            }
        }
    }
    /**
   * Create doted line to comment text.
   * @param {*} id
   * @returns {*} void
   */
    function vectorSVG(id, source, target, type = 'note') {
        if ($('.match-line').length) $('.match-line').remove();
        if (window.outerWidth < 768) {
            return;
        }

        var color = '';
        if (type === "note") {
            color = "red";
        } else if (type == "replace") {
            color = "#E91E63";
        }

        var $commentArea = $('.answer__col-right');
        var displayLeft = $commentArea.closest('.answer__answer-box')
            .find('.answer__col-left').offset().left;
        // is_mobile.
        var path1Id = id + '-svg-path1';
        var path2Id = id + '-svg-path2';
        var svgW = Math.abs(source.offset().left - (target.offset().left + target.width())) | 1;
        var svgH = Math.abs(source.offset().top - target.offset().top) + source.height() + target.height() | 1;
        if (!source.children("svg").length) {
            source.append(
                '<svg class="match-line" width="' +
                svgW +
                '" height="' +
                svgH +
                '">' +
                '<path id="' + path1Id + '" stroke="' + color + '" stroke-width="1" stroke-dasharray="3,3" fill="none"></path>' +
                '<path id="' + path2Id + '" stroke="' + color + '" stroke-width="1" stroke-dasharray="3,3" fill="none"></path>' +
                '</svg>'
            );
        }
        var svg = source.find('svg');
        var left = target.offset().left - displayLeft + target.width();
        svg.css("position", "absolute");
        svg.css("left", left + "px");
        svg.attr('height', svgH);

        var targetPosition = target.position().top;
        var targetOffset = target.offset().top;
        var targetHeight = target.height();
        if (targetHeight > 22) {
            targetPosition = target.position().top - 15;
            targetOffset = target.offset().top - 15;
            targetHeight = target.height() - 15;
        }

        if (targetOffset < source.offset().top) {
            svg.css("top", targetPosition);
        }
        else {
            svg.css("top", source.position().top);
        }

        var p1T = targetOffset + targetHeight - svg.offset().top;
        var p1W = svgW - 90;
        var p2W = 42.5;
        var p2T = 0;;
        if (source.offset().top > targetOffset) {
            if (targetOffset + targetHeight > source.offset().top) {
                p2T = - (Math.abs(targetOffset + targetHeight - source.offset().top - source.closest('.answer__status-header').height() / 2)) | 1;
            }
            else {
                p2T = (source.offset().top - svg.offset().top - source.closest('.answer__status-header').height()) | 1;
            }
        }
        else {
            p2T = (-svg.height() + source.closest('.answer__status-header').outerHeight() * 1.5) | 1;
        }
        var path1 = 'M 0 ' + p1T + ' l ' + p1W + ' 0';
        var path2 = 'M ' + p1W + ' ' + p1T + ' l ' + p2W + ' ' + p2T;
        document.getElementById(path1Id).setAttribute('d', path1);
        document.getElementById(path2Id).setAttribute('d', path2);
    }

    function caculateHeightColumns(element) {
        if (!element.length) {
            return;
        }
        var colLeft = element.find('.answer__col-left');
        var colRight = element.find('.answer__col-right');
        // get height of left and right column.
        var heightLeft = colLeft[0].clientHeight;
        var heightRight = colRight[0].clientHeight;
        if (heightLeft < heightRight) {
            colLeft.find('.mce-edit-area').css('height', (heightRight - 50) + 'px');
            colLeft.find('.ice-submitted').css('height', (heightRight - 30) + 'px');
        }
        else {
            colRight.css('max-height', (heightLeft - 50) + 'px');
        }
    }

    $(document).on('click', '.-close-btn', function (e) {
        e.preventDefault()
        $('.parent-focus').removeClass('parent-focus')
    });

    function onLoad() {
        var corrections = $('[data-drupal-selector="writing-result-corrections"]')
        corrections.each(function (indexCorrections, elmCorrections) {
            var task = $(elmCorrections).data('task')

            // Fix high.
            var container = $(elmCorrections).closest('.answer__answer-box');
            if (container.length) {
                var colRight = container.find('.answer__col-right');
                if (colRight.length) {
                    colRight[0].addEventListener('scroll', function (event) {
                        event.stopPropagation();
                    }, { passive: false });
                    colRight[0].addEventListener('touchmove', function (event) {
                        event.stopPropagation();
                    }, { passive: false });
                    // caculateHeightColumns(container);
                    // initNiceScroll(colRight);
                }
            }

            setTimeout(function () {
                $(elmCorrections).find('span.noted').each(function (index, elm) {
                    $(elm).on('click', function (e) {
                        var target = $(`[data-drupal-selector="writing-result-corrections-comments"][data-task="${task}"]`).find(`[data-index="${$(this).data('index')}"]`)
                        matchWord($(this), target, task);
                    })
                })
            }, 600)
        });
        var words = $('[data-drupal-selector="writing-result-corrections-comments"]')
        words.each(function (indexCorrections, elmCorrections) {
            var task = $(elmCorrections).data('task')

            $(elmCorrections).find('[data-drupal-selector="corrections-word"]').each(function (index, elm) {

                $(elm).on('click', function (e) {

                    var source = $(`[data-drupal-selector="writing-result-corrections"][data-task="${task}"]`).find(`[data-index="${$(this).data('index')}"]`);
                    if (window.outerWidth <= 767) {
                        $('html, body').animate({
                            scrollTop: source.offset().top - window.outerHeight / 4
                        })
                    }
                    matchWord(source, $(this), task);
                })
            })

            // Scroll.
            $(elmCorrections).on('scroll', function (e) {
                var target = $(this).find('.focus');
                var source = $(`[data-drupal-selector="writing-result-corrections"][data-task="${task}"]`).find('.focus');
                if (!source.length) {
                    return;
                }
                var type = source.data("type");
                var wIndex = source.data('index');
                var parent = target.parent();
                var isVisible = 10 <= target.position().top && target.position().top <= parent.height()
                if (isVisible) {
                    vectorSVG(`${task}-${wIndex}`, target.find('span.correct-text'), source, type)
                } else {
                    if ($('.match-line').length) $('.match-line').remove();
                }
            })
        });
    }

    window.commentsMatcher = onLoad;
    window.commentsMatcher();

});

jQuery(document).ready(function ($) {


    var tooltipVisible = false;
    var noteInput = $('#js-note-content');
    var highlightTooltip = $('#highlight-box');
    var highlighterContent = $('#highlighter-contents');

    var NoteIds = [];
    var newAddedNote = 0;
    var notes = [];
    var noteSerialized = {};
    var initNiceScroll = false;
    var noting = false;

    // --------------------------------
    // NOTE/HIGHLIGHT FUNCTIONS
    function setData(data = null) {
        if (data) {
            NoteIds = data.review_comment_ids || [];
            notes = data.review_comments || [];
        } else {
            NoteIds = [];
            notes = [];
        }
    }



    function getQuizId() {
        return 'practice_test';
    }

    // (Notepad) Setup note - Black out the text show active note and highlight.
    function setupNoteApp() {

        // Handle "input" event on the search input
        $('#note-search').on('input', function () {
            const searchTerm = $(this).val().trim().toLowerCase();
            if (searchTerm === '') {
                // If the search term is empty, display the original notes
                $('#search-results').empty();
                $('#notes-container').show();
                renderNotes();
            }
            else {
                const filteredNotes = filterNotes(searchTerm);

                // Render the filtered notes
                renderSearchResults(filteredNotes);
            }
        });

        function filterNotes(searchTerm) {
            // Filter notes that contain the search term in either selectedText or
            // noteText
            return notes.filter((note) => {
                const selectedText = note.selectedText.toLowerCase();
                const noteText = note.noteText.toLowerCase();

                return selectedText.includes(searchTerm) || noteText.includes(searchTerm);
            });
        }

        function renderSearchResults(searchResults) {
            const searchResultsContainer = $('#search-results');
            searchResultsContainer.empty();

            if (searchResults.length > 0) {
                $.each(searchResults, function (index, note) {
                    const noteId = uuidv4(); // Create a unique ID for each note.
                    note.id = noteId; // Save the ID into the note.
                    let noteTitle = note.selectedText;
                    let reasonText = note.reasonText || '';
                    let noteContent = `<div class="notepad__item-content">${note.noteText}</div>`;
                    let reasonContent = `<div class="notepad__item-reason" data-title="Reason: ">${reasonText}</div>`;
                    if (note.type === "replace") {
                        noteTitle = `Removed: <b style='color:red';>${note.selectedText}</b>`;
                        noteContent = `<div data-title="Replaced with: " class="notepad__item-content">${note.noteText}</div>`;
                        reasonContent = `<div data-title="Reason: " class="notepad__item-reason">${reasonText}</div>`;
                    } else {
                        noteTitle = `Note for: <b style='color:red';>${note.selectedText}</b>`;
                        reasonContent = ``;
                    }
    
                    const searchResultDiv = `
                        <div class="notepad__item ${note.type}" data-note-id="${noteId}" data-note-part="${note.noteOfPart}" data-ref-id="${note.noteRefId}">
                            <div class="notepad__item-title">${noteTitle}</div>
                            <div class="notepad__item-content-wrap">
                                ${noteContent}
                                ${reasonContent}
                            </div>
                            
                            <span class="notepad__item-more">
                                <span class="notepad__item-more-icon ioticon-more-vertical"></span>
                                <span class="notepad__more-card">
                                <span class="notepad__more-item-row -edit">
                                    Edit <span class="notepad__more-item-icon ioticon-edit"></span>
                                </span>
                                <span class="notepad__more-item-row">
                                    Delete <span class="notepad__more-item-icon ioticon-trash-3 -delete"></span>
                                    <span class="notepad__delete-confirm">Are you sure to delete this note?
                                    <span class="notepad__text-confirm-wrap">
                                        <span class="notepad__text-confirm -delete" data-id="${noteId}">Yes</span>
                                        <span class="notepad__text-confirm -cancel">No</span>
                                    </span>
                                    </span>
                                </span>
                                </span>
                            </span>
                        </div>
                    `;
    
                    // Add search results with delete and cancel function
                    const searchResultElement = $(searchResultDiv);
                    searchResultsContainer.prepend(searchResultElement);
                });

                $('#notes-container').hide();
            } else {
                const noResultsDiv = `<div class="notepad__no-results">No matching note found.</div>`;
                searchResultsContainer.append(noResultsDiv);
            }
        }

        function deleteNote(noteId) {
            // Find a note by its unique ID.
            const noteIndex = notes.findIndex(note => note.id === noteId);
            if (noteIndex !== -1) {
                // Remove a note from the notes array using the found index.
                notes.splice(noteIndex, 1);

                // Save the notes array to local storage.
                // localStorage.setItem('notes_' + quizID, JSON.stringify(notes));

                // Display the search results again.
                const searchTerm = $('#note-search').val().trim().toLowerCase();
                if (searchTerm === '') {
                    $('#search-results').empty();
                    $('#notes-container').show();
                    renderNotes();
                }
                else {
                    const filteredNotes = filterNotes(searchTerm);
                    renderSearchResults(filteredNotes);
                }
            }
        }

        function scrollToNotedItem(refItemId, noteOfPart) {
            if ($(`.noted.${refItemId}`).length) {
                if ($('.question-palette__part.-active').data('part') != noteOfPart) {
                    $('.question-palette__part[data-part="' + noteOfPart + '"]').trigger('click', false);
                    highlighterContent.on('transitionend', function () {
                        $(`.noted.${refItemId}`)[0].scrollIntoView({
                            behavior: 'smooth',
                            block: 'center'
                        });
                        highlighterContent.off('transitionend');
                    });
                }
                else {
                    $(`.noted.${refItemId}`)[0].scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                }
            }
        }

        // Handle click event on "Save" button
        $('#save-note').click(function () {
            saveNote();
        });

        $('#save-suggestion').click(function () {
            replaceNote();
        });

        // Event delegation for handling delete and cancel click events
        $(document).on('click', '.notepad__item-more', function (event) {
            $('.notepad__item-more').removeClass('active');
            $(this).toggleClass('active');
        });

        $(document).on('click', '.notepad__text-confirm.-delete', function (event) {
            const noteId = $(this).closest('.notepad__item').data('noteId');
            const refNoteId = $(this).closest('.notepad__item').data('refId');
            deleteNote(noteId);
            removeNoteOnTestPanel(refNoteId)
        });

        $(document).on('click', '.notepad__delete-confirm', function (event) {
            event.stopPropagation();
        });

        $(document).on('click', '.notepad__item-title', function (event) {
            event.stopPropagation();
            var itemNote = $(this).closest('.notepad__item');
            var refItemId = itemNote.data('refId');
            var noteOfPart = itemNote.data('notePart');
            scrollToNotedItem(refItemId, noteOfPart);
        });

        $(document).on('click', '.notepad__more-item-row.-edit', function (event) {
            var editableDiv = $(this).closest('.notepad__item').find('.notepad__item-content');
            var reasonDiv = $(this).closest('.notepad__item').find('.notepad__item-reason');
            var editableDivWrap = $(this).closest('.notepad__item').find('.notepad__item-content-wrap');
            var noteId = $(this).closest('.notepad__item').data('noteId');
            var btnEditTemplate = `<div class="notepad__btns-edit">
                <button class="notepad__btn-cancel iot-grbt -white">Cancel</button>
                <button class="notepad__btn-save iot-grbt" data-note-id="${noteId}">Save</button>
            </div>`;

            originalNoteContent = editableDiv.text();
            originalReasonContent = reasonDiv.text();
            $(this).closest('.notepad__item-more').removeClass('active');
            editableDiv.attr("contentEditable", "true").focus();
            reasonDiv.attr("contentEditable", "true");
            editableDivWrap.append(btnEditTemplate);
            $('#notes-container').getNiceScroll().resize();
        });

        $(document).on('click', '.notepad__btn-cancel', function (event) {
            var editableDiv = $(this).closest('.notepad__item').find('.notepad__item-content');
            var reasonDiv = $(this).closest('.notepad__item').find('.notepad__item-reason');
            editableDiv.text(originalNoteContent).attr("contentEditable", "false");
            reasonDiv.text(originalReasonContent).attr("contentEditable", "false");

            $(this).closest('.notepad__btns-edit').remove();
        });

        $(document).on('click', '.notepad__btn-save', function (event) {

            const noteId = $(this).data('note-id');
            const updatedContent = $(this).closest('.notepad__item').find('.notepad__item-content').text().trim();
            const updatedReason = $(this).closest('.notepad__item').find('.notepad__item-reason').text().trim();

            // Find the note by its unique ID.
            const noteIndex = notes.findIndex(note => note.id === noteId);

            if (noteIndex !== -1) {
                // Update the note's content.
                notes[noteIndex].noteText = updatedContent;
                notes[noteIndex].reasonText = updatedReason;

                console.log(notes[noteIndex]);

                let noteRefId = notes[noteIndex].noteRefId;
                document.querySelector(`#highlighter-contents #${noteRefId}`).dataset.replace = updatedContent;

                // Save the updated notes array to local storage.
                // localStorage.setItem('notes_' + quizID, JSON.stringify(notes));

                // Optionally, you can re-render the notes to display the updated
                // content.
                renderNotes();
            } else {
                console.log('note not found');
            }

            $(this).closest('.notepad__item-content-wrap').find('.notepad__item-content').attr("contentEditable", "false");
            $(this).closest('.notepad__item-content-wrap').find('.notepad__item-reason').attr("contentEditable", "false");
            $(this).closest('.notepad__btns-edit').remove();

        });

        $(document).on('click', '.notepad__more-item-row', function (event) {
            event.stopPropagation();
            $(this).toggleClass('active');
            const confirmDeleteElm = this.querySelector('.notepad__delete-confirm');
            const confirmEditElm = this.closest(".notepad__item").querySelector('.notepad__item-content-wrap');
            document.addEventListener('click', clickDeleteItemHandler);
            document.addEventListener('click', clickEditItemHandler);

            function clickDeleteItemHandler(event) {

                if (confirmDeleteElm) {
                    const isInsideConfirmDeleteElm = confirmDeleteElm.contains(event.target);
                    if (!isInsideConfirmDeleteElm) {
                        document.removeEventListener('click', clickDeleteItemHandler);
                        $(confirmDeleteElm).closest('.notepad__item-more').removeClass('active');
                        $(confirmDeleteElm).closest('.notepad__more-item-row').removeClass('active');
                    }
                    else {
                        if ($(event.target).is('.notepad__text-confirm')) {
                            document.removeEventListener('click', clickDeleteItemHandler);
                        }
                    }
                }
            }

            function clickEditItemHandler(event) {

                if (confirmEditElm) {
                    const isInsideConfirmEditElm = confirmEditElm.contains(event.target);
                    if (!isInsideConfirmEditElm) {
                        document.removeEventListener('click', clickEditItemHandler);
                        $('.notepad__btns-edit').remove();
                        $('.notepad__item-content').attr("contentEditable", "false");
                        $('.notepad__item-reason').attr("contentEditable", "false");
                    }
                    else {
                        if ($(event.target).is('.iot-grbt')) {
                            document.removeEventListener('click', clickEditItemHandler);
                        }
                    }
                }
            }
        });

        document.addEventListener('click', function (event) {
            const moreNote = document.querySelector('.notepad__item-more.active');
            if (moreNote) {
                const isClickInsideMoreNote = moreNote.contains(event.target);
                if (!isClickInsideMoreNote) {
                    $(moreNote).removeClass('active')
                }
            }
        });

        $(document).on('click', '.notepad__text-confirm.-cancel', function (event) {
            event.stopPropagation();
            $(this).closest('.notepad__item-more').removeClass('active');
            $(this).closest('.notepad__more-item-row').removeClass('active');
        });

        function saveNote() {
            const inputTextarea = $('#user-note-input');
            const noteText = inputTextarea.val().trim();
            const reasonTextarea = $('#user-reason-input');
            const selectedText = noteString;
            const noteOfPart = $('.question-palette__part.-active').data('part');
            const noteRefId = $('#js-note-content').data('id');
            const timestamp = $('#js-note-content').data('timestamp');

            if (!noteText) {
                inputTextarea.focus();
                return;
            }

            if (noteText && selectedText) {
                // Create a new note object
                const newNote = {
                    selectedText: selectedText,
                    noteText: noteText,
                    noteOfPart: noteOfPart,
                    noteRefId: noteRefId,
                    reasonText: '',
                    type: 'note'
                };

                // Add the note to the notes array
                notes.push(newNote);

                document.querySelector(`#highlighter-contents #${noteRefId}`).dataset.replace = noteText;
                document.querySelector(`#highlighter-contents #${noteRefId}`).dataset.index = noteRefId;
                document.querySelector(`#highlighter-contents #${noteRefId}`).classList.add('txt-note');
                console.log(document.querySelector(`#highlighter-contents #${noteRefId}`).dataset);


                // Save the notes array to local storage
                // localStorage.setItem('notes_' + quizID, JSON.stringify(notes));

                // Render the notes again
                renderNotes();

                // Clear the textarea content
                inputTextarea.val('');
                reasonTextarea.val('');
                noteString = '';

                // Hide the tooltip
                hideHighlightTooltip();

                //toggle new note status icon
                newAddedNote += 1;
                checkNewNote();
            }
        }

        function replaceNote() {
            const inputTextarea = $('#user-suggestion-input');
            const reasonTextarea = $('#user-reason-input');
            const noteText = inputTextarea.val().trim();
            const reasonText = reasonTextarea.val().trim();
            const selectedText = noteString;
            const noteOfPart = $('.question-palette__part.-active').data('part');
            const noteRefId = $('#js-note-content').data('id');
            const timestamp = $('#js-note-content').data('timestamp');

            if (!noteText) {
                inputTextarea.focus();
                return;
            }

            if (!reasonText) {
                reasonTextarea.focus();
                return;
            }

            if (noteText && selectedText && reasonText) {
                // Create a new note object
                const newNote = {
                    selectedText: selectedText,
                    noteText: noteText,
                    reasonText: reasonText,
                    noteOfPart: noteOfPart,
                    noteRefId: noteRefId,
                    type: 'replace'
                };

                // Add the note to the notes array
                notes.push(newNote);

                document.querySelector(`#highlighter-contents #${noteRefId}`).dataset.replace = noteText;
                document.querySelector(`#highlighter-contents #${noteRefId}`).classList.add('txt-replacer');
                document.querySelector(`#highlighter-contents #${noteRefId}`).dataset.index = noteRefId;
                console.log(document.querySelector(`#highlighter-contents #${noteRefId}`).dataset);


                // Save the notes array to local storage
                // localStorage.setItem('notes_' + quizID, JSON.stringify(notes));

                // Render the notes again
                renderNotes();

                // Clear the textarea content
                inputTextarea.val('');
                reasonTextarea.val('');
                noteString = '';

                // Hide the tooltip
                hideHighlightTooltip();

                //toggle new note status icon
                newAddedNote += 1;
                checkNewNote();
            }
        }

    }

    function checkNewNote() {
        if (newAddedNote > 0) {
            $('#js-bt-notepad').addClass('active');
        }
        else {
            $('#js-bt-notepad').removeClass('active');
        }
    }

    function removeNoteOnTestPanel(noteId) {
        // Ensure all highlights are serialised first!
        NoteIds.forEach(function (noteId) {
            noteSerialized[noteId] = userNote.serializeHighlights(noteId);
        });

        if (noteId) {
            userNote.removeHighlights(null, noteId);
            NoteIds = NoteIds.filter((id) => id !== noteId);
        }
        hideHighlightTooltip();
    }

    function renderNotes() {
        const notesContainer = $('#notes-container');
        if (notesContainer.length) {
            notesContainer.empty();

            $.each(notes, function (index, note) {
                const noteId = uuidv4(); // Create a unique ID for each note.
                note.id = noteId; // Save the ID into the note.
                let noteTitle = note.selectedText;
                let reasonText = note.reasonText || '';
                let noteContent = `<div class="notepad__item-content">${note.noteText}</div>`;
                let reasonContent = `<div class="notepad__item-reason" data-title="Reason: ">${reasonText}</div>`;
                if (note.type === "replace") {
                    noteTitle = `Removed: <b style='color:red';>${note.selectedText}</b>`;
                    noteContent = `<div data-title="Replaced with: " class="notepad__item-content">${note.noteText}</div>`;
                    reasonContent = `<div data-title="Reason: " class="notepad__item-reason">${reasonText}</div>`;
                } else {
                    noteTitle = `Note for: <b style='color:red';>${note.selectedText}</b>`;
                    reasonContent = ``;
                }

                const noteDiv = `
                    <div class="notepad__item ${note.type}" data-note-id="${noteId}" data-note-part="${note.noteOfPart}" data-ref-id="${note.noteRefId}">
                        <div class="notepad__item-title">${noteTitle}</div>
                        <div class="notepad__item-content-wrap">
                            ${noteContent}
                            ${reasonContent}
                        </div>
                        
                        <span class="notepad__item-more">
                            <span class="notepad__item-more-icon ioticon-more-vertical"></span>
                            <span class="notepad__more-card">
                            <span class="notepad__more-item-row -edit">
                                Edit <span class="notepad__more-item-icon ioticon-edit"></span>
                            </span>
                            <span class="notepad__more-item-row">
                                Delete <span class="notepad__more-item-icon ioticon-trash-3 -delete"></span>
                                <span class="notepad__delete-confirm">Are you sure to delete this note?
                                <span class="notepad__text-confirm-wrap">
                                    <span class="notepad__text-confirm -delete" data-id="${noteId}">Yes</span>
                                    <span class="notepad__text-confirm -cancel">No</span>
                                </span>
                                </span>
                            </span>
                            </span>
                        </span>
                    </div>
                `;

                notesContainer.prepend(noteDiv);
            });

            if (notes.length <= 0) {
                notesContainer.prepend(`<div class="no-item">No Notes found</div>`);
            }

            $("#notepad").getNiceScroll().resize();


        }
    }

    function initNote() {
        var quizID = getQuizId();
        if (highlighterContent.length) {
            var sandbox = document.getElementById("highlighter-contents");
            window.userNote = new TextHighlighter(sandbox, {
                version: "independencia",
                useDefaultEvents: false,
                color: "var(--main-color)",
                highlightedClass: 'noted',
                preprocessDescriptors: function (range, descriptors) {
                    var uniqueId = "hlt-" + Math.random()
                        .toString(36)
                        .substring(2, 15) +
                        Math.random()
                            .toString(36)
                            .substring(2, 15);
                    NoteIds.push(uniqueId);
                    addNoteId(uniqueId)
                    var descriptorsWithIds = descriptors.map(function (descriptor) {
                        var wrapper = descriptor[0];

                        var highlightedText = descriptor[1];
                        var offset = descriptor[2];
                        var length = descriptor[3];
                        var timestamp = $(wrapper).data('timestamp');
                        addNoteTimestamp(timestamp);
                        noteString = descriptor[1];
                        return [
                            wrapper.replace(
                                'class="noted"',
                                "class=\"noted " + uniqueId + "\"" + " id=\"" + uniqueId + "\""
                            ),
                            highlightedText,
                            offset,
                            length
                        ];

                    });
                    return { descriptors: descriptorsWithIds, meta: { id: uniqueId } };
                },
                onAfterHighlight: function (range, hlts) {
                    console.log(hlts);
                },
            });

            $("#user-note-input").on("blur", function () {
                console.log('this trigger 2');
                if (previousRange) {
                    // Select the previous region again
                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(previousRange);
                }
            });

            highlighterContent.on("mouseup", function () {
                var selection = window.getSelection();

                if (selection.rangeCount > 0) {
                    var range = selection.getRangeAt(0);
                    var selectedText = getSelectedText();
                    if (selectedText !== "") {
                        showHighlightControl(range);
                        // Update the previous selection with the new selection
                        previousRange = range.cloneRange();
                    }
                    else {
                        // If there is no new selection, set previousRange to null.
                        previousRange = null;
                    }
                }
            });

            $(document).on('click', '#js-remove-note', function (event) {
                // Ensure all highlights are serialised first!
                NoteIds.forEach(function (noteId) {
                    noteSerialized[noteId] = userNote.serializeHighlights(noteId);
                });

                var noteId = $(this).data('id');
                if (noteId) {
                    userNote.removeHighlights(null, noteId);
                    NoteIds = NoteIds.filter((id) => id !== noteId)
                    deleteNote(noteId);
                }
                hideHighlightTooltip();
                newAddedNote -= 1;
                checkNewNote();
            });

            function deleteNote(noteId) {
                var noteRefId = $('[data-ref-id="' + noteId + '"]').data('noteId');
                // Find a note by its unique ID.
                const noteIndex = notes.findIndex(note => note.id === noteRefId);
                if (noteIndex !== -1) {
                    // Remove a note from the notes array using the found index.
                    notes.splice(noteIndex, 1);

                    // Save the notes array to local storage.
                    // localStorage.setItem('notes_' + quizID, JSON.stringify(notes));

                    // Display the search results again.
                    const searchTerm = $('#note-search').val().trim().toLowerCase();
                    if (searchTerm === '') {
                        $('#search-results').empty();
                        $('#notes-container').show();
                        renderNotes();
                    }
                    else {
                        const filteredNotes = filterNotes(searchTerm);
                        renderSearchResults(filteredNotes);
                    }
                }
            }

            function getSelectedText() {
                if (window.getSelection) {
                    return window.getSelection().toString();
                } else if (document.selection && document.selection.type != "Control") {
                    return document.selection.createRange().text;
                }
                return "";
            }

            function addNoteTimestamp(timestamp) {
                $('#js-note-content').data('timestamp', timestamp);
                noteTimestamp = timestamp;
            }

            function addNoteId(uniqueId) {
                $('#js-note-content').data('id', uniqueId);
            }

            clickOutNotetHandler = function clickOutNotetHandler(event) {

                if (!highlightTooltip.is(event.target) && highlightTooltip.has(event.target).length === 0) {
                    hideHighlightTooltip();

                    cancelNote(noteTimestamp);
                }
            }

            function addClassSavedNote(timestamp) {
                $(`[data-timestamp="${timestamp}"]`).each(function (index, el) {
                    $(this).addClass('saved-note');
                });
            }

            function replaceNoteToHightlight(timestamp) {
                $(`[data-timestamp="${timestamp}"]`).each(function (index, el) {
                    $(this).removeClass('noted').addClass('highlighted');

                    const currentClass = $(this).attr('class');
                    const newClass = currentClass.replace(/note-up/g, 'hltr-');
                    $(this).attr('class', newClass);
                });
            }

            $('.highlight-box__note-btn.btn.-cancel').on('click', function (event) {
                var timestamp = $('#js-note-content').data('timestamp');
                cancelNote(timestamp);
            });

            $('#save-note').on('click', function (event) {
                var timestamp = $('#js-note-content').data('timestamp');
                addClassSavedNote(timestamp);
            });

            // const highlightHandler = hltr.highlightHandler.bind(hltr);
            const noteHandler = () => userNote.highlightHandler();

            $('#js-btn-note').on("click", function () {
                noting = true;
                noteHandler();
                $(document).on('click', '#highlighter-contents', clickOutNotetHandler);
            });

            $('#js-btn-highlight').on('click', function (event) {
                if (noting) {
                    console.log("nothing", noting);
                    var timestamp = $('#js-note-content').data('timestamp');
                    replaceNoteToHightlight(timestamp);
                } else {
                    console.log("not nothing", noting);
                }
            });
        }

    }

    function initHighlighter() {
        if (highlighterContent.length) {
            var highlightIds = [];
            var sandbox = document.getElementById("highlighter-contents");
            var removeHighlightBtn = document.getElementById("js-remove-highlight");
            window.hltr = new TextHighlighter(sandbox, {
                version: "independencia",
                useDefaultEvents: false,
                preprocessDescriptors: function (range, descriptors) {
                    var uniqueId = "hlt-" + Math.random()
                        .toString(36)
                        .substring(2, 15) +
                        Math.random()
                            .toString(36)
                            .substring(2, 15);
                    highlightIds.push(uniqueId);

                    var descriptorsWithIds = descriptors.map(function (descriptor) {
                        var wrapper = descriptor[0];
                        var highlightedText = descriptor[1];
                        var offset = descriptor[2];
                        var length = descriptor[3];

                        return [
                            wrapper.replace(
                                'class="highlighted"',
                                "class=\"highlighted " + uniqueId + "\"" + " id=\"" + uniqueId + "\""
                            ),
                            highlightedText,
                            offset,
                            length
                        ];
                    });
                    return { descriptors: descriptorsWithIds, meta: { id: uniqueId } };
                },
            });

            var serialized = {};

            $("#user-note-input").on("blur", function () {
                console.log('this triggers');
                if (previousRange) {
                    // Select the previous region again
                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(previousRange);
                }
            });

            highlighterContent.on("mouseup", function () {
                var selection = window.getSelection();
                if (selection.rangeCount > 0) {
                    var range = selection.getRangeAt(0);
                    var selectedText = getSelectedText();
                    if (selectedText !== "") {
                        showHighlightControl(range);
                        // Update the previous selection with the new selection
                        previousRange = range.cloneRange();
                    }
                    else {
                        // If there is no new selection, set previousRange to null.
                        previousRange = null;
                    }
                }
            });

            $(document).on('click', '#js-remove-highlight', function (event) {
                // Ensure all highlights are serialised first!
                highlightIds.forEach(function (highlightId) {
                    serialized[highlightId] = hltr.serializeHighlights(highlightId);
                });

                var highlightId = $(this).data('id');
                if (highlightId) {
                    hltr.removeHighlights(null, highlightId);
                    highlightIds = highlightIds.filter((id) => id !== highlightId)
                }
                hideHighlightTooltip();
                cancelNote(noteTimestamp);
            });

            function getSelectedText() {
                if (window.getSelection) {
                    return window.getSelection().toString();
                }
                else if (document.selection && document.selection.type != "Control") {
                    return document.selection.createRange().text;
                }
                return "";
            }

            // const highlightHandler = hltr.highlightHandler.bind(hltr);
            const highlightHandler = () => hltr.highlightHandler();

            $('#js-btn-highlight').on("click", highlightHandler);
        }

    }

    function cancelNote(timestamp) {
        $(`[data-timestamp="${timestamp}"]`).each(function (index, el) {
            const notedText = el.textContent;
            const parent = el.parentElement;
            const textNode = document.createTextNode(notedText);
            parent.replaceChild(textNode, el);
        });
        $(document).off('click', '#highlighter-contents', clickOutNotetHandler);
    }

    function showHighlightControl(range) {

        var highlightMenuWidth = highlightTooltip.outerWidth();
        var highlightMenuHalfWidth = highlightMenuWidth / 2;
        var rect = range.getBoundingClientRect();
        var noteWidth = $('#js-note-content').outerWidth();
        var viewportWidth = $(window).width();
        var highlightMenuLeft = (rect.left + rect.width / 2) - highlightMenuHalfWidth;
        var highlightMenuRight = highlightMenuLeft + highlightMenuWidth;
        var highlightNoteLeft = (rect.left + rect.width / 2) - noteWidth / 2;
        var highlightNoteRight = highlightNoteLeft + noteWidth;

        $('#js-note-content').removeAttr('style');

        // Check if the tooltip exceeds the screen size
        if (highlightMenuLeft < 0) {
            highlightMenuLeft = 0;
            highlightTooltip.removeClass("left right").addClass('left');
            $('#js-note-content').css({
                left: highlightMenuLeft,
                'transform': 'none'
            });
        }
        else if (highlightMenuRight > viewportWidth) {
            highlightMenuLeft = viewportWidth - highlightMenuWidth;
            highlightTooltip.removeClass("left right").addClass('right');
        }
        else {
            highlightTooltip.removeClass("left right");

            if (highlightNoteLeft < 0) {
                $('#js-note-content').css({
                    left: (-1 * highlightMenuLeft),
                    'transform': 'none'
                });
            }
            else if (highlightNoteRight > viewportWidth) {
                $('#js-note-content').css({
                    left: 'initial',
                    right: (highlightMenuRight - viewportWidth),
                    'transform': 'none'
                });
            }
        }

        highlightTooltip.css({
            top: rect.top - highlightTooltip.outerHeight(),
            left: highlightMenuLeft
        });
    }

    function showHighlightTooltip() {
        $(document).on('click', '#highlighter-contents', function (event) {


            if (document.querySelector('#evaluation-mode')) {
                if (!document.querySelector('#evaluation-mode').checked) {
                    return;
                }
            }

            var selection = window.getSelection(), range;
            if ($(event.target).is('input, textarea')) {
                hideHighlightTooltip(false);
                console.log("2");
                return true;
            }
            if (selection.rangeCount > 0) {
                range = selection.getRangeAt(0);

                if (!range.collapsed || $(event.target).hasClass('highlighted') || $(event.target).hasClass('noted')) {
                    // Display the tooltip for the first time
                    highlightTooltip.show();
                    tooltipVisible = true;
                    highlightTooltip.removeClass('reactive-note reactive no-range');

                    if ($(event.target).hasClass('highlighted')) {
                        showHighlightControl($(event.target)[0]);
                        var highlightId = $(event.target).attr('id');
                        $('#js-remove-highlight').data('id', highlightId);
                        highlightTooltip.addClass('reactive');
                    }
                    if ($(event.target).hasClass('noted')) {
                        showHighlightControl($(event.target)[0]);
                        var noteId = $(event.target).attr('id');
                        $('#js-remove-note').data('id', noteId);
                        highlightTooltip.addClass('reactive-note');
                    }
                    if (range.collapsed) {
                        highlightTooltip.addClass('no-range');
                        noteTimestamp = '';
                        $('#js-note-content').data('timestamp', '');
                    }
                    let isSelectedText = window.getSelection().toString().length > 0;
                    console.log("3", range);

                }
                else if (!highlightTooltip.is(event.target) && highlightTooltip.has(event.target).length === 0) {
                    hideHighlightTooltip();

                    // let isSelectedText = window.getSelection().toString().length > 0;
                    // console.log("4", isSelectedText);
                }
            }

        });





        $('#js-btn-highlight').on('click', function (event) {
            event.preventDefault();
            hideHighlightTooltip();
            clearUserSelection();
        });

        var divParent = $('.test-contents, .test-panel');
        divParent.on('scroll', function () {
            if (tooltipVisible) {
                hideHighlightTooltip();
            }
        });
    }

    function hideHighlightTooltip(clearSelection = true) {
        $('#user-note-input').val('');
        highlightTooltip.hide();
        tooltipVisible = false;
        noting = false;
        highlightTooltip.removeClass('reactive reactive-note no-range');
        noteInput.hide();
        userSelectedRange = '';
        if (clearSelection) {
            clearUserSelection();
        }
        $(document).off('click', '#highlighter-contents', clickOutNotetHandler);
    }



    function clearUserSelection() {
        if (window.getSelection) {
            if (window.getSelection().empty) { // Chrome, Firefox, Opera, Safari
                window.getSelection().empty();
            }
            else if (window.getSelection().removeAllRanges) { // IE
                window.getSelection().removeAllRanges();
            }
        }
        else if (document.selection) {  // IE 8 and below
            document.selection.empty();
        }
    }

    function showNotePad() {

        $('#js-bt-notepad, .notepad__close-icon').click(function (event) {
            console.log(notes);
            $('body').toggleClass('notepad-open');
            if ($('body').hasClass('notepad-open')) {
                var notePadWidth = $('#notepad').outerWidth();
                highlighterContent.css({
                    'width': `calc(100% - ${notePadWidth}px)`,
                    'margin-left': 0
                });
            }
            else {
                highlighterContent.removeAttr('style');
            }

            // $('.test-panel, .test-contents').getNiceScroll().hide();
            highlighterContent.on('transitionstart', function () {
                $('body').addClass('transitioning');
                $('.test-panel, .test-contents').getNiceScroll().hide();
                highlighterContent.off('transitionstart');
            });

            highlighterContent.on('transitionend', function () {
                $('body').removeClass('transitioning');
                $('.test-panel, .test-contents').getNiceScroll().show().resize();
                highlighterContent.off('transitionend');
            });
        });

        $('#js-bt-notepad, #notepad').click(function (event) {
            newAddedNote = 0;
            $('#js-bt-notepad').removeClass('active');
        });

        $('#js-btn-note').click(function (event) {
            $(".highlight-box__note-content").show();
        });

        $('#cancel-note').click(function (event) {
            $(highlightTooltip, noteInput).hide();
            userSelectedRange = '';
            $('#user-note-input').val('');
            clearUserSelection();
        });
    }

    function setNotepadHeight() {
        var headerHeight = $('.realtest-header').outerHeight();
        // var questionPaletteHeight = $('.question-palette').outerHeight();
        var toolbarHeight = $('.ql-toolbar').outerHeight();
        var windowHeight = $(window).height();
        var notepadHeight = windowHeight - (headerHeight);
        /* $('#notepad').css({
            height: notepadHeight,
        }); */
    }

    // Run nice scroll bar for notes.
    function runNotesNiceScroll() {
        var noteContainer = $('#notepad');
        noteContainer.niceScroll({
            autohidemode: true,
            cursorborderradius: 6,
            cursorwidth: "2px",
            cursorcolor: "#dfdfdf",
        });
    }

    $(document).on('click', '.tab__proqyz', function () {
        var tabId = $(this).attr('id');
        // unactive all tabs and contents
        $('.tab__proqyz').removeClass('active');
        $('.tab-content__proqyz').removeClass('active');
        $(this).addClass('active');
        $(`.${tabId}`).addClass('active');
        $("#notepad").getNiceScroll().resize();
    });

    // End NOTE/HIGHLIGHT functions
    //-----------------------------------

    window.initNote = initNote;
    window.showNotePad = showNotePad;
    window.initHighlighter = initHighlighter;
    window.setNotepadHeight = setNotepadHeight;
    window.runNotesNiceScroll = runNotesNiceScroll;

    function insertCustomHTML(htmlContent) {
        // let delta = window['quill-instence'].clipboard.convert(htmlContent); // Convert to Quill Delta
        // let range = window['quill-instence'].getSelection(true);
        // window['quill-instence'].updateContents(delta, 'api'); // Insert as Delta
        let editor = document.querySelector('#highlighter-contents .ql-editor');
        if (editor) {
            editor.innerHTML = htmlContent; // Directly insert HTML without Quill filtering
        }
    }

    window.loadNotepad = () => {

        var quill = new Quill('#highlighter-contents', {
            theme: 'snow',
            placeholder: "Enter evaluation content",
            modules: {
                toolbar: [
                    ['bold', 'italic', 'underline', 'strike'], // Text styles
                    [{ 'color': [] }, { 'background': [] }], // Color & background
                    [{ 'script': 'sub' }, { 'script': 'super' }], // Subscript/Superscript
                    [{ 'header': [1, 2, 3, false] }],
                    [{ 'align': [] }],
                    ['clean'] // Remove styles
                ]
            },
            formats: ['bold', 'italic', 'underline', 'strike', 'color', 'background', 'script', 'header', 'align']
        });
        window['quill-instence'] = quill;

        showNotePad();

        //Handle notepad.
        setupNoteApp();

        setNotepadHeight();
        $(window).resize(function () {
            setNotepadHeight();
        });

        // Run nice scroll bar for notes.


        // Show button note and highlight when black out the text.
        // initHighlighter();
        initNote();
        // // Show tooltip.
        showHighlightTooltip();
        window.runNotesNiceScroll();

        // $( ".draggable-box" ).draggable({ handle: "div.drag-handler" });

    };

    window.loadNotepad();

    // evaluation modal events
    $(document).on('submit', '.generate-teacher-evaluation-box', function (event) {
        event.preventDefault();
        $('#evaluation-modal').modal('show');
        $('#evaluation-modal').addClass('loading');
        $('body').removeClass('is-sm-open');
        var sectionId = $(this).find('[name="section_id"]');
        var sectionOrder = $(this).find('[name="section_order"]');
        var resultId = $(this).find('[name="result_id"]');
        setData(null);
        window[sectionId] = $.ajax({
            url: "/wp-admin/admin-ajax.php",
            type: 'POST',
            data: {
                action: "proqyz-get-evaluation-data-teacher",
                result_id: resultId.val(),
                section_id: sectionId.val(),
                section_order: sectionOrder.val(),
                user_response: $(`textarea[data-section-id="${sectionId.val()}"][data-section-type="writing-essay"]`).val()
            },
            beforeSend: function () {
                if (window[sectionId] != null) {
                    window[sectionId].abort();
                }

            },
            success: function (response) {
                if (response?.success) {
                    const { review_content, review_comments, review_scores, review_comment_ids } = response?.success?.data;
                    setData({
                        review_comment_ids: review_comment_ids || [],
                        review_comments: review_comments || []
                    });
                    //$('.ql-editor').html(review_content || '');

                    insertCustomHTML(review_content);
                    $('#score-1').val(review_scores[0]);
                    $('#score-2').val(review_scores[1]);
                    $('#score-3').val(review_scores[2]);
                    $('#score-4').val(review_scores[3]);
                    $('#evaluation-modal').find('.modal-footer').html(`
                        
                        <div class="box-center">
                            <div class="toggle-container">
                                <span class="toggle-label --editing-txt">
                                    <i class="fas fa-edit"></i> Editing
                                </span>
                                <label class="switch">
                                    <input type="checkbox" id="evaluation-mode">
                                    <span class="slider round"> </span>
                                </label>
                                <span class="toggle-label --suggesting-txt">
                                    
                                    <i class="fas fa-lightbulb"></i> Suggesting
                                </span>
                            </div>
                        </div>


                        <div class="box-right">
                            <input type="hidden" name="section_id" value="${sectionId.val()}" />
                            <input type="hidden" name="result_id" value="${resultId.val()}" />
                            <input type="hidden" name="section_order" value="${sectionOrder.val()}" />

                            <button type="button" class="submit-button state-0" id="teacher__evaluation-form-v2--btn" data-form-id="#teacher__evaluation-form-v2">
                                <span class="pre-state-msg">Save</span>
                                <span class="current-state-msg btn-hide">Saving...</span>
                                <span class="done-state-msg btn-hide">Saved</span>
                            </button>

                        </div>
                            
                    `);


                    $('#evaluation-modal').removeClass('loading');
                    $("#notepad").getNiceScroll().resize();
                    // Automatically open the first tab on load
                    $(".hightlight-box--tab-pills:first").trigger("click");
                    renderNotes();

                }
            },
            error: function (err) {

            }
        });

    });

    $(document).on('change', '#evaluation-mode', function () {

        if (!window['quill-instence']) {
            $(this).prop('checked', false);
            return;
        }

        var mode = $(this).prop('checked');
        if (!mode) {
            window['quill-instence']?.enable(true);
            $('[role="toolbar"]').removeClass('hide');
            $('body').removeClass('suggesting--box');
            hideHighlightTooltip();
            setNotepadHeight();
            setTimeout(() => {
                $("#notepad").getNiceScroll().resize();
            }, 500);
        } else {
            window['quill-instence']?.enable(false);
            $('[role="toolbar"]').addClass('hide');
            $('body').addClass('suggesting--box');
            hideHighlightTooltip();
            setNotepadHeight();
            setTimeout(() => {
                $("#notepad").getNiceScroll().resize();
            }, 500);

        }
    });

    $(document).on('click', '#teacher__evaluation-form-v2--btn', function (event) {
        event.preventDefault();
        var formId = $(this).data('form-id');
        var sectionId = $(formId).find('[name="section_id"]');
        var resultId = $(formId).find('[name="result_id"]');
        var sectionOrder = $(formId).find('[name="section_order"]');
        var commentContent = $('.ql-editor').html();
        const submitBtn   = $('.submit-button');

        $.ajax({
            url: "/wp-admin/admin-ajax.php",
            type: 'POST',
            data: {
                action: "proqyz-teacher__evaluation-form-v2",
                result_id: resultId.val(),
                section_id: sectionId.val(),
                section_order: sectionOrder.val(),
                content: commentContent,
                comment_ids: NoteIds || [],
                comments: notes || [],
                scores: [$('#score-1').val(), $('#score-2').val(), $('#score-3').val(), $('#score-4').val()]
            },
            beforeSend: function () {
                submitBtn.addClass('state-1');
                submitBtn.addClass('animated');
                submitBtn.attr('disabled',true);

            },
            success: function (response) {
                if (response?.success) {
                    submitBtn.addClass('state-2');
                    setTimeout(() => {
                        submitBtn.removeClass('state-1');
                        submitBtn.removeClass('state-2');
                        submitBtn.removeClass('animated');
                        submitBtn.attr('disabled',false);
                    },2000);
                }
            },
            error: function (err) {
                console.log(err);
                submitBtn.attr('disabled',false);
                submitBtn.removeClass('state-1');
                submitBtn.removeClass('state-2');
                submitBtn.removeClass('animated');
            }
        });


    });

    $(document).on("click", ".hightlight-box--tab-pills", function () {
        var targetTab = $(this).data("target");

        // Remove active class from all tabs and add it to the clicked tab
        $(".hightlight-box--tab-pills").removeClass("active");
        $(this).addClass("active");

        // Hide all tab content and show the target tab content
        $(".hightlight-box--tab-content").removeClass('active');
        $(targetTab).addClass('active');
    });

    // reset evaluation request modal
    $(document).on("click", ".-reset-evaluation", function () {
        return;
        var modalId = $(this).data('target');
        var formId = $(this).data('parent');
        var form = $(formId);
        var sectionIid = form.find('[name="section_id"]');
        var sectionOrder = form.find('[name="section_order"]');
        var resultId = form.find('[name="result_id"]');
        var dataset = `
            <input type="hidden" name="section_id" value="${sectionIid.val()}" />
            <input type="hidden" name="section_order" value="${sectionOrder.val()}" />
            <input type="hidden" name="result_id" value="${resultId.val()}" />
            <button type="submit" class="btn-popup btn-speaking -confirm">
                <i class="fa fa-trash" aria-hidden="true"></i>Confirm 
            </button> 
            <button type="submit" class="btn-popup" data-dismiss="modal" aria-label="Close">
                <i class="fa fa-remove" aria-hidden="true"></i>Cancel 
            </button> 
        `;

        $(modalId).find('#form-modal-reset-evaluation').html(dataset);
        $(modalId).modal('show');
    });

    $(document).on('submit', '#form-modal-reset-evaluation', function (event) {
        event.preventDefault();
        console.log('form rest submitted');
    });

    $(document).on('click','.-toggle-notepad--btn', function(){
        $('body').addClass('is-sm-open');
    });

    $(document).on('click','.-toggle-notepad--btn-x', function(){
        $('body').removeClass('is-sm-open');
    });

});
