// Written by Matthew Blissett
// Released into the public domain.

function start() {
	// Find all ULs and hide them
	hideChildren(document.getElementById('nav'));
}

// Hides (by setting the CSS display to ‘none’) the given node’s
//  LI-children’s UL elements, adds onclick events to LI-children’s
//  A-elements to unhide.
function hideChildren(node) {
	var liElements, liChildElements, previousAElement;

	// Step through node’s LI elements
	liElements = node.firstChild;
	while (liElements != null) {
		if (liElements.nodeType == 1) { // Element node
			if (liElements.nodeName == 'LI') {

				// Look for ULs and As
				liChildElements = liElements.firstChild;
				while (liChildElements != null) {
					if (liChildElements.nodeType == 1) {

						if (liChildElements.nodeName == 'A') {
							// Store previous A element, it will be used to unhide
							previousAElement = liChildElements;

						} else if (liChildElements.nodeName == 'UL') {
							// Hide UL element
							liChildElements.style.display = 'none';
							//liElements.style.backgroundColor = 'red';

							//previousAElement.style.backgroundColor = '#ffddee';
							previousAElement.onclick = showChildren;
							previousAElement.menuOpen = false;
							previousAElement.className = 'menucontrol';
						}
					}

					if (liChildElements) {
						liChildElements = liChildElements.nextSibling;
					} else {
						liChildElements = null;
					}
				}
			}
		}
		if (liElements) {
			liElements = liElements.nextSibling;
		} else {
			liElements = null;
		}
	}
	return;
}

// Shows child UL elements, but hides the UL elements’ child LI-ULs
// (i.e. collapses submenus).
// If already show, hides again.
function showChildren(event) {
	var ulElement = this.nextSibling;

	while (ulElement != null) {
		if (ulElement.nodeType == 1) {
			if (ulElement.nodeName == 'UL') {
				if (this.menuOpen) {
					ulElement.style.display = 'none';
					ulElement.parentNode.className = '';
					this.className = 'menucontrol';
				} else {
					ulElement.style.display = 'block';
					ulElement.parentNode.className = 'menublockactive';
					this.className = 'menucontrolactive';
					hideChildren(ulElement);
				}
				this.menuOpen = !this.menuOpen;

				// Stop a link from being followed.
				return false;
			}
		}
		if (ulElement) {
			ulElement = ulElement.nextSibling;
		} else {
			ulElement = null;
		}
	}

	return false;
}

// kate: indent-mode normal; indent-width 1; space-indent off; tab-width 2; hl javascript;

