MediaWiki:Common.js: Difference between revisions

From softwear.directory
Jump to navigation Jump to search
m (1 revision imported)
No edit summary
 
(173 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 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
     });
     });


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


         var i = cards.length, j, temp;
    $.each(cards, function (index, item) {
         while (--i > 0) {
      $(selector).parent().append(item);
            j = Math.floor(Math.random() * (i + 1));
    });
            temp = cards[i];
  }
            cards[i] = cards[j];
 
            cards[j] = temp;
  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);
         }
         }


         $.each(cards, function(index, item) {
        // LIST VIEW
             $(selector).parent().append(item);
      } 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");
     }
     }


     function sortAlphabetically(selector) {
     updateLastVisibleCard();
        var cards = $(selector).get();
    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


        cards.sort(function(a, b) {
    $("#values-" + filterType).toggle();
            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) {
    if ($("#values-" + filterType).is(":visible")) {
            $(selector).parent().append(item);
      $(this).addClass("active-filter");
        });
    } else {
      $(this).removeClass("active-filter");
     }
     }


     function updateViews() {
     // Pass the determined card selector to the function
        // Handle cards in the list view
    updateLastVisibleCard(cardSelector);
        $('.home-chronicle-list div.list-container div.card:not(.event)').each(function() {
    updateWidthBlockView(cardSelector);
            if (!$(this).closest('.home-chronicle-block').length) {
    processEventCards(cardSelector);
                var title = $(this).find('.title').detach();
    updateViews(cardSelector);
                var images = $(this).find('.images').detach();
  });
   
 
                // Remove existing .title-images if it exists
  function filterCards() {
                $(this).find('.title-images').remove();
    var displayCountsHtml = "";
   
    var cardSelector = $(".card").length > 0 ? ".card" : ".community-card"; // Determine which card type is present
                var titleImagesContainer = $('<div class="title-images"></div>').append(images, title);
 
                $(this).find('.people').after(titleImagesContainer);
    $(".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++;
             }
             }
          });
         });
         });
   
 
         // Handle cards in the block view
         displayCountsHtml +=
        $('.home-chronicle-block div.list-container div.card:not(.event)').each(function() {
          "<span>[" + count + "] " + filterValue + "</span> ";
            // 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();
    if (displayCountsHtml) {
                var images = titleImagesContainer.find('.images').detach();
      $(".count-filtered-cards").html(displayCountsHtml).show();
                titleImagesContainer.remove();
    } else {
      
      $(".count-filtered-cards").hide();
                $(this).find('.people').after(title);
    }
                $(this).find('.type').after(images);
 
            } else {
    // Apply filtering and pass the determined card selector to the function
                // If .title-images doesn't exist, ensure .images is placed correctly
    applyFiltering(cardSelector);
                var images = $(this).find('.images').detach();
 
                $(this).find('.type').after(images);
    updateLastVisibleCard(cardSelector);
             }
    updateWidthBlockView(cardSelector);
        });
    processEventCards(cardSelector);
   
    updateViews(cardSelector);
        // Additional functionality for checking consecutive .card.event
    updatePrintSelectionUI();
        $('.home-chronicle-block div.list-container .card.event, .home-chronicle-list div.list-container .card.event').each(function() {
    hidePrintSelectionOptions();
             checkConsecutiveEvents($(this));
 
    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();
    $("#filters .values button").removeClass("active");
    $(".open-filter").removeClass("active-filter");
    $(".count-filtered-cards").text("").hide();
    filterCards();
    hidePrintSelectionOptions();
  });
  $("#filters .values button").click(function () {
    $(this).toggleClass("active");
    filterCards();
  });
  // 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
     }
     }
   
  });
    function checkConsecutiveEvents(element) {
 
        if (element.next().hasClass('card') && element.next().hasClass('event')) {
  // MODAL ARTICLE  ---------------------  SECTION //
            console.log("multiple consecutive card events");
  // Format paragraphs
            $('.home-chronicle-list div.list-container div.card.event').removeClass('alone-card-event');
  function formatParagraphs(text) {
        } else {
    var paragraphs = text.split("\n").filter(function (p) {
            console.log("alone card events");
      return p.trim() !== "";
            $('.home-chronicle-list div.list-container div.card.event').addClass('alone-card-event');
    });
         }
    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 updateCardEventBorders() {
     // Attach click handlers only if navigation is enabled
        // Reset previously set classes for both block and list views
     if (enableNavigation) {
        $('.home-chronicle-block div.list-container div.card.event, .home-chronicle-list div.list-container div.card.event').removeClass('first-in-series next-in-series');
      $("#article-content").on("click", ".next-arrow", function () {
   
        showImage((currentIndex + 1) % images.length);
        // Update borders for block view cards
      });
        updateBordersForView('.home-chronicle-block div.list-container');
 
   
      $("#article-content").on("click", ".prev-arrow", function () {
         // Update borders for list view cards
         showImage((currentIndex - 1 + images.length) % images.length);
        updateBordersForView('.home-chronicle-list div.list-container');
      });
     }
     }
   
    function updateBordersForView(selector) {
        $(selector + ' div.card.event').each(function() {
            var $current = $(this);
   
            // Find the next visible .card.event element, skipping hidden ones
            var $nextVisibleEvent = $current.nextAll('.card.event').not(':hidden').first();
   
            // Check if there is a visible .card.event following the current one
            if ($nextVisibleEvent.length) {
                // Apply 'first-in-series' if the current card is not preceded by a visible .card.event
                if (!$current.prevAll('.card.event').not(':hidden').first().length) {
                    $current.addClass('first-in-series');
                }
   
                // The next visible card event gets 'next-in-series'
                $nextVisibleEvent.addClass('next-in-series');
            }
        });
    }   


     function processEventCards() {
     // Display the first image
        $('.card.event').each(function() {
    showImage(currentIndex);
            var existingContainer = $(this).find('.container-people-date');
  }
      
 
            // If the container doesn't exist, create and append it
  function getImageHtml(image, currentIndex, totalImages, enableNavigation) {
            if (existingContainer.length === 0) {
    var imageLabel = currentIndex + 1 + "/" + totalImages + " IMAGES";
                existingContainer = $('<div class="container-people-date"></div>');
 
                $(this).append(existingContainer); // Temporarily append to ensure it's in the DOM
    // Render navigation arrows based on the enableNavigation flag
            }
    var navigationHtml = enableNavigation
      
      ? '<div class="prev-arrow"><</div><div class="next-arrow">></div>'
            // Ensure the .people and .date elements are inside the container
      : "";
            var people = $(this).find('.people').detach();
 
            var date = $(this).find('.date').detach();
     return (
            existingContainer.append(people).append(date);
      '<div class="image-navigation">' +
   
      '<p class="article-label-image">' +
            // Decide where to place the container
      imageLabel +
            if ($(this).closest('.home-chronicle-block').length) {
      "</p>" +
                // Check if it's already correctly placed, if not, move it
      '<div class="image-container">' +
                if (!existingContainer.is($(this).find('.title').next())) {
      '<div class="arrows-and-image">' +
                    $(this).find('.title').after(existingContainer);
      navigationHtml +
                }
      '<img src="' +
            } else if ($(this).closest('.home-chronicle-list').length) {
      image.src +
                // Check if it's already correctly placed, if not, move it
      '" alt="' +
                if (!existingContainer.is($(this).find('.title').prev())) {
      image.alt +
                    $(this).find('.title').before(existingContainer);
      '">' +
                }
      "</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 ($('#home').length > 0) {
        if (imageElem.length) {
        console.log("The #home element exists on this page.");
          var captionText = $(cardElement)
        // This code will only run only on the homepage.
            .find(imageClass + " " + captionClass)
        // Show the block view container once everything is set up
            .text();
        $('.home-block-view').show();
          cardImages.push({
        $('.home-chronicle-block-button, .home-block-view-button').addClass('active-view-button');
            link: $(cardElement)
              .find(imageClass + " a")
              .attr("href"),
            src: imageElem.attr("src"),
            alt: imageElem.attr("alt"),
            caption: captionText,
            captionClass: "related-article-caption-image" + i,
          });
        }
      }


         // Initialization and Default Settings
      if (cardImages.length > 1) {
         // Initially hide list view sorting buttons and set the default sorted view for block
         setupImageToggle(cardImages);
         $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').hide();
      }
         sortChronologically(); // Sort the block view chronologically by default
      // Handle related-article elements
          
      var entryNumber = $(cardElement)
         updateLastVisibleCard();
         .find(".related-article-entry-number")
         updateWidthBlockView();
         .text();
        processEventCards();
      var peopleHtml = $(cardElement).find(".related-article-people").html();
         updateViews();
      var title = $(cardElement).find(".related-article-title").text();
         updateCardEventBorders();
      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();


        $('.home-list-view-button').click(function() {
      // Update modal content for related-article
            console.log("List view button clicked.");
      $("#article-title").html(
            $(".home-list-sorting-buttons").css('display', 'flex');
        '<p class="article-entry-number">' +
            // Switching view classes
          entryNumber +
            $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
          '</p><p class="article-people">' +
            // Additional class switch
          peopleHtml +
            $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
          "</p>"
            // Toggling visibility of buttons
      );
            $('.home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button').hide();
      var articleContentHtml = '<div class="article-title-link">';
            $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').show();
      articleContentHtml += '<p class="article-title">' + title + "</p>";
            updateLastVisibleCard();
      // Create a div that will wrap the links
            updateWidthBlockView();
      articleContentHtml += '<div class="link-pdf">';
            processEventCards();
            updateViews();
            updateCardEventBorders();
       
            // 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();
            updateCardEventBorders();
            $('.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 (externalPdfURL) {
            if ($('.home-chronicle-list-button').hasClass('active-view-button')) {
        articleContentHtml +=
                $('.home-chronicle-list-button').removeClass('active-view-button');
          '<a href="' +
                $('.home-chronicle-block-button').addClass('active-view-button');
          externalPdfURL +
            } else if ($('.home-random-list-button').hasClass('active-view-button')) {
          '" target="_blank" class="pdf-link-icon">[PDF<span class="text-symbol">⤴</span>]</a>';
                $('.home-random-list-button').removeClass('active-view-button');
      }
                $('.home-random-block-button').addClass('active-view-button');
      if (externalLinkURL) {
            } else if ($('.home-alphabetical-list-button').hasClass('active-view-button')) {
        articleContentHtml +=
                $('.home-alphabetical-list-button').removeClass('active-view-button');
          '<a href="' +
                $('.home-alphabetical-block-button').addClass('active-view-button');
          externalLinkURL +
            }
          '" target="_blank" class="external-link-icon">[WEB<span class="text-symbol">⤴</span>]</a>';
        });
      }
       
        // BLOCK VIEW SORTING BUTTONS
        $('.home-chronicle-block-button').click(function() {
            sortChronologically();


            updateLastVisibleCard();
      // Close the .link-pdf div
            updateWidthBlockView();
      articleContentHtml += "</div>";
            processEventCards();
      articleContentHtml += "</div>"; // Close the container div
            updateViews();
            updateCardEventBorders();
            $('.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();
      // Append type, entity, discipline, and subject details
            updateWidthBlockView();
      articleContentHtml +=
            processEventCards();
        '<p class="article-type">' +
            updateViews();
        typeHtml +
            updateCardEventBorders();
        "</p>" +
            $('.home-random-block-button').addClass('active-view-button');
        '<div class="article-metadata">' +
            $('.home-chronicle-block-button').removeClass('active-view-button');
        '<div class="article-metadata-column">' +
            $('.home-alphabetical-block-button').removeClass('active-view-button');
        '<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>";


         $('.home-alphabetical-block-button').click(function() {
      // Add images if any
             sortAlphabetically('.list-container .card');
      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>";


            updateLastVisibleCard();
      $("#article-content").html(articleContentHtml);
            updateWidthBlockView();
    } else {
            processEventCards();
      // Handle card elements (existing logic)
            updateViews();
      var cardImages = [];
            updateCardEventBorders();
      for (var i = 1; i <= 5; i++) {
            $('.home-alphabetical-block-button').addClass('active-view-button');
        var imageClass = ".image" + i;
            $('.home-chronicle-block-button').removeClass('active-view-button');
        var captionClass = ".caption-image" + i;
            $('.home-random-block-button').removeClass('active-view-button');
        var imageElem = $(cardElement).find(imageClass + " img");
        });


         // LIST VIEW SORTING BUTTONS
         if (imageElem.length) {
        $('.home-chronicle-list-button').click(function() {
          var captionText = $(cardElement)
             sortChronologically();
            .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,
          });
        }
      }


            updateLastVisibleCard();
      if (cardImages.length > 1) {
            updateWidthBlockView();
        setupImageToggle(cardImages);
            processEventCards();
      }
            updateViews();
      var entryNumber = $(cardElement).find(".entry-number").text();
            updateCardEventBorders();
      var title = $(cardElement).find(".title").text();
            $('.home-chronicle-list-button').addClass('active-view-button');
      var peopleHtml = $(cardElement).find(".people").html();
            $('.home-random-list-button').removeClass('active-view-button');
      var typeHtml = $(cardElement).find(".type").html();
            $('.home-alphabetical-list-button').removeClass('active-view-button');
      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();


        $('.home-random-list-button').click(function() {
      $("#article-title").html(
            randomizeCards('.list-container .card');
        '<p class="article-entry-number">' +
          entryNumber +
          '</p><p class="article-people">' +
          peopleHtml +
          "</p>"
      );


            updateLastVisibleCard();
      var articleContentHtml = '<div class="article-title-link">';
            updateWidthBlockView();
      articleContentHtml += '<p class="article-title">' + title + "</p>";
            processEventCards();
            updateViews();
            updateCardEventBorders();
            $('.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() {
      // Create a div that will wrap the links
            sortAlphabetically('.list-container .card');
      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


            updateLastVisibleCard();
      // Append type, entity, discipline, and subject details
            updateWidthBlockView();
      articleContentHtml +=
            processEventCards();
        '<p class="article-type">' +
            updateViews();
        typeHtml +
            updateCardEventBorders();
        "</p>" +
            $('.home-alphabetical-list-button').addClass('active-view-button');
        '<div class="article-metadata">' +
             $('.home-chronicle-list-button').removeClass('active-view-button');
        '<div class="article-metadata-column">' +
             $('.home-random-list-button').removeClass('active-view-button');
        '<p class="article-metadata-label">Entity</p>' +
        });
        '<p class="article-metadata-value">' +
    } else {
        entity +
        console.log("NOT HOMEPAGE");
        "</p>" +
         $('.home-list-view').show();
        "</div>" +
         $('.chronicle-list-button, .list-view-button').addClass('active-view-button');
        '<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>";


        // Initialization and Default Settings
      $("#article-content").html(articleContentHtml);
        // Initially hide block view sorting buttons and set the default sorted view for list
      $("#related-articles").html(relatedArticlesHtml);
        $('.chronicle-block-button, .random-block-button, .alphabetical-block-button').hide();
        sortChronologically(); // Sort the block view chronologically by default
        updateLastVisibleCard();
        updateWidthBlockView();
        processEventCards();
        updateViews();
        updateCardEventBorders();


        $('.list-view-button').click(function() {
      if (relatedArticlesHtml && relatedArticlesHtml.trim().length > 0) {
            console.log("List view button clicked.");
        $("#related-articles")
            $(".list-sorting-buttons").css('display', 'flex');
          .html(
            $('.block-sorting-buttons').hide();
             '<div class="related-articles-label">Related Articles</div><div class="related-articles-container">' +
             // Switching view classes
              relatedArticlesHtml +
            $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
              "</div>"
            // Additional class switch
          )
            $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
          .show();
            // 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();
            updateCardEventBorders();
       
            // 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() {
    // Check which view is active and set the width accordingly
            console.log("Block view button clicked.");
    if ($(".home-chronicle-list").is(":visible")) {
            $('.list-sorting-buttons').hide(); // Hide list sorting buttons
      $(".home-list-view").each(function () {
            $(".block-sorting-buttons").css('display', 'flex');
        var currentWidth = $(this).width(); // Get the current width
            $('.home-list-view').removeClass('home-list-view').addClass('home-block-view');
        $(this).data("originalWidth", currentWidth); // Store the original width
            $('.home-chronicle-list').removeClass('home-chronicle-list').addClass('home-chronicle-block');
        $(this).css("width", "calc(60% - 2px)");
            $('.chronicle-block-button, .random-block-button, .alphabetical-block-button').show();
      });
            $('.chronicle-list-button, .random-list-button, .alphabetical-list-button').hide();
            updateLastVisibleCard();
            updateWidthBlockView();
            processEventCards();
            updateViews();
            updateCardEventBorders();
            $('.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
      // Modify the .type elements within .home-chronicle-list
            if ($('.chronicle-list-button').hasClass('active-view-button')) {
      $(".home-chronicle-list .type").each(function () {
                $('.chronicle-list-button').removeClass('active-view-button');
        var currentLeft = $(this).css("left"); // Get the current left value
                $('.chronicle-block-button').addClass('active-view-button');
        $(this).data("originalLeft", currentLeft); // Store the original left value
            } else if ($('.random-list-button').hasClass('active-view-button')) {
        $(this).css("left", "85%");
                $('.random-list-button').removeClass('active-view-button');
      });
                $('.random-block-button').addClass('active-view-button');
    } else if ($(".home-chronicle-block").is(":visible")) {
            } else if ($('.alphabetical-list-button').hasClass('active-view-button')) {
      $(".home-chronicle-block div.list-container").each(function () {
                $('.alphabetical-list-button').removeClass('active-view-button');
        var currentWidth = $(this).width(); // Get the current width
                $('.alphabetical-block-button').addClass('active-view-button');
        $(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
      });
    }


        // BLOCK VIEW SORTING BUTTONS
    // Apply the fade-out effect to both #list and #list-list elements
        $('.chronicle-block-button').click(function() {
    $(".list-container").addClass("fade-out");
            sortChronologically();
  }


            updateLastVisibleCard();
  // closeModal function
            updateWidthBlockView();
  function closeModal() {
            processEventCards();
    $("#print-chooser").hide();
            updateViews();
    $("#show-article").removeClass("print-opts-open");
            updateCardEventBorders();
    if ($(".home-chronicle-list").is(":visible")) {
            $('.chronicle-block-button').addClass('active-view-button');
      $(".home-list-view").css("width", "100%");
            $('.random-block-button').removeClass('active-view-button');
      $(".home-chronicle-list div.list-container div.card div.type").css(
            $('.alphabetical-block-button').removeClass('active-view-button');
         "left",
         });
        "90%"
       
      );
        $('.random-block-button').click(function() {
    } else if ($(".home-chronicle-block").is(":visible")) {
            randomizeCards('.list-container .card');
      updateWidthBlockView();
    }
    showArticleWrapper.hide();
  }


            updateLastVisibleCard();
  $(".card").on("click", function (event) {
            updateWidthBlockView();
    // Check if the click event is originating from a link within .people or .type, or any other specific area
            processEventCards();
    if ($(event.target).closest(".people a, .type a").length) {
            updateViews();
      // The click is inside a link; let the default behavior proceed without opening the modal
            updateCardEventBorders();
      return;
            $('.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() {
    // Prevent further event handling if the card has the 'event' class
            sortAlphabetically('.list-container .card');
    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();
    }
  });


            updateLastVisibleCard();
  $("#show-article-wrapper").on("click", ".related-article", function (event) {
            updateWidthBlockView();
    openModal(this, event); // Call openModal when a related-article is clicked
            processEventCards();
    setShowArticleRotationEffect();
            updateViews();
  });
            updateCardEventBorders();
            $('.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
  /* ---------- Softwear PRINT ---------- */
        $('.chronicle-list-button').click(function() {
            sortChronologically();


            updateLastVisibleCard();
  /* helpers */
            updateWidthBlockView();
  function swPrintPreloadFont() {
            processEventCards();
    var link = document.createElement("link");
            updateViews();
    link.rel = "preload";
            updateCardEventBorders();
    link.as = "font";
            $('.chronicle-list-button').addClass('active-view-button');
    link.type = "font/woff2";
            $('.random-list-button').removeClass('active-view-button');
    link.href = "/fonts/HALColant-TextRegular.woff2?v=20250820";
            $('.alphabetical-list-button').removeClass('active-view-button');
    link.crossOrigin = "anonymous";
        });
    document.head.appendChild(link);
  }


        $('.random-list-button').click(function() {
  function swPrintCacheBust(url) {
            randomizeCards('.list-container .card');
    return url + (url.indexOf("?") > -1 ? "&" : "?") + "_=" + Date.now();
  }


            updateLastVisibleCard();
  function swEnsurePrintChooser() {
            updateWidthBlockView();
    var $chooser = jQuery("#print-chooser");
            processEventCards();
    if ($chooser.length) return $chooser;
            updateViews();
            updateCardEventBorders();
            $('.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() {
    $chooser = jQuery(
            sortAlphabetically('.list-container .card');
      '<div id="print-chooser" class="print-chooser" style="display:none;">' +
        '<a href="#" id="print-with-border" class="print-choice">show border</a> ' +
        '<a href="#" id="print-no-border" class="print-choice">hide border</a>' +
        "</div>"
    );
    jQuery("#print-button").after($chooser);


            updateLastVisibleCard();
    // Bind once on the chooser to catch nested elements
            updateWidthBlockView();
    if (!$chooser.data("swBound")) {
            processEventCards();
      function chooserFire(ev, where) {
            updateViews();
        ev = ev || window.event;
            updateCardEventBorders();
        var t = ev && (ev.target || ev.srcElement);
            $('.alphabetical-list-button').addClass('active-view-button');
        var a = t && t.closest ? t.closest("a[id]") : null;
            $('.chronicle-list-button').removeClass('active-view-button');
        if (!a) return;
            $('.random-list-button').removeClass('active-view-button');
        var id = a.getAttribute("id");
         });
        if (id !== "print-with-border" && id !== "print-no-border") return;
        if (ev.preventDefault) ev.preventDefault();
        if (ev.stopImmediatePropagation) ev.stopImmediatePropagation();
        if (ev.stopPropagation) ev.stopPropagation();
        swHandlePrintChoice(id, (window.jQuery && jQuery(a)) || null);
         return false;
      }
      $chooser.on("pointerdown", chooserFire);
      $chooser.on("touchstart", chooserFire);
      $chooser.on("mousedown", chooserFire);
      $chooser.on("click", chooserFire);
      $chooser.data("swBound", true);
     }
     }
      
     return $chooser;
     // FILTERS  ---------------------  SECTION //
  }
    // General Filters Toggle Button
 
    $('.general-toggle').click(function() {
  function swHidePrintUI() {
         var filtersDiv = $('#filters');
     jQuery("#print-chooser").hide();
        filtersDiv.toggleClass('is-visible');
    jQuery("#show-article").removeClass("print-opts-open");
       
   }
         if (filtersDiv.hasClass('is-visible')) {
 
            filtersDiv.css('display', 'grid').hide().slideDown(100);
  function updatePrintSelectionUI() {
            $(this).text('[Hide]');
    requestAnimationFrame(function () {
         var activeCount = jQuery("#filters .values button.active").length;
 
         if (activeCount > 0) {
        jQuery("#print-selection-wrapper").show();
         } else {
         } else {
            filtersDiv.slideUp(100, function() {
        jQuery("#print-selection-wrapper").hide();
                $(this).css('display', 'none');
        jQuery("#print-selection-options").hide();
                // The filter reset code has been removed to keep the filters active
            });
            $(this).text('[Show]');
         }
         }
        updateLastVisibleCard();
        updateWidthBlockView();
        processEventCards();
        updateViews();
        updateCardEventBorders();
     });
     });
      
  }
     // Specific Toggle for Filter Sections like TYPE, ENTITY, etc.
 
     $('.open-filter').click(function(event) {
  function hidePrintSelectionOptions() {
         event.stopPropagation();
        jQuery("#print-selection-options").hide();
      
     }
         var filterType = $(this).closest('.filter').data('filter');
 
         var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
  function swHandleBatchPrint(borderPref) {
   
     swPrintPreloadFont();
         console.log('Filter type:', filterType, 'Card Selector:', cardSelector);
 
   
     var $cards = jQuery(".card:visible").not(".event");
        $('#values-' + filterType).toggle();
 
   
    if (!$cards.length) {
        if ($('#values-' + filterType).is(':visible')) {
         alert("No entries to print.");
            $(this).addClass('active-filter');
        return;
         } else {
    }
             $(this).removeClass('active-filter');
 
    var requests = [];
 
     $cards.each(function () {
         var $card = jQuery(this);
        var title = $card.data("page");
 
        if (!title) return;
 
         var url =
        window.mw && mw.util && mw.util.getUrl
            ? swPrintCacheBust(mw.util.getUrl(title))
            : swPrintCacheBust("/wiki/" + String(title));
 
        requests.push(
         jQuery.get(url).then(function (html) {
            var $tmp = jQuery("<div>").html(html);
            var $print = $tmp.find(".print-only").first();
            return $print.length ? $print.prop("outerHTML") : "";
        })
        );
    });
 
    Promise.all(requests)
        .then(function (results) {
        var combinedHtml = results.join("");
 
         if (!combinedHtml.trim()) {
             alert("Could not generate print content.");
            return;
         }
         }
   
 
         // Pass the determined card selector to the function
         swBuildIframeAndPrint(
         updateLastVisibleCard(cardSelector);
            combinedHtml,
         updateWidthBlockView(cardSelector);
            borderPref,
        processEventCards(cardSelector);
            null,
        updateViews(cardSelector);
            "filtered.softwear.directory"
        updateCardEventBorders(cardSelector);
        );
      
        })
        console.log('Updated views and borders after filter toggle');
        .catch(function () {
        alert("There was a problem preparing the print selection.");
        });
  }
 
  /* small boot probe */
  (function () {
    try {
      console.log("[swprint] probe on load", {
        printButton: !!document.getElementById("print-button"),
         chooserExists: !!document.getElementById("print-chooser"),
        localPrintOnlyCount: jQuery(".print-only").length,
         showArticleExists: !!document.getElementById("show-article"),
      });
    } catch (e) {}
  })();
 
  /* core: build iframe and print */
  function swBuildIframeAndPrint(printHtml, borderPref, $btn, filenameOverride) {
    // 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 = resolve;
      linkCss.onerror = resolve;
     });
     });
   
 
     function filterCards() {
     // font preload (inside iframe)
        var displayCountsHtml = '';
    var linkFont = doc.createElement("link");
        var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
    linkFont.rel = "preload";
      
    linkFont.as = "font";
        $('.filter .values a[title]').each(function() {
    linkFont.type = "font/woff2";
            var anchor = $(this);
    linkFont.href = "/fonts/HALColant-TextRegular.woff2?v=20250820";
            var filterValue = anchor.attr('title').toLowerCase();
     linkFont.crossOrigin = "anonymous";
            var count = 0;
 
      
    doc.head.appendChild(linkFont);
            if (anchor.find('button').hasClass('active')) {
    doc.head.appendChild(linkCss);
                $(cardSelector).each(function() {
 
                    var card = $(this);
     // inject HTML
                    $('.filter').each(function() {
    doc.body.innerHTML = printHtml;
                        var filterType = $(this).data('filter');
 
                        var cardValue = card.find('.' + filterType).text().toLowerCase();
    (function () {
                        if (cardValue.indexOf(filterValue) !== -1) {
        var pres = doc.querySelectorAll(".link-pdf pre");
                            count++;
 
                        }
        Array.prototype.forEach.call(pres, function (pre) {
                    });
            // move its children out
                });
            while (pre.firstChild) {
   
            pre.parentNode.insertBefore(pre.firstChild, pre);
                displayCountsHtml += '<span>[' + count + '] ' + filterValue + '</span> ';
             }
             }
            // remove the <pre>
            pre.parentNode.removeChild(pre);
         });
         });
      
     })();
         if (displayCountsHtml) {
 
             $('.count-filtered-cards').html(displayCountsHtml).show();
    // sanitize: remove inner .print-no-border if user chose WITH border
    (function () {
      var stray = doc.querySelectorAll(".print-no-border");
      if (borderPref === "with" && stray.length) {
        Array.prototype.forEach.call(stray, function (el) {
          el.className = (el.className || "")
            .replace(/\bprint-no-border\b/g, "")
            .trim();
         });
      }
    })();
 
    // apply border preference to <html>
    (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,
            ""
          );
      }
    })();
 
    // Glue label + body together (extra safety vs. page breaks)
    (function () {
      var style = doc.createElement("style");
      style.textContent =
        "@media print{.sw-keep{break-inside:avoid;page-break-inside:avoid;}}";
      doc.head.appendChild(style);
 
      var pairs = [
        [".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"],
      ];
 
      for (var i = 0; i < pairs.length; i++) {
        var labelSel = pairs[i][0];
        var bodySel = pairs[i][1];
        var labels = doc.querySelectorAll(labelSel);
        for (var j = 0; j < labels.length; j++) {
          var label = labels[j];
          var body = label.nextElementSibling;
          if (!body || !body.matches(bodySel)) continue;
          var wrap = doc.createElement("div");
          wrap.className = "sw-keep";
          label.parentNode.insertBefore(wrap, label);
          wrap.appendChild(label);
          wrap.appendChild(body);
        }
      }
    })();
 
    // 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 &&
          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) {
        var kids = Array.prototype.slice.call(root.childNodes);
        for (var k = 0; k < kids.length; k++) {
          var n = kids[k];
          if (n.nodeType === 3 && !n.textContent.replace(/\s+/g, "")) {
            root.removeChild(n);
          }
        }
      }
    })();
 
    // inline micro-tweaks for print spacing
    (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;}" +
        "  .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 (wrapping / underline)
    (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 desiredTitle;
 
        if (filenameOverride) {
        desiredTitle = filenameOverride;
         } else {
         } else {
            $('.count-filtered-cards').hide();
        var entryNum = "";
        var numEl = doc.querySelector(".article-entry-number");
        if (numEl) {
            var m = (numEl.textContent || "").match(/\d+/);
            entryNum = m ? m[0] : "";
         }
         }
   
         desiredTitle =
         // Apply filtering and pass the determined card selector to the function
            (entryNum ? entryNum + "." : "") + "softwear.directory";
        applyFiltering(cardSelector);
        }
   
 
         updateLastVisibleCard(cardSelector);
        var oldIframeTitle = doc.title;
         updateWidthBlockView(cardSelector);
         var oldParentTitle = document.title;
        processEventCards(cardSelector);
 
        updateViews(cardSelector);
         iframe.contentWindow.onafterprint = function () {
        updateCardEventBorders(cardSelector);
          try {
   
            doc.title = oldIframeTitle;
        console.log('Filtering process complete, updated views and borders');
            document.title = oldParentTitle;
    }    
          } catch (e) {}
   
          setTimeout(function () {
    function applyFiltering() {
            if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
         // Determine which card selector to use based on the elements present in the DOM
          }, 100);
         var cardSelector = $('.card').length > 0 ? '.card' : '.community-card';
          if ($btn && $btn.length) $btn.data("busy", false);
   
        };
         // Apply the logic to the determined card type
 
         $(cardSelector).show().each(function() {
        doc.title = desiredTitle;
             var card = $(this);
        document.title = desiredTitle;
             var hideCard = false;
 
   
         //window._printDoc = doc;
            $('.filter').each(function() {
         //window._printFrame = iframe;
                if (hideCard) return;
        //console.log("PRINT DOC READY", doc);
   
        //console.log("PRINT HTML", doc.body.innerHTML);
                var filterType = $(this).data('filter');
 
                var activeFilters = $(this).find('.values a[title] button.active').map(function() {
        iframe.contentWindow.focus();
                    return $(this).parent('a').attr('title').toLowerCase();
        iframe.contentWindow.print();
                }).get();
 
   
         // safety cleanup
                if (activeFilters.length > 0) {
         setTimeout(function () {
                    var cardValue = card.find('.' + filterType).text().toLowerCase();
          try {
                    var matchesFilter = activeFilters.some(function(filterValue) {
             doc.title = oldIframeTitle;
                        return cardValue.indexOf(filterValue) !== -1;
             document.title = oldParentTitle;
                    });
          } catch (e) {}
                    if (!matchesFilter) hideCard = true;
          if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
                }
          if ($btn && $btn.length) $btn.data("busy", false);
            });
        }, 1000);
      
      })
            if (hideCard) card.hide();
      .catch(function () {
        });
        if ($btn && $btn.length) $btn.data("busy", false);
     }   
      });
   
  }
    function updateLastVisibleCard() {
 
        // Target only the list view container for updating the last visible card
  /* decide source & kick print */
        $('.home-chronicle-list div.list-container div.card').removeClass('last-visible');
  function swHandlePrintChoice(id, $btn) {
      
    if ($btn && $btn.data("busy")) return;
        // Find the last visible card within the list view and add the class
    if ($btn && $btn.length) $btn.data("busy", true);
        var lastVisibleCard = $('.home-chronicle-list div.list-container div.card:visible:last');
 
        lastVisibleCard.addClass('last-visible');
    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;
     }
     }


     function updateWidthBlockView() {
     // otherwise fetch by title (modal/home)
        // Target only the block view container for updating the with of card
    var title =
        $('.home-chronicle-block div.list-container').css('width', '100%');
      window.currentEntryTitle ||
        $('.home-chronicle-block div.list-container div.card').css('width', 'calc(20% - 0px)');
      (window.mw && mw.config && mw.config.get && mw.config.get("wgPageName"));
        $('.home-chronicle-block div.list-container div.card:nth-child(5n + 1)').css('width', 'calc(20% + 4px)');
    if (!title) {
      window.print();
      if ($btn && $btn.length) $btn.data("busy", false);
      return;
     }
     }


     // Reset function
     var pageUrl =
    $('.reset-filter').click(function() {
      window.mw && mw.util && mw.util.getUrl
        // Remove 'active' class from all filter buttons
         ? mw.util.getUrl(title)
        $('#filters .values button').removeClass('active');
         : "/wiki/" + String(title);
         $('.open-filter').removeClass('active-filter');
   
         // Show all cards that might have been hidden by the filters
        $('.card').show();
   
        // Reset and hide the filter counts
        $('.count-filtered-cards').text('').hide();
   
        filterCards();  


         updateLastVisibleCard();
    jQuery
         updateWidthBlockView();
      .get(swPrintCacheBust(pageUrl))
         processEventCards();
      .done(function (html) {
        updateViews();
         var $tmp = jQuery("<div>").html(html);
        updateCardEventBorders();
         var $print = $tmp.find(".print-only").first();
    });
         if (!$print.length) {
   
          window.print();
$('#filters .values button').click(function() {
          if ($btn && $btn.length) $btn.data("busy", false);
         console.log("Filter is clicked!!!");
          return;
$(this).toggleClass('active');
        }
filterCards(); // Re-apply the filters based on the updated active buttons
        swHidePrintUI();
        swBuildIframeAndPrint($print.prop("outerHTML"), borderPref, $btn);
      })
      .fail(function () {
         window.print();
        jQuery("#print-button").data("busy", false);
      });
  }
 
  /* bind current choice anchors (defensive, for Entry pages) */
  function swBindChoiceAnchors() {
    var sel = "#print-with-border, #print-no-border";
    var els = document.querySelectorAll(sel);
    for (var i = 0; i < els.length; i++) {
      (function (el) {
        if (el.__swChoiceBound) return;
        el.__swChoiceBound = true;


         updateLastVisibleCard();
         // ensure clickable/accessible
        updateWidthBlockView();
        try {
        processEventCards();
          el.style.pointerEvents = el.style.pointerEvents || "auto";
        updateViews();
          if (!el.getAttribute("role")) el.setAttribute("role", "button");
         updateCardEventBorders();
          if (!el.getAttribute("tabindex")) el.setAttribute("tabindex", "0");
});
         } catch (e) {}


    $(window).on('scroll', function() {
        function fire(ev) {
        var filtersDiv = $('#filters');
          if (ev && ev.preventDefault) ev.preventDefault();
        if (filtersDiv.hasClass('is-visible')) {
          if (ev && ev.stopImmediatePropagation) ev.stopImmediatePropagation();
            filtersDiv.removeClass('is-visible').slideUp(100, function() {
          if (ev && ev.stopPropagation) ev.stopPropagation();
                $(this).css('display', 'none');
          var $a = (window.jQuery && jQuery(el)) || null;
                // The filter reset code has been removed to keep the filters active
          swHandlePrintChoice(el.id, $a);
            });
          return false;
            $('.general-toggle').text('[Show]'); // Update the toggle button text
         }
         }
        // early + normal phases
        el.addEventListener("pointerdown", fire, true);
        el.addEventListener("touchstart", fire, true);
        el.addEventListener("mousedown", fire, true);
        el.addEventListener("click", fire, true);
        el.addEventListener("click", fire, false);
        if (!el.onclick) el.onclick = fire;
        // keyboard
        el.addEventListener(
          "keydown",
          function (e) {
            var k = e.key || e.keyCode;
            if (k === "Enter" || k === 13 || k === " " || k === 32) fire(e);
          },
          true
        );
      })(els[i]);
    }
  }
  /* early global catcher (minimal) */
  (function () {
    if (window.__swprintEarlyCatcher) return;
    window.__swprintEarlyCatcher = true;
    function routeEarly(ev) {
      var t = ev.target;
      if (!t || !t.closest) return;
      var a = t.closest("a#print-with-border, a#print-no-border");
      if (!a) return;
      if (ev.preventDefault) ev.preventDefault();
      if (ev.stopImmediatePropagation) ev.stopImmediatePropagation();
      if (ev.stopPropagation) ev.stopPropagation();
      swHandlePrintChoice(a.id, (window.jQuery && jQuery(a)) || null);
      return false;
    }
    window.addEventListener("pointerdown", routeEarly, true);
    window.addEventListener("touchstart", routeEarly, true);
    window.addEventListener("mousedown", routeEarly, true);
  })();
  /* wiring (namespaced) */
  jQuery(document).off("click.swprint");
  jQuery(document).on(
    "click.swprint",
    "#print-button, #print-chooser, #print-options",
    function (e) {
      // main [print] toggler
      if (jQuery(e.target).closest("#print-button").length) {
        e.preventDefault();
        var $chooser = swEnsurePrintChooser();
        $chooser.css({ position: "absolute", zIndex: 99999 });
        $chooser.toggle();
        var visible = $chooser.is(":visible");
        jQuery("#show-article").toggleClass("print-opts-open", visible);
        // ensure anchors are bound (important on Entry pages)
        swBindChoiceAnchors();
        return;
      }
      // click directly on a choice link (fallback path)
      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);
    }
  );
  // map any <button> inside chooser to its host anchor
  jQuery(document).on(
    "click.swprintChoiceBtn2",
    "#print-chooser button",
    function (e) {
      var host = this.closest(
        '[id="print-with-border"], [id="print-no-border"]'
      );
      if (!host) return;
      e.preventDefault();
      swHandlePrintChoice(host.id, (window.jQuery && jQuery(host)) || null);
    }
  );
  // hide choices on ESC
  jQuery(document).on("keydown.swprint", function (e) {
    if (e && e.keyCode === 27) {
        swHidePrintUI();
        hidePrintSelectionOptions();
    }
  });
  // toggle filtered print options
  jQuery(document).on("click", ".print-selection-toggle", function (e) {
        e.preventDefault();
        jQuery("#print-selection-options").toggle();
     });
     });
   
    // 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
  // run filtered batch print
     // Find all image containers within the article content and extract the necessary information
  jQuery(document).on(
     $('.article-images .image-container').each(function() {
     "click",
         var img = $(this).find('img');
     ".print-selection-border, .print-selection-no-border",
         var captionDiv = $(this).find('div[class^="caption-image"]');
    function (e) {
         var image = {
        e.preventDefault();
            src: img.attr('src'),
 
            alt: img.attr('alt'),
         var $btn = jQuery(this);
            caption: captionDiv.text(),
         var borderPref = $btn.hasClass("print-selection-no-border")
            captionClass: captionDiv.attr('class')
        ? "without"
        };
        : "with";
         images.push(image); // Add the image object to the images array
 
    });
        // disable all related buttons
         jQuery(".print-selection-border, .print-selection-no-border, .print-selection-toggle")
        .prop("disabled", true)
        .css("opacity", "0.5");
 
        // change ONLY clicked button text (native feeling)
        var originalText = $btn.text();
         $btn.text("working…");
 
        swHandleBatchPrint(borderPref);


    if (images.length > 0) {
        // optional reset (if user comes back)
         setupImageToggle(images); // Call the setupImageToggle function with the images array
        setTimeout(function () {
         updateImageLabel(1, images.length); // Set the label for the first image immediately
         $btn.text(originalText);
         jQuery(".print-selection-border, .print-selection-no-border, .print-selection-toggle")
            .prop("disabled", false)
            .css("opacity", "");
        }, 2000);
     }
     }
  );


    function setupImageToggle(images) {
  /* ---------- /Softwear PRINT ---------- */
        var currentIndex = 0;
 
        var enableNavigation = images.length > 1; // Enable navigation only if there is more than one image
  // Close modal with Close button
   
  $("#close-button").on("click", function () {
        function showImage(index) {
    $("#print-chooser").hide();
            currentIndex = index;
    $("#show-article").removeClass("print-opts-open");
            var image = images[currentIndex];
 
            updateImageLabel(currentIndex + 1, images.length);
    $(".list-container").removeClass("fade-out");
            $('#article-content').find('.article-images').html(getImageHtml(image, currentIndex, images.length, enableNavigation));
    closeModal();
        }
  });
   
 
        // Attach click handlers only if navigation is enabled
  // Close modal and remove fade out also when clicking outside of card
        if (enableNavigation) {
  $(document).on("mousedown", function (event) {
            $('#article-content').on('click', '.next-arrow', function() {
    var isOutsideWrapper =
                showImage((currentIndex + 1) % images.length);
      !showArticleWrapper.is(event.target) &&
            });
      showArticleWrapper.has(event.target).length === 0;
      
     var isOnCard = $(event.target).closest(".card, .list-card").length > 0;
            $('#article-content').on('click', '.prev-arrow', function() {
 
                showImage((currentIndex - 1 + images.length) % images.length);
     if (!areFiltersActive) {
            });
      if (isOutsideWrapper && !isOnCard) {
        }
         $(".list-container").removeClass("fade-out");
      
         showArticleWrapper.css("display", "none");
        // Display the first image
        closeModal(); // Use closeModal() for cleanup
        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>' +
                  navigationHtml +
                  '<div class="image-container">' +
                      '<img src="' + image.src + '" alt="' + image.alt + '">' +
                      '<div class="' + image.captionClass + '">' + image.caption + '</div>' +
                  '</div>' +
              '</div>';
     }
     }
   
  });
     function updateImageLabel(currentIndex, totalImages) {
 
        var imageLabel = currentIndex + '/' + totalImages + ' IMAGES';
  // Hover effect for scrolling
        $('#article-content .article-label-image').text(imageLabel);
  $("#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");
     }
     }
      
  );
$('.caption-image1').each(function() {
 
        // Split the caption at each <br> tag and wrap each line in a span
  // Format community card, when in the Community Entries page
        var htmlContent = $(this).html();
  if ($(".community-card").length) {
        var lines = htmlContent.split('<br>');
     formatCommunityCardDescriptions();
        var wrappedLines = lines.map(function(line) {
  }
            return '<span class="caption-line">' + line + '</span>';
 
  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();
          }
         });
         });
        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) {
  // paragraph-formatting block
        event.stopPropagation();
  if (jQuery("#show-article-wrapper-entry").length) {
        event.preventDefault();
     function formatParagraphs(text) {
   
      // split on newlines, drop empty lines, wrap each in <p>
        var url = $(element).find('.link a').attr('href');
      var parts = String(text || "").split("\n");
         if (url) {
      var out = [];
            window.open(url, '_blank').focus();
      for (var i = 0; i < parts.length; i++) {
        }
        var p = parts[i].replace(/^\s+|\s+$/g, "");
         if (p) out.push("<p>" + p + "</p>");
      }
      return out.join("");
     }
     }


     function openModal(cardElement, event) {
     jQuery(
        event.stopPropagation(); // Prevent the event from bubbling up
      "#show-article .article-description, #show-article .article-reflection"
        console.log("openModal function called.");
    ).each(function () {
    var isRelatedArticle = $(cardElement).hasClass('related-article');
      var $el = jQuery(this);
    showArticleWrapper.css('display', 'block');
      if ($el.children("p").length > 0) return; // already formatted by PageForms
      var rawText = $el.text();
      $el.html(formatParagraphs(rawText));
    });
  }


    // Clear existing content in modal
  // SEARCH  ---------------------   SECTION //
    $('#article-title').empty();
  // Check if div with class "mw-search-results-info" exists
    $('#article-content').empty();
  if ($(".mw-search-results-info").length) {
   
    // Select the child <p> element and check its content
    if (isRelatedArticle) {
    var $paragraph = $(".mw-search-results-info > p");
            // Handle card elements (existing logic)
    var currentText = $paragraph.text().trim();
        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 subject = $(cardElement).find('.related-article-subject').text();
        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
    // Check if the current text is not "There were no results matching the query."
            $('#article-title').html('<p class="article-entry-number">' + entryNumber + '</p><p class="article-people">' + peopleHtml + '</p>');
    if (currentText !== "There were no results matching the query.") {
        var articleContentHtml = '<div class="article-title-link">';
      // Overwrite the content with "Search results"
        articleContentHtml += '<p class="article-title">' + title + '</p>';
      $paragraph.text("Pages related to your Search");
            // Create a div that will wrap the links
    }
            articleContentHtml += '<div class="link-pdf">';
  }


            if (externalPdfURL) {
  // Object to store encountered titles
                articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF]</a>';
  var encounteredTitles = {};
            }
 
            if (externalLinkURL) {
  // Iterate over each search result
                articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB]</a>';
  $(".mw-search-result-heading").each(function () {
            }
    // Get the title of the current search result
            // Close the .link-pdf div
    var title = $(this).find("a").attr("title");
            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">' + subject + '</p>' +
            '</div>' +
        '</div>';


            // Add images if any
    // Check if the title has already been encountered
            if (cardImages.length > 0) {
    if (encounteredTitles[title]) {
                var initialImage = cardImages[0]; // Use the first image initially
      // Hide the duplicate search result
                var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
      $(this).hide();
                articleContentHtml +=
    } else {
                    '<div class="article-images">' +
      // Mark the title as encountered
                        getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
      encounteredTitles[title] = true;
                    '</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 {
  // Remove unwanted white spaces between lines
        // Handle card elements (existing logic)
  $(".mw-search-results-container")
        var cardImages = [];
    .contents()
        for (var i = 1; i <= 5; i++) {
    .filter(function () {
            var imageClass = '.image' + i;
       return this.nodeType === 3; // Filter text nodes
            var captionClass = '.caption-image' + i;
    })
            var imageElem = $(cardElement).find(imageClass + ' img');
    .remove();
            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 subject = $(cardElement).find('.subject').text();
        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">';
  // Edits regarding Search Results
            articleContentHtml += '<p class="article-title">' + title + '</p>';
  // 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>";


            // Create a div that will wrap the links
  // Replace the div with id="searchText" with the new form
            articleContentHtml += '<div class="link-pdf">';
  $("#searchText").replaceWith(newFormHtml);
            if (externalPdfURL) {
                articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF]</a>';
            }
            if (externalLinkURL) {
                articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB]</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">' + subject + '</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
  // Target the button based on its complex class structure
    if ($('.home-chronicle-list').is(':visible')) {
  $(".oo-ui-actionFieldLayout-button .oo-ui-buttonInputWidget").remove();
            $('.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
  // Check if #submit button exists and add event listener if it does
    $('.list-container').addClass('fade-out');
  var submitButton = document.querySelector("#submit");


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


    // closeModal function
      var email = "submit@softwear.directory";
function closeModal() {
      var subject = "new entry to the softwear directory";
         if ($('.home-chronicle-list').is(':visible')) {
      var body =
            $('.home-list-view').css('width', '100%');
        "☺ the following content could be interesting for the directory:\n\n" +
            $('.home-chronicle-list div.list-container div.card div.type').css('left', '90%');
        "[ author / creator ]\n\n" +
    } else if ($('.home-chronicle-block').is(':visible')) {
         "---\n\n" +
            updateWidthBlockView();
        "[ title ]\n\n" +
         }
        "---\n\n" +
    showArticleWrapper.hide();
        "[ why should it be included? ]\n\n" +
}
        "---\n\n" +
        "[ link or pdf ]\n\n" +
        "---\n\n" +
        "[ your name / contact / social ]\n\n" +
         "---";


    $('.card').on('click', function(event) {
      var mailtoLink =
         // Check if the click event is originating from a link within .people or .type, or any other specific area
         "mailto:" +
         if ($(event.target).closest('.people a, .type a').length) {
         encodeURIComponent(email) +
            // The click is inside a link; let the default behavior proceed without opening the modal
         "?subject=" +
            return;
         encodeURIComponent(subject) +
        }
        "&body=" +
   
        encodeURIComponent(body).replace(/%20/g, " ");
         // 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) {
      window.location.href = mailtoLink;
        openModal(this, event); // Call openModal when a related-article is clicked
        setShowArticleRotationEffect();
     });
     });
  }


    // Close modal with Close button
  // Tooltip for "wander elsewhere..." on .card.event
$('#close-button').on('click', function () {
  var tooltip = $(
    $('.list-container').removeClass('fade-out');
    '<div class="tooltip-popup">wander elsewhere...</div>'
    closeModal();
  ).appendTo("body");
});


    // Close modal and remove fade out also when clicking outside of card
  $(".card.event").on("mouseenter", function () {
    $(document).on('mousedown', function (event) {
    tooltip.css("opacity", 1);
        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
  $(".card.event").on("mousemove", function (e) {
    $('#show-article-wrapper').hover(function () {
    var offsetX = 10; // right of cursor
        // On hover, enable scrolling on #show-article-wrapper
    var offsetY = -30; // above cursor
        $(this).css('overflow-y', 'auto');
    tooltip.css({
        $(this).css('overflow-x', 'hidden');
      left: e.clientX + offsetX + "px",
    }, function () {
      top: e.clientY + offsetY + "px",
        // 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
  $(".card.event").on("mouseleave", function () {
if ($('.community-card').length) {
    tooltip.css("opacity", 0);
    formatCommunityCardDescriptions();
  });
}


    function formatCommunityCardDescriptions() {
  mw.loader.using("mediawiki.api", function () {
    $('.community-card').each(function() {
    // Only run on form edit page
        // Format paragraphs in community-description
    if (mw.config.get("wgCanonicalSpecialPageName") === "FormEdit") {
        var descriptionContainer = $(this).find('.community-description');
      new mw.Api()
        var rawDescription = descriptionContainer.text();
        .post({
        var formattedDescription = formatParagraphs(rawDescription);
          action: "purge",
        descriptionContainer.html(formattedDescription);
          titles: "Main",
         })
        // Remove empty elements in the entire card
         .fail(function (err) {
        $(this).find('*').each(function() {
          // Optional: leave a minimal fallback error log
            if ($(this).is(':empty') || $(this).html().trim() === '<br>') {
          console.warn("Main page purge failed", err);
                $(this).remove();
         });
            }
        });
    });
}
   
    // 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
  updatePrintSelectionUI();
    $('.mw-search-result-heading').each(function() {
  hidePrintSelectionOptions();
        // 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();
});
});

Latest revision as of 08:02, 22 April 2026

$(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

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

  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);
    updatePrintSelectionUI();
    hidePrintSelectionOptions();

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

    $("#filters .values button").removeClass("active");
    $(".open-filter").removeClass("active-filter");
    $(".count-filtered-cards").text("").hide();

    filterCards();
    hidePrintSelectionOptions();
  });

  $("#filters .values button").click(function () {
    $(this).toggleClass("active");
    filterCards();
  });

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

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

  /* 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">show border</a> ' +
        '<a href="#" id="print-no-border" class="print-choice">hide border</a>' +
        "</div>"
    );
    jQuery("#print-button").after($chooser);

    // Bind once on the chooser to catch nested elements
    if (!$chooser.data("swBound")) {
      function chooserFire(ev, where) {
        ev = ev || window.event;
        var t = ev && (ev.target || ev.srcElement);
        var a = t && t.closest ? t.closest("a[id]") : null;
        if (!a) return;
        var id = a.getAttribute("id");
        if (id !== "print-with-border" && id !== "print-no-border") return;
        if (ev.preventDefault) ev.preventDefault();
        if (ev.stopImmediatePropagation) ev.stopImmediatePropagation();
        if (ev.stopPropagation) ev.stopPropagation();
        swHandlePrintChoice(id, (window.jQuery && jQuery(a)) || null);
        return false;
      }
      $chooser.on("pointerdown", chooserFire);
      $chooser.on("touchstart", chooserFire);
      $chooser.on("mousedown", chooserFire);
      $chooser.on("click", chooserFire);
      $chooser.data("swBound", true);
    }
    return $chooser;
  }

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

  function updatePrintSelectionUI() {
    requestAnimationFrame(function () {
        var activeCount = jQuery("#filters .values button.active").length;

        if (activeCount > 0) {
        jQuery("#print-selection-wrapper").show();
        } else {
        jQuery("#print-selection-wrapper").hide();
        jQuery("#print-selection-options").hide();
        }
    });
  }

  function hidePrintSelectionOptions() {
        jQuery("#print-selection-options").hide();
    }

  function swHandleBatchPrint(borderPref) {
    swPrintPreloadFont();

    var $cards = jQuery(".card:visible").not(".event");

    if (!$cards.length) {
        alert("No entries to print.");
        return;
    }

    var requests = [];

    $cards.each(function () {
        var $card = jQuery(this);
        var title = $card.data("page");

        if (!title) return;

        var url =
        window.mw && mw.util && mw.util.getUrl
            ? swPrintCacheBust(mw.util.getUrl(title))
            : swPrintCacheBust("/wiki/" + String(title));

        requests.push(
        jQuery.get(url).then(function (html) {
            var $tmp = jQuery("<div>").html(html);
            var $print = $tmp.find(".print-only").first();
            return $print.length ? $print.prop("outerHTML") : "";
        })
        );
    });

    Promise.all(requests)
        .then(function (results) {
        var combinedHtml = results.join("");

        if (!combinedHtml.trim()) {
            alert("Could not generate print content.");
            return;
        }

        swBuildIframeAndPrint(
            combinedHtml,
            borderPref,
            null,
            "filtered.softwear.directory"
        );
        })
        .catch(function () {
        alert("There was a problem preparing the print selection.");
        });
  }

  /* small boot probe */
  (function () {
    try {
      console.log("[swprint] probe on load", {
        printButton: !!document.getElementById("print-button"),
        chooserExists: !!document.getElementById("print-chooser"),
        localPrintOnlyCount: jQuery(".print-only").length,
        showArticleExists: !!document.getElementById("show-article"),
      });
    } catch (e) {}
  })();

  /* core: build iframe and print */
  function swBuildIframeAndPrint(printHtml, borderPref, $btn, filenameOverride) {
    // 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 = resolve;
      linkCss.onerror = 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;

    (function () {
        var pres = doc.querySelectorAll(".link-pdf pre");

        Array.prototype.forEach.call(pres, function (pre) {
            // move its children out
            while (pre.firstChild) {
            pre.parentNode.insertBefore(pre.firstChild, pre);
            }
            // remove the <pre>
            pre.parentNode.removeChild(pre);
        });
    })();

    // sanitize: remove inner .print-no-border if user chose WITH border
    (function () {
      var stray = doc.querySelectorAll(".print-no-border");
      if (borderPref === "with" && stray.length) {
        Array.prototype.forEach.call(stray, function (el) {
          el.className = (el.className || "")
            .replace(/\bprint-no-border\b/g, "")
            .trim();
        });
      }
    })();

    // apply border preference to <html>
    (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,
            ""
          );
      }
    })();

    // Glue label + body together (extra safety vs. page breaks)
    (function () {
      var style = doc.createElement("style");
      style.textContent =
        "@media print{.sw-keep{break-inside:avoid;page-break-inside:avoid;}}";
      doc.head.appendChild(style);

      var pairs = [
        [".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"],
      ];

      for (var i = 0; i < pairs.length; i++) {
        var labelSel = pairs[i][0];
        var bodySel = pairs[i][1];
        var labels = doc.querySelectorAll(labelSel);
        for (var j = 0; j < labels.length; j++) {
          var label = labels[j];
          var body = label.nextElementSibling;
          if (!body || !body.matches(bodySel)) continue;
          var wrap = doc.createElement("div");
          wrap.className = "sw-keep";
          label.parentNode.insertBefore(wrap, label);
          wrap.appendChild(label);
          wrap.appendChild(body);
        }
      }
    })();

    // 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 &&
          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) {
        var kids = Array.prototype.slice.call(root.childNodes);
        for (var k = 0; k < kids.length; k++) {
          var n = kids[k];
          if (n.nodeType === 3 && !n.textContent.replace(/\s+/g, "")) {
            root.removeChild(n);
          }
        }
      }
    })();

    // inline micro-tweaks for print spacing
    (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;}" +
        "  .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 (wrapping / underline)
    (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 desiredTitle;

        if (filenameOverride) {
        desiredTitle = filenameOverride;
        } else {
        var entryNum = "";
        var numEl = doc.querySelector(".article-entry-number");
        if (numEl) {
            var m = (numEl.textContent || "").match(/\d+/);
            entryNum = m ? m[0] : "";
        }
        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;

        //window._printDoc = doc;
        //window._printFrame = iframe;
        //console.log("PRINT DOC READY", doc);
        //console.log("PRINT HTML", doc.body.innerHTML);

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

  /* bind current choice anchors (defensive, for Entry pages) */
  function swBindChoiceAnchors() {
    var sel = "#print-with-border, #print-no-border";
    var els = document.querySelectorAll(sel);
    for (var i = 0; i < els.length; i++) {
      (function (el) {
        if (el.__swChoiceBound) return;
        el.__swChoiceBound = true;

        // ensure clickable/accessible
        try {
          el.style.pointerEvents = el.style.pointerEvents || "auto";
          if (!el.getAttribute("role")) el.setAttribute("role", "button");
          if (!el.getAttribute("tabindex")) el.setAttribute("tabindex", "0");
        } catch (e) {}

        function fire(ev) {
          if (ev && ev.preventDefault) ev.preventDefault();
          if (ev && ev.stopImmediatePropagation) ev.stopImmediatePropagation();
          if (ev && ev.stopPropagation) ev.stopPropagation();
          var $a = (window.jQuery && jQuery(el)) || null;
          swHandlePrintChoice(el.id, $a);
          return false;
        }

        // early + normal phases
        el.addEventListener("pointerdown", fire, true);
        el.addEventListener("touchstart", fire, true);
        el.addEventListener("mousedown", fire, true);
        el.addEventListener("click", fire, true);
        el.addEventListener("click", fire, false);
        if (!el.onclick) el.onclick = fire;

        // keyboard
        el.addEventListener(
          "keydown",
          function (e) {
            var k = e.key || e.keyCode;
            if (k === "Enter" || k === 13 || k === " " || k === 32) fire(e);
          },
          true
        );
      })(els[i]);
    }
  }

  /* early global catcher (minimal) */
  (function () {
    if (window.__swprintEarlyCatcher) return;
    window.__swprintEarlyCatcher = true;

    function routeEarly(ev) {
      var t = ev.target;
      if (!t || !t.closest) return;
      var a = t.closest("a#print-with-border, a#print-no-border");
      if (!a) return;
      if (ev.preventDefault) ev.preventDefault();
      if (ev.stopImmediatePropagation) ev.stopImmediatePropagation();
      if (ev.stopPropagation) ev.stopPropagation();
      swHandlePrintChoice(a.id, (window.jQuery && jQuery(a)) || null);
      return false;
    }

    window.addEventListener("pointerdown", routeEarly, true);
    window.addEventListener("touchstart", routeEarly, true);
    window.addEventListener("mousedown", routeEarly, true);
  })();

  /* wiring (namespaced) */
  jQuery(document).off("click.swprint");
  jQuery(document).on(
    "click.swprint",
    "#print-button, #print-chooser, #print-options",
    function (e) {
      // main [print] toggler
      if (jQuery(e.target).closest("#print-button").length) {
        e.preventDefault();
        var $chooser = swEnsurePrintChooser();
        $chooser.css({ position: "absolute", zIndex: 99999 });
        $chooser.toggle();
        var visible = $chooser.is(":visible");
        jQuery("#show-article").toggleClass("print-opts-open", visible);

        // ensure anchors are bound (important on Entry pages)
        swBindChoiceAnchors();
        return;
      }

      // click directly on a choice link (fallback path)
      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);
    }
  );

  // map any <button> inside chooser to its host anchor
  jQuery(document).on(
    "click.swprintChoiceBtn2",
    "#print-chooser button",
    function (e) {
      var host = this.closest(
        '[id="print-with-border"], [id="print-no-border"]'
      );
      if (!host) return;
      e.preventDefault();
      swHandlePrintChoice(host.id, (window.jQuery && jQuery(host)) || null);
    }
  );

  // hide choices on ESC
  jQuery(document).on("keydown.swprint", function (e) {
    if (e && e.keyCode === 27) {
        swHidePrintUI();
        hidePrintSelectionOptions();
    }
  });

  // toggle filtered print options
  jQuery(document).on("click", ".print-selection-toggle", function (e) {
        e.preventDefault();
        jQuery("#print-selection-options").toggle();
    });

  // run filtered batch print
  jQuery(document).on(
    "click",
    ".print-selection-border, .print-selection-no-border",
    function (e) {
        e.preventDefault();

        var $btn = jQuery(this);
        var borderPref = $btn.hasClass("print-selection-no-border")
        ? "without"
        : "with";

        // disable all related buttons
        jQuery(".print-selection-border, .print-selection-no-border, .print-selection-toggle")
        .prop("disabled", true)
        .css("opacity", "0.5");

        // change ONLY clicked button text (native feeling)
        var originalText = $btn.text();
        $btn.text("working…");

        swHandleBatchPrint(borderPref);

        // optional reset (if user comes back)
        setTimeout(function () {
        $btn.text(originalText);
        jQuery(".print-selection-border, .print-selection-no-border, .print-selection-toggle")
            .prop("disabled", false)
            .css("opacity", "");
        }, 2000);
    }
  );

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

  // paragraph-formatting block
  if (jQuery("#show-article-wrapper-entry").length) {
    function formatParagraphs(text) {
      // split on newlines, drop empty lines, wrap each in <p>
      var parts = String(text || "").split("\n");
      var out = [];
      for (var i = 0; i < parts.length; i++) {
        var p = parts[i].replace(/^\s+|\s+$/g, "");
        if (p) out.push("<p>" + p + "</p>");
      }
      return out.join("");
    }

    jQuery(
      "#show-article .article-description, #show-article .article-reflection"
    ).each(function () {
      var $el = jQuery(this);
      if ($el.children("p").length > 0) return; // already formatted by PageForms
      var rawText = $el.text();
      $el.html(formatParagraphs(rawText));
    });
  }

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

  updatePrintSelectionUI();
  hidePrintSelectionOptions();
});