/*
 * Dynamic Table of Contents script
 * by Matt Whitlock <http://www.whitsoftdev.com/>
 */

function createLink(href, innerHTML) {
	var a = document.createElement("a");
	a.setAttribute("href", href);
	a.innerHTML = innerHTML;
	return a;
}

function generateTOC(toc) {

	if (toc != null) {

		var i2 = 0, i3 = 0, i4 = 0;
		baseDiv = document.getElementById('tocArea');
		
		var countH = 0;
		for (var i = 0; i < baseDiv.childNodes.length; ++i) {
			var node = baseDiv.childNodes[i];
			var tagName = node.nodeName.toLowerCase();
			if (tagName == "h2" || tagName == "h3" || tagName == "h4") {
				countH++;
			}
		}
		
		if (countH > 0) {
			
			var pippo = document.createElement("span");
			pippo.innerHTML = '<p>Sommario</p>';
			toc = toc.appendChild(pippo);		
			toc = toc.appendChild(document.createElement("ul"));
			
			//for (var i = 0; i < document.body.childNodes.length; ++i) {
			for (var i = 0; i < baseDiv.childNodes.length; ++i) {
				//var node = document.body.childNodes[i];
				var node = baseDiv.childNodes[i];
				var tagName = node.nodeName.toLowerCase();
				if (tagName == "h4") {
					++i4;
					if (i4 == 1) toc.lastChild.lastChild.lastChild.appendChild(document.createElement("ul"));
					var section = i2 + "." + i3 + "." + i4;
					//node.insertBefore(document.createTextNode(section + ". "), node.firstChild);
					node.id = "section" + section;
					toc.lastChild.lastChild.lastChild.lastChild.appendChild(document.createElement("li")).appendChild(createLink("#section" + section, node.innerHTML));
				}
				else if (tagName == "h3") {
					++i3, i4 = 0;
					if (i3 == 1) toc.lastChild.appendChild(document.createElement("ul"));
					var section = i2 + "." + i3;
					//node.insertBefore(document.createTextNode(section + ". "), node.firstChild);
					node.id = "section" + section;
					toc.lastChild.lastChild.appendChild(document.createElement("li")).appendChild(createLink("#section" + section, node.innerHTML));
				}
				else if (tagName == "h2") {
					++i2, i3 = 0, i4 = 0;
					var section = i2;
					//node.insertBefore(document.createTextNode(section + ". "), node.firstChild);
					node.id = "section" + section;
					toc.appendChild(h2item = document.createElement("li")).appendChild(createLink("#section" + section, node.innerHTML));
				}
			}
		}
	}
}