$(document).ready(function()
{
	$('a.accordion').filter(function()
		{
			$($(this).attr('href')).filter(':not(.open)').css({visibility: 'hidden', height: 0}).addClass('closed');
			return true;
		});
	
	// Manage accordion items.
	var accordionLinks = $('a.accordion').filter(function()
		{
			return $(this).attr('href').indexOf('#subcategories_') != -1;
		});
	$(accordionLinks).click(function(e)
	{
		e.preventDefault();
	
		var targetElement = $($(this).attr('href'));
		//targetElement.stop();
		
		var fromHeight, toHeight;
		if(targetElement.hasClass('closed'))
		{
			// Get context.
			var parents = $(this).parents('div.accordion');
			
			// Close other accordion objects.
			var openTrigger = $(parents).children('a.accordion.current');
			var openElement = $(parents).children('div.accordion:not(.closed)');
			closeAccordion(openTrigger, openElement);
			
			// Opening animation.
			toHeight   = targetElement.height('auto').height();
			fromHeight = 0;
			targetElement.css('visibility', 'visible');
			
			targetElement.removeClass('closed');
			targetElement.height(fromHeight);
			targetElement.animate({height: toHeight}, 180);
			
			// Traverse up the heirarchy and apply the height.
			$(parents).filter(function()
				{
					$(this).animate({height: $(this).height() + toHeight}, 180);
					return true;
				});
			
			// Trigger change.
			$(this).addClass('current');
		}
		else
		{
			closeAccordion(this, targetElement);
		}
	});
});

function closeAccordion(trigger, element)
{
	// Closing animation.
	toHeight   = 0;
	fromHeight = element.height('auto').height();
	
	element.addClass('closed');
	element.height(fromHeight);
	element.animate({height: toHeight}, 180, function(){$(this).css('visibility', 'hidden');});
	
	// Traverse up the heirarchy and apply the height.
	var parents = $(trigger).parents('div.accordion');
	$(parents).filter(function()
		{
			$(this).animate({height: $(this).height() - fromHeight}, 180);
			return true;
		});
	
	// Trigger change.
	$(trigger).removeClass('current');
}