var makeSommaire = function() {
	var makeNode = function(container, sections) {
		var ul = document.createElement('ul');
		var level = parseInt(sections[0].tagName.charAt(1));
		
		while(sections.length > 0) {
			section = sections.shift();

			var li = document.createElement('li');
			var link = document.createElement('a');
			link.href = '#lien-'+linkNo;
			link.innerHTML = section.innerHTML;
			
			var nextm;
			for(var m = link.firstChild; m != null; m = nextm) {
				nextm = m.nextSibling;
				if(m.nodeType != 1) continue;
				if(m.tagName != 'A') continue;
				link.removeChild(m);
			}
			
			li.appendChild(link);
			
			var anchor = document.createElement('a');
			anchor.name = 'lien-'+linkNo;
			anchor.id = 'lien-'+linkNo;
			section.parentNode.insertBefore(anchor, section);
			
			linkNo++;
			
			var innerSections = new Array();
			while(sections.length > 0) {
				futureLevel = parseInt(sections[0].tagName.charAt(1));

				if(futureLevel > level) {
					innerSections.push(sections.shift());
				} else {
					break;
				}
			}

			if(innerSections.length > 0) {
				makeNode(li, innerSections);
			}

			ul.appendChild(li);
		}

		container.appendChild(ul);
	}
	
	var findSections = function(n, sects) {
		for(var m = n.firstChild; m != null; m = m.nextSibling) {
			if(m.nodeType != 1) continue;
			if(m == container) continue;
			if(m.tagName == 'P') continue;
			
			if(m.tagName.length == 2 && m.tagName.charAt(0) == 'H' && m.tagName != 'HR') {
				sects.push(m);
			}
			else findSections(m, sects);
		}
	}

	var container = $('nav-article');
	if(!container) return;

	var linkNo = 0;
	
	var sections = [];
	findSections($('article'), sections);
	
	if(sections.length > 0) {
		var anchor = document.createElement('a');
		anchor.name = 'lien-sommaire';
		anchor.id = 'lien-sommaire';
		container.parentNode.insertBefore(anchor, container);
	
		makeNode(container.down('div.to-toggle'), sections);
		container.show();

	} else {
		container.parentNode.removeChild(container);
	}
}

makeSommaire.backLinkText = 'Retour';

if(window.addEventListener) window.addEventListener('load', makeSommaire, false);
else if(window.attachEvent) window.attachEvent('onload', makeSommaire);

