/******************************************************************************
 * Function: insertContextualImage(src, h, w, id, elTag, nth)
 *
 * Inserts an image with passed id into the div with id 'content' 
 * after the specified nth element. ie. after the first paragraph or 2nd h3.
 *
 * !!!IMPORTANT!!!
 * To ensure the image shows up on the page when javascript is disabled use
 * the following code template, placed at the top of the content div.
 *		<noscript><div><img ... ></div></noscript>
 *
 * Usage:
 *		insertContextualImage('images/i-prac-bicylcle.jpg', '192', '292', 'contextualImage', 'p', 1);
 *
 * Parameters:
 * 		src ---> the source of the image
 *		h -----> the height of the image
 *		w -----> the width of the image
 *		id ----> the id attribute of the image
 *		elTag -> the element tag to insert image after
 *		nth ---> the nth element to insert image after; ie 2 ==> 2nd
 *
 * Author:
 *		Matthew Meyer, DCT - FindLaw 07/10/2008
 *
 * Updates:
 *		07/15/2008 MM - exception handling and more exact insert added
 *		02/17/2009 MM - id, elTag and nth parameters added to insert after
 *                      the nth element.
 *		02/28/2009 MM - corrected element not found bug and added 0th position
 *						functionality.
 *		04/13/2009 MM - corrected Firefox bug -- nextSibling was returning a 
 *						Text node instead of an Element node.
 *		04/17/2009 MM - corrected nth > number of elements bug.
 ******************************************************************************/
function insertContextualImage(src, h, w, id, elTag, nth){
	try {
		if( nth < 0 )
			nth = 1;
		var contextualImage = document.createElement('img');
		contextualImage.id = id;
		contextualImage.alt = "";
	
		contextualImage.src = src;
		contextualImage.height = h;
		contextualImage.width = w;
	
		var content = document.getElementById('content');
		var elements = content.getElementsByTagName(elTag);
		var elementsNum = elements.length;
		var elNextSib;
		if( elementsNum == 0 ) //if element tag not found, insert before first element in content div
			elNextSib = content.firstChild;
		else if ( nth == 0 )
			elNextSib = elements[nth];
		else if ( nth > elementsNum ) // if nth element doesn't exist, insert before last element
			elNextSib = elements[elementsNum -1];
		else {
			elNextSib = elements[nth - 1].nextSibling;
			while ( elNextSib.nodeType != 1 ) { // Make sure next sibling is an Element node; Fix for Mozilla/FireFox
				elNextSib = elNextSib.nextSibling; 
			}
		}
		elNextSib.parentNode.insertBefore(contextualImage, elNextSib);
	}
	catch (e) {
		//alert(e);
	}
}