/**
 * Collapsable list jquery plugin.
 *
 * @author rmariuzzo
 * @version 1.0b
 */
$(function() {

	$.fn.makeCollapsableList = function(o) {
	
		// Default values.
		var defaults = {
			hideChilds: true,
			headerClass: undefined,
			headerSelector: ':first(a)',
			headerExpandedClass: undefined
		}
		
		o = $.extend(defaults, o)
		
		// Plugin function.
		return this.each(function() {
			var $this = $(this);
			// Select all list like headers, usually is a 'li' element 
			// containing an 'ul' element.
			$this.find('li:has(ul)').each(function() {
				var $list = $(this);
				var $header = $list.find(o.headerSelector);
				var $childs;
				// Apply header class?
				if (o.headerClass) {
					$header.addClass(o.headerClass);
				}
				// Bind click event for 'each' header's'
				$header.each(function() {
					$(this).bind('click', {
						header: $list
					}, function(event) {
						$parentHeader = event.data.header;
						// Get direct childs.
						$childs = $parentHeader.find('> ul > li');
						$childs.toggle();
						// Toggle the header class.
						if (o.headerExpandedClass) {
							if ($childs.is(':hidden')) {
								$(this).removeClass(o.headerExpandedClass);
							}
							else {
								$(this).addClass(o.headerExpandedClass);
							}
						}
						// Is the header an anchor link?
						if ($header.is('a')) {
							// Prevent default action for anchor links.
							return false;
						}
					});
				});
				// Hide all childs?
				if (o.hideChilds) {
					$list.each(function() {
						$(this).find('ul li').hide();
					});
				}
				else if (o.headerExpandedClass) {
					$this.find('li:has(ul)').each(function() {
						$(this).find(o.headerSelector).addClass(o.headerExpandedClass);
					});
				}
			});
			// Custom functions.
			/**
			 * Collapse all childs.
			 */
			$this.bind('collapseAll', function() {
				$(this).find('li:has(ul) ul li').hide();
			});
			/**
			 * Expand all childs
			 */
			$this.bind('expandAll', function() {
				$(this).find('li:has(ul) ul li').show();
			});
		});
		
	}
	
});

