// ==============================================================
// TOC generator, 01/07/2004 - 4h before speech at OFFF :)
// (c)2004 Sergi Meseguer (http://zigotica.com/)
// ==============================================================

var TOC = {
	// id of the node you want to insert the TOC before:
	insertbeforenode : "content",

	// ======================================================
	// DO NOT EDIT PAST THIS POINT.
	// ======================================================
	NODE_ELEMENT : 1,
	arrcounter : 0,
	counter : 0,
	contenedor : [], //{tagname, level, id, text} 
	
	// method modified from Simon Willison (encapsulated):
	addLoadEvent : function (fn) {
		var old = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = fn;
		}
		else {
			window.onload = function() {
			old();
			fn();
			}
		}
	},

	init : function() {
		var ALL = document.getElementById("content").getElementsByTagName("*");
		for (var k=0; k<ALL.length; k++) { 
			switch(ALL[k].nodeType) {
					case TOC.NODE_ELEMENT:
						if(ALL[k].tagName.toUpperCase()=="H2" 
						|| ALL[k].tagName.toUpperCase()=="H3" 
						|| ALL[k].tagName.toUpperCase()=="H4" 
						|| ALL[k].tagName.toUpperCase()=="H5" 
						|| ALL[k].tagName.toUpperCase()=="H6") {
							if(!ALL[k].id) {ALL[k].id = "toc" + TOC.counter;TOC.counter++}
							TOC.contenedor.push([ALL[k].tagName, ALL[k].tagName.substring(1,2), ALL[k].id, ALL[k].childNodes[0].nodeValue]);
						};
						break;
					default:
						alert("unknown nodetype: " + ALL[k].nodeType);
				}
		}
		//alert(TOC.contenedor)
		if(TOC.contenedor.length > 0) {
			var main = document.getElementsByTagName( 'body' ).item( 0 );
			var where = document.getElementById(TOC.insertbeforenode);
			var toc = document.createElement("div");
			toc.id = "TOC";
			
			toc.innerHTML = "<h2>Table of contents</h2>";
			
			var buffer = "<ul>";
			for (var i=0; i<TOC.contenedor.length; i++) { 
				if(i>0 && TOC.contenedor[i][1] < TOC.contenedor[i-1][1]) {
					var m = parseInt(TOC.contenedor[i][1]) + 1;
					for(var n=0;n<(TOC.contenedor[i-1][1]-TOC.contenedor[i][1]);n++) buffer += "</li></ul>";
					buffer += "<li>";
				}
				else if(i>0 && TOC.contenedor[i][1] > TOC.contenedor[i-1][1]) {
					buffer += "<ul><li>";
				}
				else if(i>0) {
					buffer += "</li><li>";
				}
				else {
					buffer += "<li>";
				}
				buffer += "<a href='#"+TOC.contenedor[i][2]+"'>"  + TOC.contenedor[i][3] + "</a>";
			}
			buffer += "</li></ul>";
			toc.innerHTML += buffer;
			document.body.insertBefore(toc,where);
		}
	}	

}

// adds 1 or more elements to an array (IE only)
// by Dave Schontzler, www.stilleye.com
if(!Array.prototype.push)
{
	Array.prototype.push =  function()
	{
		var i;
		for(i=0; j=arguments[i]; i++) this[this.length] = j;
		return this.length;
	}
}

if (document.getElementsByTagName) { 
	TOC.addLoadEvent(function(){TOC.init();}) 
}
