$(document).ready(function() {
    if (Variables.IsChangelogPage) {
        $('#wh_publication_toc').remove();
        PrependClToc();
        CreateHeadingParasAndLists();
        CreateNewToc();
        ModifyCSS();
        if (Variables.IsAuthoring) {
            sortChangelogNewFeatures();
            sortChangelogNavEnhancements();
            sortChangelogNavDefects();
            // NumberOfReleaseNotes();
        }

        // #region changelog ec
        $('.simpletable').each(function () {
            var x = Math.floor(Math.random() * 10000);
            $(this).find('.rntitle').first().addClass('parent').attr('id', x).css('border-bottom','0');
            // add type button
            var TypeFullText = $(this).find("li").first().text();
            var trimType = $.trim(TypeFullText);
            var type = trimType.split(" ").pop();
            var truncated = type.substr(0, 3);
            $(this).find('.rntitle').first().prepend ('<span class="clType ' + type + '">' + truncated + '</span');
            $(this).find('tbody > tr').each(function() {
                $(this).attr('class', ('child-' + x))
            });
        });

        $('th.parent')  
            .css("cursor", "pointer")  
            .attr("title", "Click to expand/collapse")  
            .click(function () {  
                var id = $(this).attr('id');
                var childId = 'child-' + id;
                $('.' + childId).toggle('slow');
            });
            
            
        $('.simpletable > tbody > tr[class*="child-"]').toggle();
        $('.-').css({'margin-top':'0'});
        $('section div.-').css({'display' : 'block'});
        $('.simpletable-container').css({'border-bottom' : 'none'});
        $('.wh_topic_toc').hide();

        // Create Changelog Tools from the clToc
        const changelogToolsHtml = `
            <h4 id='CLToolsHeading'>Changelog Tools</h4>
            <h5 id='CLToolsPara'>Filter</h5>
            <div class='btn-group' id='FilterButtons' role='group' aria-label='Filter Buttons'>
                <button type='button' class='btn btn-primary' title='Show only Feature release notes' onclick='FilterFeature();'>Features</button>
                <button type='button' class='btn btn-success' title='Show only Enhancement release notes' onclick='FilterEnhancement();'>Enhancements</button>
                <button type='button' class='btn btn-danger' title='Show only Defects release notes' onclick='FilterDefect()'>Defects</button>
                <button type='button' class='btn btn-secondary' onclick='ShowAllTables()'>Reset</button>
            </div>
            <h5 id='CLToolsPara'>Folding</h5>
            <div class='btn-group' id='FoldingButtons' role='group' aria-label='Folding Buttons'>
                <button type='button' class='btn btn-primary' title='Show all release notes' onclick='ShowAll()'><i class='bi bi-chevron-double-down'></i> Show All</button>
                <button type='button' class='btn btn-primary' title='Hide all release notes' onclick='HideAll()'><i class='bi bi-chevron-double-up'></i> Hide all</button>
                <button type='button' class='btn btn-primary' data-html='true' title='Show hidden release notes, Hide visible release notes' onclick='ToggleParents()'><i class='bi bi-toggles'></i> Toggle all</button>
            </div>`;
        
        $('.clToc').empty().attr('id', 'clToc').append(changelogToolsHtml);
        
        $('.simpletable > tbody > tr > td').css({ 'padding-left': '40px' });
        $('.btn_revision').parent().css('display', 'block');
        // #endregion

        // #region Filter
            // Create input box and buttons
        //Within wh_tools toolbar
        console.log($("#FilterButtons").length); // Should be > 0
        console.log("Inserting FilterContainer");
        const DefaultFilterInputText = "Enter text to start filtering";
        if ($("#FilterButtons").length) {
            $('<div class="FilterContainer">' +
                '<div id="FilterIntro" class="ph">Filter this page</div>' +
                '<div id="FilterControls">' +
                '<input type="text" id="filterText" value="' + DefaultFilterInputText + '" />' +
                '<input type="button" id="clearButton" value="Clear" />' +
                '</div>' +
                '</div>').insertBefore($("#FilterButtons"));
        } else {
            console.error("FilterButtons not found");
        }

        // Insert no match message
        const $noMatchMessage = $('<p id="noMatchMessage" style="color: red; display: none;">The term you typed is not available on this page.</p>');
        $noMatchMessage.insertAfter($('.FilterContainer'));

        $('.FilterContainer').css({
            'border': '1px solid rgba(0, 0, 0, 0.2)',
            'border-radius': '6px',
            'display': 'flex',
            'align-items': 'center',
            'margin-bottom': '10px',
            'width': '340px',
            'background-color': '#ecf2f9'
        });
        $('#FilterControls').css({
            'display': 'flex', // Use flexbox for layout
            'margin-top': '-10px',
            'margin-bottom': '4px',
            'flex-grow': '1', // Allow it to grow
            'width': '100%' // Ensure it takes full width
        });
        $('#filterText').css({
            'color': 'black',
            'font-size': 'smaller',
            'flex-grow': '1', // Allow the input to stretch
            'padding': '0 6px 0 6px',
            'margin-right': '5px',
            'border': 'none',
            'margin-top': '3px',
            'border-radius': '6px',
            // 'height': '36px', // Set a height to match the button if needed
            // 'line-height': '36px' // Center text vertically
        });
        $('#clearButton').css({
            'color': 'black',
            'font-size': 'small',
            'border-radius': '6px',
            'cursor': 'pointer',
            'margin-top': '4px',
            'background-color': '#ffffff',
            'border': '2px solid darkgrey',
            'margin-right': '4px',
        });
        $('#FilterIntro').css({
            'color': '#6d6d6d',
            'font-size': 'small',
            'font-weight': '500',
            'margin-right': '10px',
            'margin-left': '4px',
            'flex-shrink': '0' // Prevent wrapping by not allowing it to shrink
        });

        //Select all of the input box when it gets the focus
        $('#filterText').focus(function() {
            $(this).select();
        });
        
        // Cache jQuery selectors
        const $filterText = $('#filterText');
        const $tables = $('table');
        const $listItems = $('li');

        $filterText.on('keyup', function (e) {
            if (e.key === "Escape") {
                // Show tables
                $tables.show();
                // Show list items
                $listItems.show();
                // Clear text box
                $filterText.val('Enter text (case-sensitive)');
                $filterText.select();
                // Hide no match message
                $noMatchMessage.hide();
            } else {
                // Create the regular expression
                const regEx = new RegExp($.map($(this).val().trim().split(' '), function (v) {
                    return '(?=.*?' + v + ')';
                }).join(''), 'i');

                // Select all list items, hide and filter by the regex then show
                const newFeaturesMatch = $('#NewFeaturesList li').hide().filter(function () {
                    return regEx.exec($(this).text());
                }).show().length;

                const enhancementsMatch = $('#EnhancementsList li').hide().filter(function () {
                    return regEx.exec($(this).text());
                }).show().length;

                const defectsMatch = $('#DefectsList li').hide().filter(function () {
                    return regEx.exec($(this).text());
                }).show().length;

                const tablesMatch = $('.rntitle').closest('.simpletable').hide().filter(function () {
                    return regEx.exec($(this).text());
                }).show().length;

                if (newFeaturesMatch + enhancementsMatch + defectsMatch + tablesMatch === 0) {
                    $noMatchMessage.show();
                } else {
                    $noMatchMessage.hide();
                }
            }
        });

        $('#clearButton').click(function () {
            // Show tables
            $tables.show();
            // Show list items
            $listItems.show();
            // Clear text box
            $filterText.val(DefaultFilterInputText);
            $filterText.select();
            // Hide no match message
            $noMatchMessage.hide();
        });

        // #endregion
    }

});

