﻿$(document).ready(function() {
    // Get an array of the event item elements
    var eventItems = $("#eventsList .eventItem");
    
    // Loop through the array of event item elements
    $.each(eventItems, function() {
        // Get the description element child for the currently looped event item
        var itemDesc = $($(this).find(".description")[0]);
        
        // Make sure the description is longer than 156 characters.
        if (itemDesc.html().length > 256) {
            // Insert the expanded description element
            var descriptionExp = itemDesc.after('<p class="descriptionExp">' + itemDesc.html() + '&nbsp;&nbsp;<a href="" class="readLess">[collapse description]</a></p>');
            
            // Find the next space character after the 255th character
            var lastWordPos = itemDesc.html().indexOf(" ", 255);
            
            // Set the description element to the first ~255 characters of the description
            itemDesc.html(itemDesc.html().substring(0, lastWordPos) + '...');
            
            // Hide the expanded description
            $(this).find(".descriptionExp").hide();
            
            // Add the read more link to the description
            itemDesc.append('&nbsp&nbsp;<a href="" class="readMore">[read more]</a>');
            
            // Get the read more link element
            var readMore = $(this).find(".readMore")[0];
            
            // Register the read more click event handler
            $(readMore).click(function() {
                var parentItem = $(this).parents(".eventItem")[0];
                $(parentItem).find(".description").hide();
                $(parentItem).find(".descriptionExp").show();
                return false;
            });
            
            // Get the read less link element
            var readLess = $(this).find(".readLess")[0];
            
            // Register the read less link element
            $(readLess).click(function() {
                var parentItem = $(this).parents(".eventItem")[0];
                $(parentItem).find(".description").show();
                $(parentItem).find(".descriptionExp").hide();
                return false;
            });
        }
    });
});
