var _current_reference;

var _current_category;

$(document).ready(function() {

	$('#references-instructions').show();



	var toc = document.createElement('ul');

	$(toc).attr('id', 'references-toc');



	function select_reference() {

		$('#references-instructions').hide();

		if (_current_reference) {

			_current_reference.hide();

		}

		if (_current_category) {

			_current_category.hide();

		}

		if ($(this).attr('href').substr(0, 4) == '#ref') {

			_current_category = $('#cat' + $(this).attr('href').substr(4, $(this).attr('href').lastIndexOf('-') - 4)).show();

			_current_reference = $($(this).attr('href')).show();

		} else {

			_current_category = $($(this).attr('href')).show();

		}

		

	}

	

	$("#main-content .column .category").each(function (i) {

		var cat_id = 'cat-' + i;

		$(this).attr('id', cat_id);

	

		var references = document.createElement('ul');



		$('.reference', this).each(function (j) {

			var ref_id = 'ref-' + i + '-' + j;

			$(this).attr('id', ref_id);

			var ref_link = document.createElement('a');

			$(ref_link).html($("h3", this).html()).attr('href', '#' + ref_id).click(select_reference);

			var ref_list_item = document.createElement('li');

			ref_list_item.appendChild(ref_link);

			references.appendChild(ref_list_item);

		}).hide();

		

		var cat_link;

		if (references.childNodes && references.childNodes.length > 0) {

			cat_link = document.createElement('h2');

			$(cat_link).html($("h2", this).html());

		} else {

			cat_link = document.createElement('a');

			$(cat_link).attr('href', '#' + cat_id).html($("h2", this).html()).click(select_reference);



			var temp_link = document.createElement('h2');

			temp_link.appendChild(cat_link);

			cat_link = temp_link;

		}



		var cat_list_item = document.createElement('li');

		cat_list_item.appendChild(cat_link);

		cat_list_item.appendChild(references);

		toc.appendChild(cat_list_item);

	}).hide();





	$("#column-left .column").empty().append(toc);

});