$(document).ready(function () {
	function readAnchor() {
		var c = location.href.split('#', 2);
		return c[1]; 
	}
	function writeAnchor(anchor) {
		var c = location.href.split('#', 2)[0];
		if (anchor) {
			location.href = c + '#' + anchor;
		} else {
			location.href = c + '#'; 
		}
	}
	
	var id_index = 0; 
	var currentSectionAnchor = null; 
	$(".section.navigatable").parent().each(function () {
		var $sections = $(this).find("> .section.navigatable")
		$sections.hide();
		var $firstSection = $($sections[0]); 
		var $nav = $('<ul class="contextual-nav"><'+'/ul>'); 
		$firstSection.before($nav); 
		
		$sections.each(function () {
			var id = $(this).attr('id'); 
			if (id == null || id == "") {
				do {
					id_index++; 
					id = "section"+id_index; 
				} while ($('#'+id).size() > 0); 
				$(this).attr("id", id); 
			}
			$nav.append('<li id="li_'+id+'"><div>'+$(this).find('> h3:first').text()+'</div><'+'/li>');
			$(this).find('> h3:first').hide();
			var $anchor = $(this).find('> h3:first a');
			$anchor.attr('anchor', $anchor.attr('name')); 
			$anchor.removeAttr('name'); 
			$('#li_'+id)[0].target = this; 
			$('#li_'+id)[0].anchor = $(this).find('> h3:first a').attr('anchor'); 
			this.target = $('#li_'+id)[0]; 
			$('#li_'+id).click(function () {
				this.target.select(); 
				writeAnchor(this.anchor); 
				currentSectionAnchor = this.anchor; 
				return false; 
			});
			this.select = function (propagated) {
				var $nav = $(this.target).parent(); 
				$nav.parent().find("> .section.navigatable:visible").hide(); 
				$nav.find("li.selected").removeClass("selected"); 
				$(this).show(); 
				$(this.target).addClass("selected"); 
				if (propagated != true) {
					/* 
						The following line helps IE refresh the content layout.
						The problem is that IE does not re-adjust line spacing 
						and word wrapping of a block with display: none.
						Fix: We reset the font after the block has been shown 
						(after diplay became block).
					*/
					$(this).css('font-size', '0.1em'); $(this).css('font-size', null);  
					$(this).parents(".section.navigatable").each(function () {
						this.select(true); 
					});
					$(this).find(".section.navigatable").parent().each(function () {
						$(this).find("> .section.navigatable")[0].select(true); 
					});
				}
			}
		});
		$firstSection.show();
		$nav.find('li:first').addClass("first").addClass("selected"); 
		$nav.find('li').css({ cursor: "pointer" });
	});
	(syncAnchors = function () {
		if (readAnchor() == currentSectionAnchor) return; 
		var target = $("a[anchor="+readAnchor()+"]"); 
		if (readAnchor() && target.size() > 0) {
			target.parents(".section.navigatable:first").each(function () { this.select(); });  
		} else {
			$(".section.navigatable:first").each(function () { this.select(); }); 
		}
		currentSectionAnchor = readAnchor();
	})(); 
	setInterval(syncAnchors, 332); 
}); 
