$(document).ready(function(){
	// Add .toggle to the dl, activating toggle-related styles
	$(".list dl").addClass("toggle");
	
	// Hide all the definitions (dd), leaving a simple list of terms (dt)
	$(".list dd").hide();
	
	// Open up the first definition (dd) in each definition list (dl) to get things rolling
	$(".list dl").find("dd:first").each(function(){
		toggle($(this), "closed", "slide");	
	});
		
	// Make the terms (dt) clickable, so that they can be used to hide/reveal their respective definitions (dd)
	$(".list dt").click(function(){
		var definition = $(this).next();
		if (definition.is(':visible')){
			toggle(definition, "open", "slide");
		} else {
			toggle(definition, "closed", "slide");
		}
	});
	
	// Add toggle controls to the top of each definition list
	$(".toggle").each(function(){
		var controls = document.createElement("p");
		controls.className = "toggle-controls";
		
		// Create Show All option
		var option = document.createElement("span");
		option.className = "show";
		option.appendChild(document.createTextNode("Show All"));
		controls.appendChild(option);
		
		// Create space between options
		controls.appendChild(document.createTextNode(" | "));				
		
		// Create Hide All option
		option = document.createElement("span");
		option.className = "hide";
		option.appendChild(document.createTextNode("Hide All"));
		controls.appendChild(option);		

		// Insert the toggle controls inside .list-content, 
		// before the list but after the list description (if there is one)		
		$(this).before(controls);
		
		// If there's no list description, remove the space 
		// between the list title and the toggle controls 
		if ($(this).parents(".list-content").children(".list-description").length < 1){			
		//	$(this).parents(".list").find(".list-content").css("paddingTop","3px");
		};		
	});	
		
	// Make the toggle controls clickable, so that they can be used to hide/reveal all definitions
	$(".toggle-controls .show").click(function(){
		var list = $(this).parents(".list-content").find("dd").each(function(){
			// $(this).show();
			toggle($(this), "closed");
		});
	});	
	$(".toggle-controls .hide").click(function(){
		var list = $(this).parents(".list-content").find("dd").each(function(){
			// $(this).hide();
			toggle($(this), "open");
		});
	});		
	
	
	function toggle(dd, status, transition) {	
		
		if (dd) {		
			// Set default mode of transition
			if (!transition) {
				transition = "";
			};
			
			if (status == "open") {
				// Is open, so close			
				if (transition == "slide") {			
					dd.slideUp();
				} else {
					dd.hide();					
				};
				// Update class on dt
				dd.prev("dt").removeClass("open");		
			} else {
				// Status is unknown or closed, so open
				if (transition == "slide") {			
					dd.slideDown();
				} else {
					dd.show();					
				};
				// Update class on dt
				dd.prev("dt").addClass("open");			
			};
		} else {
			// No object to act on
			return false;
		};
	};
});




