/* LICENCE
 * Copyright (c) 2010 Ewoud Dronkert <ewoud@dronkert.net>
 * Source code ownership, sale & re-distribution rights reserved.
 * Otherwise unlimited commercial use licence granted to Sportsblogs, Inc.
 */

/**
 * General functions for class manipulation
 */
function classAdd(domnode, newclass)
{
	var curclass = domnode.className;

	// check if currently empty
	if (!curclass.length)
		domnode.className = newclass;

	// else if not currently identical to what needs to be added
	else if (curclass != newclass) {
		var i = 0, arr = curclass.split(" ");

		// check if already present
		while (i != arr.length && arr[i] != newclass)
			++i;

		// if not present add as first array element and integrate back
		if (i == arr.length) {
			arr.unshift(newclass);
			domnode.className = arr.join(" ");
		}
	}
}

function classRemove(domnode, oldclass)
{
	var s = domnode.className;
	if (s == oldclass)
		s = "";
	else if (s != "")
	{
		var i = 0;
		var arr = s.split(" ");
		while (i != arr.length && arr[i] != oldclass)
			++i;
		
		if (i != arr.length)
		{
			arr.splice(i, 1);
			s = arr.join(" ");
		}
	}
	domnode.className = s;
}

function classToggle(domnode, switchclass)
{
	var curclass = domnode.className;

	// if currently empty
	if (!curclass.length)
		curclass = switchclass;

	// if currently identical to what needs to be toggled
	else if (curclass == switchclass)
		curclass = "";

	// if currently atomic (one word)
	else if (curclass.indexOf(" ") == -1)
		curclass = switchclass + " " + curclass;

	// if class consists of multiple words
	else {
		var i = 0, arr = curclass.split(" ");
		
		// check if already present in class list
		while (i != arr.length && arr[i] != switchclass)
			++i;
		
		if (i == arr.length)
			// if not present add as first array element
			arr.unshift(switchclass);
		else
			// if already present, remove from array
			arr.splice(i, 1);

		curclass = arr.join(" ");
	}

	domnode.className = curclass;
}

/**
 * Add mouseover and mouseout event handlers to table rows, for IE
 */
function hoverEventsTable(enableclick)
{
	var t, r, i, j;
	if (t = document.getElementsByTagName("TABLE"))
		for (i = 0; i < t.length; ++i)
			if (t[i].className.indexOf("cell") != -1 && t[i].className.indexOf("noevents") == -1) {
				r = t[i].rows;
				for (j = 0; j < r.length; ++j) {
					if (r[j].className.indexOf("nohi") == -1) {
						r[j].onmouseover = function() { classAdd(this, "hi"); }
						r[j].onmouseout  = function() { classRemove(this, "hi"); }
					}
					if (enableclick)
						r[j].onclick     = function() { classToggle(this, "sel"); }
				}
			}
}
