/**
 * toc (Table of Contents) plugin for jQuery 1.3.0+
 * @author Scott Horlbeck <me@scotthorlbeck.com>
 * @version 0.1.0
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details:
 * http://www.gnu.org/copyleft/gpl.html
*/
(function($) {

jQuery.fn.toc = function(o) {

	o = jQuery.extend({
		"before"  : '', // jQuery selector for the element to add the TOC before.
		"after"   : '', // jQuery selector for the element to add the TOC after.
		"addHideShowToggle" : false, // this option doesn't work yet
		"defaultShow"   : true, // this option doesn't work yet
		"backToTopText" : '&uarr; Back to Top &uarr;',
		"cssBackToTop"  : 'backToTop'
	},o);
	
	// Construct the TOC.
	var toc = '<div id="toc"><strong>Table of Contents</strong><ol>';
	var prevHeadingLevel = 0;

	$(this).each(function(i) {
		var curHeadingLevel = $(this).attr('tagName').substr(1) - 0;
		
		if (prevHeadingLevel > 0 && curHeadingLevel < prevHeadingLevel) {
			for (var i = 0; i < (prevHeadingLevel - curHeadingLevel); i++) {
				toc += '</ol>';
			}
		} else if (prevHeadingLevel > 0 && curHeadingLevel > prevHeadingLevel) {
			toc += '<ol>';
		}
		
		toc += '<li><a href="#'+this.innerHTML+'">'+this.innerHTML+'</a></li>';
		
		prevHeadingLevel = curHeadingLevel;

		$(this).before('<a name="'+this.innerHTML+'"></a>')
			.append('<a href="#" class="'+o.cssBackToTop+'">'+o.backToTopText+'</a>');
	});
	toc += '</ol></div>';

	
	// Add the TOC either before or after a specified element, or just
	// return the TOC itself.
	if (o.before != '') {
		$(o.before).before(toc);
		return $;
	} else if (o.after != '') {
		$(o.after).after(toc);
		return $;
	} else {
		return toc;
	}

}

})(jQuery);