function NumberOfReleaseNotes() {
    // Counting the number of .simpletable-container and .table-container elements
    var simpleTableCount = $('.simpletable-container').length;
    var tableCount = $('.table-container').length;
    var totalCount = simpleTableCount + tableCount;
    
    console.log('Number of .simpletable-container elements:', simpleTableCount);
    console.log('Number of .table-container elements:', tableCount);
    console.log('Total number of elements:', totalCount);
    
    // Selecting the target <p> element
    var targetP = $('h1#ariaid-title1').next('div').find('section').first().find('p').first();

    // Creating a span element for the totalCount and giving it an ID of 'RnCount'
    var countSpan = $('<span>', {
        id: 'RnCount',
        text: totalCount
    });

    // Creating a new span element with the totalCount span and the desired ID for the outer span
    var spanElement = $('<span>', {
        id: 'NumOfRNs',
        text: '   Number of release notes: '
    }).append(countSpan);

    // Appending the span element to the target <p> element
    targetP.append(spanElement);
}



function CreateHeadingParasAndLists() {
    $('.ChangelogNav').append('<p style="color: black"><b>New Features</b></p>' +
        '<ul id="NewFeaturesList"></ul>' +
        '<p style="color: black"><b>Enhancements</b></p>' +
        '<ul id="EnhancementsList"></ul>' +
        '<p style="color: black"><b>Defect Corrections</b></p>' +
        '<ul id="DefectsList"></ul>');
}

