MediaWiki:Common.js: Difference between revisions

From softwear.directory
Jump to navigation Jump to search
No edit summary
No edit summary
Tag: Reverted
(46 intermediate revisions by the same user not shown)
Line 1: Line 1:
$(document).ready(function() {
$(document).ready(function () {
    // Global variables
  // Global variables
    var cards = $('.card');
  var cards = $(".card");
    var showArticleWrapper = $('#show-article-wrapper');
  var showArticleWrapper = $("#show-article-wrapper");
    var areFiltersActive = false;
  var areFiltersActive = false;


    // Make header-box in Home clickable
  // Make header-box in Home clickable
    $('.head-box').click(function() {
  $(".head-box").click(function () {
        window.location.href = '/Main_Page'; // Redirects to the home page
    window.location.href = "/Main_Page"; // Redirects to the home page
     });
  });
 
  // Loop through each card to format related articles
  cards.each(function () {
     // Check if the card has related articles
    var relatedArticles = $(this).find(".related-articles");
    if (relatedArticles.length > 0) {
      // Get all the related article elements
      var relatedArticleElements = relatedArticles.find(".related-article");
 
      // Create an array to store unique related articles
      var uniqueArticles = [];


    // Loop through each card to format related articles
      // Loop through each related article element
    cards.each(function() {
      relatedArticleElements.each(function () {
         // Check if the card has related articles
         // Remove <p> tags from the article
         var relatedArticles = $(this).find('.related-articles');
         $(this).find("p").remove();
        if (relatedArticles.length > 0) {
            // Get all the related article elements
            var relatedArticleElements = relatedArticles.find('.related-article');


            // Create an array to store unique related articles
        // Convert the article HTML to a string
            var uniqueArticles = [];
        var articleHTML = $(this)[0].outerHTML;


            // Loop through each related article element
        // Check if the article HTML already exists in the uniqueArticles array
            relatedArticleElements.each(function() {
        if ($.inArray(articleHTML, uniqueArticles) === -1) {
                // Remove <p> tags from the article
          // If it doesn't exist, add it to the uniqueArticles array
                $(this).find('p').remove();
          uniqueArticles.push(articleHTML);
        }
      });


                // Convert the article HTML to a string
      // Clear the content of the related articles container
                var articleHTML = $(this)[0].outerHTML;
      relatedArticles.empty();


                // Check if the article HTML already exists in the uniqueArticles array
      // Append the unique related articles back to the container
                if ($.inArray(articleHTML, uniqueArticles) === -1) {
      relatedArticles.append(uniqueArticles.join(""));
                    // If it doesn't exist, add it to the uniqueArticles array
    }
                    uniqueArticles.push(articleHTML);
  });
                }
            });


            // Clear the content of the related articles container
  // Utility Functions
            relatedArticles.empty();
  function sortChronologically() {
    var cards = $(".list-container .card").get();


            // Append the unique related articles back to the container
    cards.sort(function (a, b) {
            relatedArticles.append(uniqueArticles.join(''));
      var numberA = parseInt(
        }
        $(a).find(".entry-number").text().replace(/\[|\]/g, ""),
        10
      );
      var numberB = parseInt(
        $(b).find(".entry-number").text().replace(/\[|\]/g, ""),
        10
      );
      return numberB - numberA; // Descending order
     });
     });


     // Utility Functions
     $.each(cards, function (index, item) {
    function sortChronologically() {
      $(".list-container").append(item);
        var cards = $('.list-container .card').get();
    });
  }


        cards.sort(function(a, b) {
  function randomizeCards(selector) {
            var numberA = parseInt($(a).find('.entry-number').text().replace(/\[|\]/g, ''), 10);
    var cards = $(selector).get();
            var numberB = parseInt($(b).find('.entry-number').text().replace(/\[|\]/g, ''), 10);
            return numberB - numberA; // Descending order
        });


        $.each(cards, function(index, item) {
    var i = cards.length,
            $('.list-container').append(item);
      j,
        });
      temp;
    while (--i > 0) {
      j = Math.floor(Math.random() * (i + 1));
      temp = cards[i];
      cards[i] = cards[j];
      cards[j] = temp;
     }
     }


     function randomizeCards(selector) {
     $.each(cards, function (index, item) {
        var cards = $(selector).get();
      $(selector).parent().append(item);
    });
  }
 
  function sortAlphabetically(selector) {
    var cards = $(selector).get();
 
    cards.sort(function (a, b) {
      var titleA = $(a).find(".title").text().toUpperCase();
      var titleB = $(b).find(".title").text().toUpperCase();
      return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
    });
 
    $.each(cards, function (index, item) {
      $(selector).parent().append(item);
    });
  }
 
  function updateViews() {
    // Handle cards in the list view
    $(".home-chronicle-list div.list-container div.card:not(.event)").each(
      function () {
        if (!$(this).closest(".home-chronicle-block").length) {
          var title = $(this).find(".title").detach();
          var images = $(this).find(".images").detach();
 
          // Remove existing .title-images if it exists
          $(this).find(".title-images").remove();


        var i = cards.length, j, temp;
          var titleImagesContainer = $(
        while (--i > 0) {
            '<div class="title-images"></div>'
            j = Math.floor(Math.random() * (i + 1));
          ).append(images, title);
            temp = cards[i];
          $(this).find(".people").after(titleImagesContainer);
            cards[i] = cards[j];
            cards[j] = temp;
         }
         }
      }
    );
    // Handle cards in the block view
    $(".home-chronicle-block div.list-container div.card:not(.event)").each(
      function () {
        // Remove .title-images container if it exists, re-attach .title and .images to their original places
        var titleImagesContainer = $(this).find(".title-images");
        if (titleImagesContainer.length) {
          var title = titleImagesContainer.find(".title").detach();
          var images = titleImagesContainer.find(".images").detach();
          titleImagesContainer.remove();


         $.each(cards, function(index, item) {
          $(this).find(".people").after(title);
            $(selector).parent().append(item);
          $(this).find(".type").after(images);
         });
         } else {
    }
          // If .title-images doesn't exist, ensure .images is placed correctly
          var images = $(this).find(".images").detach();
          $(this).find(".type").after(images);
         }
      }
    );
  }


     function sortAlphabetically(selector) {
  function processEventCards() {
        var cards = $(selector).get();
     $(".card.event").each(function () {
      var $card = $(this);
      var existingContainer = $card.find(".container-people-date");


        cards.sort(function(a, b) {
      // Create container if missing
            var titleA = $(a).find('.title').text().toUpperCase();
      if (existingContainer.length === 0) {
            var titleB = $(b).find('.title').text().toUpperCase();
        existingContainer = $('<div class="container-people-date"></div>');
            return (titleA < titleB) ? -1 : (titleA > titleB) ? 1 : 0;
        $card.append(existingContainer); // temp placement
        });
      }


        $.each(cards, function(index, item) {
      // Detach people and date
            $(selector).parent().append(item);
      var people = $card.find(".people").detach();
        });
      var date = $card.find(".date").detach();
    }


    function updateViews() {
      // BLOCK VIEW (gallery)
        // Handle cards in the list view
      if ($card.closest(".home-chronicle-block").length) {
        $('.home-chronicle-list div.list-container div.card:not(.event)').each(function() {
        existingContainer.append(people).append(date);
            if (!$(this).closest('.home-chronicle-block').length) {
                var title = $(this).find('.title').detach();
                var images = $(this).find('.images').detach();
   
                // Remove existing .title-images if it exists
                $(this).find('.title-images').remove();
   
                var titleImagesContainer = $('<div class="title-images"></div>').append(images, title);
                $(this).find('.people').after(titleImagesContainer);
            }
        });
   
        // Handle cards in the block view
        $('.home-chronicle-block div.list-container div.card:not(.event)').each(function() {
            // Remove .title-images container if it exists, re-attach .title and .images to their original places
            var titleImagesContainer = $(this).find('.title-images');
            if (titleImagesContainer.length) {
                var title = titleImagesContainer.find('.title').detach();
                var images = titleImagesContainer.find('.images').detach();
                titleImagesContainer.remove();
   
                $(this).find('.people').after(title);
                $(this).find('.type').after(images);
            } else {
                // If .title-images doesn't exist, ensure .images is placed correctly
                var images = $(this).find('.images').detach();
                $(this).find('.type').after(images);
            }
        });
    } 


    function processEventCards() {
        // Place container after title
         $('.card.event').each(function() {
         if (!existingContainer.is($card.find(".title").next())) {
            var $card = $(this);
          $card.find(".title").after(existingContainer);
            var existingContainer = $card.find('.container-people-date');
        }


            // Create container if missing
        // LIST VIEW
            if (existingContainer.length === 0) {
      } else if ($card.closest(".home-chronicle-list").length) {
                existingContainer = $('<div class="container-people-date"></div>');
        // Only append .people into container
                $card.append(existingContainer); // temp placement
        existingContainer.empty().append(people);
            }


            // Detach people and date
        // Place container before title
            var people = $card.find('.people').detach();
        $card.find(".title").before(existingContainer);
            var date = $card.find('.date').detach();


            // BLOCK VIEW (gallery)
        // Place date after title
            if ($card.closest('.home-chronicle-block').length) {
        $card.find(".title").after(date);
                existingContainer.append(people).append(date);
      }
    });
  }


                // Place container after title
  if ($("#home").length > 0) {
                if (!existingContainer.is($card.find('.title').next())) {
    // This code will only run only on the homepage.
                    $card.find('.title').after(existingContainer);
    $(".home-block-view").show();
                }
    $(".home-chronicle-block-button, .home-block-view-button").addClass(
      "active-view-button"
    );


            // LIST VIEW
    // Initially hide list view sorting buttons and set the default sorted view for block
            } else if ($card.closest('.home-chronicle-list').length) {
    $(
                // Only append .people into container
      ".home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button"
                existingContainer.empty().append(people);
    ).hide();
    sortChronologically(); // Sort the block view chronologically by default


                // Place container before title
    updateLastVisibleCard();
                $card.find('.title').before(existingContainer);
    updateWidthBlockView();
    processEventCards();
    updateViews();


                // Place date after title
    $(".home-list-view-button").click(function () {
                $card.find('.title').after(date);
      $(".home-list-sorting-buttons").css("display", "flex");
            }
      // Switching view classes
         });
      $(".home-block-view")
    }
        .removeClass("home-block-view")
        .addClass("home-list-view");
      // Additional class switch
      $(".home-chronicle-block")
        .removeClass("home-chronicle-block")
        .addClass("home-chronicle-list");
      // Toggling visibility of buttons
      $(
        ".home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button"
      ).hide();
      $(
         ".home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button"
      ).show();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();


    if ($('#home').length > 0) {
      // Remove active class from block view button and add to list view button
        console.log("The #home element exists on this page.");
      $(".home-block-view-button").removeClass("active-view-button");
        // This code will only run only on the homepage.
      $(".home-list-view-button").addClass("active-view-button");
        // Show the block view container once everything is set up
        $('.home-block-view').show();
        $('.home-chronicle-block-button, .home-block-view-button').addClass('active-view-button');


        // Initialization and Default Settings
      // Conditional checks for transferring the active class from block to list buttons
        // Initially hide list view sorting buttons and set the default sorted view for block
      if ($(".home-chronicle-block-button").hasClass("active-view-button")) {
         $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').hide();
        $(".home-chronicle-block-button").removeClass("active-view-button");
         sortChronologically(); // Sort the block view chronologically by default
         $(".home-chronicle-list-button").addClass("active-view-button");
       
      } else if (
         updateLastVisibleCard();
        $(".home-random-block-button").hasClass("active-view-button")
         updateWidthBlockView();
      ) {
        processEventCards();
        $(".home-random-block-button").removeClass("active-view-button");
        updateViews();
         $(".home-random-list-button").addClass("active-view-button");
      } else if (
        $(".home-alphabetical-block-button").hasClass("active-view-button")
      ) {
         $(".home-alphabetical-block-button").removeClass("active-view-button");
         $(".home-alphabetical-list-button").addClass("active-view-button");
      }
    });


        $('.home-list-view-button').click(function() {
    $(".home-block-view-button").click(function () {
            console.log("List view button clicked.");
      console.log("Block view button clicked.");
            $(".home-list-sorting-buttons").css('display', 'flex');
      $(".home-list-sorting-buttons").hide(); // Hide list sorting buttons
            // Switching view classes
      $(".home-list-view")
            $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
        .removeClass("home-list-view")
            // Additional class switch
        .addClass("home-block-view");
            $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
      $(".home-chronicle-list")
            // Toggling visibility of buttons
        .removeClass("home-chronicle-list")
            $('.home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button').hide();
        .addClass("home-chronicle-block");
            $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').show();
      $(
            updateLastVisibleCard();
        ".home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button"
            updateWidthBlockView();
      ).show();
            processEventCards();
      $(
            updateViews();
        ".home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button"
      ).hide();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-list-view-button").removeClass("active-view-button");
      $(".home-block-view-button").addClass("active-view-button");


            // Remove active class from block view button and add to list view button
      // Conditional checks for transferring the active class from block to list buttons
            $('.home-block-view-button').removeClass('active-view-button');
      if ($(".home-chronicle-list-button").hasClass("active-view-button")) {
            $('.home-list-view-button').addClass('active-view-button');
        $(".home-chronicle-list-button").removeClass("active-view-button");
       
        $(".home-chronicle-block-button").addClass("active-view-button");
            // Conditional checks for transferring the active class from block to list buttons
      } else if ($(".home-random-list-button").hasClass("active-view-button")) {
            if ($('.home-chronicle-block-button').hasClass('active-view-button')) {
        $(".home-random-list-button").removeClass("active-view-button");
                $('.home-chronicle-block-button').removeClass('active-view-button');
        $(".home-random-block-button").addClass("active-view-button");
                $('.home-chronicle-list-button').addClass('active-view-button');
      } else if (
            } else if ($('.home-random-block-button').hasClass('active-view-button')) {
        $(".home-alphabetical-list-button").hasClass("active-view-button")
                $('.home-random-block-button').removeClass('active-view-button');
      ) {
                $('.home-random-list-button').addClass('active-view-button');
        $(".home-alphabetical-list-button").removeClass("active-view-button");
            } else if ($('.home-alphabetical-block-button').hasClass('active-view-button')) {
        $(".home-alphabetical-block-button").addClass("active-view-button");
                $('.home-alphabetical-block-button').removeClass('active-view-button');
      }
                $('.home-alphabetical-list-button').addClass('active-view-button');
    });
            }
        });
       
        $('.home-block-view-button').click(function() {
            console.log("Block view button clicked.");
            $('.home-list-sorting-buttons').hide(); // Hide list sorting buttons
            $('.home-list-view').removeClass('home-list-view').addClass('home-block-view');
            $('.home-chronicle-list').removeClass('home-chronicle-list').addClass('home-chronicle-block');
            $('.home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button').show();
            $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').hide();
            updateLastVisibleCard();
            updateWidthBlockView();
            processEventCards();
            updateViews();
            $('.home-list-view-button').removeClass('active-view-button');
            $('.home-block-view-button').addClass('active-view-button');


            // Conditional checks for transferring the active class from block to list buttons
    // BLOCK VIEW SORTING BUTTONS
            if ($('.home-chronicle-list-button').hasClass('active-view-button')) {
    $(".home-chronicle-block-button").click(function () {
                $('.home-chronicle-list-button').removeClass('active-view-button');
      sortChronologically();
                $('.home-chronicle-block-button').addClass('active-view-button');
            } else if ($('.home-random-list-button').hasClass('active-view-button')) {
                $('.home-random-list-button').removeClass('active-view-button');
                $('.home-random-block-button').addClass('active-view-button');
            } else if ($('.home-alphabetical-list-button').hasClass('active-view-button')) {
                $('.home-alphabetical-list-button').removeClass('active-view-button');
                $('.home-alphabetical-block-button').addClass('active-view-button');
            }
        });
       
        // BLOCK VIEW SORTING BUTTONS
        $('.home-chronicle-block-button').click(function() {
            sortChronologically();


            updateLastVisibleCard();
      updateLastVisibleCard();
            updateWidthBlockView();
      updateWidthBlockView();
            processEventCards();
      processEventCards();
            updateViews();
      updateViews();
            $('.home-chronicle-block-button').addClass('active-view-button');
      $(".home-chronicle-block-button").addClass("active-view-button");
            $('.home-random-block-button').removeClass('active-view-button');
      $(".home-random-block-button").removeClass("active-view-button");
            $('.home-alphabetical-block-button').removeClass('active-view-button');
      $(".home-alphabetical-block-button").removeClass("active-view-button");
        });
    });
       
        $('.home-random-block-button').click(function() {
            randomizeCards('.list-container .card');


            updateLastVisibleCard();
    $(".home-random-block-button").click(function () {
            updateWidthBlockView();
      randomizeCards(".list-container .card");
            processEventCards();
            updateViews();
            $('.home-random-block-button').addClass('active-view-button');
            $('.home-chronicle-block-button').removeClass('active-view-button');
            $('.home-alphabetical-block-button').removeClass('active-view-button');
        });


        $('.home-alphabetical-block-button').click(function() {
      updateLastVisibleCard();
            sortAlphabetically('.list-container .card');
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-random-block-button").addClass("active-view-button");
      $(".home-chronicle-block-button").removeClass("active-view-button");
      $(".home-alphabetical-block-button").removeClass("active-view-button");
    });


            updateLastVisibleCard();
    $(".home-alphabetical-block-button").click(function () {
            updateWidthBlockView();
      sortAlphabetically(".list-container .card");
            processEventCards();
            updateViews();
            $('.home-alphabetical-block-button').addClass('active-view-button');
            $('.home-chronicle-block-button').removeClass('active-view-button');
            $('.home-random-block-button').removeClass('active-view-button');
        });


        // LIST VIEW SORTING BUTTONS
      updateLastVisibleCard();
        $('.home-chronicle-list-button').click(function() {
      updateWidthBlockView();
            sortChronologically();
      processEventCards();
      updateViews();
      $(".home-alphabetical-block-button").addClass("active-view-button");
      $(".home-chronicle-block-button").removeClass("active-view-button");
      $(".home-random-block-button").removeClass("active-view-button");
    });


            updateLastVisibleCard();
    // LIST VIEW SORTING BUTTONS
            updateWidthBlockView();
    $(".home-chronicle-list-button").click(function () {
            processEventCards();
      sortChronologically();
            updateViews();
            $('.home-chronicle-list-button').addClass('active-view-button');
            $('.home-random-list-button').removeClass('active-view-button');
            $('.home-alphabetical-list-button').removeClass('active-view-button');
        });


        $('.home-random-list-button').click(function() {
      updateLastVisibleCard();
            randomizeCards('.list-container .card');
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-chronicle-list-button").addClass("active-view-button");
      $(".home-random-list-button").removeClass("active-view-button");
      $(".home-alphabetical-list-button").removeClass("active-view-button");
    });


            updateLastVisibleCard();
    $(".home-random-list-button").click(function () {
            updateWidthBlockView();
      randomizeCards(".list-container .card");
            processEventCards();
            updateViews();
            $('.home-random-list-button').addClass('active-view-button');
            $('.home-chronicle-list-button').removeClass('active-view-button');
            $('.home-alphabetical-list-button').removeClass('active-view-button');
        });


        $('.home-alphabetical-list-button').click(function() {
      updateLastVisibleCard();
            sortAlphabetically('.list-container .card');
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-random-list-button").addClass("active-view-button");
      $(".home-chronicle-list-button").removeClass("active-view-button");
      $(".home-alphabetical-list-button").removeClass("active-view-button");
    });


            updateLastVisibleCard();
    $(".home-alphabetical-list-button").click(function () {
            updateWidthBlockView();
      sortAlphabetically(".list-container .card");
            processEventCards();
            updateViews();
            $('.home-alphabetical-list-button').addClass('active-view-button');
            $('.home-chronicle-list-button').removeClass('active-view-button');
            $('.home-random-list-button').removeClass('active-view-button');
        });
    } else {
        console.log("NOT HOMEPAGE");
        $('.home-list-view').show();
        $('.chronicle-list-button, .list-view-button').addClass('active-view-button');


        // Initialization and Default Settings
      updateLastVisibleCard();
        // Initially hide block view sorting buttons and set the default sorted view for list
      updateWidthBlockView();
        $('.chronicle-block-button, .random-block-button, .alphabetical-block-button').hide();
      processEventCards();
        sortChronologically(); // Sort the block view chronologically by default
      updateViews();
        updateLastVisibleCard();
      $(".home-alphabetical-list-button").addClass("active-view-button");
        updateWidthBlockView();
      $(".home-chronicle-list-button").removeClass("active-view-button");
        processEventCards();
      $(".home-random-list-button").removeClass("active-view-button");
        updateViews();
    });
  } else {
    console.log("NOT HOMEPAGE");
    $(".home-list-view").show();
    $(".chronicle-list-button, .list-view-button").addClass(
      "active-view-button"
    );


        $('.list-view-button').click(function() {
    // Initialization and Default Settings
            console.log("List view button clicked.");
    // Initially hide block view sorting buttons and set the default sorted view for list
            $(".list-sorting-buttons").css('display', 'flex');
    $(
            $('.block-sorting-buttons').hide();
      ".chronicle-block-button, .random-block-button, .alphabetical-block-button"
            // Switching view classes
    ).hide();
            $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
    sortChronologically(); // Sort the block view chronologically by default
            // Additional class switch
    updateLastVisibleCard();
            $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
    updateWidthBlockView();
            // Toggling visibility of buttons
    processEventCards();
            $('.chronicle-block-button, random-block-button, alphabetical-block-button').hide();
    updateViews();
            $('.chronicle-list-button, .random-list-button, .alphabetical-list-button').show();
            updateLastVisibleCard();
            updateWidthBlockView();
            processEventCards();
            updateViews();
       
            // Remove active class from block view button and add to list view button
            $('.block-view-button').removeClass('active-view-button');
            $('.list-view-button').addClass('active-view-button');
       
            // Conditional checks for transferring the active class from block to list buttons
            if ($('.chronicle-block-button').hasClass('active-view-button')) {
                $('.chronicle-block-button').removeClass('active-view-button');
                $('.chronicle-list-button').addClass('active-view-button');
            } else if ($('.random-block-button').hasClass('active-view-button')) {
                $('.random-block-button').removeClass('active-view-button');
                $('.random-list-button').addClass('active-view-button');
            } else if ($('.alphabetical-block-button').hasClass('active-view-button')) {
                $('.alphabetical-block-button').removeClass('active-view-button');
                $('.alphabetical-list-button').addClass('active-view-button');
            }
        });


        $('.block-view-button').click(function() {
    $(".list-view-button").click(function () {
            console.log("Block view button clicked.");
      console.log("List view button clicked.");
            $('.list-sorting-buttons').hide(); // Hide list sorting buttons
      $(".list-sorting-buttons").css("display", "flex");
            $(".block-sorting-buttons").css('display', 'flex');
      $(".block-sorting-buttons").hide();
            $('.home-list-view').removeClass('home-list-view').addClass('home-block-view');
      // Switching view classes
            $('.home-chronicle-list').removeClass('home-chronicle-list').addClass('home-chronicle-block');
      $(".home-block-view")
            $('.chronicle-block-button, .random-block-button, .alphabetical-block-button').show();
        .removeClass("home-block-view")
            $('.chronicle-list-button, .random-list-button, .alphabetical-list-button').hide();
        .addClass("home-list-view");
            updateLastVisibleCard();
      // Additional class switch
            updateWidthBlockView();
      $(".home-chronicle-block")
            processEventCards();
        .removeClass("home-chronicle-block")
            updateViews();
        .addClass("home-chronicle-list");
            $('.list-view-button').removeClass('active-view-button');
      // Toggling visibility of buttons
            $('.block-view-button').addClass('active-view-button');
      $(
        ".chronicle-block-button, .random-block-button, .alphabetical-block-button"
      ).hide();
      $(
        ".chronicle-list-button, .random-list-button, .alphabetical-list-button"
      ).show();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();


            // Conditional checks for transferring the active class from block to list buttons
      // Remove active class from block view button and add to list view button
            if ($('.chronicle-list-button').hasClass('active-view-button')) {
      $(".block-view-button").removeClass("active-view-button");
                $('.chronicle-list-button').removeClass('active-view-button');
      $(".list-view-button").addClass("active-view-button");
                $('.chronicle-block-button').addClass('active-view-button');
            } else if ($('.random-list-button').hasClass('active-view-button')) {
                $('.random-list-button').removeClass('active-view-button');
                $('.random-block-button').addClass('active-view-button');
            } else if ($('.alphabetical-list-button').hasClass('active-view-button')) {
                $('.alphabetical-list-button').removeClass('active-view-button');
                $('.alphabetical-block-button').addClass('active-view-button');
            }
        });


        // BLOCK VIEW SORTING BUTTONS
      // Conditional checks for transferring the active class from block to list buttons
         $('.chronicle-block-button').click(function() {
      if ($(".chronicle-block-button").hasClass("active-view-button")) {
            sortChronologically();
         $(".chronicle-block-button").removeClass("active-view-button");
        $(".chronicle-list-button").addClass("active-view-button");
      } else if ($(".random-block-button").hasClass("active-view-button")) {
        $(".random-block-button").removeClass("active-view-button");
        $(".random-list-button").addClass("active-view-button");
      } else if (
        $(".alphabetical-block-button").hasClass("active-view-button")
      ) {
        $(".alphabetical-block-button").removeClass("active-view-button");
        $(".alphabetical-list-button").addClass("active-view-button");
      }
    });


            updateLastVisibleCard();
    $(".block-view-button").click(function () {
            updateWidthBlockView();
      console.log("Block view button clicked.");
            processEventCards();
      $(".list-sorting-buttons").hide(); // Hide list sorting buttons
            updateViews();
      $(".block-sorting-buttons").css("display", "flex");
            $('.chronicle-block-button').addClass('active-view-button');
      $(".home-list-view")
            $('.random-block-button').removeClass('active-view-button');
        .removeClass("home-list-view")
            $('.alphabetical-block-button').removeClass('active-view-button');
        .addClass("home-block-view");
        });
      $(".home-chronicle-list")
       
        .removeClass("home-chronicle-list")
        $('.random-block-button').click(function() {
        .addClass("home-chronicle-block");
            randomizeCards('.list-container .card');
      $(
        ".chronicle-block-button, .random-block-button, .alphabetical-block-button"
      ).show();
      $(
        ".chronicle-list-button, .random-list-button, .alphabetical-list-button"
      ).hide();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".list-view-button").removeClass("active-view-button");
      $(".block-view-button").addClass("active-view-button");


            updateLastVisibleCard();
      // Conditional checks for transferring the active class from block to list buttons
            updateWidthBlockView();
      if ($(".chronicle-list-button").hasClass("active-view-button")) {
            processEventCards();
        $(".chronicle-list-button").removeClass("active-view-button");
            updateViews();
        $(".chronicle-block-button").addClass("active-view-button");
            $('.random-block-button').addClass('active-view-button');
      } else if ($(".random-list-button").hasClass("active-view-button")) {
            $('.chronicle-block-button').removeClass('active-view-button');
        $(".random-list-button").removeClass("active-view-button");
            $('.alphabetical-block-button').removeClass('active-view-button');
        $(".random-block-button").addClass("active-view-button");
        });
      } else if (
        $(".alphabetical-list-button").hasClass("active-view-button")
      ) {
        $(".alphabetical-list-button").removeClass("active-view-button");
        $(".alphabetical-block-button").addClass("active-view-button");
      }
    });


        $('.alphabetical-block-button').click(function() {
    // BLOCK VIEW SORTING BUTTONS
            sortAlphabetically('.list-container .card');
    $(".chronicle-block-button").click(function () {
      sortChronologically();


            updateLastVisibleCard();
      updateLastVisibleCard();
            updateWidthBlockView();
      updateWidthBlockView();
            processEventCards();
      processEventCards();
            updateViews();
      updateViews();
            $('.alphabetical-block-button').addClass('active-view-button');
      $(".chronicle-block-button").addClass("active-view-button");
            $('.chronicle-block-button').removeClass('active-view-button');
      $(".random-block-button").removeClass("active-view-button");
            $('.random-block-button').removeClass('active-view-button');
      $(".alphabetical-block-button").removeClass("active-view-button");
        });
    });


        // LIST VIEW SORTING BUTTONS
    $(".random-block-button").click(function () {
        $('.chronicle-list-button').click(function() {
      randomizeCards(".list-container .card");
            sortChronologically();


            updateLastVisibleCard();
      updateLastVisibleCard();
            updateWidthBlockView();
      updateWidthBlockView();
            processEventCards();
      processEventCards();
            updateViews();
      updateViews();
            $('.chronicle-list-button').addClass('active-view-button');
      $(".random-block-button").addClass("active-view-button");
            $('.random-list-button').removeClass('active-view-button');
      $(".chronicle-block-button").removeClass("active-view-button");
            $('.alphabetical-list-button').removeClass('active-view-button');
      $(".alphabetical-block-button").removeClass("active-view-button");
        });
    });


        $('.random-list-button').click(function() {
    $(".alphabetical-block-button").click(function () {
            randomizeCards('.list-container .card');
      sortAlphabetically(".list-container .card");


            updateLastVisibleCard();
      updateLastVisibleCard();
            updateWidthBlockView();
      updateWidthBlockView();
            processEventCards();
      processEventCards();
            updateViews();
      updateViews();
            $('.random-list-button').addClass('active-view-button');
      $(".alphabetical-block-button").addClass("active-view-button");
            $('.chronicle-list-button').removeClass('active-view-button');
      $(".chronicle-block-button").removeClass("active-view-button");
            $('.alphabetical-list-button').removeClass('active-view-button');
      $(".random-block-button").removeClass("active-view-button");
        });
    });


        $('.alphabetical-list-button').click(function() {
    // LIST VIEW SORTING BUTTONS
            sortAlphabetically('.list-container .card');
    $(".chronicle-list-button").click(function () {
      sortChronologically();


            updateLastVisibleCard();
      updateLastVisibleCard();
            updateWidthBlockView();
      updateWidthBlockView();
            processEventCards();
      processEventCards();
            updateViews();
      updateViews();
            $('.alphabetical-list-button').addClass('active-view-button');
      $(".chronicle-list-button").addClass("active-view-button");
            $('.chronicle-list-button').removeClass('active-view-button');
      $(".random-list-button").removeClass("active-view-button");
            $('.random-list-button').removeClass('active-view-button');
      $(".alphabetical-list-button").removeClass("active-view-button");
        });
     });
     }
   
    // FILTERS  ---------------------  SECTION //
    // General Filters Toggle Button
    $('.general-toggle').click(function() {
        var filtersDiv = $('#filters');
        var resetButton = $('.reset-button');


        filtersDiv.toggleClass('is-visible');
    $(".random-list-button").click(function () {
      randomizeCards(".list-container .card");


        if (filtersDiv.hasClass('is-visible')) {
      updateLastVisibleCard();
            filtersDiv.css('display', 'grid').hide().slideDown(100);
      updateWidthBlockView();
            $(this).text('[FILTER]');
      processEventCards();
            // Attach click handler to document
      updateViews();
            $(document).on('mousedown.hideFilters', function(event) {
      $(".random-list-button").addClass("active-view-button");
                var isOutsideFilters = !filtersDiv.is(event.target) && filtersDiv.has(event.target).length === 0;
      $(".chronicle-list-button").removeClass("active-view-button");
                var isOnToggle = $(event.target).closest('.general-toggle').length > 0;
      $(".alphabetical-list-button").removeClass("active-view-button");
    });


                if (isOutsideFilters && !isOnToggle) {
    $(".alphabetical-list-button").click(function () {
                    filtersDiv.removeClass('is-visible').slideUp(100, function() {
      sortAlphabetically(".list-container .card");
                        $(this).css('display', 'none');
                    });
                    $('.general-toggle').text('[FILTER]');
                    // Remove the document click handler
                    $(document).off('mousedown.hideFilters');
                }
            });
        } else {
            filtersDiv.slideUp(100, function() {
                $(this).css('display', 'none');
            });
            $(this).text('[FILTER]');
            // Remove the document click handler
            $(document).off('mousedown.hideFilters');
        }


        updateLastVisibleCard();
      updateLastVisibleCard();
        updateWidthBlockView();
      updateWidthBlockView();
        processEventCards();
      processEventCards();
        updateViews();
      updateViews();
      $(".alphabetical-list-button").addClass("active-view-button");
      $(".chronicle-list-button").removeClass("active-view-button");
      $(".random-list-button").removeClass("active-view-button");
     });
     });
  }
  // FILTERS  ---------------------  SECTION //
  // General Filters Toggle Button
  $(".general-toggle").click(function () {
    var filtersDiv = $("#filters");
    var resetButton = $(".reset-button");
    filtersDiv.toggleClass("is-visible");


     // Specific Toggle for Filter Sections like TYPE, ENTITY, etc.
     if (filtersDiv.hasClass("is-visible")) {
    $('.open-filter').click(function(event) {
      filtersDiv.css("display", "grid").hide().slideDown(100);
         event.stopPropagation();
      $(this).text("[FILTER]");
      // Attach click handler to document
      $(document).on("mousedown.hideFilters", function (event) {
         var isOutsideFilters =
          !filtersDiv.is(event.target) &&
          filtersDiv.has(event.target).length === 0;
        var isOnToggle = $(event.target).closest(".general-toggle").length > 0;


         var filterType = $(this).closest('.filter').data('filter');
         if (isOutsideFilters && !isOnToggle) {
        var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
          filtersDiv.removeClass("is-visible").slideUp(100, function () {
   
            $(this).css("display", "none");
        console.log('Filter type:', filterType, 'Card Selector:', cardSelector);
          });
   
          $(".general-toggle").text("[FILTER]");
        $('#values-' + filterType).toggle();
          // Remove the document click handler
   
          $(document).off("mousedown.hideFilters");
        if ($('#values-' + filterType).is(':visible')) {
            $(this).addClass('active-filter');
        } else {
            $(this).removeClass('active-filter');
         }
         }
      
      });
         // Pass the determined card selector to the function
     } else {
        updateLastVisibleCard(cardSelector);
      filtersDiv.slideUp(100, function () {
        updateWidthBlockView(cardSelector);
         $(this).css("display", "none");
        processEventCards(cardSelector);
      });
        updateViews(cardSelector);
      $(this).text("[FILTER]");
      
      // Remove the document click handler
        console.log('Updated views and borders after filter toggle');
      $(document).off("mousedown.hideFilters");
    });
    }
   
 
    function filterCards() {
    updateLastVisibleCard();
        var displayCountsHtml = '';
    updateWidthBlockView();
        var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
    processEventCards();
      
    updateViews();
        $('.filter .values a[title]').each(function() {
  });
            var anchor = $(this);
 
            var filterValue = anchor.attr('title').toLowerCase();
  // Specific Toggle for Filter Sections like TYPE, ENTITY, etc.
            var count = 0;
  $(".open-filter").click(function (event) {
   
    event.stopPropagation();
            if (anchor.find('button').hasClass('active')) {
 
                $(cardSelector).each(function() {
    var filterType = $(this).closest(".filter").data("filter");
                    var card = $(this);
    var cardSelector = $(".card").length > 0 ? ".card" : ".community-card"; // Determine which card type is present
                    $('.filter').each(function() {
 
                        var filterType = $(this).data('filter');
    console.log("Filter type:", filterType, "Card Selector:", cardSelector);
                        var cardValue = card.find('.' + filterType).text().toLowerCase();
 
                        if (cardValue.indexOf(filterValue) !== -1) {
    $("#values-" + filterType).toggle();
                            count++;
 
                        }
    if ($("#values-" + filterType).is(":visible")) {
                    });
      $(this).addClass("active-filter");
                });
    } else {
   
      $(this).removeClass("active-filter");
                displayCountsHtml += '<span>[' + count + '] ' + filterValue + '</span> ';
    }
 
    // Pass the determined card selector to the function
    updateLastVisibleCard(cardSelector);
    updateWidthBlockView(cardSelector);
    processEventCards(cardSelector);
    updateViews(cardSelector);
 
     console.log("Updated views and borders after filter toggle");
  });
 
  function filterCards() {
    var displayCountsHtml = "";
    var cardSelector = $(".card").length > 0 ? ".card" : ".community-card"; // Determine which card type is present
 
     $(".filter .values a[title]").each(function () {
      var anchor = $(this);
      var filterValue = anchor.attr("title").toLowerCase();
      var count = 0;
 
      if (anchor.find("button").hasClass("active")) {
        $(cardSelector).each(function () {
          var card = $(this);
          $(".filter").each(function () {
            var filterType = $(this).data("filter");
            var cardValue = card
              .find("." + filterType)
              .text()
              .toLowerCase();
            if (cardValue.indexOf(filterValue) !== -1) {
              count++;
             }
             }
          });
         });
         });
      
 
        if (displayCountsHtml) {
        displayCountsHtml +=
            $('.count-filtered-cards').html(displayCountsHtml).show();
          "<span>[" + count + "] " + filterValue + "</span> ";
        } else {
      }
            $('.count-filtered-cards').hide();
     });
        }
 
      
    if (displayCountsHtml) {
        // Apply filtering and pass the determined card selector to the function
      $(".count-filtered-cards").html(displayCountsHtml).show();
        applyFiltering(cardSelector);
    } else {
      
      $(".count-filtered-cards").hide();
        updateLastVisibleCard(cardSelector);
    }
        updateWidthBlockView(cardSelector);
 
        processEventCards(cardSelector);
     // Apply filtering and pass the determined card selector to the function
        updateViews(cardSelector);
    applyFiltering(cardSelector);
      
 
        console.log('Filtering process complete, updated views and borders');
     updateLastVisibleCard(cardSelector);
    }    
    updateWidthBlockView(cardSelector);
   
    processEventCards(cardSelector);
    function applyFiltering() {
    updateViews(cardSelector);
        // Determine which card selector to use based on the elements present in the DOM
 
        var cardSelector = $('.card').length > 0 ? '.card' : '.community-card';
     console.log("Filtering process complete, updated views and borders");
      
  }
        // Apply the logic to the determined card type
 
        $(cardSelector).show().each(function() {
  function applyFiltering() {
            var card = $(this);
    // Determine which card selector to use based on the elements present in the DOM
            var hideCard = false;
    var cardSelector = $(".card").length > 0 ? ".card" : ".community-card";
   
 
            $('.filter').each(function() {
     // Apply the logic to the determined card type
                if (hideCard) return;
    $(cardSelector)
   
      .show()
                var filterType = $(this).data('filter');
      .each(function () {
                var activeFilters = $(this).find('.values a[title] button.active').map(function() {
        var card = $(this);
                    return $(this).parent('a').attr('title').toLowerCase();
        var hideCard = false;
                }).get();
 
   
        $(".filter").each(function () {
                if (activeFilters.length > 0) {
          if (hideCard) return;
                    var cardValue = card.find('.' + filterType).text().toLowerCase();
 
                    var matchesFilter = activeFilters.some(function(filterValue) {
          var filterType = $(this).data("filter");
                        return cardValue.indexOf(filterValue) !== -1;
          var activeFilters = $(this)
                    });
            .find(".values a[title] button.active")
                    if (!matchesFilter) hideCard = true;
            .map(function () {
                }
              return $(this).parent("a").attr("title").toLowerCase();
            })
            .get();
 
          if (activeFilters.length > 0) {
            var cardValue = card
              .find("." + filterType)
              .text()
              .toLowerCase();
            var matchesFilter = activeFilters.some(function (filterValue) {
              return cardValue.indexOf(filterValue) !== -1;
             });
             });
   
             if (!matchesFilter) hideCard = true;
             if (hideCard) card.hide();
          }
         });
         });
    }  
 
   
        if (hideCard) card.hide();
    function updateLastVisibleCard() {
      });
        // Target only the list view container for updating the last visible card
  }
        $('.home-chronicle-list div.list-container div.card').removeClass('last-visible');
 
      
  function updateLastVisibleCard() {
        // Find the last visible card within the list view and add the class
    // Target only the list view container for updating the last visible card
        var lastVisibleCard = $('.home-chronicle-list div.list-container div.card:visible:last');
    $(".home-chronicle-list div.list-container div.card").removeClass(
        lastVisibleCard.addClass('last-visible');
      "last-visible"
    );
 
     // Find the last visible card within the list view and add the class
    var lastVisibleCard = $(
      ".home-chronicle-list div.list-container div.card:visible:last"
    );
    lastVisibleCard.addClass("last-visible");
  }
 
  function updateWidthBlockView() {
    // Target only the block view container for updating the with of card
    $(".home-chronicle-block div.list-container").css("width", "100%");
    $(".home-chronicle-block div.list-container div.card").css(
      "width",
      "calc(20% - 0px)"
    );
    $(
      ".home-chronicle-block div.list-container div.card:nth-child(5n + 1)"
    ).css("width", "calc(20% + 4px)");
  }
 
  // Reset function to remove active filters
  $(".reset-filter").click(function (event) {
    event.stopPropagation(); // Prevent event bubbling
 
    // Remove 'active' class from all filter buttons
    $("#filters .values button").removeClass("active");
    $(".open-filter").removeClass("active-filter");
 
    // Reset and hide the filter counts
    $(".count-filtered-cards").text("").hide();
 
    filterCards(); // Reapply filtering based on the updated active buttons
 
    // Update other UI elements as needed, excluding the general toggle button
    updateLastVisibleCard();
    updateWidthBlockView();
    processEventCards();
    updateViews();
  });
 
  $("#filters .values button").click(function () {
    console.log("Filter is clicked!!!");
    $(this).toggleClass("active");
    filterCards(); // Re-apply the filters based on the updated active buttons
 
    updateLastVisibleCard();
    updateWidthBlockView();
    processEventCards();
    updateViews();
  });
 
  // Hide filters when window is scrolled
  $(window).on("scroll", function () {
    var filtersDiv = $("#filters");
 
    if (filtersDiv.hasClass("is-visible")) {
      filtersDiv.removeClass("is-visible").slideUp(100, function () {
        $(this).css("display", "none");
        // The filter reset code has been removed to keep the filters active
      });
      $(".general-toggle").text("[FILTER]"); // Update the toggle button text
    }
  });
 
  // MODAL ARTICLE  ---------------------  SECTION //
  // Format paragraphs
  function formatParagraphs(text) {
    var paragraphs = text.split("\n").filter(function (p) {
      return p.trim() !== "";
    });
    return paragraphs
      .map(function (p) {
        return "<p>" + p.trim() + "</p>";
      })
      .join("");
  }
 
  var images = []; // Initialize an empty array to store the images
  // Find all image containers within the article content and extract the necessary information
  $(".article-images .image-container").each(function () {
    var img = $(this).find("img");
    var captionDiv = $(this).find('div[class^="caption-image"]');
    var image = {
      src: img.attr("src"),
      alt: img.attr("alt"),
      caption: captionDiv.text(),
      captionClass: captionDiv.attr("class"),
    };
    images.push(image); // Add the image object to the images array
  });
 
  if (images.length > 0) {
    setupImageToggle(images); // Call the setupImageToggle function with the images array
    updateImageLabel(1, images.length); // Set the label for the first image immediately
  }
 
  function setupImageToggle(images) {
    var currentIndex = 0;
    var enableNavigation = images.length > 1; // Enable navigation only if there is more than one image
 
    function showImage(index) {
      currentIndex = index;
      var image = images[currentIndex];
      updateImageLabel(currentIndex + 1, images.length);
      $("#article-content")
        .find(".article-images")
        .html(
          getImageHtml(image, currentIndex, images.length, enableNavigation)
        );
     }
     }


     function updateWidthBlockView() {
     // Attach click handlers only if navigation is enabled
        // Target only the block view container for updating the with of card
    if (enableNavigation) {
        $('.home-chronicle-block div.list-container').css('width', '100%');
      $("#article-content").on("click", ".next-arrow", function () {
         $('.home-chronicle-block div.list-container div.card').css('width', 'calc(20% - 0px)');
         showImage((currentIndex + 1) % images.length);
        $('.home-chronicle-block div.list-container div.card:nth-child(5n + 1)').css('width', 'calc(20% + 4px)');
      });
 
      $("#article-content").on("click", ".prev-arrow", function () {
        showImage((currentIndex - 1 + images.length) % images.length);
      });
     }
     }


     // Reset function to remove active filters
     // Display the first image
     $('.reset-filter').click(function(event) {
     showImage(currentIndex);
        event.stopPropagation(); // Prevent event bubbling
  }
 
  function getImageHtml(image, currentIndex, totalImages, enableNavigation) {
    var imageLabel = currentIndex + 1 + "/" + totalImages + " IMAGES";


        // Remove 'active' class from all filter buttons
    // Render navigation arrows based on the enableNavigation flag
        $('#filters .values button').removeClass('active');
    var navigationHtml = enableNavigation
        $('.open-filter').removeClass('active-filter');
      ? '<div class="prev-arrow"><</div><div class="next-arrow">></div>'
      : "";


        // Reset and hide the filter counts
    return (
        $('.count-filtered-cards').text('').hide();
      '<div class="image-navigation">' +
      '<p class="article-label-image">' +
      imageLabel +
      "</p>" +
      '<div class="image-container">' +
      '<div class="arrows-and-image">' +
      navigationHtml +
      '<img src="' +
      image.src +
      '" alt="' +
      image.alt +
      '">' +
      "</div>" +
      '<div class="' +
      image.captionClass +
      '">' +
      image.caption +
      "</div>" +
      "</div>" +
      "</div>"
    );
  }


        filterCards(); // Reapply filtering based on the updated active buttons
  function updateImageLabel(currentIndex, totalImages) {
    var imageLabel = currentIndex + "/" + totalImages + " IMAGES";
    $("#article-content .article-label-image").text(imageLabel);
  }


        // Update other UI elements as needed, excluding the general toggle button
  $(".caption-image1").each(function () {
        updateLastVisibleCard();
    // Split the caption at each <br> tag and wrap each line in a span
        updateWidthBlockView();
    var htmlContent = $(this).html();
        processEventCards();
    var lines = htmlContent.split("<br>");
        updateViews();
    var wrappedLines = lines.map(function (line) {
      return '<span class="caption-line">' + line + "</span>";
     });
     });
      
     var newHtml = wrappedLines.join("<br>");
    $('#filters .values button').click(function() {
    $(this).html(newHtml);
        console.log("Filter is clicked!!!");
  });
        $(this).toggleClass('active');
        filterCards(); // Re-apply the filters based on the updated active buttons


        updateLastVisibleCard();
  function setShowArticleRotationEffect() {
        updateWidthBlockView();
    const offset = 20;
        processEventCards();
    const showArticle = document.querySelector("#show-article");
        updateViews();
    const h = showArticle.clientHeight;
     });
    const theta = -Math.atan(offset / h);
    const a = Math.cos(theta);
    const b = Math.sin(theta);
    const c = -Math.sin(theta);
    const d = Math.cos(theta);
    const showArticleBefore = document.querySelector("#show-article-before");
     const transformValue =
      "matrix(" + a + "," + b + "," + c + "," + d + ",0,0)";
    showArticleBefore.style.transform = transformValue;
  }


    // Hide filters when window is scrolled
  function openEvent(element, event) {
     $(window).on('scroll', function() {
     event.stopPropagation();
        var filtersDiv = $('#filters');
    event.preventDefault();


        if (filtersDiv.hasClass('is-visible')) {
    var url = $(element).find(".link a").attr("href");
            filtersDiv.removeClass('is-visible').slideUp(100, function() {
     if (url) {
                $(this).css('display', 'none');
      window.open(url, "_blank").focus();
                // The filter reset code has been removed to keep the filters active
            });
            $('.general-toggle').text('[FILTER]'); // Update the toggle button text
        }
     });
   
   
    // MODAL ARTICLE  ---------------------  SECTION //
    // Format paragraphs
    function formatParagraphs(text) {
        var paragraphs = text.split('\n').filter(function (p) { return p.trim() !== '' });
        return paragraphs.map(function (p) { return '<p>' + p.trim() + '</p>'; }).join('');
     }
     }
  }
  function openModal(cardElement, event) {
    event.stopPropagation();
    $("#print-chooser").hide();
    $("#show-article").removeClass("print-opts-open");
    var pageTitle = $(cardElement).data("page") || null; // e.g. "090"
    window.currentEntryTitle = pageTitle;
    var isRelatedArticle = $(cardElement).hasClass("related-article");
    showArticleWrapper.css("display", "block");


     var images = []; // Initialize an empty array to store the images
     // Clear existing content in modal
    // Find all image containers within the article content and extract the necessary information
     $("#article-title").empty();
     $('.article-images .image-container').each(function() {
    $("#article-content").empty();
        var img = $(this).find('img');
        var captionDiv = $(this).find('div[class^="caption-image"]');
        var image = {
            src: img.attr('src'),
            alt: img.attr('alt'),
            caption: captionDiv.text(),
            captionClass: captionDiv.attr('class')
        };
        images.push(image); // Add the image object to the images array
    });


     if (images.length > 0) {
     if (isRelatedArticle) {
        setupImageToggle(images); // Call the setupImageToggle function with the images array
      // Handle card elements (existing logic)
        updateImageLabel(1, images.length); // Set the label for the first image immediately
      var cardImages = [];
    }
      for (var i = 1; i <= 5; i++) {
        var imageClass = ".related-article-image" + i;
        var captionClass = ".related-article-caption-image" + i;
        var imageElem = $(cardElement).find(imageClass + " img");


    function setupImageToggle(images) {
        if (imageElem.length) {
        var currentIndex = 0;
          var captionText = $(cardElement)
        var enableNavigation = images.length > 1; // Enable navigation only if there is more than one image
            .find(imageClass + " " + captionClass)
   
             .text();
        function showImage(index) {
          cardImages.push({
             currentIndex = index;
             link: $(cardElement)
            var image = images[currentIndex];
              .find(imageClass + " a")
            updateImageLabel(currentIndex + 1, images.length);
              .attr("href"),
             $('#article-content').find('.article-images').html(getImageHtml(image, currentIndex, images.length, enableNavigation));
            src: imageElem.attr("src"),
            alt: imageElem.attr("alt"),
            caption: captionText,
            captionClass: "related-article-caption-image" + i,
          });
         }
         }
   
      }
         // Attach click handlers only if navigation is enabled
 
         if (enableNavigation) {
      if (cardImages.length > 1) {
            $('#article-content').on('click', '.next-arrow', function() {
         setupImageToggle(cardImages);
                showImage((currentIndex + 1) % images.length);
      }
            });
      // Handle related-article elements
   
      var entryNumber = $(cardElement)
             $('#article-content').on('click', '.prev-arrow', function() {
        .find(".related-article-entry-number")
                showImage((currentIndex - 1 + images.length) % images.length);
        .text();
             });
      var peopleHtml = $(cardElement).find(".related-article-people").html();
      var title = $(cardElement).find(".related-article-title").text();
      var typeHtml = $(cardElement).find(".related-article-type").html();
      var externalPdfURL = $(cardElement)
        .find(".related-article-pdf a")
        .attr("href");
      var externalLinkURL = $(cardElement)
        .find(".related-article-link a")
        .attr("href");
      var entity = $(cardElement).find(".related-article-entity").text();
      var discipline = $(cardElement)
        .find(".related-article-discipline")
        .text();
      var subjectHtml = $(cardElement).find(".related-article-subject").html();
      var description = $(cardElement)
        .find(".related-article-description")
        .html();
      var reflection = $(cardElement)
        .find(".related-article-reflection")
        .html();
      var quote = $(cardElement).find(".related-article-quote").text();
      var modificationDate = $(cardElement)
        .find(".related-article-modification-date")
         .text();
 
      // Update modal content for related-article
      $("#article-title").html(
        '<p class="article-entry-number">' +
          entryNumber +
          '</p><p class="article-people">' +
          peopleHtml +
          "</p>"
      );
      var articleContentHtml = '<div class="article-title-link">';
      articleContentHtml += '<p class="article-title">' + title + "</p>";
      // Create a div that will wrap the links
      articleContentHtml += '<div class="link-pdf">';
 
      if (externalPdfURL) {
        articleContentHtml +=
          '<a href="' +
          externalPdfURL +
          '" target="_blank" class="pdf-link-icon">[PDF<span class="text-symbol">⤴</span>]</a>';
      }
      if (externalLinkURL) {
        articleContentHtml +=
          '<a href="' +
          externalLinkURL +
          '" target="_blank" class="external-link-icon">[WEB<span class="text-symbol">⤴</span>]</a>';
      }
 
      // Close the .link-pdf div
      articleContentHtml += "</div>";
      articleContentHtml += "</div>"; // Close the container div
 
      // Append type, entity, discipline, and subject details
      articleContentHtml +=
        '<p class="article-type">' +
        typeHtml +
        "</p>" +
        '<div class="article-metadata">' +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Entity</p>' +
        '<p class="article-metadata-value">' +
        entity +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Discipline</p>' +
        '<p class="article-metadata-value">' +
        discipline +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Subject(s)</p>' +
        '<p class="article-metadata-value">' +
        subjectHtml +
        "</p>" +
        "</div>" +
        "</div>";
 
      // Add images if any
      if (cardImages.length > 0) {
        var initialImage = cardImages[0]; // Use the first image initially
        var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
        articleContentHtml +=
          '<div class="article-images">' +
          getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
          "</div>";
      }
      // Add non-image content (description, reflection, etc.)
      articleContentHtml +=
        (description
          ? '<p class="article-label-description">Description</p>' +
            '<div class="article-description">' +
            formatParagraphs(description) +
             "</div>"
          : "") +
        (reflection
          ? '<p class="article-label-reflection">Reflection</p>' +
            '<div class="article-reflection">' +
            formatParagraphs(reflection) +
            "</div>"
          : "") +
        (quote
          ? '<p class="article-label-quote">Quote</p>' +
            '<p class="article-quote">' +
            quote +
            "</p>"
          : "") +
        '<p class="article-label-modification-date">Added on</p>' +
        '<div class="article-modification-date">' +
        modificationDate +
        "</div>";
 
      $("#article-content").html(articleContentHtml);
    } else {
      // Handle card elements (existing logic)
      var cardImages = [];
      for (var i = 1; i <= 5; i++) {
        var imageClass = ".image" + i;
        var captionClass = ".caption-image" + i;
        var imageElem = $(cardElement).find(imageClass + " img");
 
        if (imageElem.length) {
          var captionText = $(cardElement)
            .find(imageClass + " " + captionClass)
            .text();
          cardImages.push({
             link: $(cardElement)
              .find(imageClass + " a")
              .attr("href"),
            src: imageElem.attr("src"),
            alt: imageElem.attr("alt"),
            caption: captionText,
            captionClass: "caption-image" + i,
          });
         }
         }
   
      }
        // Display the first image
 
         showImage(currentIndex);
      if (cardImages.length > 1) {
    }    
         setupImageToggle(cardImages);
         
      }
   
      var entryNumber = $(cardElement).find(".entry-number").text();
    function getImageHtml(image, currentIndex, totalImages, enableNavigation) {
      var title = $(cardElement).find(".title").text();
         var imageLabel = (currentIndex + 1) + '/' + totalImages + ' IMAGES';
      var peopleHtml = $(cardElement).find(".people").html();
   
      var typeHtml = $(cardElement).find(".type").html();
        // Render navigation arrows based on the enableNavigation flag
      var externalPdfURL = $(cardElement).find(".pdf a").attr("href");
         var navigationHtml = enableNavigation ?
      var externalLinkURL = $(cardElement).find(".link a").attr("href");
            '<div class="prev-arrow"><</div><div class="next-arrow">></div>' : '';
      var entity = $(cardElement).find(".entity").text();
   
      var discipline = $(cardElement).find(".discipline").text();
         return '<div class="image-navigation">' +
      var subjectHtml = $(cardElement).find(".subject").html();
                    '<p class="article-label-image">' + imageLabel + '</p>' +
      var description = $(cardElement).find(".description").html();
                    '<div class="image-container">' +
      var reflection = $(cardElement).find(".reflection").html();
                        '<div class="arrows-and-image">' +
      var quote = $(cardElement).find(".quote").text();
                            navigationHtml +  
      var externalReferenceHtml = $(cardElement)
                            '<img src="' + image.src + '" alt="' + image.alt + '">' +
        .find(".external-reference")
                        '</div>' +
         .html();
                        '<div class="' + image.captionClass + '">' + image.caption + '</div>' +
      var modificationDate = $(cardElement).find(".modification-date").text();
                    '</div>' +
      var relatedArticlesHtml = $(cardElement).find(".related-articles").html();
                '</div>';
 
      $("#article-title").html(
        '<p class="article-entry-number">' +
          entryNumber +
          '</p><p class="article-people">' +
          peopleHtml +
          "</p>"
      );
 
      var articleContentHtml = '<div class="article-title-link">';
      articleContentHtml += '<p class="article-title">' + title + "</p>";
 
      // Create a div that will wrap the links
      articleContentHtml += '<div class="link-pdf">';
      if (externalPdfURL) {
         articleContentHtml +=
          '<a href="' +
          externalPdfURL +
          '" target="_blank" class="pdf-link-icon">[PDF<span class="text-symbol"></span>]</a>';
      }
      if (externalLinkURL) {
        articleContentHtml +=
          '<a href="' +
          externalLinkURL +
          '" target="_blank" class="external-link-icon">[WEB<span class="text-symbol">⤴</span>]</a>';
      }
      // Close the .link-pdf div
      articleContentHtml += "</div>";
      articleContentHtml += "</div>"; // Close the new div
 
      // Append type, entity, discipline, and subject details
      articleContentHtml +=
        '<p class="article-type">' +
        typeHtml +
        "</p>" +
        '<div class="article-metadata">' +
         '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Entity</p>' +
        '<p class="article-metadata-value">' +
        entity +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Discipline</p>' +
        '<p class="article-metadata-value">' +
        discipline +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Subject(s)</p>' +
        '<p class="article-metadata-value">' +
        subjectHtml +
        "</p>" +
        "</div>" +
        "</div>";
      // Add images if any
      if (cardImages.length > 0) {
        var initialImage = cardImages[0]; // Use the first image initially
        var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
        articleContentHtml +=
          '<div class="article-images">' +
          getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
          "</div>";
      }
      // Add non-image content (description, reflection, etc.)
      articleContentHtml +=
        (description
          ? '<p class="article-label-description">Description</p>' +
            '<div class="article-description">' +
            formatParagraphs(description) +
            "</div>"
          : "") +
        (reflection
          ? '<p class="article-label-reflection">Reflection</p>' +
            '<div class="article-reflection">' +
            formatParagraphs(reflection) +
            "</div>"
          : "") +
        (externalReferenceHtml
          ? '<p class="article-label-external-reference">References</p>' +
            '<p class="article-external-reference">' +
            externalReferenceHtml +
            "</p>"
          : "") +
        (quote
          ? '<p class="article-label-quote">Quote</p>' +
            '<p class="article-quote">' +
            quote +
            "</p>"
          : "") +
        '<p class="article-label-modification-date">Added on</p>' +
        '<div class="article-modification-date">' +
        modificationDate +
        "</div>";
 
      $("#article-content").html(articleContentHtml);
      $("#related-articles").html(relatedArticlesHtml);
 
      if (relatedArticlesHtml && relatedArticlesHtml.trim().length > 0) {
        $("#related-articles")
          .html(
            '<div class="related-articles-label">Related Articles</div><div class="related-articles-container">' +
              relatedArticlesHtml +
              "</div>"
          )
          .show();
      }
    }
 
    // Check which view is active and set the width accordingly
    if ($(".home-chronicle-list").is(":visible")) {
      $(".home-list-view").each(function () {
        var currentWidth = $(this).width(); // Get the current width
        $(this).data("originalWidth", currentWidth); // Store the original width
        $(this).css("width", "calc(60% - 2px)");
      });
 
      // Modify the .type elements within .home-chronicle-list
      $(".home-chronicle-list .type").each(function () {
        var currentLeft = $(this).css("left"); // Get the current left value
        $(this).data("originalLeft", currentLeft); // Store the original left value
        $(this).css("left", "85%");
      });
    } else if ($(".home-chronicle-block").is(":visible")) {
      $(".home-chronicle-block div.list-container").each(function () {
        var currentWidth = $(this).width(); // Get the current width
        $(this).css("width", "calc(60% - 0px)"); // Set the new width as 30% of the current width
      });
      $(".home-chronicle-block div.list-container div.card").each(function () {
        var currentWidth = $(this).width(); // Get the current width
        $(this).css("width", "calc(33.333% - 0px)"); // Set the new width as 30% of the current width
      });
     }
     }
      
 
     function updateImageLabel(currentIndex, totalImages) {
     // Apply the fade-out effect to both #list and #list-list elements
        var imageLabel = currentIndex + '/' + totalImages + ' IMAGES';
     $(".list-container").addClass("fade-out");
        $('#article-content .article-label-image').text(imageLabel);
  }
 
  // closeModal function
  function closeModal() {
    $("#print-chooser").hide();
    $("#show-article").removeClass("print-opts-open");
    if ($(".home-chronicle-list").is(":visible")) {
      $(".home-list-view").css("width", "100%");
      $(".home-chronicle-list div.list-container div.card div.type").css(
        "left",
        "90%"
      );
    } else if ($(".home-chronicle-block").is(":visible")) {
      updateWidthBlockView();
     }
     }
      
     showArticleWrapper.hide();
    $('.caption-image1').each(function() {
  }
        // Split the caption at each <br> tag and wrap each line in a span
 
        var htmlContent = $(this).html();
  $(".card").on("click", function (event) {
        var lines = htmlContent.split('<br>');
    // Check if the click event is originating from a link within .people or .type, or any other specific area
        var wrappedLines = lines.map(function(line) {
    if ($(event.target).closest(".people a, .type a").length) {
            return '<span class="caption-line">' + line + '</span>';
      // The click is inside a link; let the default behavior proceed without opening the modal
        });
      return;
        var newHtml = wrappedLines.join('<br>');
        $(this).html(newHtml);
    });
   
    function setShowArticleRotationEffect() {
        const offset = 20;
        const showArticle = document.querySelector('#show-article');
        const h = showArticle.clientHeight;
        const theta = -Math.atan(offset/h);
        const a = Math.cos(theta);
        const b = Math.sin(theta);
        const c = -Math.sin(theta);
        const d = Math.cos(theta);
        const showArticleBefore = document.querySelector('#show-article-before');
        const transformValue = 'matrix('+a+','+b+','+c+','+d+',0,0)';
        showArticleBefore.style.transform = transformValue;
     }
     }


     function openEvent(element, event) {
     // Prevent further event handling if the card has the 'event' class
        event.stopPropagation();
    if ($(this).hasClass("event")) {
        event.preventDefault();
      event.stopImmediatePropagation();
   
      openEvent(this, event);
        var url = $(element).find('.link a').attr('href');
      $(".list-container").removeClass("fade-out");
        if (url) {
      closeModal();
            window.open(url, '_blank').focus();
    } else {
        }
      // Handle cards without the 'event' class
      openModal(this, event);
      setShowArticleRotationEffect();
     }
     }
  });
  $("#show-article-wrapper").on("click", ".related-article", function (event) {
    openModal(this, event); // Call openModal when a related-article is clicked
    setShowArticleRotationEffect();
  });
  // HERE SHOULD BE THE NEW CODE!!!!
  /* ---------- Softwear PRINT (scoped, ES5-safe) ---------- */
  /* helpers */
  function swPrintPreloadFont() {
    var link = document.createElement("link");
    link.rel = "preload";
    link.as = "font";
    link.type = "font/woff2";
    link.href = "/fonts/HALColant-TextRegular.woff2?v=20250820";
    link.crossOrigin = "anonymous";
    document.head.appendChild(link);
  }
  function swPrintCacheBust(url) {
    return url + (url.indexOf("?") > -1 ? "&" : "?") + "_=" + Date.now();
  }
  function swEnsurePrintChooser() {
    var $chooser = jQuery("#print-chooser");
    if ($chooser.length) return $chooser;
    $chooser = jQuery(
      '<div id="print-chooser" class="print-chooser" style="display:none;">' +
        '<a href="#" id="print-with-border" class="print-choice">border</a> ' +
        '<a href="#" id="print-no-border" class="print-choice">no border</a>' +
        "</div>"
    );
    jQuery("#print-button").after($chooser);
    return $chooser;
  }
  function swHidePrintUI() {
    jQuery("#print-chooser").hide();
    jQuery("#show-article").removeClass("print-opts-open");
  }


    function openModal(cardElement, event) {
  /* core: build iframe and print */
        event.stopPropagation(); // Prevent the event from bubbling up
  function swBuildIframeAndPrint(printHtml, borderPref, $btn) {
        console.log("openModal function called.");
    // iframe
        var isRelatedArticle = $(cardElement).hasClass('related-article');
    var iframe = document.createElement("iframe");
        showArticleWrapper.css('display', 'block');
    iframe.style.position = "fixed";
    iframe.style.right = "0";
    iframe.style.bottom = "0";
    iframe.style.width = "0";
    iframe.style.height = "0";
    iframe.style.border = "0";
    document.body.appendChild(iframe);


        // Clear existing content in modal
    var doc = iframe.contentDocument || iframe.contentWindow.document;
        $('#article-title').empty();
     doc.open();
        $('#article-content').empty();
    doc.write(
       
      '<!doctype html><html><head><meta charset="utf-8"><title>Print</title></head><body></body></html>'
        if (isRelatedArticle) {
    );
            // Handle card elements (existing logic)
    doc.close();
            var cardImages = [];
            for (var i = 1; i <= 5; i++) {
                var imageClass = '.related-article-image' + i;
                var captionClass = '.related-article-caption-image' + i;
                var imageElem = $(cardElement).find(imageClass + ' img');
      
                if (imageElem.length) {
                    var captionText = $(cardElement).find(imageClass + ' ' + captionClass).text();
                    cardImages.push({
                        link: $(cardElement).find(imageClass + ' a').attr('href'),
                        src: imageElem.attr('src'),
                        alt: imageElem.attr('alt'),
                        caption: captionText,
                        captionClass: 'related-article-caption-image' + i
                    });
                }
            }
           
            if (cardImages.length > 1) {
                setupImageToggle(cardImages);
            }
            // Handle related-article elements
            var entryNumber = $(cardElement).find('.related-article-entry-number').text();
            var peopleHtml = $(cardElement).find('.related-article-people').html();
            var title = $(cardElement).find('.related-article-title').text();
            var typeHtml = $(cardElement).find('.related-article-type').html();
            var externalPdfURL = $(cardElement).find('.related-article-pdf a').attr('href');     
            var externalLinkURL = $(cardElement).find('.related-article-link a').attr('href');
            var entity = $(cardElement).find('.related-article-entity').text();
            var discipline = $(cardElement).find('.related-article-discipline').text();
            var subjectHtml = $(cardElement).find('.related-article-subject').html();
            var description = $(cardElement).find('.related-article-description').html();
            var reflection = $(cardElement).find('.related-article-reflection').html();
            var quote = $(cardElement).find('.related-article-quote').text();
            var modificationDate = $(cardElement).find('.related-article-modification-date').text();


            // Update modal content for related-article
    // make relative URLs resolve
            $('#article-title').html('<p class="article-entry-number">' + entryNumber + '</p><p class="article-people">' + peopleHtml + '</p>');
    var base = doc.createElement("base");
            var articleContentHtml = '<div class="article-title-link">';
    base.href = location.origin + "/";
            articleContentHtml += '<p class="article-title">' + title + '</p>';
    doc.head.appendChild(base);
            // Create a div that will wrap the links
            articleContentHtml += '<div class="link-pdf">';


            if (externalPdfURL) {
    // print.css
                articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF<span class="text-symbol">⤴</span>]</a>';
    var linkCss = doc.createElement("link");
            }
    linkCss.rel = "stylesheet";
            if (externalLinkURL) {
    linkCss.href = swPrintCacheBust(
                articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB<span class="text-symbol">⤴</span>]</a>';
      "/index.php?title=MediaWiki:Print.css&action=raw&ctype=text/css"
            }
    );


            // Close the .link-pdf div
     var cssLoaded = new Promise(function (resolve) {
            articleContentHtml += '</div>';
      linkCss.onload = function () {
            articleContentHtml += '</div>'; // Close the container div
        resolve();
      
      };
            // Append type, entity, discipline, and subject details
      linkCss.onerror = function () {
            articleContentHtml += '<p class="article-type">' + typeHtml + '</p>' +
        resolve();
            '<div class="article-metadata">' +
      };
                '<div class="article-metadata-column">' +
    });
                    '<p class="article-metadata-label">Entity</p>' +
                    '<p class="article-metadata-value">' + entity + '</p>' +
                '</div>' +
                '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Discipline</p>' +
                    '<p class="article-metadata-value">' + discipline + '</p>' +
                '</div>' +
                '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Subject(s)</p>' +
                    '<p class="article-metadata-value">' + subjectHtml + '</p>' +
                '</div>' +
            '</div>';


            // Add images if any
    // font preload (inside iframe)
            if (cardImages.length > 0) {
    var linkFont = doc.createElement("link");
                var initialImage = cardImages[0]; // Use the first image initially
    linkFont.rel = "preload";
                var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
    linkFont.as = "font";
                articleContentHtml +=
    linkFont.type = "font/woff2";
                    '<div class="article-images">' +
    linkFont.href = "/fonts/HALColant-TextRegular.woff2?v=20250820";
                        getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
     linkFont.crossOrigin = "anonymous";
                    '</div>';
            }
            // Add non-image content (description, reflection, etc.)   
            articleContentHtml +=
            (description ? '<p class="article-label-description">Description</p>' +
            '<div class="article-description">' + formatParagraphs(description) + '</div>' : '') +
            (reflection ? '<p class="article-label-reflection">Reflection</p>' +
            '<div class="article-reflection">' + formatParagraphs(reflection) + '</div>' : '') +
            (quote ? '<p class="article-label-quote">Quote</p>' +
            '<p class="article-quote">' + quote + '</p>' : '') +
            '<p class="article-label-modification-date">Added on</p>' +
            '<div class="article-modification-date">' + modificationDate + '</div>';
      
            $('#article-content').html(articleContentHtml);


        } else {
    doc.head.appendChild(linkFont);
            // Handle card elements (existing logic)
     doc.head.appendChild(linkCss);
            var cardImages = [];
            for (var i = 1; i <= 5; i++) {
                var imageClass = '.image' + i;
                var captionClass = '.caption-image' + i;
                var imageElem = $(cardElement).find(imageClass + ' img');
      
                if (imageElem.length) {
                    var captionText = $(cardElement).find(imageClass + ' ' + captionClass).text();
                    cardImages.push({
                        link: $(cardElement).find(imageClass + ' a').attr('href'),
                        src: imageElem.attr('src'),
                        alt: imageElem.attr('alt'),
                        caption: captionText,
                        captionClass: 'caption-image' + i
                    });
                }
            }
           
            if (cardImages.length > 1) {
                setupImageToggle(cardImages);
            }
            var entryNumber = $(cardElement).find('.entry-number').text();
            var title = $(cardElement).find('.title').text();
            var peopleHtml = $(cardElement).find('.people').html();
            var typeHtml = $(cardElement).find('.type').html();
            var externalPdfURL = $(cardElement).find('.pdf a').attr('href');     
            var externalLinkURL = $(cardElement).find('.link a').attr('href');
            var entity = $(cardElement).find('.entity').text();
            var discipline = $(cardElement).find('.discipline').text();
            var subjectHtml = $(cardElement).find('.subject').html();
            var description = $(cardElement).find('.description').html();
            var reflection = $(cardElement).find('.reflection').html();
            var quote = $(cardElement).find('.quote').text();
            var externalReferenceHtml = $(cardElement).find('.external-reference').html();
            var modificationDate = $(cardElement).find('.modification-date').text();
            var relatedArticlesHtml = $(cardElement).find('.related-articles').html();
   
            $('#article-title').html('<p class="article-entry-number">' + entryNumber + '</p><p class="article-people">' + peopleHtml + '</p>');


            var articleContentHtml = '<div class="article-title-link">';
    // inject HTML
            articleContentHtml += '<p class="article-title">' + title + '</p>';
    doc.body.innerHTML = printHtml;


            // Create a div that will wrap the links
    // border preference -> <html> class
            articleContentHtml += '<div class="link-pdf">';
    (function () {
            if (externalPdfURL) {
      var htmlEl = doc.documentElement;
                articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF<span class="text-symbol">⤴</span>]</a>';
      if (borderPref === "without") {
            }
        if (htmlEl.classList) htmlEl.classList.add("print-no-border");
            if (externalLinkURL) {
        else if (
                articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB<span class="text-symbol">⤴</span>]</a>';
          (" " + htmlEl.className + " ").indexOf(" print-no-border ") === -1
            }
        ) {
            // Close the .link-pdf div
          htmlEl.className += " print-no-border";
            articleContentHtml += '</div>';
            articleContentHtml += '</div>'; // Close the new div
   
            // Append type, entity, discipline, and subject details
            articleContentHtml += '<p class="article-type">' + typeHtml + '</p>' +
            '<div class="article-metadata">' +
                '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Entity</p>' +
                    '<p class="article-metadata-value">' + entity + '</p>' +
                '</div>' +
                '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Discipline</p>' +
                    '<p class="article-metadata-value">' + discipline + '</p>' +
                '</div>' +
                '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Subject(s)</p>' +
                    '<p class="article-metadata-value">' + subjectHtml + '</p>' +
                '</div>' +
            '</div>';
            // Add images if any
            if (cardImages.length > 0) {
                var initialImage = cardImages[0]; // Use the first image initially
                var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
                articleContentHtml +=
                    '<div class="article-images">' +
                        getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
                    '</div>';
            }
            // Add non-image content (description, reflection, etc.)   
            articleContentHtml +=
            (description ? '<p class="article-label-description">Description</p>' +
            '<div class="article-description">' + formatParagraphs(description) + '</div>' : '') +
            (reflection ? '<p class="article-label-reflection">Reflection</p>' +
            '<div class="article-reflection">' + formatParagraphs(reflection) + '</div>' : '') +
            (externalReferenceHtml ? '<p class="article-label-external-reference">References</p>' +
            '<p class="article-external-reference">' + externalReferenceHtml + '</p>' : '') +
            (quote ? '<p class="article-label-quote">Quote</p>' +
            '<p class="article-quote">' + quote + '</p>' : '') +
            '<p class="article-label-modification-date">Added on</p>' +
            '<div class="article-modification-date">' + modificationDate + '</div>';
   
            $('#article-content').html(articleContentHtml);
            $('#related-articles').html(relatedArticlesHtml);
   
            if (relatedArticlesHtml && relatedArticlesHtml.trim().length > 0) {
                $('#related-articles').html('<div class="related-articles-label">Related Articles</div><div class="related-articles-container">' + relatedArticlesHtml + '</div>').show();
            }
         }
         }
      } else {
        if (htmlEl.classList) htmlEl.classList.remove("print-no-border");
        else
          htmlEl.className = htmlEl.className.replace(
            /\bprint-no-border\b/g,
            ""
          );
      }
    })();


        // Check which view is active and set the width accordingly
    // clean empty paragraphs
        if ($('.home-chronicle-list').is(':visible')) {
    (function () {
            $('.home-list-view').each(function() {
      var ps = doc.querySelectorAll("#article-content p");
                var currentWidth = $(this).width();  // Get the current width
      Array.prototype.forEach.call(ps, function (p) {
                $(this).data('originalWidth', currentWidth); // Store the original width
        var txt = (p.textContent || "").replace(/\u00a0/g, " ").trim();
                $(this).css('width', 'calc(60% - 2px)');
        var onlyBr =
            });   
          p.children.length === 1 &&
           
          p.firstElementChild &&
            // Modify the .type elements within .home-chronicle-list
          p.firstElementChild.tagName === "BR";
            $('.home-chronicle-list .type').each(function() {
        if (
                var currentLeft = $(this).css('left');  // Get the current left value
          (!txt && !p.querySelector("img, a, strong, em, span:not(:empty)")) ||
                $(this).data('originalLeft', currentLeft); // Store the original left value
          onlyBr
                $(this).css('left', '85%');
        ) {
            });
          if (p.parentNode) p.parentNode.removeChild(p);
        } else if ($('.home-chronicle-block').is(':visible')) {
            $('.home-chronicle-block div.list-container').each(function() {
                var currentWidth = $(this).width();  // Get the current width
                $(this).css('width', 'calc(60% - 0px)');  // Set the new width as 30% of the current width
            });
            $('.home-chronicle-block div.list-container div.card').each(function() {
                var currentWidth = $(this).width();  // Get the current width
                $(this).css('width', 'calc(33.333% - 0px)');  // Set the new width as 30% of the current width
            });          
         }
         }
      });
      var root = doc.getElementById("article-content");
      if (root) {
        Array.prototype.slice.call(root.childNodes).forEach(function (n) {
          if (n.nodeType === 3 && !n.textContent.replace(/\s+/g, "")) {
            root.removeChild(n);
          }
        });
      }
    })();
    // small inline tweaks
    (function () {
      var css =
        "@media print{" +
        "  .article-description p,.article-reflection p,.article-external-reference p,.article-quote p{margin:0 0 1.2mm!important;}" +
        "  .article-description p:last-child,.article-reflection p:last-child,.article-external-reference p:last-child,.article-quote p:last-child{margin-bottom:0!important;}" +
        "  .article-entry-number,.link-pdf,.article-type,.article-metadata,.article-images,.article-description,.article-reflection,.article-external-reference,.article-quote,.article-mod-line{padding-bottom:1mm!important;}" +
        '  [class^\\"article-label-\\"]{margin-top:0!important;}' +
        '  .article-entry-number + [class^\\"article-label-\\"],' +
        '  .link-pdf + [class^\\"article-label-\\"],' +
        '  .article-type + [class^\\"article-label-\\"],' +
        '  .article-metadata + [class^\\"article-label-\\"],' +
        '  .article-images + [class^\\"article-label-\\"],' +
        '  .article-description + [class^\\"article-label-\\"],' +
        '  .article-reflection + [class^\\"article-label-\\"],' +
        '  .article-external-reference + [class^\\"article-label-\\"],' +
        '  .article-quote + [class^\\"article-label-\\"],' +
        '  .article-mod-line + [class^\\"article-label-\\"]{margin-top:0.9mm!important;}' +
        "  .article-label-description + .article-description," +
        "  .article-label-reflection + .article-reflection," +
        "  .article-label-external-reference + .article-external-reference," +
        "  .article-label-quote + .article-quote," +
        "  .article-label-modification-date + .article-modification-date{margin-top:0!important;}" +
        "  .article-title-link{margin:0!important;padding:0!important;}" +
        "  .article-title-link > *{margin:0!important;}" +
        "  .link-pdf{margin-top:0!important;}" +
        "  #article-content > :last-child{padding-bottom:0!important;}" +
        "  #article-content > :last-child::after{content:none!important;}" +
        "}";
      var style = doc.createElement("style");
      style.type = "text/css";
      style.appendChild(doc.createTextNode(css));
      doc.head.appendChild(style);
    })();


        // Apply the fade-out effect to both #list and #list-list elements
    // link tweaks
         $('.list-container').addClass('fade-out');
    (function () {
      var styleFix = doc.createElement("style");
      styleFix.textContent =
        "@media print {.article-external-reference a,.link-pdf a{white-space:nowrap!important;word-break:normal!important;overflow-wrap:normal!important;text-decoration:underline}.article-external-reference{overflow-wrap:anywhere;word-break:break-word}a[href]{position:relative}}";
      doc.head.appendChild(styleFix);
      var refs = doc.querySelectorAll(".article-external-reference a[href]");
      Array.prototype.forEach.call(refs, function (a) {
        var txt = (a.textContent || "").trim();
         var href = a.getAttribute("href") || "";
        var looksLongUrl = /^https?:\/\//i.test(txt) && txt.length > 60;
        if (looksLongUrl) {
          try {
            var u = new URL(href, doc.baseURI);
            var label =
              u.hostname + (u.pathname.replace(/\/$/, "") ? u.pathname : "");
            if (label.length > 40) label = label.slice(0, 37) + "…";
            a.textContent = label;
          } catch (e) {
            a.textContent = "Link";
          }
        }
        a.style.whiteSpace = "nowrap";
        a.style.wordBreak = "normal";
        a.style.overflowWrap = "normal";
      });
    })();


    // waits
    function waitImages() {
      var imgs = [].slice.call(doc.images || []);
      if (!imgs.length) return Promise.resolve();
      return Promise.all(
        imgs.map(function (img) {
          if (img.decode) {
            try {
              return img.decode().catch(function () {});
            } catch (e) {}
          }
          return new Promise(function (res) {
            if (img.complete) return res();
            img.onload = img.onerror = function () {
              res();
            };
          });
        })
      );
    }
    function waitFonts(timeoutMs) {
      if (!doc.fonts || !doc.fonts.ready) return Promise.resolve();
      var ready = doc.fonts.ready;
      var t = new Promise(function (res) {
        setTimeout(res, timeoutMs || 1200);
      });
      return Promise.race([ready, t]);
    }
    function waitSpecificFont(timeoutMs) {
      if (!doc.fonts || !doc.fonts.load) return Promise.resolve();
      var p = Promise.all([
        doc.fonts.load('400 16px "HALColant-TextRegular"'),
        doc.fonts.load('normal 16px "HALColant-TextRegular"'),
      ]);
      var t = new Promise(function (res) {
        setTimeout(res, timeoutMs || 1200);
      });
      return Promise.race([p, t]);
    }
    function nextFrame() {
      return new Promise(function (res) {
        (iframe.contentWindow.requestAnimationFrame || setTimeout)(res, 0);
      });
     }
     }


     // closeModal function
     Promise.all([
    function closeModal() {
      cssLoaded,
        if ($('.home-chronicle-list').is(':visible')) {
      waitImages(),
            $('.home-list-view').css('width', '100%');
      waitFonts(1200),
            $('.home-chronicle-list div.list-container div.card div.type').css('left', '90%');
      waitSpecificFont(1200),
         } else if ($('.home-chronicle-block').is(':visible')) {
      nextFrame(),
            updateWidthBlockView();
    ])
      .then(function () {
        // filename via document.title
        var entryNum = "";
        var numEl = doc.querySelector(".article-entry-number");
         if (numEl) {
          var m = (numEl.textContent || "").match(/\d+/);
          entryNum = m ? m[0] : "";
         }
         }
         showArticleWrapper.hide();
         var desiredTitle =
          (entryNum ? entryNum + "." : "") + "softwear.directory";
        var oldIframeTitle = doc.title;
        var oldParentTitle = document.title;
 
        iframe.contentWindow.onafterprint = function () {
          try {
            doc.title = oldIframeTitle;
            document.title = oldParentTitle;
          } catch (e) {}
          setTimeout(function () {
            if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
          }, 100);
          if ($btn && $btn.length) $btn.data("busy", false);
        };
 
        doc.title = desiredTitle;
        document.title = desiredTitle;
 
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
 
        // safety cleanup
        setTimeout(function () {
          try {
            doc.title = oldIframeTitle;
            document.title = oldParentTitle;
          } catch (e) {}
          if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
          if ($btn && $btn.length) $btn.data("busy", false);
        }, 1000);
      })
      .catch(function () {
        if ($btn && $btn.length) $btn.data("busy", false);
      });
  }
 
  /* decide source & kick print */
  function swHandlePrintChoice(id, $btn) {
    if ($btn && $btn.data("busy")) return;
    if ($btn && $btn.length) $btn.data("busy", true);
 
    var borderPref = id === "print-no-border" ? "without" : "with";
    swPrintPreloadFont();
 
    // prefer local .print-only (Entry page)
    var localPrintOnly = jQuery(".print-only").first();
    if (localPrintOnly.length) {
      swHidePrintUI();
      swBuildIframeAndPrint(localPrintOnly.prop("outerHTML"), borderPref, $btn);
      return;
    }
 
    // otherwise fetch by title (modal/home list flow)
    var title =
      window.currentEntryTitle ||
      (window.mw && mw.config && mw.config.get && mw.config.get("wgPageName"));
    if (!title) {
      window.print();
      if ($btn && $btn.length) $btn.data("busy", false);
      return;
     }
     }


     $('.card').on('click', function(event) {
     var pageUrl =
         // Check if the click event is originating from a link within .people or .type, or any other specific area
      window.mw && mw.util && mw.util.getUrl
         if ($(event.target).closest('.people a, .type a').length) {
        ? mw.util.getUrl(title)
            // The click is inside a link; let the default behavior proceed without opening the modal
        : "/wiki/" + String(title);
            return;
    jQuery
      .get(swPrintCacheBust(pageUrl))
      .done(function (html) {
         var $tmp = jQuery("<div>").html(html);
        var $print = $tmp.find(".print-only").first();
         if (!$print.length) {
          window.print();
          if ($btn && $btn.length) $btn.data("busy", false);
          return;
         }
         }
      
        swHidePrintUI();
        // Prevent further event handling if the card has the 'event' class
        swBuildIframeAndPrint($print.prop("outerHTML"), borderPref, $btn);
        if ($(this).hasClass('event')) {
      })
            event.stopImmediatePropagation();
      .fail(function () {
            openEvent(this, event);
        window.print();
            $('.list-container').removeClass('fade-out');
        jQuery("#print-button").data("busy", false);
            closeModal();
      });
        } else {
  }
            // Handle cards without the 'event' class
 
            openModal(this, event);
  /* wiring (namespaced) */
            setShowArticleRotationEffect();
  jQuery(document).off("click.swprint");
        }
  jQuery(document).on(
     });
    "click.swprint",
    "#print-button, #print-chooser, #print-options",
     function (e) {
      // click on the main [print]
      if (jQuery(e.target).closest("#print-button").length) {
        e.preventDefault();
        var $chooser = swEnsurePrintChooser();
        $chooser.toggle();
        jQuery("#show-article").toggleClass(
          "print-opts-open",
          $chooser.is(":visible")
        );
        return;
      }
      // click on a choice link
      var $choice = jQuery(e.target).closest(
        "a#print-with-border, a#print-no-border"
      );
      if (!$choice.length) return;
      e.preventDefault();
      swHandlePrintChoice($choice.attr("id"), $choice);
    }
  );
 
  // --- extra safety bindings for Entry page / widgets ---
 
  // 1) Directly bind the anchors (works even if container delegation misses)
  jQuery(document).on(
    "click.swprintChoice",
    "a#print-with-border, a#print-no-border, #print-with-border, #print-no-border",
    function (e) {
      console.log("[print] direct anchor handler fired:", this.id);
      e.preventDefault();
      swHandlePrintChoice(this.id, jQuery(this));
     }
  );


    $('#show-article-wrapper').on('click', '.related-article', function(event) {
  // 2) If using the Button widget (<a id=...><button>...</button></a>),
        openModal(this, event); // Call openModal when a related-article is clicked
  //    capture clicks on the <button> and route via its parent <a>.
         setShowArticleRotationEffect();
  jQuery(document).on(
     });
    "click.swprintChoiceBtn",
    "#print-options button",
    function (e) {
      var $a = jQuery(this).closest("a[id]");
      if (!$a.length) return;
      console.log(
        "[print] widget button handler fired; parent anchor id:",
         $a.attr("id")
      );
      e.preventDefault();
      swHandlePrintChoice($a.attr("id"), $a);
     }
  );


    // Print current entry only
  // also hide choices on ESC; your close-button handler already hides them
    $('#print-button').on('click', function () {
  jQuery(document).on("keydown.swprint", function (e) {
     $('body').addClass('print-entry-only');
     if (e && e.keyCode === 27) swHidePrintUI();
    window.print();
  });


    // remove the class after print (covers most browsers)
  /* ---------- /Softwear PRINT ---------- */
    setTimeout(function(){ $('body').removeClass('print-entry-only'); }, 500);
    });


    // optional: also remove class when print dialog closes (Firefox/Chromium support)
  // Close modal with Close button
     window.onafterprint = function () {
  $("#close-button").on("click", function () {
     $('body').removeClass('print-entry-only');
     $("#print-chooser").hide();
    };
     $("#show-article").removeClass("print-opts-open");


    // Close modal with Close button
     $(".list-container").removeClass("fade-out");
     $('#close-button').on('click', function () {
    closeModal();
        $('.list-container').removeClass('fade-out');
  });
        closeModal();
    });


    // Close modal and remove fade out also when clicking outside of card
  // Close modal and remove fade out also when clicking outside of card
    $(document).on('mousedown', function (event) {
  $(document).on("mousedown", function (event) {
        var isOutsideWrapper = !showArticleWrapper.is(event.target) && showArticleWrapper.has(event.target).length === 0;
    var isOutsideWrapper =
        var isOnCard = $(event.target).closest('.card, .list-card').length > 0;
      !showArticleWrapper.is(event.target) &&
       
      showArticleWrapper.has(event.target).length === 0;
        if (!areFiltersActive) {
    var isOnCard = $(event.target).closest(".card, .list-card").length > 0;
            if (isOutsideWrapper && !isOnCard) {
                $('.list-container').removeClass('fade-out');
                showArticleWrapper.css('display', 'none');
                closeModal();  // Use closeModal() for cleanup
            }
        }
    });


     // Hover effect for scrolling
     if (!areFiltersActive) {
    $('#show-article-wrapper').hover(function () {
      if (isOutsideWrapper && !isOnCard) {
        // On hover, enable scrolling on #show-article-wrapper
         $(".list-container").removeClass("fade-out");
         $(this).css('overflow-y', 'auto');
         showArticleWrapper.css("display", "none");
         $(this).css('overflow-x', 'hidden');
        closeModal(); // Use closeModal() for cleanup
    }, function () {
      }
        // On hover out, disable scrolling on #show-article-wrapper
     }
        $(this).css('overflow-y', 'hidden');
  });
        $(this).css('overflow-x', 'hidden');
     });


     // Format community card, when in the Community Entries page
  // Hover effect for scrolling
    if ($('.community-card').length) {
  $("#show-article-wrapper").hover(
        formatCommunityCardDescriptions();
     function () {
      // On hover, enable scrolling on #show-article-wrapper
      $(this).css("overflow-y", "auto");
      $(this).css("overflow-x", "hidden");
    },
    function () {
      // On hover out, disable scrolling on #show-article-wrapper
      $(this).css("overflow-y", "hidden");
      $(this).css("overflow-x", "hidden");
     }
     }
  );
  // Format community card, when in the Community Entries page
  if ($(".community-card").length) {
    formatCommunityCardDescriptions();
  }
  function formatCommunityCardDescriptions() {
    $(".community-card").each(function () {
      // Format paragraphs in community-description
      var descriptionContainer = $(this).find(".community-description");
      var rawDescription = descriptionContainer.text();
      var formattedDescription = formatParagraphs(rawDescription);
      descriptionContainer.html(formattedDescription);


    function formatCommunityCardDescriptions() {
      // Remove empty elements in the entire card
        $('.community-card').each(function() { 
      $(this)
            // Format paragraphs in community-description
        .find("*")
            var descriptionContainer = $(this).find('.community-description');
        .each(function () {
            var rawDescription = descriptionContainer.text();
          if ($(this).is(":empty") || $(this).html().trim() === "<br>") {
            var formattedDescription = formatParagraphs(rawDescription);
            $(this).remove();
            descriptionContainer.html(formattedDescription);
          }
   
            // Remove empty elements in the entire card
            $(this).find('*').each(function() {
                if ($(this).is(':empty') || $(this).html().trim() === '<br>') {
                    $(this).remove();
                }
            });
         });
         });
    });
  }
  if ($("#show-article-wrapper-entry").length) {
    // Your existing formatParagraphs function
    function formatParagraphs(text) {
      var paragraphs = text.split("\n").filter(function (p) {
        return p.trim() !== "";
      });
      return paragraphs
        .map(function (p) {
          return "<p>" + p.trim() + "</p>";
        })
        .join("");
     }
     }
   
    // NRS ENTRIES  ---------------------  SECTION //
    console.log("Document ready!"); // Check if document ready event is triggered
   
    if ($("#show-article-wrapper-entry").length) {
        console.log("Element with id 'show-article-wrapper-entry' found!"); // Check if the target element exists
       
        // Your existing formatParagraphs function
        function formatParagraphs(text) {
            var paragraphs = text.split('\n').filter(function (p) { return p.trim() !== '' });
            return paragraphs.map(function (p) { return '<p>' + p.trim() + '</p>'; }).join('');
        }


        // Check if ".article-description" exists and format its text
    // Check if ".article-description" exists and format its text
        if ($(".article-description").length) {
    if ($(".article-description").length) {
            console.log("Element with class 'article-description' found!"); // Check if the target element exists
      var descriptionText = $(".article-description").text();
            var descriptionText = $(".article-description").text();
      var formattedDescription = formatParagraphs(descriptionText);
            console.log("Original description text:", descriptionText); // Log the original text
      $(".article-description").html(formattedDescription); // Set the formatted text
            var formattedDescription = formatParagraphs(descriptionText);
    }
            console.log("Formatted description text:", formattedDescription); // Log the formatted text
            $(".article-description").html(formattedDescription); // Set the formatted text
        }


        // Check if ".article-reflection" exists and format its text
    // Check if ".article-reflection" exists and format its text
        if ($(".article-reflection").length) {
    if ($(".article-reflection").length) {
            console.log("Element with class 'article-reflection' found!"); // Check if the target element exists
      var reflectionText = $(".article-reflection").text();
            var reflectionText = $(".article-reflection").text();
      var formattedReflection = formatParagraphs(reflectionText);
            console.log("Original reflection text:", reflectionText); // Log the original text
      $(".article-reflection").html(formattedReflection); // Set the formatted text
            var formattedReflection = formatParagraphs(reflectionText);
            console.log("Formatted reflection text:", formattedReflection); // Log the formatted text
            $(".article-reflection").html(formattedReflection); // Set the formatted text
        }
     }
     }
  }
  // SEARCH  ---------------------  SECTION //
  // Check if div with class "mw-search-results-info" exists
  if ($(".mw-search-results-info").length) {
    // Select the child <p> element and check its content
    var $paragraph = $(".mw-search-results-info > p");
    var currentText = $paragraph.text().trim();


     // SEARCH  ---------------------  SECTION //
     // Check if the current text is not "There were no results matching the query."
    // Check if div with class "mw-search-results-info" exists
    if (currentText !== "There were no results matching the query.") {
    if ($('.mw-search-results-info').length) {
      // Overwrite the content with "Search results"
        // Select the child <p> element and check its content
      $paragraph.text("Pages related to your Search");
        var $paragraph = $('.mw-search-results-info > p');
        var currentText = $paragraph.text().trim();
       
        // Check if the current text is not "There were no results matching the query."
        if (currentText !== "There were no results matching the query.") {
            // Overwrite the content with "Search results"
            $paragraph.text('Pages related to your Search');
        }
     }
     }
   
  }
    // Object to store encountered titles
    var encounteredTitles = {};


    // Iterate over each search result
  // Object to store encountered titles
    $('.mw-search-result-heading').each(function() {
  var encounteredTitles = {};
        // Get the title of the current search result
        var title = $(this).find('a').attr('title');


        // Check if the title has already been encountered
  // Iterate over each search result
        if (encounteredTitles[title]) {
  $(".mw-search-result-heading").each(function () {
            // Hide the duplicate search result
    // Get the title of the current search result
            $(this).hide();
    var title = $(this).find("a").attr("title");
        } else {
 
            // Mark the title as encountered
    // Check if the title has already been encountered
            encounteredTitles[title] = true;
    if (encounteredTitles[title]) {
        }
      // Hide the duplicate search result
    });
      $(this).hide();
   
    } else {
    // Remove unwanted white spaces between lines
      // Mark the title as encountered
    $('.mw-search-results-container').contents().filter(function() {
      encounteredTitles[title] = true;
        return this.nodeType === 3; // Filter text nodes
    }
     }).remove();
  });
   
 
    // Edits regarding Search Results
  // Remove unwanted white spaces between lines
     // Define the new form HTML as a string
  $(".mw-search-results-container")
    var newFormHtml = '<form action="/index.php" id="searchform">' +
    .contents()
        '<div id="simpleSearchSpecial" class="right-inner-addon">' +
    .filter(function () {
        '<span>[ Search ]</span>' +
      return this.nodeType === 3; // Filter text nodes
        '<input class="form-control" name="search" placeholder="" title="Search [alt-shift-f]" accesskey="f" id="searchInput" tabindex="1" autocomplete="off" type="search">' +
     })
        '<span class="closing-bracket">]</span>' +
     .remove();
        '<input value="Special:Search" name="title" type="hidden">' +
        '</div>' +
        '</form>';
   
    // Replace the div with id="searchText" with the new form
    $('#searchText').replaceWith(newFormHtml);
   
    // Target the button based on its complex class structure
    $(".oo-ui-actionFieldLayout-button .oo-ui-buttonInputWidget").remove();


     // Check if #submit button exists and add event listener if it does
  // Edits regarding Search Results
     var submitButton = document.querySelector('#submit');
  // Define the new form HTML as a string
     console.log("Submit button:", submitButton);
  var newFormHtml =
     '<form action="/index.php" id="searchform">' +
    '<div id="simpleSearchSpecial" class="right-inner-addon">' +
    "<span>[ Search ]</span>" +
     '<input class="form-control" name="search" placeholder="" title="Search [alt-shift-f]" accesskey="f" id="searchInput" tabindex="1" autocomplete="off" type="search">' +
    '<span class="closing-bracket">]</span>' +
     '<input value="Special:Search" name="title" type="hidden">' +
    "</div>" +
    "</form>";


    if (submitButton) {
  // Replace the div with id="searchText" with the new form
        console.log("#submit button found.");
  $("#searchText").replaceWith(newFormHtml);


        // Add click event listener
  // Target the button based on its complex class structure
        submitButton.addEventListener('click', function(event) {
  $(".oo-ui-actionFieldLayout-button .oo-ui-buttonInputWidget").remove();
            console.log("Submit button clicked.");
            event.preventDefault(); // Prevent the default link behavior


            var email = 'submit@softwear.directory';
  // Check if #submit button exists and add event listener if it does
            var subject = 'new entry to the softwear directory';
  var submitButton = document.querySelector("#submit");
            var body = '☺ the following content could be interesting for the directory:\n\n' +
                      '[ author / creator ]\n\n' +
                      '---\n\n' +
                      '[ title ]\n\n' +
                      '---\n\n' +
                      '[ why should it be included? ]\n\n' +
                      '---\n\n' +
                      '[ link or pdf ]\n\n' +
                      '---\n\n' +
                      '[ your name / contact / social ]\n\n' +
                      '---';


            var mailtoLink = 'mailto:' + encodeURIComponent(email) +
  if (submitButton) {
                            '?subject=' + encodeURIComponent(subject) +
    // Add click event listener
                            '&body=' + encodeURIComponent(body).replace(/%20/g, ' ');
    submitButton.addEventListener("click", function (event) {
      event.preventDefault(); // Prevent the default link behavior


            window.location.href = mailtoLink;
      var email = "submit@softwear.directory";
         });
      var subject = "new entry to the softwear directory";
    }
      var body =
        "☺ the following content could be interesting for the directory:\n\n" +
        "[ author / creator ]\n\n" +
         "---\n\n" +
        "[ title ]\n\n" +
        "---\n\n" +
        "[ why should it be included? ]\n\n" +
        "---\n\n" +
        "[ link or pdf ]\n\n" +
        "---\n\n" +
        "[ your name / contact / social ]\n\n" +
        "---";


    // Tooltip for "wander elsewhere..." on .card.event
      var mailtoLink =
    var tooltip = $('<div class="tooltip-popup">wander elsewhere...</div>').appendTo('body');
        "mailto:" +
        encodeURIComponent(email) +
        "?subject=" +
        encodeURIComponent(subject) +
        "&body=" +
        encodeURIComponent(body).replace(/%20/g, " ");


    $('.card.event').on('mouseenter', function () {
      window.location.href = mailtoLink;
        tooltip.css('opacity', 1);
     });
     });
  }


     $('.card.event').on('mousemove', function (e) {
  // Tooltip for "wander elsewhere..." on .card.event
        var offsetX = 10; // right of cursor
  var tooltip = $(
        var offsetY = -30; // above cursor
     '<div class="tooltip-popup">wander elsewhere...</div>'
        tooltip.css({
  ).appendTo("body");
            left: e.clientX + offsetX + 'px',
 
            top: e.clientY + offsetY + 'px'
  $(".card.event").on("mouseenter", function () {
        });
    tooltip.css("opacity", 1);
    });
  });


    $('.card.event').on('mouseleave', function () {
  $(".card.event").on("mousemove", function (e) {
        tooltip.css('opacity', 0);
    var offsetX = 10; // right of cursor
    var offsetY = -30; // above cursor
    tooltip.css({
      left: e.clientX + offsetX + "px",
      top: e.clientY + offsetY + "px",
     });
     });
  });


    mw.loader.using('mediawiki.api', function () {
  $(".card.event").on("mouseleave", function () {
        // Only run on form edit page
    tooltip.css("opacity", 0);
        if (mw.config.get('wgCanonicalSpecialPageName') === 'FormEdit') {
  });
            new mw.Api().post({
                action: 'purge',
                titles: 'Main'
            }).fail(function (err) {
                // Optional: leave a minimal fallback error log
                console.warn("Main page purge failed", err);
            });
        }
    });


  mw.loader.using("mediawiki.api", function () {
    // Only run on form edit page
    if (mw.config.get("wgCanonicalSpecialPageName") === "FormEdit") {
      new mw.Api()
        .post({
          action: "purge",
          titles: "Main",
        })
        .fail(function (err) {
          // Optional: leave a minimal fallback error log
          console.warn("Main page purge failed", err);
        });
    }
  });
});
});

