/*  footnote.js */
/*  This is a short sample to solve some of the issues with footnotes on GrokLaw. 
	This code is written by Maarten Sneep, and is placed in the public domain.
	
	Tested with Firefox 1.0.3, Mozilla 1.7.5, Safari 1.3. 
	Also tested on Internet Explorer 5.2.3 (mac). It fails there, but the links 
	still work. That shouldn't be a problem for the regular GrokLaw audience.
	   
	Have fun, Maarten (April 2005).
*/

/* set some properties */

var g_offsetX = 0;
var g_offsetY = 18;
var g_margins = 10;
var g_footnoteVisible = false;

function showfootnote(fn_ref){
	// This function should be called on a mouseover of the reference
	// The argument is the id of the span that contains the text of the footnote
	var fn = document.getElementById("footnote");
	var contents = document.getElementById(fn_ref);
	if (!fn) {
		return true;
	} else if(!contents) {
		return true;
	} else if( !contents.innerHTML ) {
		return true;
	} else {
		fn.innerHTML = contents.innerHTML;
		g_footnoteVisible = true;
		return false;
	}
}

function clearfootnote(){
	// hide the footnote again
	var fn = document.getElementById("footnote");
	if (g_footnoteVisible && fn) {
		g_footnoteVisible = false;
		fn.style.display="none";
		fn.innerHTML = "";
	}
}

function moveFootnote(event) {
	// the big one: it figures out where the room is and places the label.
	if(g_footnoteVisible) {
		var fn = document.getElementById("footnote");
		var wwidth = window.innerWidth - g_margins;
		var wheight = window.innerHeight - g_margins;
		
		if (!fn ) { return; }
		
		if ( !wwidth ) { // alternative code for IE
			wwidth=body.clientWidth
		}
		
		if ( !wheight ) { // alternative code for IE
			wheight=body.clientHeight
		}
		
		if ( !wwidth || !wheight ) { return; }
		
		var floatWidth = fn.offsetWidth + g_margins;
		var left = event.pageX - window.pageXOffset; 
		var right = wwidth - left - g_margins; // correct for scroll bar
		
		if ( !floatWidth || !left || !right ) { return; }
		
		if ( left < floatWidth/2 ){
			fn.style.left = (g_margins/2) + "px"
		} else if ( right < floatWidth/2 ) {
			fn.style.left = (wwidth - floatWidth) + "px"
		} else {
			fn.style.left = (event.pageX - floatWidth/2) + "px";
		}
		
		var fromBottom = wheight - event.pageY + window.pageYOffset;
		if ( fromBottom < fn.offsetHeight + g_margins ){
			fn.style.top = (event.pageY - fn.offsetHeight - g_margins) + "px";
		} else {
			fn.style.top = (event.pageY + g_offsetY) + "px";
		}
		fn.style.visibility = "visible";
	}
}

function moveFootnoteEventHandler(evt) {
	event = (evt) ? evt : ((window.event) ? window.event : false);
	if (event && g_footnoteVisible){
		moveFootnote(event);
	}
}
// set the mouse moved event handler to the code that will 
// position the footnote floating box
document.onmousemove = moveFootnoteEventHandler;
