//Change top to the id of the parent element that contains all of the headers. Change toc to the idea o f the div you added to the page
//window.onload = function(){new tocGen('top','toc')};
//This script was written By Brady Mulhollem - WebTech101.com
function tocGen(id,writeTo,tocholder){
	this.id = id;
	this.num = 0;
	this.opened = 1;
	this.writeOut = '';
	this.previous = 1;
	if(document.getElementById){
		//current requirements;
		this.parentOb = document.getElementById(id);
		var headers = this.getHeaders(this.parentOb);
		if(headers.length > 4){
			//this.writeOut += '<ul>';
			var num;
			for(var i=0;i<headers.length;i++){
				num = headers[i].nodeName.substr(1);
				if(num > this.previous){
					//this.writeOut +="num:"+num + "this.previous:"+this.previous+"Opened:"+this.opened;
					for(var j=this.previous;j<num;j++){
						this.writeOut += '<ol>';
						this.opened++;
						if (j > num-1) {
							this.writeOut += '<li>';
						}
					}
					this.addLink(headers[i]);
				}
				else if(num < this.previous){
					//this.writeOut +="num:"+num + "this.previous:"+this.previous+"Opened:"+this.opened;
					//for(var j=0;j<this.opened;j++){
					for(var j=this.opened;j>num;j--){
						this.writeOut += '<\/li><\/ol>';//+"++j:"+j+" num:"+num+" previous:"+this.previous+" opened:"+this.opened;
						//this.writeOut += '<\/li><\/ul>';
						this.opened--;
					}
					this.addLink(headers[i]);
				}
				else{
					this.writeOut += '<\/li>';
					this.addLink(headers[i]);
				}
				this.previous = num;
			}
			for(var j=2;j<=this.opened;j++){
				this.writeOut += '<\/li><\/ol>';
			}
			document.getElementById(writeTo).innerHTML = this.writeOut;
			}else{
			//document.getElementById(tocholder).style.display = "none";
			
		}
	}
}
tocGen.prototype.addLink = function(ob){
	var id = this.getId(ob);
	var link = '<li><a href="#'+id+'">'+ob.innerHTML+'<\/a>';
	this.writeOut += link;
}
tocGen.prototype.getId = function(ob){
	if(!ob.id){
		ob.id = this.id+'toc'+this.num;
		this.num++;
	}
	return ob.id;
}
tocGen.prototype.getHeaders = function(parent){
	var return_array = new Array();
	var pat = new RegExp("H[1-6]");
	for(var i=0;i<parent.childNodes.length;i++){
		if(pat.test(parent.childNodes[i].nodeName)){
			return_array[return_array.length] = parent.childNodes[i];
		}
	}
	return return_array;
}


/* Display Function */

function toggleToc() {
	var toc = document.getElementById('toc').getElementsByTagName('ol')[0];
	var toggleLink = document.getElementById('togglelink');

	if (toc.style.display == 'none') {
		toc.style.display = 'block';
		document.getElementById('toclink').innerHTML = 'Hide';
		document.cookie = "hidetoc=0";
		
	} else {
		toc.style.display = 'none';
		document.getElementById('toclink').innerHTML = 'Show';
		document.cookie = "hidetoc=1";
	}
}