window.onload=init;

function init(){
	// loop through all elements that can possibly be toggled
	var theKids = document.body.getElementsByTagName('dt');
	// substitute whatever tag you're toggling if it's not a dt
	
	// loop through all of them
	for (var i=0; i<theKids.length; i++)
	{
		// does it have a class name?
		if (theKids[i].className)
		{
			// is it a closed toggle?
			if (theKids[i].className.match('toggle closed'))
			{
				// find the next sibling
				var nextSib = getNextSibling(theKids[i]);
				// apply (or add) hidden class
				if (!nextSib.className)
				{
					nextSib.className = 'hidden';
				}	
				else	
				{
					nextSib.className = nextSib.className + ' hidden';
				}
			}
		}
	}
	
	// wait for a click
	document.onmousedown = k;
}

// handle mousedown
function k(v)
{
	// find target element el
	var tg = (v) ? v : event;
	if (tg.target) 
	{
		var el = (tg.target.nodeType == 3) ? tg.target.parentNode : tg.target;
	} 
	else 
	{ 
		var el = tg.srcElement;
	}
	
	// is it a toggled element
	if (el.className.match('toggle')) 
	{
		// is it closed? Open it
		if (el.className.match(' closed')) 
		{
			// open it up
			el.className = el.className.replace(/ closed/gi, '');
			toggleSib(el);
		}
		else
		// it's open, so close it
		{
			el.className = el.className + ' closed';
			toggleSib(el);
		}
	}
}

// change visibility state of the next sibling of the element you just toggled
function toggleSib(el)
{
	var nextSib = getNextSibling(el);
	
	// is it hidden?
	if(nextSib.className.match('hidden'))
	{
		// yes: show it
		nextSib.className = nextSib.className.replace(/hidden/, '');
	}
	else
	{
		// no: hide it
		nextSib.className += ' hidden';
	}
}

// complicated due to Gecko -- suggestions to simply would be welcome
function getNextSibling(el)
{
	// in a perfect world, this would be all it would take
	var nextSib = el.nextSibling;
	
	// however ... there's this:
	if (nextSib.nodeType != 1)
	{
		// skip empty element in Gecko	
		nextSib = nextSib.nextSibling;
	}
	return nextSib;
}