function CreateNewToc() {
    $(".simpletable").each(function () {
        var ReleasenoteEqualsDatarev = false;
    });
}

function FilterDefect() {
    $('table').show();
    $('.rntitle').each(function () {
        var text = $(this).closest('.simpletable').find('li:first').text();
        if (text.indexOf('Defect') === -1) {
            $(this).closest('table').hide();
        }
    });
}

function FilterEnhancement() {
    $('table').show();
    $('.rntitle').each(function () {
        var text = $(this).closest('.simpletable').find('li:first').text();
        if (text.indexOf('Enhancement') === -1) {
            $(this).closest('table').hide();
        }
    });
}

function FilterFeature() {
    $('table').show();
    $('.rntitle').each(function () {
        var text = $(this).closest('.simpletable').find('li:first').text();
        if (text.indexOf('Feature') === -1) {
            $(this).closest('table').hide();
        }
    });
}

function HideAll(){
    $('th.parent').each(function (index) {
        var id = $(this).attr('id');
        var childId = 'child-' + id;
        $('.' + childId).animate( { "opacity": "hide", top:"150"} , 800 );
    })
}

function InsertCurrentReleaseTitle() {
    if (Variables.IsPnP || IsWKHosted) {
        if (revLevel !== null) {
            $('.ChangelogNav').append('<p><b>Current Release:</b>  ' + revLevel + '</p>');
        } else {
            $('.ChangelogNav').append('<p><b>Current Release:</b>  </p>');
        }
    }
}

function ModifyCSS() { $('.ChangelogLink').css({ });
}

function PrependClToc() {
    $('#wh_topic_body').attr("class", "col-lg-8 col-sm-12");

    $('<nav class="clToc col-lg-4 d-none d-lg-block navbar d-print-none"><section class="section ChangelogNav" style="background-color: #C5C5C5; border-radius: 10px; padding: 10px 20px;"></section></nav>').insertAfter('#wh_topic_body');
}

function sortChangelogNavDefects() {
    var myDeflist = $('#DefectsList');
    var DefListItems = myDeflist.children('li').get();
    DefListItems.sort(function (a, b) {
        return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
    })
    $.each(DefListItems, function (idx, itm) {
        myDeflist.append(itm);
    });
}

function sortChangelogNavEnhancements() {
    var myEnhlist = $('#EnhancementsList');
    var EnhListItems = myEnhlist.children('li').get();
    EnhListItems.sort(function (a, b) {
        return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
    })
    $.each(EnhListItems, function (idx, itm) {
        myEnhlist.append(itm);
    });
}

function sortChangelogNewFeatures() {
    var myFeatlist = $('#NewFeaturesList');
    var NewFeatureListItems = myFeatlist.children('li').get();
    NewFeatureListItems.sort(function (a, b) {
        return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
    })
    $.each(NewFeatureListItems, function (idx, itm) {
        myFeatlist.append(itm);
    });
}

function ShowAll(){
    $('th.parent').each(function (index) {
        var id = $(this).attr('id');
        var childId = 'child-' + id;
        $('.' + childId).animate( { "opacity": "show", top:"150"} , 1000 );
    })
}

function ShowAllTables(){
    $('table').show();
}

function ToggleParents(){
    $('th.parent').each(function (index) {
        var id = $(this).attr('id');
        var childId = 'child-' + id;
        $('.' + childId).toggle('slow');
    })
}
