/*
enhance.js
Generic enhancement functions
*/

var W3CDOM = (document.createElement && document.getElementsByTagName);

// Dependant on elements in HTML
//addLoadEvent(replaceTextLoader);
addLoadEvent(replaceEmailAddr);

// Attach functions to window.onload event
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

// Searches doc for anchors with class="email", replaces content and sets href attribute
// To prevent SPAM
function replaceEmailAddr() {
	if (!W3CDOM) return;
	var email, enode, n;
	var links = document.getElementsByTagName('a');
	for (var i=0; i<links.length; i++) {
		// Using getAttribute('class') did not work on IE! 
		if (links[i].className == 'email') {
			// Reconstruct email address
			email = links[i].firstChild.nodeValue;
			email = email.replace(/ -at- /g,'@');
			email = email.replace(/ -dot- /g,'.');			
			//alert(email);
			enode = document.createTextNode(email);
			//links[i].setAttribute('href','mailto:'+email);
			links[i].href = 'mailto:' + email;
			links[i].replaceChild(enode,links[i].firstChild);
		}
	}
}

// Initiates function to replace text headings with images
function replaceTextLoader() {
	if (!W3CDOM) return;
	var test = new Image();
	var tmp = new Date();
	var suffix = tmp.getTime();
	test.src = '/img/test.gif?'+suffix;
	test.onload = replaceTextInit;
}

// Which groups of elements to replace...
function replaceTextInit() {
	replaceText(document.getElementsByTagName('h1'));
	replaceText(document.getElementsByTagName('h2'));
}

// Look for elements with id attribute within group
function replaceText(x) {
  var txtnode;
	var replace = document.createElement('img');
	for (var i=0; i<x.length; i++) {
		if (x[i].id) {
			// Quicker than creating element from scratch each time
			var y = replace.cloneNode(true);
			y.src = '/img/' + x[i].id + '.png';
			y.setAttribute('border','0');
			// Find first textNode, as we might have an anchor within this one!
			txtnode = findTextNode(x[i]);
		  y.alt = txtnode.nodeValue;
			txtnode.parentNode.replaceChild(y,txtnode);
		}
	}
}

// Finds and returns first TEXT_NODE, even if within another ELEMENT_NODE (recursive)
function findTextNode(elem) {
	//alert(elem.nodeType);
	// Works, but is it quite correct in [ALL] situations?
	if (elem.nodeType != 3) {
	  if (elem.hasChildNodes) { 
			return findTextNode(elem.firstChild);
		}
	} else {
		// TEXT_NODE
		return elem;
	}
}