/*
	Footnote
	--------
	A simple resource for creating inline footnotes. Wrap any text in a <span class="footnote"></span> block to create
	a footnote on the containing element. By default the containing element is the closest parent DIV block to the new
	footnote. A superscript label will be inserted, and a footnote block created on the containing element. Numbering
	for footnotes is page global.
	
	By default the Footnote script will automatically scan the document and create footnotes after the page has finished
	loading. To turn off this mechanism, include the '?auto=false' parameter in the script tag:
		<script src="footnote.js?auto=false" type="text/javascript"></script>
		
	It is then up to you to call the 'footnote' method, with any parameters you need to create the footnotes.
*/

// find our script tag and figure out if we're going to auto-footnote the document
var scripts = document.getElementsByTagName('script');
var auto_footnote = true;
$A(scripts).each(
	function (scr) {
		if (scr.src.indexOf("footnote.js") > -1) {
			var p = scr.src.toQueryParams();
			
			if (p.auto == 'false' || p.auto == false) {
				auto_footnote = false;
			}
		}
	}
);

if (auto_footnote) {
	document.observe('dom:loaded', footnote);
}

function footnote(args) {
	
	var opts = {
		'footnoteClass': 'footnoteWrapper',
		'contentTag': 'div'
	};
	Object.extend(opts, args || {});
	
	var notesToBe = $$('.footnote');
	var parents = $H();
	var noteIndex = 1;
	
	notesToBe.each(
		function (noteToBe) {
			
			// get the element parent
			var parent = noteToBe.up(opts.contentTag);
			
			// see if we've already id'd this element
			var pID = parent.identify();
			
			var pNode = null;
			if (parents.get(pID) == undefined) {
				// create the element
				var pNode = new Element('div',
					{
						'class': opts.footnoteClass,
						'id': pID + '_footnote'
					}
				);
				parent.insert({'after': pNode});
				parents.set(pID, pNode);
			}
			else {	
				pNode = parents.get(pID);
			}
			
			var noteIndexAnchor = "footnote_" + noteIndex;
			
			// create the note
			pNode.insert("<a name='" + noteIndexAnchor + "' class='footnote_anchor'/><strong>" + noteIndex + ". </strong>");
			pNode.insert(noteToBe.innerHTML);
			pNode.insert("<br/>");
			
			// remove the old note, and create the super script
			var superscript = "<sup><a href='#" + noteIndexAnchor + "' class='footnote_link'>" + noteIndex + "</a></sup>";
			noteToBe.insert({'before': superscript});
			noteToBe.remove();
			
			noteIndex++;
		}
	);
}