var userAgent = navigator.userAgent.toLowerCase();
var appName = navigator.appName.toLowerCase();
var sImageReplacementRoot = '/images/';

//if we detect IR has failed we call this with a delay to try and  make it kick in
function delayedImageReplacement()
{
	//we dont want to ever get into a cycle of calling ImageReplacement 
	//and delayed image replacement in a cycle, hence we dont
	//just call imageREplacement again but a non fail testing equivalent
	setTimeout( "imageReplacementAfterFailure();", 1000 );
}	

function imageReplacementAfterFailure()
{
	replaceThem(document.getElementsByTagName('h1'));
	replaceThem(document.getElementsByTagName('h2'));
	replaceThem(document.getElementsByTagName('h3'));
	
}

function imageReplacement()
{
	/*for ie which seems to have a timing issue we
	   test whether the code worked by flagging before and after 
	   states for the hi tags html content if they are the same the code hasn't kicked 
	   in and we need to try again*/ 
	
	var szBeforeState = document.getElementsByTagName('h1');
	var szBeforeStateHTML  = szBeforeState[0].innerHTML;

	replaceThem(document.getElementsByTagName('h1'));
	replaceThem(document.getElementsByTagName('h2'));
	replaceThem(document.getElementsByTagName('h3'));
	
	var szAfterState = document.getElementsByTagName('h1');
	var szAfterStateHTML  = szBeforeState[0].innerHTML;
	
	if(szAfterStateHTML == szBeforeStateHTML)
	{
		delayedImageReplacement();
	}
	
}

/**
 * If image replacement does not appear to fire, check the value of the
 * sImageReplacementRoot variable - does it point to the correct images folder?
 */
function replaceThem(x)
{
	var replace = document.createElement('img');
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id)
		{
			var y = replace.cloneNode(true);
			// '/images/' SHOULD BE THE RELATIVE PATH FOLLOWED BY 'images/'
			y.src = window.sImageReplacementRoot + x[i].id + '.gif';
			//need to stop ie mac from showing this
			if(!(userAgent.indexOf('mac') != -1 && appName == "microsoft internet explorer")){
				y.alt = x[i].firstChild.nodeValue;
			}
			x[i].replaceChild(y,x[i].firstChild);
		}
	}
}


/**
 * Sets the URL from which replacement images will be loaded
 */
function setGlobalImgReplacementRoot( sRoot ) {
	window.sImageReplacementRoot = sRoot;
}
