/*
*** Usage:
	In HTML <head>:
	<script type="text/javascript" src="#templateBaseHREF/libs/jsimagereplacement/jsimagereplacement.js"></script>

	In the HTML <body>:
	<h2 id="replacement.png" class="replaceable">Replace me!</h2>

	Then for image replacement:

		Once enough of the DOM has loaded:

		<script type="text/javascript">
		//<![CDATA[
			var jsimagereplacement = new JsImageReplacement('#templateBaseHREF/images/text-replacement/', 'replaceable', 'h2', 'image');
			jsimagereplacement.replace();
		//]]>
		</script>

	Or for Flash replacement:

		Once enough of the DOM has loaded: (Avoid flash of pre-replaced content)

		<script type="text/javascript">
		//<!CDATA[
			if (jsimagereplacementAtYourService) {
				document.getElementById('at-your-service.swf').style.visibility = 'hidden';
			}
		//]]>
		</script>

		And once the DOM has loaded (IE6 doesn't like you doing over-complex DOM operations until the tree is fully loaded):

		<script type="text/javascript">
		//<![CDATA[
			var jsimagereplacement = new JsImageReplacement('#templateBaseHREF/images/text-replacement/', 'replaceable', 'p', 'flash');
			jsimagereplacement.replace(200, 120);
		//]]>
		</script>


*** Modified: 2008/05/14 by Anton Prowse
	- Made it an option to replace with a Flash movie instead of an image (although no Flash detection is undertaken)

*** Modified: 2008/05/05 by Anton Prowse
	- Made code object-oriented
	- Allowed for specifying the class name and the tag name to be targeted

*** Modified: 2007/11/07 by Jakob Givoni
	- Added check for child elements before inserting text into alt tag (if not, a warning is printed to console.error)
	- Changed: Image is only inserted if it is found; the image's onload event will insert the image
	
*** Modified: 2007/05/28 by Anton Prowse
	- Removed the "image id is set to h1 id" behaviour.
	- Changed the affected element to "h2", and removed onload event handling which must be controlled centrally, not here!
	   The following JavaScript should go in the header:
		//jsimagereplacement
		ipath = '/images/titles/'; // or change to any suitable path
	   while the following tag should directly follow the last (and only the last) occurrance of a h2.title* in the body.
		<script type="text/javascript">replaceTitles()</script>
	   Yes it's nasty, but it's the most effective way of preventing a pre-replacement flash of header text.


*** ORIGINAL FILE METADATA FOllOWS

	replacetitles.js	Version 1.1 6-May-2007
	----------------------------------------
	Copyright (c) 2007 Conrad Consulting, Inc.
	Author: Charles J. Conrad
	
	Description:
	Replaces content titles (h1 tags with class 'title*') with images
	
	h1 tag id is image filename.
	No replacement occurs if id is missing.
	Replacement images are assumed to be stored in directory defined by variable ipath.
	
	image src is set to ipath + id
		Note: xhtml does not allow '/' in an id name, even though browsers may support it.
	image class is set to h1 class
	image id is set to h1 id
	
	Usage:
	include as external script
	activated by onload event
	
	Acknowledgements:
	prior image replacement advocates
	
	replacetitles.js is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.
	
	replacetitles.js is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.
	
	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

/**
 * Modifies the dom to replace the text content of each of a specified set of tags with the replacement image or flash movie
 * specified by the tag's id attribute.  The replacement is given the same class as the tag being replaced.
 *
 * @param {String} iPath the absolute or relative path to the directory in which the replacement files lie
 * @param {String} className the class name of the HTML DOM element nodes to be targeted
 * @param {String} tagName the node name of the HTML DOM element nodes to be targeted, or omitted/null/'*' if all nodes are to be targeted
 * @param {String} type 'image' or 'flash'; default is 'image'
 */
function JsImageReplacement(ipath, className, /*optional*/ tagName, /*optional*/ type) {

	var that = this;
	var className = className;
	var tagName = tagName || '*';
	var type = (type == 'image' || type == 'flash') ? type : 'image';


	function _replace(node, /*optional*/ width, /*optional*/ height) {
		if (!node.id) {
			throw new Error('Node has no id and hence the filepath to replacement is unknown');
		}
		if (type == 'image') {
			var replacement = document.createElement('img');
			replacement.src = ipath + node.id;
	
			if (width) {
				replacement.width = width;
			}
			if (height) {
				replacement.height = height;
			}

			//switch the nodes
			if (node.firstChild) {
					node.replaceChild(replacement, node.firstChild);
			} else {
				node.appendChild(replacement);
			}

			//If tag's first child node is text, this becomes the alt text
			if ( window.console && (!node.firstChild || node.firstChild.nodeType == 3 /*TEXT_NODE*/) ) {
				console.error("Node's first child is not text (jsimagereplacement)");
			} else {
				if (node.firstChild.nodeValue) {
					replacement.alt = node.firstChild.nodeValue;
				}
			}
		} else if (type == 'flash') {
			var replacement = document.createElement('object');
			replacement.data = ipath + node.id;
			replacement.type = 'application/x-shockwave-flash';
			
			var param_movie = document.createElement('param');
			param_movie.name = 'movie';
			param_movie.value = replacement.data;

			var param_quality = document.createElement('param');
			param_quality.name = 'quality';
			param_quality.value = 'high';

			var param_wmode = document.createElement('param');
			param_wmode.name = 'wmode';
			param_wmode.value = 'transparent';

			replacement.appendChild(param_movie);
			replacement.appendChild(param_quality);
			replacement.appendChild(param_wmode);
	
			if (width) {
				replacement.width = width;
			}
			if (height) {
				replacement.height = height;
			}

			//switch the nodes
			replacement.id = node.id;
			replacement.className = node.className;

			node.parentNode.replaceChild(replacement, node);

			//Tag becomes object fallback
			replacement.appendChild(node);
			node.style.visibility = 'visible';
		}

		replacement.className=node.className;
		node.className = null;
	}


	/**
	 * @param {int} width the width of the replacement; required ONLY when type is 'flash' in which case default is 100, but used when type is 'image' if not omitted and not null
	 * @param {int} height the height of the replacement; required and used ONLY when type is 'flash' in which case default is 50, but used when type is 'image' if not omitted and not null
	 */
	this.replace = function(/*optional*/ width, /*optional*/ height) {
		var width = (type == 'image') ? width :
		                                        (type == 'flash') ? width || 100 : null;
		var height = (type == 'image') ? height :
		                                          (type == 'flash') ? height || 50 : null;

		// Check for DOM support
		if (!(document && document.implementation && document.implementation.hasFeature)) {
	  	  	return;
		}
		// Check for image support
		if (!document.images) {
			return;
		}

		var pattern = new RegExp('(^|\\s)' + className);
		var replaceables = document.getElementsByTagName(tagName);
		for (var i=0; i < replaceables.length; i++) {
			if ( pattern.test(replaceables[i].className) ) {
				try {
					_replace(replaceables[i], width, height);
				} catch(e) {
				}
			}
		}
	}

}
