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;

    // --------------------------------
    // NOTE/HIGHLIGHT FUNCTIONS
    function getQuizId() {
        return 'practice_test';
    }

    // (Notepad) Setup note - Black out the text show active note and highlight.
    function setupNoteApp() {
        // var quizID = getQuizId();
        // // let notes = [];
        // // Check if localstorage contains any data
        // const localData = localStorage.getItem('notes_' + quizID);
        // // Retrieve the list of notes from localstorage
        // if (localData) {
        //   notes = JSON.parse(localData);
        // }
        //
        // if (notes && notes.length > 0) {
        //   // Display the saved notes
        //   renderNotes();
        // }

        // 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 searchResultDiv = `
            <div class="notepad__item" data-note-id="${note.id}" data-note-part="${note.noteOfPart}"  data-ref-id="${note.noteRefId}">
              <div class="notepad__item-title">${note.selectedText}</div>
              <div class="notepad__item-content-wrap">
                <div class="notepad__item-content">${note.noteText}</div>
              </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="${note.id}">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();
        });

        // 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 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();
            $(this).closest('.notepad__item-more').removeClass('active');
            editableDiv.attr("contentEditable", "true").focus();
            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');
            editableDiv.text(originalNoteContent).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();

            // 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;

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

            $(this).closest('.notepad__item-content-wrap').find('.notepad__item-content').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");
                    }
                    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 selectedText = noteString;
            const noteOfPart = $('.question-palette__part.-active').data('part');
            const noteRefId = $('#js-note-content').data('id');

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

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

                // 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('');
                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.
                const noteDiv = `
            <div class="notepad__item" data-note-id="${noteId}" data-note-part="${note.noteOfPart}" data-ref-id="${note.noteRefId}">
              <div class="notepad__item-title">${note.selectedText}</div>
              <div class="notepad__item-content-wrap">
                <div class="notepad__item-content">${note.noteText}</div>
              </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);
            });
        }
    }

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

            $("#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);
                });
            }

            $('#cancel-note').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) {
                    var timestamp = $('#js-note-content').data('timestamp');
                    replaceNoteToHightlight(timestamp);
                }
            });
        }

    }

    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('#note-mode')){
            //     return;
            // }

            if($('#evaluation-mode').val() == "editing"){
                return;
            }

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

            console.log("1");

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

    // Get user selected text.
    function getUserSelection() {
        let selectedText = '';
        if (typeof window.getSelection !== 'undefined') {
            selectedText = window.getSelection().toString();
        }
        else if (typeof document.selection !== 'undefined' && document.selection.type === 'Text') {
            selectedText = document.selection.createRange().text;
        }
        return selectedText;
    }

    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 windowHeight = $(window).height();
        var notepadHeight = windowHeight - (headerHeight + questionPaletteHeight);
        $('#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",
        });
    }

    // Clear data note.
    function clearDataNote() {
        var quizID = getQuizId();
        localStorage.removeItem('notes_' + quizID);
    }

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

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

    window.loadNotepad = () => {
        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.loadNotepad();
    window.runNotesNiceScroll();

    

    

});