function createTOC() {

	// Create the list, that'll contain the TOC
	var toc = $('<ul />');

	// Initiate the heading level
	var tocLevel = 1;
	// This will hold the toc item that had been added in the loop before
	var lastItem;
	// This will be set to true if the TOC-creation loop encountered problems
	// and thus it will prevent the insertion of the TOC
	var aborted = false;

	// Get all heading elements within content and loop over them
	$('#contentFrame > h1, #contentFrame > h2, #contentFrame > h3, #contentFrame > h4, #contentFrame > h5, #contentFrame > h6').each(function(i, el) {
		// Generate an id for the link target in the heading
		var id = 'autoTOCId-' + i;
		var el = $(el);

		// The text to appear in the TOC item for the current heading
		var text = el.html();
		text = text.replace(/<[^>]+>/g, '');

		// Construct the link target
		el.prepend('<a id="' + id + '" name="' + id + '" />');

		// Read which heading level the current heading has
		var currentLevel = parseInt((el.attr('tagName')).substr(1));
		// Check if you should increase the level (i.e. indent the TOC-item)
		if (currentLevel > tocLevel) {
			// If the level differs from the previous by more than one the TOC
			// cannot be created.
			if (currentLevel > tocLevel + 1) {
				aborted = true;
				return false;
			}
			// Build the new - inner - level of the TOC
			toc = $('<ul />').appendTo(lastItem);
			// Remember that you increased the TOC-level
			tocLevel++;
		}
		// Check if you should decrease the level (i.e. outdent the TOC-item)
		if (currentLevel < tocLevel) {
			toc = toc.parent().parent();
			tocLevel--;
		}
		// Insert a link for the current heading into the TOC
		lastItem = $('<li />');
		lastItem.append($('<a class="tocItem" href="#' + id + '">' + text + '</a>'));
		toc.append(lastItem);

		return true;
	});
	
	if (!aborted) {
		// Outdent until you're at level 1 again
		while (tocLevel > 1) {
			toc = toc.parent().parent();
			tocLevel--;
		}
		// Insert the list in the TOC frame
		toc = $('#tableOfContents').append(toc);
		$('#tableOfContents h1').toggle(
			function () {
				$('#tableOfContents ul').slideUp('slow');
				$('#tableOfContents span.openCloseToggle').html('[+]');
			},
			function () {
				$('#tableOfContents ul').slideDown('slow');
				$('#tableOfContents span.openCloseToggle').html('[&minus;]');
			}
		);
	}
}

$(document).ready(createTOC);