Revision as of 10:15, 30 August 2025

$(document).ready(function () {
  // Global variables
  var cards = $(".card");
  var showArticleWrapper = $("#show-article-wrapper");
  var areFiltersActive = false;

  // Make header-box in Home clickable
  $(".head-box").click(function () {
    window.location.href = "/Main_Page"; // Redirects to the home page
  });

  // Loop through each card to format related articles
  cards.each(function () {
    // Check if the card has related articles
    var relatedArticles = $(this).find(".related-articles");
    if (relatedArticles.length > 0) {
      // Get all the related article elements
      var relatedArticleElements = relatedArticles.find(".related-article");

      // Create an array to store unique related articles
      var uniqueArticles = [];

      // Loop through each related article element
      relatedArticleElements.each(function () {
        // Remove <p> tags from the article
        $(this).find("p").remove();

        // Convert the article HTML to a string
        var articleHTML = $(this)[0].outerHTML;

        // Check if the article HTML already exists in the uniqueArticles array
        if ($.inArray(articleHTML, uniqueArticles) === -1) {
          // If it doesn't exist, add it to the uniqueArticles array
          uniqueArticles.push(articleHTML);
        }
      });

      // Clear the content of the related articles container
      relatedArticles.empty();

      // Append the unique related articles back to the container
      relatedArticles.append(uniqueArticles.join(""));
    }
  });

  // Utility Functions
  function sortChronologically() {
    var cards = $(".list-container .card").get();

    cards.sort(function (a, b) {
      var numberA = parseInt(
        $(a).find(".entry-number").text().replace(/\[|\]/g, ""),
        10
      );
      var numberB = parseInt(
        $(b).find(".entry-number").text().replace(/\[|\]/g, ""),
        10
      );
      return numberB - numberA; // Descending order
    });

    $.each(cards, function (index, item) {
      $(".list-container").append(item);
    });
  }

  function randomizeCards(selector) {
    var cards = $(selector).get();

    var i = cards.length,
      j,
      temp;
    while (--i > 0) {
      j = Math.floor(Math.random() * (i + 1));
      temp = cards[i];
      cards[i] = cards[j];
      cards[j] = temp;
    }

    $.each(cards, function (index, item) {
      $(selector).parent().append(item);
    });
  }

  function sortAlphabetically(selector) {
    var cards = $(selector).get();

    cards.sort(function (a, b) {
      var titleA = $(a).find(".title").text().toUpperCase();
      var titleB = $(b).find(".title").text().toUpperCase();
      return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
    });

    $.each(cards, function (index, item) {
      $(selector).parent().append(item);
    });
  }

  function updateViews() {
    // Handle cards in the list view
    $(".home-chronicle-list div.list-container div.card:not(.event)").each(
      function () {
        if (!$(this).closest(".home-chronicle-block").length) {
          var title = $(this).find(".title").detach();
          var images = $(this).find(".images").detach();

          // Remove existing .title-images if it exists
          $(this).find(".title-images").remove();

          var titleImagesContainer = $(
            '<div class="title-images"></div>'
          ).append(images, title);
          $(this).find(".people").after(titleImagesContainer);
        }
      }
    );

    // Handle cards in the block view
    $(".home-chronicle-block div.list-container div.card:not(.event)").each(
      function () {
        // Remove .title-images container if it exists, re-attach .title and .images to their original places
        var titleImagesContainer = $(this).find(".title-images");
        if (titleImagesContainer.length) {
          var title = titleImagesContainer.find(".title").detach();
          var images = titleImagesContainer.find(".images").detach();
          titleImagesContainer.remove();

          $(this).find(".people").after(title);
          $(this).find(".type").after(images);
        } else {
          // If .title-images doesn't exist, ensure .images is placed correctly
          var images = $(this).find(".images").detach();
          $(this).find(".type").after(images);
        }
      }
    );
  }

  function processEventCards() {
    $(".card.event").each(function () {
      var $card = $(this);
      var existingContainer = $card.find(".container-people-date");

      // Create container if missing
      if (existingContainer.length === 0) {
        existingContainer = $('<div class="container-people-date"></div>');
        $card.append(existingContainer); // temp placement
      }

      // Detach people and date
      var people = $card.find(".people").detach();
      var date = $card.find(".date").detach();

      // BLOCK VIEW (gallery)
      if ($card.closest(".home-chronicle-block").length) {
        existingContainer.append(people).append(date);

        // Place container after title
        if (!existingContainer.is($card.find(".title").next())) {
          $card.find(".title").after(existingContainer);
        }

        // LIST VIEW
      } else if ($card.closest(".home-chronicle-list").length) {
        // Only append .people into container
        existingContainer.empty().append(people);

        // Place container before title
        $card.find(".title").before(existingContainer);

        // Place date after title
        $card.find(".title").after(date);
      }
    });
  }

  if ($("#home").length > 0) {
    // This code will only run only on the homepage.
    $(".home-block-view").show();
    $(".home-chronicle-block-button, .home-block-view-button").addClass(
      "active-view-button"
    );

    // Initially hide list view sorting buttons and set the default sorted view for block
    $(
      ".home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button"
    ).hide();
    sortChronologically(); // Sort the block view chronologically by default

    updateLastVisibleCard();
    updateWidthBlockView();
    processEventCards();
    updateViews();

    $(".home-list-view-button").click(function () {
      $(".home-list-sorting-buttons").css("display", "flex");
      // Switching view classes
      $(".home-block-view")
        .removeClass("home-block-view")
        .addClass("home-list-view");
      // Additional class switch
      $(".home-chronicle-block")
        .removeClass("home-chronicle-block")
        .addClass("home-chronicle-list");
      // Toggling visibility of buttons
      $(
        ".home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button"
      ).hide();
      $(
        ".home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button"
      ).show();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();

      // Remove active class from block view button and add to list view button
      $(".home-block-view-button").removeClass("active-view-button");
      $(".home-list-view-button").addClass("active-view-button");

      // Conditional checks for transferring the active class from block to list buttons
      if ($(".home-chronicle-block-button").hasClass("active-view-button")) {
        $(".home-chronicle-block-button").removeClass("active-view-button");
        $(".home-chronicle-list-button").addClass("active-view-button");
      } else if (
        $(".home-random-block-button").hasClass("active-view-button")
      ) {
        $(".home-random-block-button").removeClass("active-view-button");
        $(".home-random-list-button").addClass("active-view-button");
      } else if (
        $(".home-alphabetical-block-button").hasClass("active-view-button")
      ) {
        $(".home-alphabetical-block-button").removeClass("active-view-button");
        $(".home-alphabetical-list-button").addClass("active-view-button");
      }
    });

    $(".home-block-view-button").click(function () {
      console.log("Block view button clicked.");
      $(".home-list-sorting-buttons").hide(); // Hide list sorting buttons
      $(".home-list-view")
        .removeClass("home-list-view")
        .addClass("home-block-view");
      $(".home-chronicle-list")
        .removeClass("home-chronicle-list")
        .addClass("home-chronicle-block");
      $(
        ".home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button"
      ).show();
      $(
        ".home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button"
      ).hide();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-list-view-button").removeClass("active-view-button");
      $(".home-block-view-button").addClass("active-view-button");

      // Conditional checks for transferring the active class from block to list buttons
      if ($(".home-chronicle-list-button").hasClass("active-view-button")) {
        $(".home-chronicle-list-button").removeClass("active-view-button");
        $(".home-chronicle-block-button").addClass("active-view-button");
      } else if ($(".home-random-list-button").hasClass("active-view-button")) {
        $(".home-random-list-button").removeClass("active-view-button");
        $(".home-random-block-button").addClass("active-view-button");
      } else if (
        $(".home-alphabetical-list-button").hasClass("active-view-button")
      ) {
        $(".home-alphabetical-list-button").removeClass("active-view-button");
        $(".home-alphabetical-block-button").addClass("active-view-button");
      }
    });

    // BLOCK VIEW SORTING BUTTONS
    $(".home-chronicle-block-button").click(function () {
      sortChronologically();

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-chronicle-block-button").addClass("active-view-button");
      $(".home-random-block-button").removeClass("active-view-button");
      $(".home-alphabetical-block-button").removeClass("active-view-button");
    });

    $(".home-random-block-button").click(function () {
      randomizeCards(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-random-block-button").addClass("active-view-button");
      $(".home-chronicle-block-button").removeClass("active-view-button");
      $(".home-alphabetical-block-button").removeClass("active-view-button");
    });

    $(".home-alphabetical-block-button").click(function () {
      sortAlphabetically(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-alphabetical-block-button").addClass("active-view-button");
      $(".home-chronicle-block-button").removeClass("active-view-button");
      $(".home-random-block-button").removeClass("active-view-button");
    });

    // LIST VIEW SORTING BUTTONS
    $(".home-chronicle-list-button").click(function () {
      sortChronologically();

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-chronicle-list-button").addClass("active-view-button");
      $(".home-random-list-button").removeClass("active-view-button");
      $(".home-alphabetical-list-button").removeClass("active-view-button");
    });

    $(".home-random-list-button").click(function () {
      randomizeCards(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-random-list-button").addClass("active-view-button");
      $(".home-chronicle-list-button").removeClass("active-view-button");
      $(".home-alphabetical-list-button").removeClass("active-view-button");
    });

    $(".home-alphabetical-list-button").click(function () {
      sortAlphabetically(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".home-alphabetical-list-button").addClass("active-view-button");
      $(".home-chronicle-list-button").removeClass("active-view-button");
      $(".home-random-list-button").removeClass("active-view-button");
    });
  } else {
    console.log("NOT HOMEPAGE");
    $(".home-list-view").show();
    $(".chronicle-list-button, .list-view-button").addClass(
      "active-view-button"
    );

    // Initialization and Default Settings
    // Initially hide block view sorting buttons and set the default sorted view for list
    $(
      ".chronicle-block-button, .random-block-button, .alphabetical-block-button"
    ).hide();
    sortChronologically(); // Sort the block view chronologically by default
    updateLastVisibleCard();
    updateWidthBlockView();
    processEventCards();
    updateViews();

    $(".list-view-button").click(function () {
      console.log("List view button clicked.");
      $(".list-sorting-buttons").css("display", "flex");
      $(".block-sorting-buttons").hide();
      // Switching view classes
      $(".home-block-view")
        .removeClass("home-block-view")
        .addClass("home-list-view");
      // Additional class switch
      $(".home-chronicle-block")
        .removeClass("home-chronicle-block")
        .addClass("home-chronicle-list");
      // Toggling visibility of buttons
      $(
        ".chronicle-block-button, .random-block-button, .alphabetical-block-button"
      ).hide();
      $(
        ".chronicle-list-button, .random-list-button, .alphabetical-list-button"
      ).show();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();

      // Remove active class from block view button and add to list view button
      $(".block-view-button").removeClass("active-view-button");
      $(".list-view-button").addClass("active-view-button");

      // Conditional checks for transferring the active class from block to list buttons
      if ($(".chronicle-block-button").hasClass("active-view-button")) {
        $(".chronicle-block-button").removeClass("active-view-button");
        $(".chronicle-list-button").addClass("active-view-button");
      } else if ($(".random-block-button").hasClass("active-view-button")) {
        $(".random-block-button").removeClass("active-view-button");
        $(".random-list-button").addClass("active-view-button");
      } else if (
        $(".alphabetical-block-button").hasClass("active-view-button")
      ) {
        $(".alphabetical-block-button").removeClass("active-view-button");
        $(".alphabetical-list-button").addClass("active-view-button");
      }
    });

    $(".block-view-button").click(function () {
      console.log("Block view button clicked.");
      $(".list-sorting-buttons").hide(); // Hide list sorting buttons
      $(".block-sorting-buttons").css("display", "flex");
      $(".home-list-view")
        .removeClass("home-list-view")
        .addClass("home-block-view");
      $(".home-chronicle-list")
        .removeClass("home-chronicle-list")
        .addClass("home-chronicle-block");
      $(
        ".chronicle-block-button, .random-block-button, .alphabetical-block-button"
      ).show();
      $(
        ".chronicle-list-button, .random-list-button, .alphabetical-list-button"
      ).hide();
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".list-view-button").removeClass("active-view-button");
      $(".block-view-button").addClass("active-view-button");

      // Conditional checks for transferring the active class from block to list buttons
      if ($(".chronicle-list-button").hasClass("active-view-button")) {
        $(".chronicle-list-button").removeClass("active-view-button");
        $(".chronicle-block-button").addClass("active-view-button");
      } else if ($(".random-list-button").hasClass("active-view-button")) {
        $(".random-list-button").removeClass("active-view-button");
        $(".random-block-button").addClass("active-view-button");
      } else if (
        $(".alphabetical-list-button").hasClass("active-view-button")
      ) {
        $(".alphabetical-list-button").removeClass("active-view-button");
        $(".alphabetical-block-button").addClass("active-view-button");
      }
    });

    // BLOCK VIEW SORTING BUTTONS
    $(".chronicle-block-button").click(function () {
      sortChronologically();

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".chronicle-block-button").addClass("active-view-button");
      $(".random-block-button").removeClass("active-view-button");
      $(".alphabetical-block-button").removeClass("active-view-button");
    });

    $(".random-block-button").click(function () {
      randomizeCards(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".random-block-button").addClass("active-view-button");
      $(".chronicle-block-button").removeClass("active-view-button");
      $(".alphabetical-block-button").removeClass("active-view-button");
    });

    $(".alphabetical-block-button").click(function () {
      sortAlphabetically(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".alphabetical-block-button").addClass("active-view-button");
      $(".chronicle-block-button").removeClass("active-view-button");
      $(".random-block-button").removeClass("active-view-button");
    });

    // LIST VIEW SORTING BUTTONS
    $(".chronicle-list-button").click(function () {
      sortChronologically();

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".chronicle-list-button").addClass("active-view-button");
      $(".random-list-button").removeClass("active-view-button");
      $(".alphabetical-list-button").removeClass("active-view-button");
    });

    $(".random-list-button").click(function () {
      randomizeCards(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".random-list-button").addClass("active-view-button");
      $(".chronicle-list-button").removeClass("active-view-button");
      $(".alphabetical-list-button").removeClass("active-view-button");
    });

    $(".alphabetical-list-button").click(function () {
      sortAlphabetically(".list-container .card");

      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();
      $(".alphabetical-list-button").addClass("active-view-button");
      $(".chronicle-list-button").removeClass("active-view-button");
      $(".random-list-button").removeClass("active-view-button");
    });
  }

  // FILTERS  ---------------------   SECTION //
  // General Filters Toggle Button
  $(".general-toggle").click(function () {
    var filtersDiv = $("#filters");
    var resetButton = $(".reset-button");

    filtersDiv.toggleClass("is-visible");

    if (filtersDiv.hasClass("is-visible")) {
      filtersDiv.css("display", "grid").hide().slideDown(100);
      $(this).text("[FILTER]");
      // Attach click handler to document
      $(document).on("mousedown.hideFilters", function (event) {
        var isOutsideFilters =
          !filtersDiv.is(event.target) &&
          filtersDiv.has(event.target).length === 0;
        var isOnToggle = $(event.target).closest(".general-toggle").length > 0;

        if (isOutsideFilters && !isOnToggle) {
          filtersDiv.removeClass("is-visible").slideUp(100, function () {
            $(this).css("display", "none");
          });
          $(".general-toggle").text("[FILTER]");
          // Remove the document click handler
          $(document).off("mousedown.hideFilters");
        }
      });
    } else {
      filtersDiv.slideUp(100, function () {
        $(this).css("display", "none");
      });
      $(this).text("[FILTER]");
      // Remove the document click handler
      $(document).off("mousedown.hideFilters");
    }

    updateLastVisibleCard();
    updateWidthBlockView();
    processEventCards();
    updateViews();
  });

  // Specific Toggle for Filter Sections like TYPE, ENTITY, etc.
  $(".open-filter").click(function (event) {
    event.stopPropagation();

    var filterType = $(this).closest(".filter").data("filter");
    var cardSelector = $(".card").length > 0 ? ".card" : ".community-card"; // Determine which card type is present

    console.log("Filter type:", filterType, "Card Selector:", cardSelector);

    $("#values-" + filterType).toggle();

    if ($("#values-" + filterType).is(":visible")) {
      $(this).addClass("active-filter");
    } else {
      $(this).removeClass("active-filter");
    }

    // Pass the determined card selector to the function
    updateLastVisibleCard(cardSelector);
    updateWidthBlockView(cardSelector);
    processEventCards(cardSelector);
    updateViews(cardSelector);

    console.log("Updated views and borders after filter toggle");
  });

  function filterCards() {
    var displayCountsHtml = "";
    var cardSelector = $(".card").length > 0 ? ".card" : ".community-card"; // Determine which card type is present

    $(".filter .values a[title]").each(function () {
      var anchor = $(this);
      var filterValue = anchor.attr("title").toLowerCase();
      var count = 0;

      if (anchor.find("button").hasClass("active")) {
        $(cardSelector).each(function () {
          var card = $(this);
          $(".filter").each(function () {
            var filterType = $(this).data("filter");
            var cardValue = card
              .find("." + filterType)
              .text()
              .toLowerCase();
            if (cardValue.indexOf(filterValue) !== -1) {
              count++;
            }
          });
        });

        displayCountsHtml +=
          "<span>[" + count + "] " + filterValue + "</span> ";
      }
    });

    if (displayCountsHtml) {
      $(".count-filtered-cards").html(displayCountsHtml).show();
    } else {
      $(".count-filtered-cards").hide();
    }

    // Apply filtering and pass the determined card selector to the function
    applyFiltering(cardSelector);

    updateLastVisibleCard(cardSelector);
    updateWidthBlockView(cardSelector);
    processEventCards(cardSelector);
    updateViews(cardSelector);

    console.log("Filtering process complete, updated views and borders");
  }

  function applyFiltering() {
    // Determine which card selector to use based on the elements present in the DOM
    var cardSelector = $(".card").length > 0 ? ".card" : ".community-card";

    // Apply the logic to the determined card type
    $(cardSelector)
      .show()
      .each(function () {
        var card = $(this);
        var hideCard = false;

        $(".filter").each(function () {
          if (hideCard) return;

          var filterType = $(this).data("filter");
          var activeFilters = $(this)
            .find(".values a[title] button.active")
            .map(function () {
              return $(this).parent("a").attr("title").toLowerCase();
            })
            .get();

          if (activeFilters.length > 0) {
            var cardValue = card
              .find("." + filterType)
              .text()
              .toLowerCase();
            var matchesFilter = activeFilters.some(function (filterValue) {
              return cardValue.indexOf(filterValue) !== -1;
            });
            if (!matchesFilter) hideCard = true;
          }
        });

        if (hideCard) card.hide();
      });
  }

  function updateLastVisibleCard() {
    // Target only the list view container for updating the last visible card
    $(".home-chronicle-list div.list-container div.card").removeClass(
      "last-visible"
    );

    // Find the last visible card within the list view and add the class
    var lastVisibleCard = $(
      ".home-chronicle-list div.list-container div.card:visible:last"
    );
    lastVisibleCard.addClass("last-visible");
  }

  function updateWidthBlockView() {
    // Target only the block view container for updating the with of card
    $(".home-chronicle-block div.list-container").css("width", "100%");
    $(".home-chronicle-block div.list-container div.card").css(
      "width",
      "calc(20% - 0px)"
    );
    $(
      ".home-chronicle-block div.list-container div.card:nth-child(5n + 1)"
    ).css("width", "calc(20% + 4px)");
  }

  // Reset function to remove active filters
  $(".reset-filter").click(function (event) {
    event.stopPropagation(); // Prevent event bubbling

    // Remove 'active' class from all filter buttons
    $("#filters .values button").removeClass("active");
    $(".open-filter").removeClass("active-filter");

    // Reset and hide the filter counts
    $(".count-filtered-cards").text("").hide();

    filterCards(); // Reapply filtering based on the updated active buttons

    // Update other UI elements as needed, excluding the general toggle button
    updateLastVisibleCard();
    updateWidthBlockView();
    processEventCards();
    updateViews();
  });

  $("#filters .values button").click(function () {
    console.log("Filter is clicked!!!");
    $(this).toggleClass("active");
    filterCards(); // Re-apply the filters based on the updated active buttons

    updateLastVisibleCard();
    updateWidthBlockView();
    processEventCards();
    updateViews();
  });

  // Hide filters when window is scrolled
  $(window).on("scroll", function () {
    var filtersDiv = $("#filters");

    if (filtersDiv.hasClass("is-visible")) {
      filtersDiv.removeClass("is-visible").slideUp(100, function () {
        $(this).css("display", "none");
        // The filter reset code has been removed to keep the filters active
      });
      $(".general-toggle").text("[FILTER]"); // Update the toggle button text
    }
  });

  // MODAL ARTICLE  ---------------------   SECTION //
  // Format paragraphs
  function formatParagraphs(text) {
    var paragraphs = text.split("\n").filter(function (p) {
      return p.trim() !== "";
    });
    return paragraphs
      .map(function (p) {
        return "<p>" + p.trim() + "</p>";
      })
      .join("");
  }

  var images = []; // Initialize an empty array to store the images
  // Find all image containers within the article content and extract the necessary information
  $(".article-images .image-container").each(function () {
    var img = $(this).find("img");
    var captionDiv = $(this).find('div[class^="caption-image"]');
    var image = {
      src: img.attr("src"),
      alt: img.attr("alt"),
      caption: captionDiv.text(),
      captionClass: captionDiv.attr("class"),
    };
    images.push(image); // Add the image object to the images array
  });

  if (images.length > 0) {
    setupImageToggle(images); // Call the setupImageToggle function with the images array
    updateImageLabel(1, images.length); // Set the label for the first image immediately
  }

  function setupImageToggle(images) {
    var currentIndex = 0;
    var enableNavigation = images.length > 1; // Enable navigation only if there is more than one image

    function showImage(index) {
      currentIndex = index;
      var image = images[currentIndex];
      updateImageLabel(currentIndex + 1, images.length);
      $("#article-content")
        .find(".article-images")
        .html(
          getImageHtml(image, currentIndex, images.length, enableNavigation)
        );
    }

    // Attach click handlers only if navigation is enabled
    if (enableNavigation) {
      $("#article-content").on("click", ".next-arrow", function () {
        showImage((currentIndex + 1) % images.length);
      });

      $("#article-content").on("click", ".prev-arrow", function () {
        showImage((currentIndex - 1 + images.length) % images.length);
      });
    }

    // Display the first image
    showImage(currentIndex);
  }

  function getImageHtml(image, currentIndex, totalImages, enableNavigation) {
    var imageLabel = currentIndex + 1 + "/" + totalImages + " IMAGES";

    // Render navigation arrows based on the enableNavigation flag
    var navigationHtml = enableNavigation
      ? '<div class="prev-arrow"><</div><div class="next-arrow">></div>'
      : "";

    return (
      '<div class="image-navigation">' +
      '<p class="article-label-image">' +
      imageLabel +
      "</p>" +
      '<div class="image-container">' +
      '<div class="arrows-and-image">' +
      navigationHtml +
      '<img src="' +
      image.src +
      '" alt="' +
      image.alt +
      '">' +
      "</div>" +
      '<div class="' +
      image.captionClass +
      '">' +
      image.caption +
      "</div>" +
      "</div>" +
      "</div>"
    );
  }

  function updateImageLabel(currentIndex, totalImages) {
    var imageLabel = currentIndex + "/" + totalImages + " IMAGES";
    $("#article-content .article-label-image").text(imageLabel);
  }

  $(".caption-image1").each(function () {
    // Split the caption at each <br> tag and wrap each line in a span
    var htmlContent = $(this).html();
    var lines = htmlContent.split("<br>");
    var wrappedLines = lines.map(function (line) {
      return '<span class="caption-line">' + line + "</span>";
    });
    var newHtml = wrappedLines.join("<br>");
    $(this).html(newHtml);
  });

  function setShowArticleRotationEffect() {
    const offset = 20;
    const showArticle = document.querySelector("#show-article");
    const h = showArticle.clientHeight;
    const theta = -Math.atan(offset / h);
    const a = Math.cos(theta);
    const b = Math.sin(theta);
    const c = -Math.sin(theta);
    const d = Math.cos(theta);
    const showArticleBefore = document.querySelector("#show-article-before");
    const transformValue =
      "matrix(" + a + "," + b + "," + c + "," + d + ",0,0)";
    showArticleBefore.style.transform = transformValue;
  }

  function openEvent(element, event) {
    event.stopPropagation();
    event.preventDefault();

    var url = $(element).find(".link a").attr("href");
    if (url) {
      window.open(url, "_blank").focus();
    }
  }

  function openModal(cardElement, event) {
    event.stopPropagation();
    $("#print-chooser").hide();
    $("#show-article").removeClass("print-opts-open");
    var pageTitle = $(cardElement).data("page") || null; // e.g. "090"
    window.currentEntryTitle = pageTitle;

    var isRelatedArticle = $(cardElement).hasClass("related-article");
    showArticleWrapper.css("display", "block");

    // Clear existing content in modal
    $("#article-title").empty();
    $("#article-content").empty();

    if (isRelatedArticle) {
      // Handle card elements (existing logic)
      var cardImages = [];
      for (var i = 1; i <= 5; i++) {
        var imageClass = ".related-article-image" + i;
        var captionClass = ".related-article-caption-image" + i;
        var imageElem = $(cardElement).find(imageClass + " img");

        if (imageElem.length) {
          var captionText = $(cardElement)
            .find(imageClass + " " + captionClass)
            .text();
          cardImages.push({
            link: $(cardElement)
              .find(imageClass + " a")
              .attr("href"),
            src: imageElem.attr("src"),
            alt: imageElem.attr("alt"),
            caption: captionText,
            captionClass: "related-article-caption-image" + i,
          });
        }
      }

      if (cardImages.length > 1) {
        setupImageToggle(cardImages);
      }
      // Handle related-article elements
      var entryNumber = $(cardElement)
        .find(".related-article-entry-number")
        .text();
      var peopleHtml = $(cardElement).find(".related-article-people").html();
      var title = $(cardElement).find(".related-article-title").text();
      var typeHtml = $(cardElement).find(".related-article-type").html();
      var externalPdfURL = $(cardElement)
        .find(".related-article-pdf a")
        .attr("href");
      var externalLinkURL = $(cardElement)
        .find(".related-article-link a")
        .attr("href");
      var entity = $(cardElement).find(".related-article-entity").text();
      var discipline = $(cardElement)
        .find(".related-article-discipline")
        .text();
      var subjectHtml = $(cardElement).find(".related-article-subject").html();
      var description = $(cardElement)
        .find(".related-article-description")
        .html();
      var reflection = $(cardElement)
        .find(".related-article-reflection")
        .html();
      var quote = $(cardElement).find(".related-article-quote").text();
      var modificationDate = $(cardElement)
        .find(".related-article-modification-date")
        .text();

      // Update modal content for related-article
      $("#article-title").html(
        '<p class="article-entry-number">' +
          entryNumber +
          '</p><p class="article-people">' +
          peopleHtml +
          "</p>"
      );
      var articleContentHtml = '<div class="article-title-link">';
      articleContentHtml += '<p class="article-title">' + title + "</p>";
      // Create a div that will wrap the links
      articleContentHtml += '<div class="link-pdf">';

      if (externalPdfURL) {
        articleContentHtml +=
          '<a href="' +
          externalPdfURL +
          '" target="_blank" class="pdf-link-icon">[PDF<span class="text-symbol">⤴</span>]</a>';
      }
      if (externalLinkURL) {
        articleContentHtml +=
          '<a href="' +
          externalLinkURL +
          '" target="_blank" class="external-link-icon">[WEB<span class="text-symbol">⤴</span>]</a>';
      }

      // Close the .link-pdf div
      articleContentHtml += "</div>";
      articleContentHtml += "</div>"; // Close the container div

      // Append type, entity, discipline, and subject details
      articleContentHtml +=
        '<p class="article-type">' +
        typeHtml +
        "</p>" +
        '<div class="article-metadata">' +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Entity</p>' +
        '<p class="article-metadata-value">' +
        entity +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Discipline</p>' +
        '<p class="article-metadata-value">' +
        discipline +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Subject(s)</p>' +
        '<p class="article-metadata-value">' +
        subjectHtml +
        "</p>" +
        "</div>" +
        "</div>";

      // Add images if any
      if (cardImages.length > 0) {
        var initialImage = cardImages[0]; // Use the first image initially
        var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
        articleContentHtml +=
          '<div class="article-images">' +
          getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
          "</div>";
      }
      // Add non-image content (description, reflection, etc.)
      articleContentHtml +=
        (description
          ? '<p class="article-label-description">Description</p>' +
            '<div class="article-description">' +
            formatParagraphs(description) +
            "</div>"
          : "") +
        (reflection
          ? '<p class="article-label-reflection">Reflection</p>' +
            '<div class="article-reflection">' +
            formatParagraphs(reflection) +
            "</div>"
          : "") +
        (quote
          ? '<p class="article-label-quote">Quote</p>' +
            '<p class="article-quote">' +
            quote +
            "</p>"
          : "") +
        '<p class="article-label-modification-date">Added on</p>' +
        '<div class="article-modification-date">' +
        modificationDate +
        "</div>";

      $("#article-content").html(articleContentHtml);
    } else {
      // Handle card elements (existing logic)
      var cardImages = [];
      for (var i = 1; i <= 5; i++) {
        var imageClass = ".image" + i;
        var captionClass = ".caption-image" + i;
        var imageElem = $(cardElement).find(imageClass + " img");

        if (imageElem.length) {
          var captionText = $(cardElement)
            .find(imageClass + " " + captionClass)
            .text();
          cardImages.push({
            link: $(cardElement)
              .find(imageClass + " a")
              .attr("href"),
            src: imageElem.attr("src"),
            alt: imageElem.attr("alt"),
            caption: captionText,
            captionClass: "caption-image" + i,
          });
        }
      }

      if (cardImages.length > 1) {
        setupImageToggle(cardImages);
      }
      var entryNumber = $(cardElement).find(".entry-number").text();
      var title = $(cardElement).find(".title").text();
      var peopleHtml = $(cardElement).find(".people").html();
      var typeHtml = $(cardElement).find(".type").html();
      var externalPdfURL = $(cardElement).find(".pdf a").attr("href");
      var externalLinkURL = $(cardElement).find(".link a").attr("href");
      var entity = $(cardElement).find(".entity").text();
      var discipline = $(cardElement).find(".discipline").text();
      var subjectHtml = $(cardElement).find(".subject").html();
      var description = $(cardElement).find(".description").html();
      var reflection = $(cardElement).find(".reflection").html();
      var quote = $(cardElement).find(".quote").text();
      var externalReferenceHtml = $(cardElement)
        .find(".external-reference")
        .html();
      var modificationDate = $(cardElement).find(".modification-date").text();
      var relatedArticlesHtml = $(cardElement).find(".related-articles").html();

      $("#article-title").html(
        '<p class="article-entry-number">' +
          entryNumber +
          '</p><p class="article-people">' +
          peopleHtml +
          "</p>"
      );

      var articleContentHtml = '<div class="article-title-link">';
      articleContentHtml += '<p class="article-title">' + title + "</p>";

      // Create a div that will wrap the links
      articleContentHtml += '<div class="link-pdf">';
      if (externalPdfURL) {
        articleContentHtml +=
          '<a href="' +
          externalPdfURL +
          '" target="_blank" class="pdf-link-icon">[PDF<span class="text-symbol">⤴</span>]</a>';
      }
      if (externalLinkURL) {
        articleContentHtml +=
          '<a href="' +
          externalLinkURL +
          '" target="_blank" class="external-link-icon">[WEB<span class="text-symbol">⤴</span>]</a>';
      }
      // Close the .link-pdf div
      articleContentHtml += "</div>";
      articleContentHtml += "</div>"; // Close the new div

      // Append type, entity, discipline, and subject details
      articleContentHtml +=
        '<p class="article-type">' +
        typeHtml +
        "</p>" +
        '<div class="article-metadata">' +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Entity</p>' +
        '<p class="article-metadata-value">' +
        entity +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Discipline</p>' +
        '<p class="article-metadata-value">' +
        discipline +
        "</p>" +
        "</div>" +
        '<div class="article-metadata-column">' +
        '<p class="article-metadata-label">Subject(s)</p>' +
        '<p class="article-metadata-value">' +
        subjectHtml +
        "</p>" +
        "</div>" +
        "</div>";
      // Add images if any
      if (cardImages.length > 0) {
        var initialImage = cardImages[0]; // Use the first image initially
        var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
        articleContentHtml +=
          '<div class="article-images">' +
          getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
          "</div>";
      }
      // Add non-image content (description, reflection, etc.)
      articleContentHtml +=
        (description
          ? '<p class="article-label-description">Description</p>' +
            '<div class="article-description">' +
            formatParagraphs(description) +
            "</div>"
          : "") +
        (reflection
          ? '<p class="article-label-reflection">Reflection</p>' +
            '<div class="article-reflection">' +
            formatParagraphs(reflection) +
            "</div>"
          : "") +
        (externalReferenceHtml
          ? '<p class="article-label-external-reference">References</p>' +
            '<p class="article-external-reference">' +
            externalReferenceHtml +
            "</p>"
          : "") +
        (quote
          ? '<p class="article-label-quote">Quote</p>' +
            '<p class="article-quote">' +
            quote +
            "</p>"
          : "") +
        '<p class="article-label-modification-date">Added on</p>' +
        '<div class="article-modification-date">' +
        modificationDate +
        "</div>";

      $("#article-content").html(articleContentHtml);
      $("#related-articles").html(relatedArticlesHtml);

      if (relatedArticlesHtml && relatedArticlesHtml.trim().length > 0) {
        $("#related-articles")
          .html(
            '<div class="related-articles-label">Related Articles</div><div class="related-articles-container">' +
              relatedArticlesHtml +
              "</div>"
          )
          .show();
      }
    }

    // Check which view is active and set the width accordingly
    if ($(".home-chronicle-list").is(":visible")) {
      $(".home-list-view").each(function () {
        var currentWidth = $(this).width(); // Get the current width
        $(this).data("originalWidth", currentWidth); // Store the original width
        $(this).css("width", "calc(60% - 2px)");
      });

      // Modify the .type elements within .home-chronicle-list
      $(".home-chronicle-list .type").each(function () {
        var currentLeft = $(this).css("left"); // Get the current left value
        $(this).data("originalLeft", currentLeft); // Store the original left value
        $(this).css("left", "85%");
      });
    } else if ($(".home-chronicle-block").is(":visible")) {
      $(".home-chronicle-block div.list-container").each(function () {
        var currentWidth = $(this).width(); // Get the current width
        $(this).css("width", "calc(60% - 0px)"); // Set the new width as 30% of the current width
      });
      $(".home-chronicle-block div.list-container div.card").each(function () {
        var currentWidth = $(this).width(); // Get the current width
        $(this).css("width", "calc(33.333% - 0px)"); // Set the new width as 30% of the current width
      });
    }

    // Apply the fade-out effect to both #list and #list-list elements
    $(".list-container").addClass("fade-out");
  }

  // closeModal function
  function closeModal() {
    $("#print-chooser").hide();
    $("#show-article").removeClass("print-opts-open");
    if ($(".home-chronicle-list").is(":visible")) {
      $(".home-list-view").css("width", "100%");
      $(".home-chronicle-list div.list-container div.card div.type").css(
        "left",
        "90%"
      );
    } else if ($(".home-chronicle-block").is(":visible")) {
      updateWidthBlockView();
    }
    showArticleWrapper.hide();
  }

  $(".card").on("click", function (event) {
    // Check if the click event is originating from a link within .people or .type, or any other specific area
    if ($(event.target).closest(".people a, .type a").length) {
      // The click is inside a link; let the default behavior proceed without opening the modal
      return;
    }

    // Prevent further event handling if the card has the 'event' class
    if ($(this).hasClass("event")) {
      event.stopImmediatePropagation();
      openEvent(this, event);
      $(".list-container").removeClass("fade-out");
      closeModal();
    } else {
      // Handle cards without the 'event' class
      openModal(this, event);
      setShowArticleRotationEffect();
    }
  });

  $("#show-article-wrapper").on("click", ".related-article", function (event) {
    openModal(this, event); // Call openModal when a related-article is clicked
    setShowArticleRotationEffect();
  });

  // HERE SHOULD BE THE NEW CODE!!!!
  /* ---------- Softwear PRINT (scoped, ES5-safe) ---------- */

  /* helpers */
  function swPrintPreloadFont() {
    var link = document.createElement("link");
    link.rel = "preload";
    link.as = "font";
    link.type = "font/woff2";
    link.href = "/fonts/HALColant-TextRegular.woff2?v=20250820";
    link.crossOrigin = "anonymous";
    document.head.appendChild(link);
  }

  function swPrintCacheBust(url) {
    return url + (url.indexOf("?") > -1 ? "&" : "?") + "_=" + Date.now();
  }

  function swEnsurePrintChooser() {
    var $chooser = jQuery("#print-chooser");
    if ($chooser.length) return $chooser;
    $chooser = jQuery(
      '<div id="print-chooser" class="print-chooser" style="display:none;">' +
        '<a href="#" id="print-with-border" class="print-choice">border</a> ' +
        '<a href="#" id="print-no-border" class="print-choice">no border</a>' +
        "</div>"
    );
    jQuery("#print-button").after($chooser);
    return $chooser;
  }

  function swHidePrintUI() {
    jQuery("#print-chooser").hide();
    jQuery("#show-article").removeClass("print-opts-open");
  }

  /* core: build iframe and print */
  function swBuildIframeAndPrint(printHtml, borderPref, $btn) {
    // iframe
    var iframe = document.createElement("iframe");
    iframe.style.position = "fixed";
    iframe.style.right = "0";
    iframe.style.bottom = "0";
    iframe.style.width = "0";
    iframe.style.height = "0";
    iframe.style.border = "0";
    document.body.appendChild(iframe);

    var doc = iframe.contentDocument || iframe.contentWindow.document;
    doc.open();
    doc.write(
      '<!doctype html><html><head><meta charset="utf-8"><title>Print</title></head><body></body></html>'
    );
    doc.close();

    // make relative URLs resolve
    var base = doc.createElement("base");
    base.href = location.origin + "/";
    doc.head.appendChild(base);

    // print.css
    var linkCss = doc.createElement("link");
    linkCss.rel = "stylesheet";
    linkCss.href = swPrintCacheBust(
      "/index.php?title=MediaWiki:Print.css&action=raw&ctype=text/css"
    );

    var cssLoaded = new Promise(function (resolve) {
      linkCss.onload = function () {
        resolve();
      };
      linkCss.onerror = function () {
        resolve();
      };
    });

    // font preload (inside iframe)
    var linkFont = doc.createElement("link");
    linkFont.rel = "preload";
    linkFont.as = "font";
    linkFont.type = "font/woff2";
    linkFont.href = "/fonts/HALColant-TextRegular.woff2?v=20250820";
    linkFont.crossOrigin = "anonymous";

    doc.head.appendChild(linkFont);
    doc.head.appendChild(linkCss);

    // inject HTML
    doc.body.innerHTML = printHtml;

    // border preference -> <html> class
    (function () {
      var htmlEl = doc.documentElement;
      if (borderPref === "without") {
        if (htmlEl.classList) htmlEl.classList.add("print-no-border");
        else if (
          (" " + htmlEl.className + " ").indexOf(" print-no-border ") === -1
        ) {
          htmlEl.className += " print-no-border";
        }
      } else {
        if (htmlEl.classList) htmlEl.classList.remove("print-no-border");
        else
          htmlEl.className = htmlEl.className.replace(
            /\bprint-no-border\b/g,
            ""
          );
      }
    })();

    // clean empty paragraphs
    (function () {
      var ps = doc.querySelectorAll("#article-content p");
      Array.prototype.forEach.call(ps, function (p) {
        var txt = (p.textContent || "").replace(/\u00a0/g, " ").trim();
        var onlyBr =
          p.children.length === 1 &&
          p.firstElementChild &&
          p.firstElementChild.tagName === "BR";
        if (
          (!txt && !p.querySelector("img, a, strong, em, span:not(:empty)")) ||
          onlyBr
        ) {
          if (p.parentNode) p.parentNode.removeChild(p);
        }
      });
      var root = doc.getElementById("article-content");
      if (root) {
        Array.prototype.slice.call(root.childNodes).forEach(function (n) {
          if (n.nodeType === 3 && !n.textContent.replace(/\s+/g, "")) {
            root.removeChild(n);
          }
        });
      }
    })();

    // small inline tweaks
    (function () {
      var css =
        "@media print{" +
        "  .article-description p,.article-reflection p,.article-external-reference p,.article-quote p{margin:0 0 1.2mm!important;}" +
        "  .article-description p:last-child,.article-reflection p:last-child,.article-external-reference p:last-child,.article-quote p:last-child{margin-bottom:0!important;}" +
        "  .article-entry-number,.link-pdf,.article-type,.article-metadata,.article-images,.article-description,.article-reflection,.article-external-reference,.article-quote,.article-mod-line{padding-bottom:1mm!important;}" +
        '  [class^\\"article-label-\\"]{margin-top:0!important;}' +
        '  .article-entry-number + [class^\\"article-label-\\"],' +
        '  .link-pdf + [class^\\"article-label-\\"],' +
        '  .article-type + [class^\\"article-label-\\"],' +
        '  .article-metadata + [class^\\"article-label-\\"],' +
        '  .article-images + [class^\\"article-label-\\"],' +
        '  .article-description + [class^\\"article-label-\\"],' +
        '  .article-reflection + [class^\\"article-label-\\"],' +
        '  .article-external-reference + [class^\\"article-label-\\"],' +
        '  .article-quote + [class^\\"article-label-\\"],' +
        '  .article-mod-line + [class^\\"article-label-\\"]{margin-top:0.9mm!important;}' +
        "  .article-label-description + .article-description," +
        "  .article-label-reflection + .article-reflection," +
        "  .article-label-external-reference + .article-external-reference," +
        "  .article-label-quote + .article-quote," +
        "  .article-label-modification-date + .article-modification-date{margin-top:0!important;}" +
        "  .article-title-link{margin:0!important;padding:0!important;}" +
        "  .article-title-link > *{margin:0!important;}" +
        "  .link-pdf{margin-top:0!important;}" +
        "  #article-content > :last-child{padding-bottom:0!important;}" +
        "  #article-content > :last-child::after{content:none!important;}" +
        "}";
      var style = doc.createElement("style");
      style.type = "text/css";
      style.appendChild(doc.createTextNode(css));
      doc.head.appendChild(style);
    })();

    // link tweaks
    (function () {
      var styleFix = doc.createElement("style");
      styleFix.textContent =
        "@media print {.article-external-reference a,.link-pdf a{white-space:nowrap!important;word-break:normal!important;overflow-wrap:normal!important;text-decoration:underline}.article-external-reference{overflow-wrap:anywhere;word-break:break-word}a[href]{position:relative}}";
      doc.head.appendChild(styleFix);
      var refs = doc.querySelectorAll(".article-external-reference a[href]");
      Array.prototype.forEach.call(refs, function (a) {
        var txt = (a.textContent || "").trim();
        var href = a.getAttribute("href") || "";
        var looksLongUrl = /^https?:\/\//i.test(txt) && txt.length > 60;
        if (looksLongUrl) {
          try {
            var u = new URL(href, doc.baseURI);
            var label =
              u.hostname + (u.pathname.replace(/\/$/, "") ? u.pathname : "");
            if (label.length > 40) label = label.slice(0, 37) + "…";
            a.textContent = label;
          } catch (e) {
            a.textContent = "Link";
          }
        }
        a.style.whiteSpace = "nowrap";
        a.style.wordBreak = "normal";
        a.style.overflowWrap = "normal";
      });
    })();

    // waits
    function waitImages() {
      var imgs = [].slice.call(doc.images || []);
      if (!imgs.length) return Promise.resolve();
      return Promise.all(
        imgs.map(function (img) {
          if (img.decode) {
            try {
              return img.decode().catch(function () {});
            } catch (e) {}
          }
          return new Promise(function (res) {
            if (img.complete) return res();
            img.onload = img.onerror = function () {
              res();
            };
          });
        })
      );
    }
    function waitFonts(timeoutMs) {
      if (!doc.fonts || !doc.fonts.ready) return Promise.resolve();
      var ready = doc.fonts.ready;
      var t = new Promise(function (res) {
        setTimeout(res, timeoutMs || 1200);
      });
      return Promise.race([ready, t]);
    }
    function waitSpecificFont(timeoutMs) {
      if (!doc.fonts || !doc.fonts.load) return Promise.resolve();
      var p = Promise.all([
        doc.fonts.load('400 16px "HALColant-TextRegular"'),
        doc.fonts.load('normal 16px "HALColant-TextRegular"'),
      ]);
      var t = new Promise(function (res) {
        setTimeout(res, timeoutMs || 1200);
      });
      return Promise.race([p, t]);
    }
    function nextFrame() {
      return new Promise(function (res) {
        (iframe.contentWindow.requestAnimationFrame || setTimeout)(res, 0);
      });
    }

    Promise.all([
      cssLoaded,
      waitImages(),
      waitFonts(1200),
      waitSpecificFont(1200),
      nextFrame(),
    ])
      .then(function () {
        // filename via document.title
        var entryNum = "";
        var numEl = doc.querySelector(".article-entry-number");
        if (numEl) {
          var m = (numEl.textContent || "").match(/\d+/);
          entryNum = m ? m[0] : "";
        }
        var desiredTitle =
          (entryNum ? entryNum + "." : "") + "softwear.directory";
        var oldIframeTitle = doc.title;
        var oldParentTitle = document.title;

        iframe.contentWindow.onafterprint = function () {
          try {
            doc.title = oldIframeTitle;
            document.title = oldParentTitle;
          } catch (e) {}
          setTimeout(function () {
            if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
          }, 100);
          if ($btn && $btn.length) $btn.data("busy", false);
        };

        doc.title = desiredTitle;
        document.title = desiredTitle;

        iframe.contentWindow.focus();
        iframe.contentWindow.print();

        // safety cleanup
        setTimeout(function () {
          try {
            doc.title = oldIframeTitle;
            document.title = oldParentTitle;
          } catch (e) {}
          if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
          if ($btn && $btn.length) $btn.data("busy", false);
        }, 1000);
      })
      .catch(function () {
        if ($btn && $btn.length) $btn.data("busy", false);
      });
  }

  /* decide source & kick print */
  function swHandlePrintChoice(id, $btn) {
    if ($btn && $btn.data("busy")) return;
    if ($btn && $btn.length) $btn.data("busy", true);

    var borderPref = id === "print-no-border" ? "without" : "with";
    swPrintPreloadFont();

    // prefer local .print-only (Entry page)
    var localPrintOnly = jQuery(".print-only").first();
    if (localPrintOnly.length) {
      swHidePrintUI();
      swBuildIframeAndPrint(localPrintOnly.prop("outerHTML"), borderPref, $btn);
      return;
    }

    // otherwise fetch by title (modal/home list flow)
    var title =
      window.currentEntryTitle ||
      (window.mw && mw.config && mw.config.get && mw.config.get("wgPageName"));
    if (!title) {
      window.print();
      if ($btn && $btn.length) $btn.data("busy", false);
      return;
    }

    var pageUrl =
      window.mw && mw.util && mw.util.getUrl
        ? mw.util.getUrl(title)
        : "/wiki/" + String(title);
    jQuery
      .get(swPrintCacheBust(pageUrl))
      .done(function (html) {
        var $tmp = jQuery("<div>").html(html);
        var $print = $tmp.find(".print-only").first();
        if (!$print.length) {
          window.print();
          if ($btn && $btn.length) $btn.data("busy", false);
          return;
        }
        swHidePrintUI();
        swBuildIframeAndPrint($print.prop("outerHTML"), borderPref, $btn);
      })
      .fail(function () {
        window.print();
        jQuery("#print-button").data("busy", false);
      });
  }

  /* wiring (namespaced) */
  jQuery(document).off("click.swprint");
  jQuery(document).on(
    "click.swprint",
    "#print-button, #print-chooser, #print-options",
    function (e) {
      // click on the main [print]
      if (jQuery(e.target).closest("#print-button").length) {
        e.preventDefault();
        var $chooser = swEnsurePrintChooser();
        $chooser.toggle();
        jQuery("#show-article").toggleClass(
          "print-opts-open",
          $chooser.is(":visible")
        );
        return;
      }
      // click on a choice link
      var $choice = jQuery(e.target).closest(
        "a#print-with-border, a#print-no-border"
      );
      if (!$choice.length) return;
      e.preventDefault();
      swHandlePrintChoice($choice.attr("id"), $choice);
    }
  );

  // --- extra safety bindings for Entry page / widgets ---

  // 1) Directly bind the anchors (works even if container delegation misses)
  jQuery(document).on(
    "click.swprintChoice",
    "a#print-with-border, a#print-no-border, #print-with-border, #print-no-border",
    function (e) {
      console.log("[print] direct anchor handler fired:", this.id);
      e.preventDefault();
      swHandlePrintChoice(this.id, jQuery(this));
    }
  );

  // 2) If using the Button widget (<a id=...><button>...</button></a>),
  //    capture clicks on the <button> and route via its parent <a>.
  jQuery(document).on(
    "click.swprintChoiceBtn",
    "#print-options button",
    function (e) {
      var $a = jQuery(this).closest("a[id]");
      if (!$a.length) return;
      console.log(
        "[print] widget button handler fired; parent anchor id:",
        $a.attr("id")
      );
      e.preventDefault();
      swHandlePrintChoice($a.attr("id"), $a);
    }
  );

  // also hide choices on ESC; your close-button handler already hides them
  jQuery(document).on("keydown.swprint", function (e) {
    if (e && e.keyCode === 27) swHidePrintUI();
  });

  /* ---------- /Softwear PRINT ---------- */

  // Close modal with Close button
  $("#close-button").on("click", function () {
    $("#print-chooser").hide();
    $("#show-article").removeClass("print-opts-open");

    $(".list-container").removeClass("fade-out");
    closeModal();
  });

  // Close modal and remove fade out also when clicking outside of card
  $(document).on("mousedown", function (event) {
    var isOutsideWrapper =
      !showArticleWrapper.is(event.target) &&
      showArticleWrapper.has(event.target).length === 0;
    var isOnCard = $(event.target).closest(".card, .list-card").length > 0;

    if (!areFiltersActive) {
      if (isOutsideWrapper && !isOnCard) {
        $(".list-container").removeClass("fade-out");
        showArticleWrapper.css("display", "none");
        closeModal(); // Use closeModal() for cleanup
      }
    }
  });

  // Hover effect for scrolling
  $("#show-article-wrapper").hover(
    function () {
      // On hover, enable scrolling on #show-article-wrapper
      $(this).css("overflow-y", "auto");
      $(this).css("overflow-x", "hidden");
    },
    function () {
      // On hover out, disable scrolling on #show-article-wrapper
      $(this).css("overflow-y", "hidden");
      $(this).css("overflow-x", "hidden");
    }
  );

  // Format community card, when in the Community Entries page
  if ($(".community-card").length) {
    formatCommunityCardDescriptions();
  }

  function formatCommunityCardDescriptions() {
    $(".community-card").each(function () {
      // Format paragraphs in community-description
      var descriptionContainer = $(this).find(".community-description");
      var rawDescription = descriptionContainer.text();
      var formattedDescription = formatParagraphs(rawDescription);
      descriptionContainer.html(formattedDescription);

      // Remove empty elements in the entire card
      $(this)
        .find("*")
        .each(function () {
          if ($(this).is(":empty") || $(this).html().trim() === "<br>") {
            $(this).remove();
          }
        });
    });
  }

  if ($("#show-article-wrapper-entry").length) {
    // Your existing formatParagraphs function
    function formatParagraphs(text) {
      var paragraphs = text.split("\n").filter(function (p) {
        return p.trim() !== "";
      });
      return paragraphs
        .map(function (p) {
          return "<p>" + p.trim() + "</p>";
        })
        .join("");
    }

    // Check if ".article-description" exists and format its text
    if ($(".article-description").length) {
      var descriptionText = $(".article-description").text();
      var formattedDescription = formatParagraphs(descriptionText);
      $(".article-description").html(formattedDescription); // Set the formatted text
    }

    // Check if ".article-reflection" exists and format its text
    if ($(".article-reflection").length) {
      var reflectionText = $(".article-reflection").text();
      var formattedReflection = formatParagraphs(reflectionText);
      $(".article-reflection").html(formattedReflection); // Set the formatted text
    }
  }

  // SEARCH  ---------------------   SECTION //
  // Check if div with class "mw-search-results-info" exists
  if ($(".mw-search-results-info").length) {
    // Select the child <p> element and check its content
    var $paragraph = $(".mw-search-results-info > p");
    var currentText = $paragraph.text().trim();

    // Check if the current text is not "There were no results matching the query."
    if (currentText !== "There were no results matching the query.") {
      // Overwrite the content with "Search results"
      $paragraph.text("Pages related to your Search");
    }
  }

  // Object to store encountered titles
  var encounteredTitles = {};

  // Iterate over each search result
  $(".mw-search-result-heading").each(function () {
    // Get the title of the current search result
    var title = $(this).find("a").attr("title");

    // Check if the title has already been encountered
    if (encounteredTitles[title]) {
      // Hide the duplicate search result
      $(this).hide();
    } else {
      // Mark the title as encountered
      encounteredTitles[title] = true;
    }
  });

  // Remove unwanted white spaces between lines
  $(".mw-search-results-container")
    .contents()
    .filter(function () {
      return this.nodeType === 3; // Filter text nodes
    })
    .remove();

  // Edits regarding Search Results
  // Define the new form HTML as a string
  var newFormHtml =
    '<form action="/index.php" id="searchform">' +
    '<div id="simpleSearchSpecial" class="right-inner-addon">' +
    "<span>[ Search ]</span>" +
    '<input class="form-control" name="search" placeholder="" title="Search [alt-shift-f]" accesskey="f" id="searchInput" tabindex="1" autocomplete="off" type="search">' +
    '<span class="closing-bracket">]</span>' +
    '<input value="Special:Search" name="title" type="hidden">' +
    "</div>" +
    "</form>";

  // Replace the div with id="searchText" with the new form
  $("#searchText").replaceWith(newFormHtml);

  // Target the button based on its complex class structure
  $(".oo-ui-actionFieldLayout-button .oo-ui-buttonInputWidget").remove();

  // Check if #submit button exists and add event listener if it does
  var submitButton = document.querySelector("#submit");

  if (submitButton) {
    // Add click event listener
    submitButton.addEventListener("click", function (event) {
      event.preventDefault(); // Prevent the default link behavior

      var email = "submit@softwear.directory";
      var subject = "new entry to the softwear directory";
      var body =
        "☺ the following content could be interesting for the directory:\n\n" +
        "[ author / creator ]\n\n" +
        "---\n\n" +
        "[ title ]\n\n" +
        "---\n\n" +
        "[ why should it be included? ]\n\n" +
        "---\n\n" +
        "[ link or pdf ]\n\n" +
        "---\n\n" +
        "[ your name / contact / social ]\n\n" +
        "---";

      var mailtoLink =
        "mailto:" +
        encodeURIComponent(email) +
        "?subject=" +
        encodeURIComponent(subject) +
        "&body=" +
        encodeURIComponent(body).replace(/%20/g, " ");

      window.location.href = mailtoLink;
    });
  }

  // Tooltip for "wander elsewhere..." on .card.event
  var tooltip = $(
    '<div class="tooltip-popup">wander elsewhere...</div>'
  ).appendTo("body");

  $(".card.event").on("mouseenter", function () {
    tooltip.css("opacity", 1);
  });

  $(".card.event").on("mousemove", function (e) {
    var offsetX = 10; // right of cursor
    var offsetY = -30; // above cursor
    tooltip.css({
      left: e.clientX + offsetX + "px",
      top: e.clientY + offsetY + "px",
    });
  });

  $(".card.event").on("mouseleave", function () {
    tooltip.css("opacity", 0);
  });

  mw.loader.using("mediawiki.api", function () {
    // Only run on form edit page
    if (mw.config.get("wgCanonicalSpecialPageName") === "FormEdit") {
      new mw.Api()
        .post({
          action: "purge",
          titles: "Main",
        })
        .fail(function (err) {
          // Optional: leave a minimal fallback error log
          console.warn("Main page purge failed", err);
        });
    }
  });
});