/*---------------------------------------------------------------------------

	Title: Truncate List
	
	Author: Josh Minnich
	
	Version: 1.0
	
	Requires: jQuery 1.3.2
	
	Options:
	- expandedClass(string)
	- showCount(int)
	- targetContainer(string) jQuery selector string
	- targetList(string) jQuery selector string
	- toggleText(string)
	
	Callbacks: None
	
	Description: Truncate list makes it easy to truncate one or
	multiple HTML lists on a page.

---------------------------------------------------------------------------*/

(function($)
{
	$.fn.truncateList = function(options)
	{
		// Setting defaults
		var defaults = {
			expandedClass: 'expanded',
			showCount: 3,
			targetContainer: '.truncate-list-container',
			targetList: '.toggle-list',
			toggleText: 'See Fewer'
		};
		
		// Merging defaults with sent options
  		var options = $.extend(defaults, options);
  		
  		// Provide methods for every matched element
  		return this.each(function()
  		{
  			// Variables
  			var showCount = options.showCount - 1; // Convert human readable variable to 0 index based
  			
  			// Selector data variable stored on jQuery object
  			$(this).data('originalText', $(this).text());
  			$(this).data('listCollapsed', true);
  			
  			// Hide list items greater than sent count
			$(options.targetContainer).find(options.targetList + ' li:gt('+ showCount +')').hide();
			
			// Event listender
			$(this).click(function(event)
			{
				// Preventing link from following href
				event.preventDefault();
				
				// Toggle item count when user clicks button
				if($.browser.msie)
				{
					// Needed cause IE has trouble with toggling on the "gt" selector
					if($(this).data('listCollapsed') === true)
					{
						$(this).closest(options.targetContainer).find(options.targetList + ' li:gt('+ showCount +')').show();
					}
					else
					{
						$(this).closest(options.targetContainer).find(options.targetList + ' li:gt('+ showCount +')').hide();
					}
				}
				else
				{
				    $(this).closest(options.targetContainer).find(options.targetList + ' li:gt('+ showCount +')').slideToggle();
				}
				
				// Figure out list state (collapsed or expanded)
				if($(this).data('listCollapsed') === true) // Checking if any list items are hidden
				{
					$(this).addClass(options.expandedClass).text(options.toggleText);
					
					$(this).data('listCollapsed', false);
				}
				else
				{
					$(this).removeClass(options.expandedClass).text($(this).data('originalText'));
					
					$(this).data('listCollapsed', true);
				}
			});
  		});
	};
})(jQuery);
