if (IsChangelogPage) {
    $('#wh_publication_toc').remove();
    PrependClToc();
    CreateHeadingParasAndLists();
    CreateNewToc();
    ModifyCSS();
    if (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
    $('.clToc').empty().attr('id','clToc');
    $( ".clToc" ).append( "<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>" +
    "");
    $('.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
    $('<div class="FilterContainer">' + 
        '<div id="FilterIntro" class="ph">Filter this page</div>' + 
        '<div id="FilterControls">' +
            '<input type="text" id="filterText" value="' + DefaultText + '" />' + 
            // '<input type="button" id="filterButton" value="Filter" />' + 
            '<input type="button" id="clearButton" value="Clear" />' + 
        '</div>' +
        '</div>').insertBefore($("#FilterButtons"));
    $('.FilterContainer').css({
        // 'position':'absolute',
        // 'right':'300px',
        // 'margin-top' : '4px',
        'border' : '1px solid rgba(0, 0, 0, 0.2)',
        'border-radius' : '6px',
        'display' : 'flex',
        'align-items' : 'center'
    });
    $('#FilterControls').css({
        'margin-top':'-10px',
        'margin-bottom' : '4px'
    });
    $('#filterText').css({
        'color' : 'black',
        'font-size' : 'smaller',
        'width' : '184px',
        'padding': '0 6px 0 6px',
        'margin-right' : '5px',
        'border' : 'none'});
    $('#filterButton').css({
        'color' : 'black',
        'font-size' : 'smaller',
        'margin-right' : '2px',
        'border-radius' : '6px',
        'border' : 'none',
        'cursor' : 'pointer'});
    $('#clearButton').css({
        'color' : 'black',
        'font-size' : 'small',
        'border-radius' : '6px',
        'border' : 'none',
        'cursor' : 'pointer',
        'margin-top' : '4px'});
    $('#FilterIntro').css({
        'color' : '#6d6d6d',
        'font-size' : 'small',
        'font-weight' : '500',
        'margin-right' : '10px',
        'margin-left' : '4px'});

    //Select all of the input box when it gets the focus
    $('#filterText').focus(function() {
        $(this).select();
     });
    $('#filterText').keyup(function(e) {      

        if (event.key == "Escape") {
            //show tables
            $('table').each(function (){
                $(this).show();
            });

            //show list items
            $('li').each(function (){
                $(this).show();
            });

            //clear text box
            $('#filterText').val('Enter text (case-sensitive)');
            $('#filterText').select();
        }
        else {
                    // create the regular expression
        var 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
        $('#NewFeaturesList li').hide().filter(function() {
            return regEx.exec($(this).text());
        }).show();

        $('#EnhancementsList li').hide().filter(function() {
            return regEx.exec($(this).text());
        }).show();
        
        $('#DefectsList li').hide().filter(function() {
            return regEx.exec($(this).text());
        }).show();
        
        $('.rntitle').closest('.simpletable').hide().filter(function() {
            return regEx.exec($(this).text());
        }).show();

        }

    });

    $('#clearButton').click(function(){
        //show tables
        $('table').each(function (){
            $(this).show();
        });

        //show list items
        $('li').each(function (){
            $(this).show();
        });

        //clear text box
        $('#filterText').val(DefaultText);
        $('#filterText').select();
    });


    
    $('#filterButton').click(function(){
        var filterString = $('#filterText').val();

        //==== Do the filtering ====

        // filter the list items
        $('#EnhancementsList>li>a').each(function () {
            var index = $(this).index();
            var text = $(this).text();
            var n = text.startsWith(filterString);

            if (n == false){
                // $(this).remove();
                $(this).closest('li').hide();
            }
        });
        $('#DefectsList>li>a').each(function () {
            var index = $(this).index();
            var text = $(this).text();
            var n = text.startsWith(filterString);

            if (n == false){
                // $(this).remove();
                $(this).closest('li').hide();
            }
        });

        // filter the tables
        $('.rntitle').each(function () {
            var index = $(this).index();
            var text = $(this).text();
            var n = text.startsWith(filterString);

            if (n == false){
                // $(this).remove();
                $(this).closest('table').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;
        if (IsWKHosted || IsDGS
        ) {
            var curRev = $(this).closest('section').attr('data-rev');
            var EqualRevs = versionCompare(revLevel, curRev, true);
            if (curRev === revLevel) {
                ReleasenoteEqualsDatarev = true;
            } else {
                ReleasenoteEqualsDatarev = false;
            }
            if (EqualRevs > -1) {
                var title = $(this).find("th").text();
                var id = $(this).attr("id");
                var TypeFullText = $(this).find("li").first().text();
                var trimType = $.trim(TypeFullText);
                var type = trimType.split(" ").pop();
            }
        } else {
            var title = $(this).find("th").text();
            var id = $(this).attr("id");
            var TypeFullText = $(this).find("li").first().text();
            var trimType = $.trim(TypeFullText);
            var type = trimType.split(" ").pop();
        }
        if (
            (!IsWKHosted && !IsDGS) ||
            (IsWKHosted && ReleasenoteEqualsDatarev) ||
            (IsDGS && ReleasenoteEqualsDatarev)
        ) {
            if (type == "Feature") {
                $('#NewFeaturesList').append("<li>" +
                    "<a style='color: black' href='#" + id + "'>" + title + "</a></li>");
            }
            if (type == "Enhancement") {
                $('#EnhancementsList').append("<li>" +
                    "<a style='color: black' href='#" + id + "'>" + title + "</a></li>");
            }
            if (type == "Defect" || type == "Correction") {
                $('#DefectsList').append("<li>" +
                    "<a style='color: black' href='#" + id + "'>" + title + "</a></li>");
            }
        }
    });
}

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

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

function FilterFeature(){
    $('table').show();
    $('.rntitle').each(function () {
        var index = $(this).index();
        var text = $(this).closest('.simpletable').find('li:first').text();
        var n = text.indexOf('Feature');
        if (n === -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 (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');
    })
}
