$(document).ready(function() {
		
	//hide ordered lists with .toc class (used if javascript doesn't load)
	$('.accordion .toc').hide();
	
	//convert headings to anchors; carry over ID and tagname to anchor's class; carry over ID to anchor's ID
	$('#accordion .header, .accordion .header').each(function() {
		var tag = (this.tagName).toLowerCase();
		$(this).replaceWith('<a id="' + $(this).attr('id') + '" class="header ' + tag + ' ' + $(this).attr('id') + '" href="#' + $(this).attr('id') + '">' + this.innerHTML + '</a>');
	});	
	
	
	//initialize accordions
	$('#accordion, .accordion').accordion({
		active: false,
		autoHeight: false,
		collapsible: true,
		header: '.header',
		icons: {'header': 'ui-icon-collapse', 'headerSelected': 'ui-icon-expand'},
		navigation: true,
		
		change : function(event, ui) {
			event.preventDefault();
			
			if(ui.newHeader.text()) {
				var href = getValidHash( ui.newHeader.attr('href') );
							
				if( href && (href != '#notice') && (href != '#na') ) {
					//alert('1: ' + href + '\n2: ' + ui.newHeader);
					$.scrollTo(ui.newHeader,{duration:500});
				}
			}
		}
	});
	
	//if page opens with hash, scroll to that position
	winHash = getValidHash( window.location.hash );
	//alert(winHash);
	if( (winHash) && (winHash != '#notice') && (winHash != '#na') ) {
		$.scrollTo(winHash, {duration:500});
	}
	
	//remember last clicked item
	$('#accordion .header, .accordion .header').click(function(event){
		event.preventDefault();
		
		if(window.location.hash == this.hash) {			
			window.location.hash = 'na';
		} else {
			window.location.hash = this.hash;
		}
	});
	
	
	//Enable crosslinking of accordion content panels
	$('.ui-accordion-content a[href^="#"]').click(function() {
														   
		var hrefClass = $(this).attr('href').replace('#','.');
		var acc = $($(this).parents('.ui-accordion').get(0));
		
		acc.accordion('activate', hrefClass );
	});

	
	//set top margin
	$('#accordion ul:first-child, .accordion ul:first-child').css('margin-top', 0);
	
});


//ensure just the hash portion of a url is returned, ex: "#hash"
function getValidHash(h) {
	//alert('1: ' + h + '\nSubstring (0,1): ' + h.substring(0,1) +'\nIndex of #: ' + h.indexOf('#') + '\nh.substring(0,1) != "#": ' + (h.substring(0,1) != '#') );
	if(h.substring(0,1) != '#') {
		if (h.indexOf('#') != -1) {
			h = h.substring(h.indexOf('#'));
		} else {
			h = null;
		}
	}
	//alert('2: ' + h);
	return h;
}



