addLoadEvent(function () {
	findAccordionsInDom();
});

function accordion(dl) {

	// Grab its dt and dd children nodes
	var dts = dl.getElementsByTagName('dt');
	var dds = dl.getElementsByTagName('dd');

	// Empty variable to be used as a reference to the expanded dt
	var expandedDt;

	// Loop through all dts in the accordion
	for (var i = 0; i < dts.length; i++) {

		// Store the dt index as a property of the node
		dts[i].i = i;

		// If the dt has an "expanded" class, or is being linked to as a page anchor,
		// store a reference to it as expanded, then remove "expanded" class
		if (hasClass(dts[i], 'expanded')) {
			expandedDt = dts[i];
			removeClass(dts[i], 'expanded');
		}

		// Else, hide dt and dd
		else {
			addClass(dts[i], 'contracted');
			addClass(dds[i], 'contracted');
		}

		// When a dt is moused over, add "hover" class, or "expandedHover" if it's expanded
		dts[i].onmouseover = function () {
			addClass(this, (this === expandedDt) ? 'expandedHover' : 'hover');
		}

		// When a dt is moused off of, remove "hover" or "expandedHover" class		
		dts[i].onmouseout = function () {
			removeClass(this, 'hover');
			removeClass(this, 'expandedHover');
		}

		// When a dt is clicked...
		dts[i].onclick = function () {

			// Ensure, if it has a "hover" class, that it be changed to "expandedHover"
			replaceClass(this, 'hover', 'expandedHover');

			// Contract all dts and dds
			for (var i = 0; i < dts.length; i++) {
				addClass(dts[i], 'contracted');
				addClass(dds[i], 'contracted');
			}

			// If this is a new selection
			if (this !== expandedDt) {

				// Store a reference to the selected dt, expand it and its dd
				expandedDt = this;
				removeClass(expandedDt, 'contracted');
				removeClass(dds[expandedDt.i], 'contracted');
			}

			// If the dt has been clicked on again, remove the reference to it as the selected dt
			else {
					expandedDt = null;
			}
		}
	}
}

function findAccordionsInDom() {
	var dls = document.getElementsByTagName('dl');	

	// Loop through all dl elements
	for (var j = 0; j < dls.length; j++) {

		// If the dl has a class of "accordion"
		if (hasClass(dls[j], 'accordion')) {
		
			// Prepare accordion
			accordion(dls[j]);
		}
	}
}