/*
 * cssTarget - CSS3 :target pseudo selector like support.
 *
 * Copyright (c) 2008 Peter Ryan (peter-ryan.co.uk)
 * This function is free for anyone to use, modify and redistribute.
 *
 * $Date: 2008-03-14 00:41:22 +0000 (Fri, 14 Mar 2008) $
 * $Rev: 17 $
 */

/* http://simonwillison.net/2004/May/26/addLoadEvent/ */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
};

addLoadEvent(function() {

	var cssClass = 'target';

	// Initialise targeted fragments if any.
	var target = document.getElementById(window.location.hash.slice(1));
	if (target) {
		target.className += ' ' + cssClass;
	}

	// Click event handler function generator. This is passed a "frag" argument
	//   that is a reference to the target element.
	var reCSS = new RegExp("\\b" + cssClass + "\\b");
	function newTargetClickHandler(frag) {
		return function() {
			if (target) {
				target.className = target.className.replace(reCSS, '');
			}
			target = frag;
			target.className += ' ' + cssClass;
		}
	}

	// Run thru <a> elements and add an onclick handler to those that reference
	//   document fragments within the current page.
	var reURI = new RegExp('^' + window.location.href.match(/^[^#]+/)[0] + '#([^#]+)$');
	var elems = document.getElementsByTagName('a');

	for (var i=0; i<elems.length; i++) {

		if (elems[i].href && elems[i].href.match(reURI)) {
			elems[i].onclick = newTargetClickHandler(document.getElementById(RegExp.$1));
		}
	}
});

