/**
 * A decidedly unscientific (read "fun") way of collecting user behavior stats
 */
createPackage = function (packageName) {
	var packages = packageName.split('.');
	var packagesLength = packages.length;
	var base = this;
	for (var i = 0; i < packagesLength; i++) {
		if (typeof base[packages[i]] == 'undefined') {
			base[packages[i]] = new Object();
			base = base[packages[i]];
		}
	}
}

createPackage ('com.ioyu.stats');
com.ioyu.stats = {
	lastPosition:null,
	distance:0,
	clicks:0,
	onmousemoveHandler:function(evt) {
		var e = evt ? evt : event;
		var x = e.clientX;
		var y = e.clientY;
		if (com.ioyu.stats.lastPosition != null) {
			com.ioyu.stats.distance += Math.sqrt(Math.pow(x-com.ioyu.stats.lastPosition.x,2)+Math.pow(y-com.ioyu.stats.lastPosition.y,2));
		}
		com.ioyu.stats.lastPosition = {x:x,y:y};
	},
	onmousedownHandler:function() {
		com.ioyu.stats.clicks++;
	},
	onbeforeunloadHandler:function() {
		document.cookie = 'statusDistance=' + escape(com.ioyu.stats.distance);
		document.cookie = 'statusClicks=' + escape(com.ioyu.stats.clicks);
	}
}

function getCookie(cookieName) {
	var results = document.cookie.match ( cookieName + '=(.*?)(;|$)' );
	if (results) {
		return unescape(results[1]);
	}
	else {
		return false;
	}
}

/**
 * initPage executes a series of standard page-level JavaScript functions
 * that serve to enhance various aspects of the page being viewed.
 */
function initPage() {
	document.onmousemove= com.ioyu.stats.onmousemoveHandler;
	document.onclick = com.ioyu.stats.onmousedownHandler;
	window.onbeforeunload = com.ioyu.stats.onbeforeunloadHandler;

	initHoverable();
	if (typeof onloadHandler=='function') onloadHandler();
}

/** 
 * initHoverable facilitates the application of mouseover hover treatments
 * on table rows that have the "hoverable" class applied to them without
 * requiring additional JavaScript on the page.
 */
function initHoverable() {
	var rows = document.getElementsByTagName('TR');
	for (var i = 0;i < rows.length;i++) {
		if (rows[i].className.match(/\bhoverable\b/)) {
			rows[i].onmouseover = function() {
				replaceClassName(this,'hoverable','hoverableActive');
			}
			rows[i].onmouseout = function() {
				replaceClassName(this,'hoverableActive','hoverable');
			}
		}
	}
}

/** 
 * replaceClassName swaps one class reference for another in an element's
 * className property while preserving other stacked classes if they exist.
 */
function replaceClassName(elem,oldClassName,newClassName) {
	elem.className = elem.className.replace(new RegExp('\\b' + oldClassName + '\\b'),newClassName);
}