//	======================================================================
//
//
//	bsn.replaceTxtWithImg.js
//
//
//	project:	BrandSpankingNew
//
//	author:		Timothy Groves	desk [at] brandspankingnew.net
//	version:	1.0
//	
//	language:	javascript
//	requires:	nothing
//
//	tested on:	Safari 2.0 / FF 1.0.6 Mac
//
//	history:	10.01.2006	-	created
//
//	======================================================================


// check for bsn Object
var bsn;
if (!bsn) bsn = {};



bsn.replaceTxtWithImg = function( ele, repTxt, imgObj )
{
	// check if element is text node
	
	if (ele.nodeType == 3) // is text node
	{
		var txt = bsn.trimWhitespace( ele.nodeValue );
		
		var sPos = txt.indexOf( repTxt );
		
		if (sPos >= 0)
		{
			var sTxt = txt.substr(0,sPos);
			var eTxt = txt.substr(sPos + repTxt.length);
			
			// remove old text node
			var parNode = ele.parentNode;
			parNode.removeChild(ele);
			
			//alert(sTxt+" | "+eTxt);
			if (sTxt.length)
			{
				// create start textNode
				var sNode = document.createTextNode( sTxt );
				parNode.appendChild(sNode);
			}
			
			// create image node
			var iNode = document.createElement("img");
			iNode.src = imgObj.src;
			iNode.width = imgObj.width;
			iNode.height = imgObj.height;
			iNode.className = imgObj.className;
			iNode.alt = repTxt;
			parNode.appendChild(iNode);
			
			if (eTxt.length)
			{
				// create start textNode
				var eNode = document.createTextNode( eTxt ); 
				parNode.appendChild(eNode);
			}
		}
		
	}
	else if (ele.childNodes.length != 0)
	{
		var nodes_arr = ele.childNodes;
		
		for (var i=0; i<nodes_arr.length; i++)
		{
			// recursion!
			arguments.callee( nodes_arr[i], repTxt, imgObj );		
		}
	}
}





// HELPER FUNCTIONS

if (typeof(bsn.trimWhitespace) != "function")
{
	bsn.trimWhitespace = function (str)
	{
		if (typeof(str) != "string")
			return str;
		// clear leading whitespace
		while( str.substring(0,1)==" "||str.substring(0,1)=="\t"||str.substring(0,1)=="\n")
			str = str.substring(1);
		// clear trailing whitespace
		while( str.substring(-1)==" "||str.substring(-1)=="\t"||str.substring(-1)=="\n")
			str = str.substring(0,(str.length-1));
	
		return str;
	}
}