function ChapterCounter() {
	this.counters = new Array();
	this.counters.push(0);
}

ChapterCounter.prototype.inc = function() {
	++this.counters[this.counters.length - 1];
}

ChapterCounter.prototype.incLevel = function() {
	this.counters.push(0);
}

ChapterCounter.prototype.decLevel = function() {
	this.counters.pop();
}

ChapterCounter.prototype.toString = function() {
	var str = "";
	for (var i = 0; i < this.counters.length; ++i) {
		if (i > 0) str += ".";
		str += this.counters[i];
	}
	return str;
}

function autoTOC(elm, h_level_1, h_level_2, toc_list_elm, last_level, chap_cnt) {
	last_level = last_level || h_level_1;
	chap_cnt = chap_cnt || new ChapterCounter();

	for (var child = elm.firstChild; child; child = child.nextSibling) {
		if (child.nodeType != 1) continue;

		if (!child.nodeName.match(/^H[1-6]$/)) {
			autoTOC(child, h_level_1, h_level_2, toc_list_elm, last_level, chap_cnt);
			continue;
		}

		var lvl = parseInt(child.nodeName.charAt(1));
		if (lvl < h_level_1 || lvl > h_level_2) continue;

		if (lvl > last_level) {
			while (lvl != last_level) {
				var list = document.createElement("ol");
				if (!toc_list_elm.lastChild) {
					toc_list_elm.appendChild(document.createElement("li"));
				}
				toc_list_elm = toc_list_elm.lastChild.appendChild(list);
				chap_cnt.incLevel();
				++last_level;
			}
		} else {
			while (lvl != last_level) {
				toc_list_elm = toc_list_elm.parentNode.parentNode;
				chap_cnt.decLevel();
				--last_level;
			}
		}

		chap_cnt.inc();

		if (!child.id) {
			child.id = "autoTOC" + chap_cnt.toString();
		}
		child.insertBefore(document.createTextNode(chap_cnt.toString() + " "), child.firstChild);

		var a = document.createElement("a");
		a.href = "#" + child.id;
		for (var childchild = child.firstChild; childchild; childchild = childchild.nextSibling) {
			a.appendChild(childchild.cloneNode(true));
		}

		var li = document.createElement("li");
		li.appendChild(a);
		toc_list_elm.appendChild(li);
	}
}
