var container = null;
var list = null;
var panels = null;
var oldHash = null;
var baseTitle = document.title;

if (window.addEventListener) {
	window.addEventListener ('DOMContentLoaded', init, false);
	window.addEventListener ('load', init, false);
} else {
	window.attachEvent ('onload', init);
}

function init () {
	if (window.removeEventListener) {
		window.removeEventListener ('DOMContentLoaded', init, false);
		window.removeEventListener ('load', init, false);
	} else {
		window.detachEvent ('onload', init);
	}

	container = document.getElementById ('container');

	list = document.createElement ('ul');
	list.id = 'list';
	container.parentNode.insertBefore (list, container);

	panels = [];

	for (var i = 0; i < container.childNodes.length; i++) {
		var panel = container.childNodes [i];
		if (panel.nodeType != 1) {
			continue;
		}
		panels.push (panel);

		var h3 = panel.getElementsByTagName ('h3').item (0);
		var title = h3.textContent || h3.innerText;
		var hash = panel.id || title.replace (/['"]/g, '').replace (/[^a-z0-9]/gi, '_').toLowerCase ();
		panel.id = 'panel+' + hash;

		var listitem = document.createElement ('li');
		var link = document.createElement ('a');
		link.href = '#' + hash;
		link.appendChild (document.createTextNode (title));
		listitem.appendChild (link);
		list.appendChild (listitem);
	}

	setInterval (function () {
		if (location.hash != oldHash) {
			oldHash = location.hash;
			hashChange ();
		}
	}, 150);

	container.className = 'js_enabled';
	if (location.hash == '') {
		location.replace ('#' + container.children [0].id.substring (6));
	}
}

function hashChange () {
	for (var i = 0; i < panels.length; i++) {
		if (panels [i].id.substring (6) == location.hash.substring (1)) {
			panels [i].className = 'selected';
			list.childNodes [i].className = 'selected';
			list.childNodes [i].firstChild.blur ();
			document.title = baseTitle + ' - ' + (list.childNodes [i].textContent || list.childNodes [i].innerText);
		} else {
			panels [i].className = '';
			list.childNodes [i].className = '';
		}
	}
}
