var speed = 550;

$(document).ready(function() {
	//Find all accordions on the page and add the code to them
	$(".ui-accordion-container").each(function(i) {
		addHandlers(this);
	});
	
	//If there's an element containing accordion instructions make it visible
	if (document.getElementById('accordionInstructions')) {
		document.getElementById('accordionInstructions').style.display = 'inline';	
	}	
 });

function addHandlers(object) {
	var open = $(object).children(".open");	
	var className = $(object).attr("class");		
	var selection;	
	
	/*Define what will be left open
		if the ul has a class containing closed, open nothing
		if there's at least 1 li with a class of open, open it (only the first if more than one)
		otherwise, open the first li*/		
	if (className.indexOf(' closed') != -1 || className.indexOf('closed ') != -1) {
		selection = '';
	} else if (open.length != 0) {
		selection = ':not(.open:first)';			
	} else {
		selection = ':not(:first)';		
	}
	
	//Hide all li's not specified above
	$(object).children(selection).find("div").each(function(i) {
		$(this).hide();	
	});
	
	//Attach event handlers to each link (heading)
	$(object).find("a").each(function(i) {
		if ( !$(this).parent().parent().hasClass('ui-accordion-container') ) {
			return;
		}
		$(this).bind("click", function() {return false;});
		$(this).click(function () { //When the link is clicked:			
			hideAll(object); //Hide all li's
			$(this).siblings().show(speed); //Show the link's sibling (the div)
		});
	});
		
}

function hideAll(object) {	
	$(object).children().find("div").each(function(i) {      	
		$(this).hide(speed);
	}); 
}