// $('#searchForm div').addClass('divSearch');

$(document).ready(function() {
    // Remove any existing submit handlers from the search form
    $('#searchForm').off('submit');

    //#region More button and menu
    // Create the three-dots button
    var moreButton = $('<button type="button" class="btn btn-secondary" ' +
        'id="moreButton" aria-label="More options">' +
        '<i class="bi bi-three-dots-vertical"></i>' +
        '</button>');
    // Append the button to the body or another container
    $('body').append(moreButton);

    $('#moreButton').css({
        position: 'absolute',
        top: '20px',
        right: '20px',
        fontSize: 'x-large',
        color: '#ffffff',
        backgroundColor: '#85bc20',
        border: 'none',
    });

    // Create the menu
    var moreMenu = $('<div id="moreMenu" class="dropdown-menu">' +
        '<button class="dropdown-item" id="learnWebhelp"><i class="bi bi-mortarboard"></i>Learn about Webhelp features  <i class="bi bi-box-arrow-up-right"></i></button>' +
        '<div class="dropdown-divider"></div>' + 
        '<button class="dropdown-item" id="clearSessionStorage"><i class="bi bi-arrow-clockwise"></i>Reload page (F5)</button>' +
        '<button class="dropdown-item" id="clearLocalStorage"><i class="bi bi-trash"></i>Clear local storage and reload page</button>' +
        '<div class="dropdown-divider" id="logoutSeparator" hidden></div>' + 
        '<button class="dropdown-item" id="printButton"><i class="bi bi-printer"></i>Print page (Ctrl+P)</button>' +
        '<div class="dropdown-divider" id="logoutSeparator" hidden></div>' + 
        '<button class="dropdown-item" id="logoutButton" hidden><i class="bi bi-door-closed"></i>Logout</button>' +
        '</div>');
        
    // Style the menu
    moreMenu.css({
        position: 'absolute',
        display: 'none', // Initially hidden
        backgroundColor: '#ffffff',
        border: '1px solid #ccc',
        borderRadius: '8px',
        padding: '10px',
        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
        zIndex: 1000,
        width: 'fit-content',
    });

    // Append the menu to the body
    $('body').append(moreMenu);

    $("#logoutButton").click(function() {
        window.location.href = "/Logout.ashx";
    });

    // Toggle the menu on button click
    $('#moreButton').click(function() {
        // Get button position and size
        var buttonOffset = $(this).offset();
        var buttonHeight = $(this).outerHeight();
        var buttonWidth = $(this).outerWidth();
        
        // Position the menu right-aligned with the button
        moreMenu.css({
            top: buttonOffset.top + buttonHeight, // Position it below the button
            left: buttonOffset.left + buttonWidth - moreMenu.outerWidth() // Right-align it with the button
        });

        // Show/hide the menu
        moreMenu.toggle();
    });

    // Add hover effect to change background color
    $('#moreButton').hover(
        function() { // On mouse over
            $(this).css('backgroundColor', '#a3d34f'); // Lighter shade of #85bc20
        },
        function() { // On mouse out
            $(this).css('backgroundColor', '#85bc20'); // Original color
        }
    );

    // Attach function to Webhelp Learning
    $('#learnWebhelp').click(function() {
        window.open('/InfoDev/Using%20InfoDev%20WebHelp/index.html', '_blank');
    });

    // Attach function to clear local storage
    $('#clearLocalStorage').click(function() {
        localStorage.clear(); // Clears local storage for the current domain
        alert('Local storage cleared!');
        location.reload(true); // Force a reload, bypassing cache
    });

    // Attach function to clear session storage and reload page
    $('#clearSessionStorage').click(function() {
        // Clear session storage for the current domain
        // sessionStorage.clear();
        location.reload(true); // Force a reload, bypassing cache
    });

    // Attach function to print button
    $('#printButton').click(function() {
        window.print();
    });

    // Hide the menu when clicking outside of it
    $(document).click(function(event) {
        var target = $(event.target);
        // Check if the click is outside of the moreButton or moreMenu
        if (!target.closest('#moreButton').length && !target.closest('#moreMenu').length) {
            moreMenu.hide(); // Hide the menu
        }
    });

    // Append the button to the right side of the header
    $('#searchForm').append(moreButton); // Append button to the flex container
    //#endregion









    // Call CollapseHeaderTOC after the document is ready
    CollapseHeaderTOC();

    function CollapseHeaderTOC() {
    if (
        Variables.IsAssumptions ||
        Variables.IsAuthRNArchives ||
        Variables.IsExpereImpGuide ||
        Variables.IsFormsDesignUG ||
        Variables.IsMortgage || 
        Variables.IsSecAdmin || 
        Variables.IsSecAdminSelfHosted || 
        Variables.IsVanceo
    ) {
        // Set the divSearch to use flexbox
        $('.divSearch').css({
            'display': 'flex', // Use flexbox for layout
            'align-items': 'center', // Center items vertically
            'position': 'absolute', // Set position to absolute
            'width': '400px'
        });

        // Report the height of the header toc and adjust
        $('.wh_top_menu').addClass("collapse");
        var b = $('<input type="button" class="btn btn-primary" id="collapsebutton" value="Hide TOC"/>');

        // Append the button to the divSearch
        if (Variables.IsExpereImpGuide) {
            $('div.divSearch').append(b); // Append button to divSearch
        } else {
            $(b).insertAfter('#btnLogout'); // If not, insert after #btnLogout
        }

        $('#collapsebutton').click(function() {
            if ($('#collapsebutton').attr('value') == 'Show TOC') {
                $('.wh_top_menu').removeClass("collapse");
                $('#collapsebutton').attr('value', 'Hide TOC');
            } else {
                $('.wh_top_menu').addClass("collapse");
                $('#collapsebutton').attr('value', 'Show TOC');
            }
        });

        var toc_height = $('.wh_top_menu').height();
        if (toc_height >= 60) {
            $('.wh_top_menu').addClass("collapse");
            $('#collapsebutton').attr('value', 'Show TOC');
        } else {
            $('.wh_top_menu').removeClass("collapse");
            $('#collapsebutton').attr('value', 'Hide TOC');
        }
    }
    }

    


    // Intercept the search form submission
    $('#searchForm').off('submit').on('submit', function(event) {
        console.log('searchForm submitted');

        // Capture the search term
        var searchTerm = $('#textToSearch').val();

        // Send the search term to the PHP file via AJAX
        $.ajax({
            type: 'POST',
            url: '/feedback/submit-search.php',
            data: { searchTerm: searchTerm },
            dataType: 'json',
            success: function(response) {
                // Handle the response from the PHP file if needed
                console.log('search term submitted');
                // Optionally, you can show a success message or handle errors here
                $('#searchForm')[0].submit();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Error submitting search term:", textStatus, errorThrown);
                // Handle the error if needed
            }
        });

        // Continue with the original action
        // event.preventDefault(); // Prevent the default form submission
    });
});

