MediaWiki:Mobile.js: Difference between revisions

From softwear.directory
Jump to navigation Jump to search
m (1 revision imported)
No edit summary
Line 91: Line 91:


     // Intercept clicks on disabled links
     // Intercept clicks on disabled links
$(".header-authors-title a, .header-community a, .header-people a, .people a, .type a").click(function(event) {
$(".header-authors a, .header-community a, .header-people a, .people a, .type a").click(function(event) {
event.preventDefault(); // Prevent default action (following the link)
event.preventDefault(); // Prevent default action (following the link)
openCustomPopup();
openCustomPopup();

Revision as of 08:18, 15 July 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
    });

	// Select the divs and wrap them in a new div with class 'container-nav-links'
    $('.head-nav.head-col, .head-links.head-col').wrapAll('<div class="container-nav-links"></div>');
    
	// Detach the div with the class .header-date
    var detachedHeaderDate = $('.header-date').detach();

    // Append the detached .header-date div under the div with the id #header-container
    $('#header-container').append(detachedHeaderDate);
    
	// Find the div with the class .home-block-view
    var targetDiv = $('.home-block-view');

    // Create a new div with the message for mobile viewing and insert it before the target div
    var messageDiv = $('<div><p class="message-for-mobile">This directory is not mobile ready (yet). Please switch to desktop mode for a better viewing experience.</p></div>');
    targetDiv.before(messageDiv);

    // Create another new div for the latest 5 entries and insert it before the .home-block-view element
    var latestEntriesDiv = $('<div class="latest-5-entries"><p>Latest 5 added entries</p></div>');
    targetDiv.before(latestEntriesDiv);
	
	sortAndDisplayLastFiveCards();

	// Attach click event handler to the "View more entries" link
    $("#view-more-link").click(function() {
        // Open the custom popup
        openCustomPopup();
    });

	// Function to open the custom popup
	function openCustomPopup() {
		// Create custom popup HTML
		var popupHTML = '<div id="custom-popup">' +
						'<div class="popup-content">' +
						'<button id="close-popup">[ CLOSE ]</button>' +
						'<p>To view this content, please switch to desktop view!</p>' +
						'</div>' +
						'</div>';

		// Append custom popup to the body
		$("body").append(popupHTML);

		// Show custom popup
		$("#custom-popup").fadeIn();
        $("body").children().not("#custom-popup").addClass("fade-out-alert");
	}

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

		// Filter out cards with the 'event' class
		cards = cards.filter(function(card) {
			return !$(card).hasClass('event');
		});

		// Sort the remaining cards in descending order based on the .entry-number
		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
		});

		// Hide all cards initially
		$('.list-container .card').hide();

		// Append only the last 5 sorted cards (excluding .event cards) back to the container and show them
		var lastFiveCards = cards.slice(0, 5);
		$.each(lastFiveCards, function(index, item) {
			$(item).show(); // Ensure the card is visible
			$('.list-container').append(item); // Re-append the card to the container
		});

		// Insert the "View more entries >>" link after all the cards
		$('.list-container').after('<div id="view-more-footer"><div id="view-more-link">View more entries >></div></div>');
	}

	$('body').show(); // Only if you want to show some loading indicator

	$(".header-about a").contents().unwrap();

    // Intercept clicks on disabled links
	$(".header-authors a, .header-community a, .header-people a, .people a, .type a").click(function(event) {
		event.preventDefault(); // Prevent default action (following the link)
		openCustomPopup();
	});

	// Close custom popup when close button is clicked
	$("body").on("click", "#close-popup", function() {
		$("#custom-popup").fadeOut(function() {
			$(this).remove(); // Remove popup from DOM after fading out
		});
		$("body").children().removeClass("fade-out-alert"); // Remove fade-out class from elements except the popup
	});

    // Variable to keep track of whether .about-hide is visible
    var isAboutVisible = false;

    // Attach click event to toggle .about-hide
    $(".header-about").click(function(){
        // Toggle the visibility of .about-hide based on the current state
        if (isAboutVisible) {
            $(".about-hide").hide();
            isAboutVisible = false;
        } else {
            $(".about-hide").show();
            isAboutVisible = true;
        }
        
        // Toggle the underline class
        $(this).toggleClass('underline');
    });

	// 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>' +
                   navigationHtml +
                   '<div class="image-container">' +
                       '<img src="' + image.src + '" alt="' + image.alt + '">' +
                       '<div class="' + image.captionClass + '">' + image.caption + '</div>' +
                   '</div>' +
               '</div>';
    }
    
    function updateImageLabel(currentIndex, totalImages) {
        var imageLabel = currentIndex + '/' + totalImages + ' IMAGES';
        $('#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 openModal(cardElement, event) {
        event.stopPropagation(); // Prevent the event from bubbling up
        console.log("openModal function called.");
	    showArticleWrapper.css('display', 'block');

	    // Clear existing content in modal
	    $('#article-title').empty();
	    $('#article-content').empty();
	    
		// 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 subject = $(cardElement).find('.subject').text();
		var description = $(cardElement).find('.description').html();
		var reflection = $(cardElement).find('.reflection').html();
		var quote = $(cardElement).find('.quote').text();
		var externalReferenceHtml = $(cardElement).find('.external-reference').html();
		var modificationDate = $(cardElement).find('.modification-date').text();
		var relatedArticlesHtml = $(cardElement).find('.related-articles').html();

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

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

		$('#article-content').html(articleContentHtml);
		
	    // Apply the fade-out effect to both #list and #list-list elements
	    $('.list-container').addClass('fade-out');

    }

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

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