/*
 * jCollapsableMenu 0.1 - Collapsable Menu jQuery
 *
 * Copyright (c) 2009 jQuery HowTo
 *
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * URL:
 *   http://jquery-howto.blogspot.com
 *
 * Author URL:
 *   http://theled.co.uk
 *
 */

(function($j){
	$j.fn.extend({
		jCollapsableMenu : function(){
			if (this != '') {
				this.children().each(function(index) {
					if ($j(this).has('ul').length > 0) {
						$j(this).addClass('hasChildren');
						$j(this).find('a:first').prepend('<span></span>');
						
						// This works if the top level item is selected
						if ($j(this).hasClass('current'))
							$j(this).find('span').addClass('open');
							
						// Check if it's a subnode that is selected
						var selectedChild = $j(this).find('.current');
						if (selectedChild.length > 0) {
							$j(selectedChild.parent().parent().addClass('open'));
							$j(selectedChild.parent().prev().children().addClass('open'));
						}
						
						$j(this).find('span').click(function(){
							if ($j(this).hasClass('open')) {
								$j(this).removeClass('open');
								$j(this).parent().parent().removeClass('open');
								$j(this).parent().parent().removeClass('current');
								
							}
							else {
								$j(this).addClass('open');
								$j(this).parent().parent().addClass('open');
							}
							return false;
						});
					}
				});
			} 
		}
	});
})(jQuery);

