//Generates a table of contents from a list of questions, keeping only the headings.
linknum = 0;

function genTOC(docroot) {
	if (!docroot.hasChildNodes())
		return null;
	
	var subheadings = docroot.childNodes;
	
	var toclist = document.createElement("ol");
	
	for (var sh_idx = 0; sh_idx < subheadings.length; sh_idx++) {
		if (subheadings[sh_idx].nodeName.toUpperCase() != "LI")
			continue;	//Only interested in list nodes.

		//Check for a header.
		var headertext = subheadings[sh_idx].firstChild;
		while (headertext != null && headertext.nodeName.toUpperCase().charAt(0) != 'H')
			headertext = headertext.nextSibling;

		if (headertext == null)
			continue;	//Skip anything without a proper header.

		//Put a sequentially-named anchor around the header text.
		var section_anchor = document.createElement("a");
		section_anchor.name = ++linknum;
		
		var headertextnode = headertext.firstChild;
		section_anchor.appendChild(headertextnode);
		headertext.appendChild(section_anchor);
				
		//Add this header to the list.
		var toclink = document.createElement("a");
		toclink.href = "#" + linknum;
		toclink.appendChild(document.createTextNode(headertextnode.data));
		
		//Create the individual list item (but don't add it quite yet).
		var tocitem = document.createElement("li");
		tocitem.appendChild(toclink);
		
		//Recursively check the next level of the list.
		var sublists = subheadings[sh_idx].getElementsByTagName("ul");
		for (var sl_idx = 0; sl_idx < sublists.length; sl_idx++)
			tocitem.appendChild(genTOC(sublists[sl_idx]));

		//Now add the final sublist to the TOC.
		toclist.appendChild(tocitem);
	}	
	
	return toclist;
}

//Embeds the TOC above the specified element.
function embedTOCBefore(targ) {
	var newtoc = genTOC(targ);
	if (newtoc != null) {
		newtoc.className = "TOC";
		targ.parentNode.insertBefore(newtoc, targ);
	}
}
