// common.js - Michael Huang's common javascript functions. 1.00. mikhuang@gmail.com


/** Adds a class (string) to the end of an element's class. Checks for repeat. */
function addClassToElement(searchClass, element) {
	if (!isClassInElement(searchClass, element)) {
		element.className += " " + searchClass + " ";
	}
}

/** Removes all mentions of a class (string) from an element's class list. If class not present, does nothing */
function removeClassFromElement(searchClass, element) {
	// if (!isClassInElement(searchClass, element)) alert(searchClass + " not found");
	var str = " " + element.className + " ";
	while (str.indexOf(" " + searchClass + " ") != -1) {
		str = str.replace(" " + searchClass + " ", " ");
	}
	element.className = str;
}

/** Returns true or false depending on whether or not a class is in an element */
function isClassInElement(searchClass, element) {
	var pattern = new RegExp("\\b" + searchClass + "\\b");
	return pattern.test(element.className);
}

/** Shows a div. Assumes block style */
function showDiv(div) { if (div && div.style) div.style.display = "block"; }

/** Hides a div */
function hideDiv(div) { if (div && div.style) div.style.display = "none"; }

/** Creates an alert from an array, comma seperated */
function alertFromArray(array) {
	var str = "[" + array.length + "] ";
	for (var i = 0; i < array.length; i++) {
		str += array[i].id + " (" +  array[i].className + "), ";
	}
	alert(str);
}

/* OTHER PEOPLE'S WORK */

function addEvent(elm, evType, fn, useCapture) {
// cross-browser event handling for IE5+, NS6+ and Mozilla/Gecko
// By Scott Andrew
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	} else {
		elm['on' + evType] = fn;
	}
}

/* http://www.dustindiaz.com/getelementsbyclass */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}