MediaWiki:Common.js: Difference between revisions

From softwear.directory
Jump to navigation Jump to search
No edit summary
No edit summary
Tag: Reverted
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
  // Loop through each card to format related articles
    cards.each(function() {
  cards.each(function() {
        // Check if the card has related articles
      // Check if the card has related articles
        var relatedArticles = $(this).find('.related-articles');
      var relatedArticles = $(this).find('.related-articles');
        if (relatedArticles.length > 0) {
      if (relatedArticles.length > 0) {
            // Get all the related article elements
          // Get all the related article elements
            var relatedArticleElements = relatedArticles.find('.related-article');
          var relatedArticleElements = relatedArticles.find('.related-article');


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


    function updateViews() {
  function updateViews() {
        // Handle cards in the list view
      // Handle cards in the list view
        $('.home-chronicle-list div.list-container div.card:not(.event)').each(function() {
      $('.home-chronicle-list div.list-container div.card:not(.event)').each(function() {
            if (!$(this).closest('.home-chronicle-block').length) {
          if (!$(this).closest('.home-chronicle-block').length) {
                var title = $(this).find('.title').detach();
              var title = $(this).find('.title').detach();
                var images = $(this).find('.images').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);
          }
      });
 
      // Additional functionality for checking consecutive .card.event
      $('.home-chronicle-block div.list-container .card.event, .home-chronicle-list div.list-container .card.event').each(function() {
          checkConsecutiveEvents($(this));
      });
  }
 
  function checkConsecutiveEvents(element) {
      if (element.next().hasClass('card') && element.next().hasClass('event')) {
          console.log("multiple consecutive card events");
          $('.home-chronicle-list div.list-container div.card.event').removeClass('alone-card-event');
      } else {
          console.log("alone card events");
          $('.home-chronicle-list div.list-container div.card.event').addClass('alone-card-event');
      }
  }
      
      
                // Remove existing .title-images if it exists
  function processEventCards() {
                $(this).find('.title-images').remove();
      $('.card.event').each(function() {
   
          var existingContainer = $(this).find('.container-people-date');
                var titleImagesContainer = $('<div class="title-images"></div>').append(images, title);
 
                $(this).find('.people').after(titleImagesContainer);
          // If the container doesn't exist, create and append it
            }
          if (existingContainer.length === 0) {
        });
              existingContainer = $('<div class="container-people-date"></div>');
   
              $(this).append(existingContainer); // Temporarily append to ensure it's in the DOM
        // 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
          // Ensure the .people and .date elements are inside the container
            var titleImagesContainer = $(this).find('.title-images');
          var people = $(this).find('.people').detach();
            if (titleImagesContainer.length) {
          var date = $(this).find('.date').detach();
                var title = titleImagesContainer.find('.title').detach();
          existingContainer.append(people).append(date);
                var images = titleImagesContainer.find('.images').detach();
 
                titleImagesContainer.remove();
          // Decide where to place the container
   
          if ($(this).closest('.home-chronicle-block').length) {
                $(this).find('.people').after(title);
              // Check if it's already correctly placed, if not, move it
                $(this).find('.type').after(images);
              if (!existingContainer.is($(this).find('.title').next())) {
            } else {
                  $(this).find('.title').after(existingContainer);
                // If .title-images doesn't exist, ensure .images is placed correctly
              }
                var images = $(this).find('.images').detach();
          } else if ($(this).closest('.home-chronicle-list').length) {
                $(this).find('.type').after(images);
              // Check if it's already correctly placed, if not, move it
            }
              if (!existingContainer.is($(this).find('.title').prev())) {
        });
                  $(this).find('.title').before(existingContainer);
   
              }
        // Additional functionality for checking consecutive .card.event
          }
        $('.home-chronicle-block div.list-container .card.event, .home-chronicle-list div.list-container .card.event').each(function() {
      });
            checkConsecutiveEvents($(this));
  }
        });
    }
   
    function checkConsecutiveEvents(element) {
        if (element.next().hasClass('card') && element.next().hasClass('event')) {
            console.log("multiple consecutive card events");
            $('.home-chronicle-list div.list-container div.card.event').removeClass('alone-card-event');
        } else {
            console.log("alone card events");
            $('.home-chronicle-list div.list-container div.card.event').addClass('alone-card-event');
        }
    }
   
    function updateCardEventBorders() {
        // Reset previously set classes for both block and list views
        $('.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');
   
        // Update borders for block view cards
        updateBordersForView('.home-chronicle-block div.list-container');
   
        // Update borders for list view cards
        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() {
  if ($('#home').length > 0) {
        $('.card.event').each(function() {
      console.log("The #home element exists on this page.");
            var existingContainer = $(this).find('.container-people-date');
      // This code will only run only on the homepage.
   
      // Show the block view container once everything is set up
            // If the container doesn't exist, create and append it
      $('.home-block-view').show();
            if (existingContainer.length === 0) {
      $('.home-chronicle-block-button, .home-block-view-button').addClass('active-view-button');
                existingContainer = $('<div class="container-people-date"></div>');
                $(this).append(existingContainer); // Temporarily append to ensure it's in the DOM
            }
   
            // Ensure the .people and .date elements are inside the container
            var people = $(this).find('.people').detach();
            var date = $(this).find('.date').detach();
            existingContainer.append(people).append(date);
   
            // Decide where to place the container
            if ($(this).closest('.home-chronicle-block').length) {
                // Check if it's already correctly placed, if not, move it
                if (!existingContainer.is($(this).find('.title').next())) {
                    $(this).find('.title').after(existingContainer);
                }
            } else if ($(this).closest('.home-chronicle-list').length) {
                // Check if it's already correctly placed, if not, move it
                if (!existingContainer.is($(this).find('.title').prev())) {
                    $(this).find('.title').before(existingContainer);
                }
            }
        });
    }


    if ($('#home').length > 0) {
      // Initialization and Default Settings
        console.log("The #home element exists on this page.");
      // Initially hide list view sorting buttons and set the default sorted view for block
        // This code will only run only on the homepage.
      $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').hide();
        // Show the block view container once everything is set up
      sortChronologically(); // Sort the block view chronologically by default
        $('.home-block-view').show();
     
        $('.home-chronicle-block-button, .home-block-view-button').addClass('active-view-button');
      updateLastVisibleCard();
      updateWidthBlockView();
      processEventCards();
      updateViews();


        // Initialization and Default Settings
      $('.home-list-view-button').click(function() {
        // Initially hide list view sorting buttons and set the default sorted view for block
          console.log("List view button clicked.");
        $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').hide();
          $(".home-list-sorting-buttons").css('display', 'flex');
        sortChronologically(); // Sort the block view chronologically by default
          // Switching view classes
       
          $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
        updateLastVisibleCard();
          // Additional class switch
        updateWidthBlockView();
          $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
        processEventCards();
          // Toggling visibility of buttons
        updateViews();
          $('.home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button').hide();
        updateCardEventBorders();
          $('.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');


        $('.home-list-view-button').click(function() {
          // Conditional checks for transferring the active class from block to list buttons
            console.log("List view button clicked.");
          if ($('.home-chronicle-list-button').hasClass('active-view-button')) {
            $(".home-list-sorting-buttons").css('display', 'flex');
              $('.home-chronicle-list-button').removeClass('active-view-button');
            // Switching view classes
              $('.home-chronicle-block-button').addClass('active-view-button');
            $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
          } else if ($('.home-random-list-button').hasClass('active-view-button')) {
            // Additional class switch
              $('.home-random-list-button').removeClass('active-view-button');
            $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
              $('.home-random-block-button').addClass('active-view-button');
            // Toggling visibility of buttons
          } else if ($('.home-alphabetical-list-button').hasClass('active-view-button')) {
            $('.home-chronicle-block-button, .home-random-block-button, .home-alphabetical-block-button').hide();
              $('.home-alphabetical-list-button').removeClass('active-view-button');
            $('.home-chronicle-list-button, .home-random-list-button, .home-alphabetical-list-button').show();
              $('.home-alphabetical-block-button').addClass('active-view-button');
            updateLastVisibleCard();
          }
            updateWidthBlockView();
      });
            processEventCards();
     
            updateViews();
      // BLOCK VIEW SORTING BUTTONS
            updateCardEventBorders();
      $('.home-chronicle-block-button').click(function() {
       
          sortChronologically();
            // 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
          updateLastVisibleCard();
            if ($('.home-chronicle-list-button').hasClass('active-view-button')) {
          updateWidthBlockView();
                $('.home-chronicle-list-button').removeClass('active-view-button');
          processEventCards();
                $('.home-chronicle-block-button').addClass('active-view-button');
          updateViews();
            } else if ($('.home-random-list-button').hasClass('active-view-button')) {
          $('.home-chronicle-block-button').addClass('active-view-button');
                $('.home-random-list-button').removeClass('active-view-button');
          $('.home-random-block-button').removeClass('active-view-button');
                $('.home-random-block-button').addClass('active-view-button');
          $('.home-alphabetical-block-button').removeClass('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');
      $('.home-random-block-button').click(function() {
            }
          randomizeCards('.list-container .card');
        });
       
        // BLOCK VIEW SORTING BUTTONS
        $('.home-chronicle-block-button').click(function() {
            sortChronologically();


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


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


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


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


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


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


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


            updateLastVisibleCard();
      $('.home-alphabetical-list-button').click(function() {
            updateWidthBlockView();
          sortAlphabetically('.list-container .card');
            processEventCards();
            updateViews();
            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() {
          updateLastVisibleCard();
            sortAlphabetically('.list-container .card');
          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');


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


        // Initialization and Default Settings
      $('.list-view-button').click(function() {
        // Initially hide block view sorting buttons and set the default sorted view for list
          console.log("List view button clicked.");
        $('.chronicle-block-button, .random-block-button, .alphabetical-block-button').hide();
          $(".list-sorting-buttons").css('display', 'flex');
        sortChronologically(); // Sort the block view chronologically by default
          $('.block-sorting-buttons').hide();
        updateLastVisibleCard();
          // Switching view classes
        updateWidthBlockView();
          $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
        processEventCards();
          // Additional class switch
        updateViews();
          $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
        updateCardEventBorders();
          // 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');
          }
      });


        $('.list-view-button').click(function() {
      $('.block-view-button').click(function() {
            console.log("List view button clicked.");
          console.log("Block view button clicked.");
            $(".list-sorting-buttons").css('display', 'flex');
          $('.list-sorting-buttons').hide(); // Hide list sorting buttons
            $('.block-sorting-buttons').hide();
          $(".block-sorting-buttons").css('display', 'flex');
            // Switching view classes
          $('.home-list-view').removeClass('home-list-view').addClass('home-block-view');
            $('.home-block-view').removeClass('home-block-view').addClass('home-list-view');
          $('.home-chronicle-list').removeClass('home-chronicle-list').addClass('home-chronicle-block');
            // Additional class switch
          $('.chronicle-block-button, .random-block-button, .alphabetical-block-button').show();
            $('.home-chronicle-block').removeClass('home-chronicle-block').addClass('home-chronicle-list');
          $('.chronicle-list-button, .random-list-button, .alphabetical-list-button').hide();
            // Toggling visibility of buttons
          updateLastVisibleCard();
            $('.chronicle-block-button, random-block-button, alphabetical-block-button').hide();
          updateWidthBlockView();
            $('.chronicle-list-button, .random-list-button, .alphabetical-list-button').show();
          processEventCards();
            updateLastVisibleCard();
          updateViews();
            updateWidthBlockView();
          $('.list-view-button').removeClass('active-view-button');
            processEventCards();
          $('.block-view-button').addClass('active-view-button');
            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() {
          // Conditional checks for transferring the active class from block to list buttons
            console.log("Block view button clicked.");
          if ($('.chronicle-list-button').hasClass('active-view-button')) {
            $('.list-sorting-buttons').hide(); // Hide list sorting buttons
              $('.chronicle-list-button').removeClass('active-view-button');
            $(".block-sorting-buttons").css('display', 'flex');
              $('.chronicle-block-button').addClass('active-view-button');
            $('.home-list-view').removeClass('home-list-view').addClass('home-block-view');
          } else if ($('.random-list-button').hasClass('active-view-button')) {
            $('.home-chronicle-list').removeClass('home-chronicle-list').addClass('home-chronicle-block');
              $('.random-list-button').removeClass('active-view-button');
            $('.chronicle-block-button, .random-block-button, .alphabetical-block-button').show();
              $('.random-block-button').addClass('active-view-button');
            $('.chronicle-list-button, .random-list-button, .alphabetical-list-button').hide();
          } else if ($('.alphabetical-list-button').hasClass('active-view-button')) {
            updateLastVisibleCard();
              $('.alphabetical-list-button').removeClass('active-view-button');
            updateWidthBlockView();
              $('.alphabetical-block-button').addClass('active-view-button');
            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
      // BLOCK VIEW SORTING BUTTONS
            if ($('.chronicle-list-button').hasClass('active-view-button')) {
      $('.chronicle-block-button').click(function() {
                $('.chronicle-list-button').removeClass('active-view-button');
          sortChronologically();
                $('.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
          updateLastVisibleCard();
        $('.chronicle-block-button').click(function() {
          updateWidthBlockView();
            sortChronologically();
          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();
          updateLastVisibleCard();
            updateWidthBlockView();
          updateWidthBlockView();
            processEventCards();
          processEventCards();
            updateViews();
          updateViews();
            updateCardEventBorders();
          $('.random-block-button').addClass('active-view-button');
            $('.chronicle-block-button').addClass('active-view-button');
          $('.chronicle-block-button').removeClass('active-view-button');
            $('.random-block-button').removeClass('active-view-button');
          $('.alphabetical-block-button').removeClass('active-view-button');
            $('.alphabetical-block-button').removeClass('active-view-button');
      });
        });
       
        $('.random-block-button').click(function() {
            randomizeCards('.list-container .card');


            updateLastVisibleCard();
      $('.alphabetical-block-button').click(function() {
            updateWidthBlockView();
          sortAlphabetically('.list-container .card');
            processEventCards();
            updateViews();
            updateCardEventBorders();
            $('.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() {
          updateLastVisibleCard();
            sortAlphabetically('.list-container .card');
          updateWidthBlockView();
          processEventCards();
          updateViews();
          $('.alphabetical-block-button').addClass('active-view-button');
          $('.chronicle-block-button').removeClass('active-view-button');
          $('.random-block-button').removeClass('active-view-button');
      });


            updateLastVisibleCard();
      // LIST VIEW SORTING BUTTONS
            updateWidthBlockView();
      $('.chronicle-list-button').click(function() {
            processEventCards();
          sortChronologically();
            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
          updateLastVisibleCard();
        $('.chronicle-list-button').click(function() {
          updateWidthBlockView();
            sortChronologically();
          processEventCards();
          updateViews();
          $('.chronicle-list-button').addClass('active-view-button');
          $('.random-list-button').removeClass('active-view-button');
          $('.alphabetical-list-button').removeClass('active-view-button');
      });


            updateLastVisibleCard();
      $('.random-list-button').click(function() {
            updateWidthBlockView();
          randomizeCards('.list-container .card');
            processEventCards();
            updateViews();
            updateCardEventBorders();
            $('.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() {
          updateLastVisibleCard();
            randomizeCards('.list-container .card');
          updateWidthBlockView();
          processEventCards();
          updateViews();
          $('.random-list-button').addClass('active-view-button');
          $('.chronicle-list-button').removeClass('active-view-button');
          $('.alphabetical-list-button').removeClass('active-view-button');
      });


            updateLastVisibleCard();
      $('.alphabetical-list-button').click(function() {
            updateWidthBlockView();
          sortAlphabetically('.list-container .card');
            processEventCards();
            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() {
          updateLastVisibleCard();
            sortAlphabetically('.list-container .card');
          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');


            updateLastVisibleCard();
      filtersDiv.toggleClass('is-visible');
            updateWidthBlockView();
            processEventCards();
            updateViews();
            updateCardEventBorders();
            $('.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]');
          resetButton.css('display', 'inline-block'); // Show the reset button
      } else {
          filtersDiv.slideUp(100, function() {
              $(this).css('display', 'none');
              // The filter reset code has been removed to keep the filters active
          });
          $(this).text('[FILTER]');
          resetButton.css('display', 'none'); // Hide the reset button when filters are not visible
      }


        if (filtersDiv.hasClass('is-visible')) {
      updateLastVisibleCard();
            filtersDiv.css('display', 'grid').hide().slideDown(100);
      updateWidthBlockView();
            $(this).text('[FILTER]');
      processEventCards();
            resetButton.css('display', 'inline-block'); // Show the reset button
      updateViews();
        } else {
  });
            filtersDiv.slideUp(100, function() {
                $(this).css('display', 'none');
                // The filter reset code has been removed to keep the filters active
            });
            $(this).text('[FILTER]');
            resetButton.css('display', 'none'); // Hide the reset button when filters are not visible
        }


        updateLastVisibleCard();
 
        updateWidthBlockView();
  // Specific Toggle for Filter Sections like TYPE, ENTITY, etc.
        processEventCards();
  $('.open-filter').click(function(event) {
        updateViews();
      event.stopPropagation();
        updateCardEventBorders();
    });


   
      var filterType = $(this).closest('.filter').data('filter');
    // Specific Toggle for Filter Sections like TYPE, ENTITY, etc.
      var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
    $('.open-filter').click(function(event) {
 
        event.stopPropagation();
      console.log('Filter type:', filterType, 'Card Selector:', cardSelector);
 
      $('#values-' + filterType).toggle();
 
      if ($('#values-' + filterType).is(':visible')) {
          $(this).addClass('active-filter');
      } else {
          $(this).removeClass('active-filter');
      }
 
      // Pass the determined card selector to the function
      updateLastVisibleCard(cardSelector);
      updateWidthBlockView(cardSelector);
      processEventCards(cardSelector);
      updateViews(cardSelector);
 
      console.log('Updated views and borders after filter toggle');
  });
 
  function filterCards() {
      var displayCountsHtml = '';
      var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
 
      $('.filter .values a[title]').each(function() {
          var anchor = $(this);
          var filterValue = anchor.attr('title').toLowerCase();
          var count = 0;
 
          if (anchor.find('button').hasClass('active')) {
              $(cardSelector).each(function() {
                  var card = $(this);
                  $('.filter').each(function() {
                      var filterType = $(this).data('filter');
                      var cardValue = card.find('.' + filterType).text().toLowerCase();
                      if (cardValue.indexOf(filterValue) !== -1) {
                          count++;
                      }
                  });
              });
 
              displayCountsHtml += '<span>[' + count + '] ' + filterValue + '</span> ';
          }
      });
 
      if (displayCountsHtml) {
          $('.count-filtered-cards').html(displayCountsHtml).show();
      } else {
          $('.count-filtered-cards').hide();
      }
 
      // Apply filtering and pass the determined card selector to the function
      applyFiltering(cardSelector);
 
      updateLastVisibleCard(cardSelector);
      updateWidthBlockView(cardSelector);
      processEventCards(cardSelector);
      updateViews(cardSelector);
 
      console.log('Filtering process complete, updated views and borders');
  }     
 
  function applyFiltering() {
      // Determine which card selector to use based on the elements present in the DOM
      var cardSelector = $('.card').length > 0 ? '.card' : '.community-card';
 
      // Apply the logic to the determined card type
      $(cardSelector).show().each(function() {
          var card = $(this);
          var hideCard = false;
 
          $('.filter').each(function() {
              if (hideCard) return;
 
              var filterType = $(this).data('filter');
              var activeFilters = $(this).find('.values a[title] button.active').map(function() {
                  return $(this).parent('a').attr('title').toLowerCase();
              }).get();
 
              if (activeFilters.length > 0) {
                  var cardValue = card.find('.' + filterType).text().toLowerCase();
                  var matchesFilter = activeFilters.some(function(filterValue) {
                      return cardValue.indexOf(filterValue) !== -1;
                  });
                  if (!matchesFilter) hideCard = true;
              }
          });
 
          if (hideCard) card.hide();
      });
  }   
 
  function updateLastVisibleCard() {
      // Target only the list view container for updating the last visible card
      $('.home-chronicle-list div.list-container div.card').removeClass('last-visible');
 
      // Find the last visible card within the list view and add the class
      var lastVisibleCard = $('.home-chronicle-list div.list-container div.card:visible:last');
      lastVisibleCard.addClass('last-visible');
  }


        var filterType = $(this).closest('.filter').data('filter');
  function updateWidthBlockView() {
        var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
      // Target only the block view container for updating the with of card
   
      $('.home-chronicle-block div.list-container').css('width', '100%');
        console.log('Filter type:', filterType, 'Card Selector:', cardSelector);
      $('.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)');
        $('#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);
        updateCardEventBorders(cardSelector);
   
        console.log('Updated views and borders after filter toggle');
    });
   
    function filterCards() {
        var displayCountsHtml = '';
        var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
   
        $('.filter .values a[title]').each(function() {
            var anchor = $(this);
            var filterValue = anchor.attr('title').toLowerCase();
            var count = 0;
   
            if (anchor.find('button').hasClass('active')) {
                $(cardSelector).each(function() {
                    var card = $(this);
                    $('.filter').each(function() {
                        var filterType = $(this).data('filter');
                        var cardValue = card.find('.' + filterType).text().toLowerCase();
                        if (cardValue.indexOf(filterValue) !== -1) {
                            count++;
                        }
                    });
                });
   
                displayCountsHtml += '<span>[' + count + '] ' + filterValue + '</span> ';
            }
        });
   
        if (displayCountsHtml) {
            $('.count-filtered-cards').html(displayCountsHtml).show();
        } else {
            $('.count-filtered-cards').hide();
        }
   
        // Apply filtering and pass the determined card selector to the function
        applyFiltering(cardSelector);
   
        updateLastVisibleCard(cardSelector);
        updateWidthBlockView(cardSelector);
        processEventCards(cardSelector);
        updateViews(cardSelector);
        updateCardEventBorders(cardSelector);
   
        console.log('Filtering process complete, updated views and borders');
    }     
   
    function applyFiltering() {
        // Determine which card selector to use based on the elements present in the DOM
        var cardSelector = $('.card').length > 0 ? '.card' : '.community-card';
   
        // Apply the logic to the determined card type
        $(cardSelector).show().each(function() {
            var card = $(this);
            var hideCard = false;
   
            $('.filter').each(function() {
                if (hideCard) return;
   
                var filterType = $(this).data('filter');
                var activeFilters = $(this).find('.values a[title] button.active').map(function() {
                    return $(this).parent('a').attr('title').toLowerCase();
                }).get();
   
                if (activeFilters.length > 0) {
                    var cardValue = card.find('.' + filterType).text().toLowerCase();
                    var matchesFilter = activeFilters.some(function(filterValue) {
                        return cardValue.indexOf(filterValue) !== -1;
                    });
                    if (!matchesFilter) hideCard = true;
                }
            });
   
            if (hideCard) card.hide();
        });
    }   
   
    function updateLastVisibleCard() {
        // Target only the list view container for updating the last visible card
        $('.home-chronicle-list div.list-container div.card').removeClass('last-visible');
   
        // Find the last visible card within the list view and add the class
        var lastVisibleCard = $('.home-chronicle-list div.list-container div.card:visible:last');
        lastVisibleCard.addClass('last-visible');
    }


    function updateWidthBlockView() {
  // Reset function
        // Target only the block view container for updating the with of card
  $('.reset-filter').click(function() {
        $('.home-chronicle-block div.list-container').css('width', '100%');
      // Remove 'active' class from all filter buttons
        $('.home-chronicle-block div.list-container div.card').css('width', 'calc(20% - 0px)');
      $('#filters .values button').removeClass('active');
        $('.home-chronicle-block div.list-container div.card:nth-child(5n + 1)').css('width', 'calc(20% + 4px)');
      $('.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();  


    // Reset function
      updateLastVisibleCard();
    $('.reset-filter').click(function() {
      updateWidthBlockView();
        // Remove 'active' class from all filter buttons
      processEventCards();
        $('#filters .values button').removeClass('active');
      updateViews();
        $('.open-filter').removeClass('active-filter');
  });
   
 
        // Show all cards that might have been hidden by the filters
  $('#filters .values button').click(function() {
        $('.card').show();
      console.log("Filter is clicked!!!");
   
      $(this).toggleClass('active');
        // Reset and hide the filter counts
      filterCards(); // Re-apply the filters based on the updated active buttons
        $('.count-filtered-cards').text('').hide();
   
        filterCards();  


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


        updateLastVisibleCard();
  $(window).on('scroll', function() {
        updateWidthBlockView();
      var filtersDiv = $('#filters');
        processEventCards();
      if (filtersDiv.hasClass('is-visible')) {
        updateViews();
          filtersDiv.removeClass('is-visible').slideUp(100, function() {
        updateCardEventBorders();
              $(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('');
  }


    $(window).on('scroll', function() {
   var images = []; // Initialize an empty array to store the images
        var filtersDiv = $('#filters');
  // Find all image containers within the article content and extract the necessary information
        if (filtersDiv.hasClass('is-visible')) {
  $('.article-images .image-container').each(function() {
            filtersDiv.removeClass('is-visible').slideUp(100, function() {
      var img = $(this).find('img');
                $(this).css('display', 'none');
      var captionDiv = $(this).find('div[class^="caption-image"]');
                // The filter reset code has been removed to keep the filters active
      var image = {
            });
          src: img.attr('src'),
            $('.general-toggle').text('[FILTER]'); // Update the toggle button text
          alt: img.attr('alt'),
        }
          caption: captionDiv.text(),
    });
          captionClass: captionDiv.attr('class')
   
      };
   
      images.push(image); // Add the image object to the images array
    // 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) {
  if (images.length > 0) {
        setupImageToggle(images); // Call the setupImageToggle function with the images array
      setupImageToggle(images); // Call the setupImageToggle function with the images array
        updateImageLabel(1, images.length); // Set the label for the first image immediately
      updateImageLabel(1, images.length); // Set the label for the first image immediately
    }
  }


    function setupImageToggle(images) {
  function setupImageToggle(images) {
        var currentIndex = 0;
      var currentIndex = 0;
        var enableNavigation = images.length > 1; // Enable navigation only if there is more than one image
      var enableNavigation = images.length > 1; // Enable navigation only if there is more than one image
   
 
        function showImage(index) {
      function showImage(index) {
            currentIndex = index;
          currentIndex = index;
            var image = images[currentIndex];
          var image = images[currentIndex];
            updateImageLabel(currentIndex + 1, images.length);
          updateImageLabel(currentIndex + 1, images.length);
            $('#article-content').find('.article-images').html(getImageHtml(image, currentIndex, images.length, enableNavigation));
          $('#article-content').find('.article-images').html(getImageHtml(image, currentIndex, images.length, enableNavigation));
        }
      }
   
 
        // Attach click handlers only if navigation is enabled
      // Attach click handlers only if navigation is enabled
        if (enableNavigation) {
      if (enableNavigation) {
            $('#article-content').on('click', '.next-arrow', function() {
          $('#article-content').on('click', '.next-arrow', function() {
                showImage((currentIndex + 1) % images.length);
              showImage((currentIndex + 1) % images.length);
            });
          });
   
 
            $('#article-content').on('click', '.prev-arrow', function() {
          $('#article-content').on('click', '.prev-arrow', function() {
                showImage((currentIndex - 1 + images.length) % images.length);
              showImage((currentIndex - 1 + images.length) % images.length);
            });
          });
        }
      }
   
 
        // Display the first image
      // Display the first image
        showImage(currentIndex);
      showImage(currentIndex);
    }       
  }       
         
       
   
 
    function getImageHtml(image, currentIndex, totalImages, enableNavigation) {
  function getImageHtml(image, currentIndex, totalImages, enableNavigation) {
        var imageLabel = (currentIndex + 1) + '/' + totalImages + ' IMAGES';
      var imageLabel = (currentIndex + 1) + '/' + totalImages + ' IMAGES';
   
 
        // Render navigation arrows based on the enableNavigation flag
      // Render navigation arrows based on the enableNavigation flag
        var navigationHtml = enableNavigation ?  
      var navigationHtml = enableNavigation ?  
            '<div class="prev-arrow"><</div><div class="next-arrow">></div>' : '';
          '<div class="prev-arrow"><</div><div class="next-arrow">></div>' : '';
   
 
        return '<div class="image-navigation">' +
      return '<div class="image-navigation">' +
                    '<p class="article-label-image">' + imageLabel + '</p>' +
                  '<p class="article-label-image">' + imageLabel + '</p>' +
                    '<div class="image-container">' +
                  '<div class="image-container">' +
                        '<div class="arrows-and-image">' +
                      '<div class="arrows-and-image">' +
                            navigationHtml +  
                          navigationHtml +  
                            '<img src="' + image.src + '" alt="' + image.alt + '">' +
                          '<img src="' + image.src + '" alt="' + image.alt + '">' +
                        '</div>' +
                      '</div>' +
                        '<div class="' + image.captionClass + '">' + image.caption + '</div>' +
                      '<div class="' + image.captionClass + '">' + image.caption + '</div>' +
                    '</div>' +
                  '</div>' +
                '</div>';
              '</div>';
    }
  }
   
 
    function updateImageLabel(currentIndex, totalImages) {
  function updateImageLabel(currentIndex, totalImages) {
        var imageLabel = currentIndex + '/' + totalImages + ' IMAGES';
      var imageLabel = currentIndex + '/' + totalImages + ' IMAGES';
        $('#article-content .article-label-image').text(imageLabel);
      $('#article-content .article-label-image').text(imageLabel);
    }
  }
   
 
    $('.caption-image1').each(function() {
  $('.caption-image1').each(function() {
        // Split the caption at each <br> tag and wrap each line in a span
      // Split the caption at each <br> tag and wrap each line in a span
        var htmlContent = $(this).html();
      var htmlContent = $(this).html();
        var lines = htmlContent.split('<br>');
      var lines = htmlContent.split('<br>');
        var wrappedLines = lines.map(function(line) {
      var wrappedLines = lines.map(function(line) {
            return '<span class="caption-line">' + line + '</span>';
          return '<span class="caption-line">' + line + '</span>';
        });
      });
        var newHtml = wrappedLines.join('<br>');
      var newHtml = wrappedLines.join('<br>');
        $(this).html(newHtml);
      $(this).html(newHtml);
    });
  });
   
 
    function setShowArticleRotationEffect() {
  function setShowArticleRotationEffect() {
        const offset = 20;
      const offset = 20;
        const showArticle = document.querySelector('#show-article');
      const showArticle = document.querySelector('#show-article');
        const h = showArticle.clientHeight;
      const h = showArticle.clientHeight;
        const theta = -Math.atan(offset/h);
      const theta = -Math.atan(offset/h);
        const a = Math.cos(theta);
      const a = Math.cos(theta);
        const b = Math.sin(theta);
      const b = Math.sin(theta);
        const c = -Math.sin(theta);
      const c = -Math.sin(theta);
        const d = Math.cos(theta);
      const d = Math.cos(theta);
        const showArticleBefore = document.querySelector('#show-article-before');
      const showArticleBefore = document.querySelector('#show-article-before');
        const transformValue = 'matrix('+a+','+b+','+c+','+d+',0,0)';
      const transformValue = 'matrix('+a+','+b+','+c+','+d+',0,0)';
        showArticleBefore.style.transform = transformValue;
      showArticleBefore.style.transform = transformValue;
    }
  }


    function openEvent(element, event) {
  function openEvent(element, event) {
        event.stopPropagation();
      event.stopPropagation();
        event.preventDefault();
      event.preventDefault();
   
 
        var url = $(element).find('.link a').attr('href');
      var url = $(element).find('.link a').attr('href');
        if (url) {
      if (url) {
            window.open(url, '_blank').focus();
          window.open(url, '_blank').focus();
        }
      }
    }
  }


    function openModal(cardElement, event) {
  function openModal(cardElement, event) {
        event.stopPropagation(); // Prevent the event from bubbling up
      event.stopPropagation(); // Prevent the event from bubbling up
        console.log("openModal function called.");
      console.log("openModal function called.");
        var isRelatedArticle = $(cardElement).hasClass('related-article');
      var isRelatedArticle = $(cardElement).hasClass('related-article');
        showArticleWrapper.css('display', 'block');
      showArticleWrapper.css('display', 'block');


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


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


            if (externalPdfURL) {
          if (externalPdfURL) {
                articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF]</a>';
              articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF]</a>';
            }
          }
            if (externalLinkURL) {
          if (externalLinkURL) {
                articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB]</a>';
              articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB]</a>';
            }
          }
            // Close the .link-pdf div
          // Close the .link-pdf div
            articleContentHtml += '</div>';
          articleContentHtml += '</div>';
            articleContentHtml += '</div>'; // Close the container div
          articleContentHtml += '</div>'; // Close the container div
   
 
            // Append type, entity, discipline, and subject details
          // Append type, entity, discipline, and subject details
            articleContentHtml += '<p class="article-type">' + typeHtml + '</p>' +
          articleContentHtml += '<p class="article-type">' + typeHtml + '</p>' +
            '<div class="article-metadata">' +
          '<div class="article-metadata">' +
                '<div class="article-metadata-column">' +
              '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Entity</p>' +
                  '<p class="article-metadata-label">Entity</p>' +
                    '<p class="article-metadata-value">' + entity + '</p>' +
                  '<p class="article-metadata-value">' + entity + '</p>' +
                '</div>' +
              '</div>' +
                '<div class="article-metadata-column">' +
              '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Discipline</p>' +
                  '<p class="article-metadata-label">Discipline</p>' +
                    '<p class="article-metadata-value">' + discipline + '</p>' +
                  '<p class="article-metadata-value">' + discipline + '</p>' +
                '</div>' +
              '</div>' +
                '<div class="article-metadata-column">' +
              '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Subject(s)</p>' +
                  '<p class="article-metadata-label">Subject(s)</p>' +
                    '<p class="article-metadata-value">' + subjectHtml + '</p>' +
                  '<p class="article-metadata-value">' + subjectHtml + '</p>' +
                '</div>' +
              '</div>' +
            '</div>';
          '</div>';


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


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


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


            // Create a div that will wrap the links
          // Create a div that will wrap the links
            articleContentHtml += '<div class="link-pdf">';
          articleContentHtml += '<div class="link-pdf">';
            if (externalPdfURL) {
          if (externalPdfURL) {
                articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF]</a>';
              articleContentHtml += '<a href="' + externalPdfURL + '" target="_blank" class="pdf-link-icon">[PDF]</a>';
            }
          }
            if (externalLinkURL) {
          if (externalLinkURL) {
                articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB]</a>';
              articleContentHtml += '<a href="' + externalLinkURL + '" target="_blank" class="external-link-icon">[WEB]</a>';
            }
          }
            // Close the .link-pdf div
          // Close the .link-pdf div
            articleContentHtml += '</div>';
          articleContentHtml += '</div>';
            articleContentHtml += '</div>'; // Close the new div
          articleContentHtml += '</div>'; // Close the new div
   
 
            // Append type, entity, discipline, and subject details
          // Append type, entity, discipline, and subject details
            articleContentHtml += '<p class="article-type">' + typeHtml + '</p>' +
          articleContentHtml += '<p class="article-type">' + typeHtml + '</p>' +
            '<div class="article-metadata">' +
          '<div class="article-metadata">' +
                '<div class="article-metadata-column">' +
              '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Entity</p>' +
                  '<p class="article-metadata-label">Entity</p>' +
                    '<p class="article-metadata-value">' + entity + '</p>' +
                  '<p class="article-metadata-value">' + entity + '</p>' +
                '</div>' +
              '</div>' +
                '<div class="article-metadata-column">' +
              '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Discipline</p>' +
                  '<p class="article-metadata-label">Discipline</p>' +
                    '<p class="article-metadata-value">' + discipline + '</p>' +
                  '<p class="article-metadata-value">' + discipline + '</p>' +
                '</div>' +
              '</div>' +
                '<div class="article-metadata-column">' +
              '<div class="article-metadata-column">' +
                    '<p class="article-metadata-label">Subject(s)</p>' +
                  '<p class="article-metadata-label">Subject(s)</p>' +
                    '<p class="article-metadata-value">' + subjectHtml + '</p>' +
                  '<p class="article-metadata-value">' + subjectHtml + '</p>' +
                '</div>' +
              '</div>' +
            '</div>';
          '</div>';
            // Add images if any
          // Add images if any
            if (cardImages.length > 0) {
          if (cardImages.length > 0) {
                var initialImage = cardImages[0]; // Use the first image initially
              var initialImage = cardImages[0]; // Use the first image initially
                var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
              var enableNavigation = cardImages.length > 1; // Enable navigation only if more than one image
                articleContentHtml +=
              articleContentHtml +=
                    '<div class="article-images">' +
                  '<div class="article-images">' +
                        getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
                      getImageHtml(initialImage, 0, cardImages.length, enableNavigation) +
                    '</div>';
                  '</div>';
            }
          }
            // Add non-image content (description, reflection, etc.)     
          // Add non-image content (description, reflection, etc.)     
            articleContentHtml +=  
          articleContentHtml +=  
            (description ? '<p class="article-label-description">Description</p>' +
          (description ? '<p class="article-label-description">Description</p>' +
            '<div class="article-description">' + formatParagraphs(description) + '</div>' : '') +
          '<div class="article-description">' + formatParagraphs(description) + '</div>' : '') +
            (reflection ? '<p class="article-label-reflection">Reflection</p>' +
          (reflection ? '<p class="article-label-reflection">Reflection</p>' +
            '<div class="article-reflection">' + formatParagraphs(reflection) + '</div>' : '') +
          '<div class="article-reflection">' + formatParagraphs(reflection) + '</div>' : '') +
            (externalReferenceHtml ? '<p class="article-label-external-reference">References</p>' +
          (externalReferenceHtml ? '<p class="article-label-external-reference">References</p>' +
            '<p class="article-external-reference">' + externalReferenceHtml + '</p>' : '') +
          '<p class="article-external-reference">' + externalReferenceHtml + '</p>' : '') +
            (quote ? '<p class="article-label-quote">Quote</p>' +
          (quote ? '<p class="article-label-quote">Quote</p>' +
            '<p class="article-quote">' + quote + '</p>' : '') +
          '<p class="article-quote">' + quote + '</p>' : '') +
            '<p class="article-label-modification-date">Added on</p>' +
          '<p class="article-label-modification-date">Added on</p>' +
            '<div class="article-modification-date">' + modificationDate + '</div>';
          '<div class="article-modification-date">' + modificationDate + '</div>';
   
 
            $('#article-content').html(articleContentHtml);
          $('#article-content').html(articleContentHtml);
            $('#related-articles').html(relatedArticlesHtml);
          $('#related-articles').html(relatedArticlesHtml);
   
 
            if (relatedArticlesHtml && relatedArticlesHtml.trim().length > 0) {
          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();
              $('#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
      // Check which view is active and set the width accordingly
        if ($('.home-chronicle-list').is(':visible')) {
      if ($('.home-chronicle-list').is(':visible')) {
            $('.home-list-view').each(function() {
          $('.home-list-view').each(function() {
                var currentWidth = $(this).width();  // Get the current width
              var currentWidth = $(this).width();  // Get the current width
                $(this).data('originalWidth', currentWidth); // Store the original width
              $(this).data('originalWidth', currentWidth); // Store the original width
                $(this).css('width', 'calc(60% - 2px)');
              $(this).css('width', 'calc(60% - 2px)');
            });     
          });     
           
         
            // Modify the .type elements within .home-chronicle-list
          // Modify the .type elements within .home-chronicle-list
            $('.home-chronicle-list .type').each(function() {
          $('.home-chronicle-list .type').each(function() {
                var currentLeft = $(this).css('left');  // Get the current left value
              var currentLeft = $(this).css('left');  // Get the current left value
                $(this).data('originalLeft', currentLeft); // Store the original left value
              $(this).data('originalLeft', currentLeft); // Store the original left value
                $(this).css('left', '85%');
              $(this).css('left', '85%');
            });
          });
        } else if ($('.home-chronicle-block').is(':visible')) {
      } else if ($('.home-chronicle-block').is(':visible')) {
            $('.home-chronicle-block div.list-container').each(function() {
          $('.home-chronicle-block div.list-container').each(function() {
                var currentWidth = $(this).width();  // Get the current width
              var currentWidth = $(this).width();  // Get the current width
                $(this).css('width', 'calc(60% - 0px)');  // Set the new width as 30% of 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() {
          $('.home-chronicle-block div.list-container div.card').each(function() {
                var currentWidth = $(this).width();  // Get the current width
              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
              $(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
      // Apply the fade-out effect to both #list and #list-list elements
        $('.list-container').addClass('fade-out');
      $('.list-container').addClass('fade-out');


    }
  }


    // closeModal function
  // closeModal function
    function closeModal() {
  function closeModal() {
        if ($('.home-chronicle-list').is(':visible')) {
      if ($('.home-chronicle-list').is(':visible')) {
            $('.home-list-view').css('width', '100%');
          $('.home-list-view').css('width', '100%');
            $('.home-chronicle-list div.list-container div.card div.type').css('left', '90%');
          $('.home-chronicle-list div.list-container div.card div.type').css('left', '90%');
        } else if ($('.home-chronicle-block').is(':visible')) {
      } else if ($('.home-chronicle-block').is(':visible')) {
            updateWidthBlockView();
          updateWidthBlockView();
        }
      }
        showArticleWrapper.hide();
      showArticleWrapper.hide();
    }
  }


    $('.card').on('click', function(event) {
  $('.card').on('click', function(event) {
        // Check if the click event is originating from a link within .people or .type, or any other specific area
      // 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) {
      if ($(event.target).closest('.people a, .type a').length) {
            // The click is inside a link; let the default behavior proceed without opening the modal
          // The click is inside a link; let the default behavior proceed without opening the modal
            return;
          return;
        }
      }
   
 
        // Prevent further event handling if the card has the 'event' class
      // Prevent further event handling if the card has the 'event' class
        if ($(this).hasClass('event')) {
      if ($(this).hasClass('event')) {
            event.stopImmediatePropagation();
          event.stopImmediatePropagation();
            openEvent(this, event);
          openEvent(this, event);
            $('.list-container').removeClass('fade-out');
          $('.list-container').removeClass('fade-out');
            closeModal();
          closeModal();
        } else {
      } else {
            // Handle cards without the 'event' class
          // Handle cards without the 'event' class
            openModal(this, event);
          openModal(this, event);
            setShowArticleRotationEffect();
          setShowArticleRotationEffect();
        }
      }
    });
  });


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


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


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


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


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


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


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


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


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


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


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


    document.querySelector('#submit').addEventListener('click', function(event) {
  document.querySelector('#submit').addEventListener('click', function(event) {
        event.preventDefault(); // Prevent the default link behavior
      event.preventDefault(); // Prevent the default link behavior


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


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


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

Revision as of 12:09, 25 June 2024

$(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);
          }
      });
  
      // Additional functionality for checking consecutive .card.event
      $('.home-chronicle-block div.list-container .card.event, .home-chronicle-list div.list-container .card.event').each(function() {
          checkConsecutiveEvents($(this));
      });
  }
  
  function checkConsecutiveEvents(element) {
      if (element.next().hasClass('card') && element.next().hasClass('event')) {
          console.log("multiple consecutive card events");
          $('.home-chronicle-list div.list-container div.card.event').removeClass('alone-card-event');
      } else {
          console.log("alone card events");
          $('.home-chronicle-list div.list-container div.card.event').addClass('alone-card-event');
      }
  }
    
  function processEventCards() {
      $('.card.event').each(function() {
          var existingContainer = $(this).find('.container-people-date');
  
          // If the container doesn't exist, create and append it
          if (existingContainer.length === 0) {
              existingContainer = $('<div class="container-people-date"></div>');
              $(this).append(existingContainer); // Temporarily append to ensure it's in the DOM
          }
  
          // Ensure the .people and .date elements are inside the container
          var people = $(this).find('.people').detach();
          var date = $(this).find('.date').detach();
          existingContainer.append(people).append(date);
  
          // Decide where to place the container
          if ($(this).closest('.home-chronicle-block').length) {
              // Check if it's already correctly placed, if not, move it
              if (!existingContainer.is($(this).find('.title').next())) {
                  $(this).find('.title').after(existingContainer);
              }
          } else if ($(this).closest('.home-chronicle-list').length) {
              // Check if it's already correctly placed, if not, move it
              if (!existingContainer.is($(this).find('.title').prev())) {
                  $(this).find('.title').before(existingContainer);
              }
          }
      });
  }

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

      // Initialization and Default Settings
      // 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() {
          console.log("List view button clicked.");
          $(".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]');
          resetButton.css('display', 'inline-block'); // Show the reset button
      } else {
          filtersDiv.slideUp(100, function() {
              $(this).css('display', 'none');
              // The filter reset code has been removed to keep the filters active
          });
          $(this).text('[FILTER]');
          resetButton.css('display', 'none'); // Hide the reset button when filters are not visible
      }

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

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

      var filterType = $(this).closest('.filter').data('filter');
      var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
  
      console.log('Filter type:', filterType, 'Card Selector:', cardSelector);
  
      $('#values-' + filterType).toggle();
  
      if ($('#values-' + filterType).is(':visible')) {
          $(this).addClass('active-filter');
      } else {
          $(this).removeClass('active-filter');
      }
  
      // Pass the determined card selector to the function
      updateLastVisibleCard(cardSelector);
      updateWidthBlockView(cardSelector);
      processEventCards(cardSelector);
      updateViews(cardSelector);
  
      console.log('Updated views and borders after filter toggle');
  });
  
  function filterCards() {
      var displayCountsHtml = '';
      var cardSelector = $('.card').length > 0 ? '.card' : '.community-card'; // Determine which card type is present
  
      $('.filter .values a[title]').each(function() {
          var anchor = $(this);
          var filterValue = anchor.attr('title').toLowerCase();
          var count = 0;
  
          if (anchor.find('button').hasClass('active')) {
              $(cardSelector).each(function() {
                  var card = $(this);
                  $('.filter').each(function() {
                      var filterType = $(this).data('filter');
                      var cardValue = card.find('.' + filterType).text().toLowerCase();
                      if (cardValue.indexOf(filterValue) !== -1) {
                          count++;
                      }
                  });
              });
  
              displayCountsHtml += '<span>[' + count + '] ' + filterValue + '</span> ';
          }
      });
  
      if (displayCountsHtml) {
          $('.count-filtered-cards').html(displayCountsHtml).show();
      } else {
          $('.count-filtered-cards').hide();
      }
  
      // Apply filtering and pass the determined card selector to the function
      applyFiltering(cardSelector);
  
      updateLastVisibleCard(cardSelector);
      updateWidthBlockView(cardSelector);
      processEventCards(cardSelector);
      updateViews(cardSelector);
  
      console.log('Filtering process complete, updated views and borders');
  }      
  
  function applyFiltering() {
      // Determine which card selector to use based on the elements present in the DOM
      var cardSelector = $('.card').length > 0 ? '.card' : '.community-card';
  
      // Apply the logic to the determined card type
      $(cardSelector).show().each(function() {
          var card = $(this);
          var hideCard = false;
  
          $('.filter').each(function() {
              if (hideCard) return;
  
              var filterType = $(this).data('filter');
              var activeFilters = $(this).find('.values a[title] button.active').map(function() {
                  return $(this).parent('a').attr('title').toLowerCase();
              }).get();
  
              if (activeFilters.length > 0) {
                  var cardValue = card.find('.' + filterType).text().toLowerCase();
                  var matchesFilter = activeFilters.some(function(filterValue) {
                      return cardValue.indexOf(filterValue) !== -1;
                  });
                  if (!matchesFilter) hideCard = true;
              }
          });
  
          if (hideCard) card.hide();
      });
  }    
  
  function updateLastVisibleCard() {
      // Target only the list view container for updating the last visible card
      $('.home-chronicle-list div.list-container div.card').removeClass('last-visible');
  
      // Find the last visible card within the list view and add the class
      var lastVisibleCard = $('.home-chronicle-list div.list-container div.card:visible:last');
      lastVisibleCard.addClass('last-visible');
  }

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

  // Reset function
  $('.reset-filter').click(function() {
      // Remove 'active' class from all filter buttons
      $('#filters .values button').removeClass('active');
      $('.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();
      updateWidthBlockView();
      processEventCards();
      updateViews();
  });
  
  $('#filters .values button').click(function() {
      console.log("Filter is clicked!!!");
      $(this).toggleClass('active');
      filterCards(); // Re-apply the filters based on the updated active buttons

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

  $(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(); // Prevent the event from bubbling up
      console.log("openModal function called.");
      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]</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 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]</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">' + 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() {
      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();
  });

  // Close modal with Close button
  $('#close-button').on('click', function () {
      $('.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();
              }
          });
      });
  }
  
  // NRS ENTRIES  ---------------------   SECTION //
  console.log("Document ready!"); // Check if document ready event is triggered
  
  if ($("#show-article-wrapper-entry").length) {
      console.log("Element with id 'show-article-wrapper-entry' found!"); // Check if the target element exists
      
      // Your existing formatParagraphs function
      function formatParagraphs(text) {
          var paragraphs = text.split('\n').filter(function (p) { return p.trim() !== '' });
          return paragraphs.map(function (p) { return '<p>' + p.trim() + '</p>'; }).join('');
      }

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

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

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

  document.querySelector('#submit').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;
  });
});