/**
 * This script should be placed at end of HTML, prior to </body> tag.
 * When loaded it will locate all anchors in a page and for those that point to hosts
 * NOT included in aIgnoreHosts, it will assign an onClick call to log the
 * click through.
 *
 * Author: James Caws
 * Website: http://www.jamescaws.co.uk
 */

/**
 * Adjustable variables
 */

/**
 * Array of hostnames you don't want to count the clicking of. You'll probably
 * want to include the hostname of your website unless you really want to count
 * every internal click. If this is the case, other adjustments will be required
 * to this script.
 */
var aIgnoreHosts = new Array ('www.phdseek.com','ads.phdseek.com');

/**
 * The location of the PHP script that will be called to log the click
 */
var sLogScript = '/logger' + '.php';

/** NO NEED TO EDIT BELOW THIS LINE UNLESS YOU WANT TO MAKE CHANGES TO THE STANDARD WAY OF WORKING **/

/**
 * A few helper functions to make life easier / more straight forward
 */

/**
 * This allows us to use $('elementID') as opposed to document.getElementById('elementID')
 */
var $ = function(el) {
	return document.getElementById(el);
}

/**
 * JS implementation of PHP's parse_url.
 * Taken from http://www.bytemycode.com/snippets/snippet/798/
 */
String.prototype.parse_url = function(query) {
	var url=this,
		rx=/^((?:ht|f|nn)tps?)\:\/\/(?:([^\:\@]*)(?:\:([^\@]*))?\@)?([^\/]*)([^\?\#]*)(?:\?([^\#]*))?(?:\#(.*))?$/,
		rg=[null,'scheme','user','pass','host','path','query','fragment'],
		r=url.match(rx),i,q,ret={};

	if (r==null) { return ret; }

	for (i=1; i<rg.length; i++) {
		if (r[i]!=undefined) { ret[rg[i]]=r[i]; }
		if (ret.path=='') { ret.path='/'; }
		if (query!=undefined && r[6]!=undefined) {
			var q=r[6];
			ret.query={};
			q=q.split('&');
			for (var i=0; i<q.length; i++) {
				q[i]=q[i].split('=',2);
				ret.query[unescape(q[i][0])]=unescape(q[i][1]);
			}
		}
	}

	return ret;
}

/**
 * JS implementation of PHP's in_array.
 * Taken from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_in_array/
 */
function in_array(needle, haystack, strict) {
	var found = false, key, strict = !!strict;
 
	for (key in haystack) {
		if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		}
	}
 
	return found;
}

/** End of helpers, start of the main code **/

if (typeof CT_LOGGER == "undefined") {
	CT_LOGGER = { logger_set: false }; 
}

/**
 * Initialisation function. Finds 'loggable' links and attaches a handler to them.
 */
CT_LOGGER.init_logger = function() {
	if (CT_LOGGER.logger_set === true) {
		return;
	}

	CT_LOGGER.logger_set = true;

	var aLinks = document.getElementsByTagName('a');

	for (var i=0; i<aLinks.length; i++) {
		if (CT_LOGGER.logableLink(aLinks[i].href)) {
			if (typeof aLinks[i].id == 'undefined' || aLinks[i].id == '') {
				aLinks[i].setAttribute('id', 'loggerlink_' + parseInt(Math.random()*99999999));
			}

			CT_LOGGER.attachLogger(aLinks[i].id);
		}
	}
}

/**
 * Decides whether a given link should be loggable. This decision is made purely on the
 * value of the hostname i.e. if it is/isn't in the aIgnoreHosts array.
 */
CT_LOGGER.logableLink = function(sLink) {
	var aLink = sLink.parse_url();

	if (typeof aLink['host'] == 'undefined' || aLink['host'] == '') {
		return false;
	}

	if (in_array(aLink['host'], aIgnoreHosts)) {
		return false;
	}

	return true;
}

/**
 * For a loggable link, set the onclick handler to call our log_click function.
 * The method used below will override any existing onclick handler defined in the
 * link. You might like to modify this function to be a bit more intelligent and use
 * addEventListener (W3C) + attachEvent (Microsoft). These make things a bit more
 * complicated and were not required in the app this software was designed for,
 * hence why not included.
 */
CT_LOGGER.attachLogger = function(id) {
	$(id).onclick = CT_LOGGER.log_click;
}

/**
 * Called when a loggable link is clicked. It determines what the destination URL is, strips off
 * any '#name', ensures that the anchor has a 'target="_blank"' attribute to force a new window
 * to open the link (just remove it if you don't want this or will define targets in your links)
 * then adds the logging script as a hidden image. This calls the logging script, passing along the 
 * URL to log a count against.
 */
CT_LOGGER.log_click = function() {
	if (typeof this.target == 'undefined' || this.target != '_blank') {
		this.setAttribute('target', '_blank');
	}

	var elLoggerImage = document.createElement('img');
	elLoggerImage.setAttribute('id', 'loggerbeacon_' + parseInt(Math.random()*99999999));
	elLoggerImage.setAttribute('alt', 'Link logger');

	var sEncoder = encodeURIComponent||escape, aURL = this.href.split('#');

	var sURL = sEncoder(aURL[0]).replace(/\+/g,'%2B');
	var aMatch = document.URL.match('\/phds\/([0-9]+)[\/]*');
	var iPhDID = aMatch[1];

	elLoggerImage.setAttribute('src', sLogScript + '?url=' + sURL + '&cb=' + parseInt(Math.random()*99999999) + '&phdid=' + iPhDID);

	elLoggerImage.style.display = 'none';

	document.body.appendChild(elLoggerImage);

	return true;
}

/**
 * Set-up and instantiate our logger
 */

CT_LOGGER.window_onload = function() {
	CT_LOGGER.window_loaded = true;
};

if (window.addEventListener) {
	window.addEventListener("load", CT_LOGGER.window_onload, false);
} else if (window.attachEvent) {
	window.attachEvent("onload", CT_LOGGER.window_onload);
}

CT_LOGGER.init_logger();

