// 
/**
 * jQuery.makeIndex
 * Copyright (c) 2009 Allison Richmond - arichmond79@gmail.com - allisonrichmond.com
// Dual licensed under MIT and GPL.
 * Date: 6/12/2009
 *
 * @projectDescription Creates an index of an ordered or unordered list
 * @projectURI
 * @author Allison Richmond
 * @version 1.0
 *
 * @id jQuery.fn.makeIndex
 * @param {Object} 
 * @return {jQuery} Outputs an index outside of the original list; adds "Top" links to each item in original list.
 *
 * @example $('ul.list').makeIndex();
 *
 * @example $('ul.list').makeIndex({ after:TRUE, before:FALSE, duration:400, topLink: FALSE });
 *
 * Notes:
 *	- Requires jquery.scrollTo.js
 **/
(function($){
$.fn.makeIndex = function(options) {
	
	var defaults = {
		header:		false,		// The Header used for indexing each section // if not specified, the first <h#> is used
		before:		true,		// Add index before LIST
		after:		false,		// Add index after LIST
		highlight:	'hilite',	// classname to give highlighted LI
		topLink:	true,		// adds like to the top of page
		scrollTo:	true,		// Use jquery.scrollTo for pretty scrolling
			duration:	300,	// How long to animate on click	// irrelevant if scrollTo = FALSE
			easing:		'swing'	// Easing for scrollTo animation// irrelevant if scrollTo = FALSE
	};
	var options = $.extend(defaults, options);
	
	// used for scrolling back to top
	bodd = $('body').attr('id');
	topp = (bodd) ? bodd : $('body').children('*[id]').eq(0).attr('id');
	// if BODY has an ID : otherwise use first DIV's ID
	
	var list = '<ol class="index">';
	
	$(this).children('li').each(function(x){
		var hText = $(this).find(options.header).text();
		hText = (hText!='') ? hText : $(this).children('h1,h2,h3,h4').eq(0).text();
		i = x+1;
		$(this).attr('id','section_'+i).addClass('indexed');
		if (options.topLink) $(this).append('<a href="#'+topp+ '" class="top-link" id="top-link_'+i+'">&uarr; Top</a>');
		list += '<li><a href="#section_'+i+'" class="index-link">';
		list += hText +'</a></li>';
	});

	list += '</ol>';
	
	if (options.before) $(this).before(list);
	if (options.after)  $(this).after(list);
	
	// END make index list
	
	thiss = $(this); //		
	thiss.css({ listStyleType:'decimal', color:'#888' });
	
	var gotoSection = function () {
		thisHash = (this.hash) ? this.hash : "#" + $(this).parent().attr('id');
		
		durr = options.duration * 2;
		if (this.hash) { // if it's a link, and has further to go
			idx = thisHash.split('_')[1];
			id2 = $(this).attr('id').split('_')[1];
			idx = (idx) ? parseInt(idx)+1 : parseInt(id2)+1;
			durr *= (idx + 2)/4;
		} // adjust the duration for the scroll
		
		if (options.scrollTo) $.scrollTo(thisHash, durr, { easing: options.easing });
		thiss.find('li').removeClass(options.highlight);
		$(thisHash).not('#'+topp).addClass(options.highlight);
		if (options.scrollTo) return false;
	};
	
	$('a.index-link, a.top-link').add( thiss.children('li').children('h1,h2,h3,h4') ).bind('click',gotoSection);
	
};
})(jQuery);