var text_next_clue = "Hint # of #";
var text_last_clue = "No hints anymore – close";

function childrenWithTag(el, tag) {    
	if (el == null) return null;
	
	var ch = el.childNodes;
	if (ch == null) return null;
	
	var ct = [];
	for (var i = 0; i < ch.length; i++) {
		if (ch[i].nodeType == 1 && ch[i].nodeName == tag) {
			ct.push(ch[i]);
		}
	}
	return ct;
}

function clueify_clue(li, ix, nx) {
	var tx = text_next_clue;
	tx = tx.replace("#", ix + 1);
	tx = tx.replace("#", nx);
	
	var ht = li.innerHTML;
	li.innerHTML = "<a href=\"#\">" 
		+ tx + "</a> <span class=\"hint\">" 
		+ ht + "</span>";
	li.firstChild.onclick = reveal;
		
	if (ix) li.style.display = "none";
}

function clueify_hint(ol) {
	var li = childrenWithTag(ol, "LI");

	for (var i = 0; i < li.length; i++) {
		clueify_clue(li[i], i, li.length);
	}

	var li = document.createElement("li");
	li.style.display = "none";
	li.innerHTML = "<a href=\"#\">" + text_last_clue + "</a>";
	li.firstChild.onclick = collapse;
	ol.appendChild(li);
	
}

function clueify(dl) {
	var dd = childrenWithTag(dl, "DD");
	
	for (var i = 0; i < dd.length; i++) {
		var ol = childrenWithTag(dd[i], "OL");
		
		for (var j = 0; j < ol.length; j++) {
			ol[j].style.listStyleType = "none";
			clueify_hint(ol[j]);
		}
	}
}

function reveal() {
	var sb = this.nextSibling;

	while (sb) {
		if (sb.nodeType == 1 && sb.nodeName == "SPAN") {
			sb.firstChild.style.color = "black";
			sb.style.display = "inline";
			break;
		}
		sb = sb.nextSibling;
	}
	
	this.style.display = "none";
	next_clue(this.parentNode);
	return false;
}

function next_clue(li) {
	li = li.nextSibling;
	
	while (li) {
		if (li.nodeType == 1 && li.nodeName == "LI") {
			li.style.display = "list-item";
			
			var aa = childrenWithTag(li, "A");                
			if (aa.length > 0) aa[0].focus();
			break;
		}
		li = li.nextSibling;
	}
	return false;
}

function collapse() {
	var li = this.parentNode;
	var ol = li.parentNode;
	var aa = null;
	
	li = childrenWithTag(ol, "LI");
	for (var i = 0; i < li.length; i++) {
		var sb = li[i].firstChild;
		
		while (sb) {
			if (sb.nodeName == "A") {
				sb.style.display = "inline";
				if (aa == null) aa = sb;
			}
			if (sb.nodeName == "SPAN") {
				sb.style.display = "none";
			}
			sb = sb.nextSibling;            
		}
		li[i].style.display = i ? "none" : "list-item";
	}
	
	if (aa) aa.focus();
	return false;
}
