// NB Utlility functions are liable to assume presence of buglog without documentation

// In general utility functions assume they are being given sensable parameters


DEBUG=false; // Set to true for debugging output

// DEBUG logging---use Firebug if available, else just alert...
if (window.console) {
	outputLog=window.console.log;
} else {
	outputLog=window.alert;
}

function buglog(theLog,forceAlert) {
	//If forceAlert is true we alert whether we have a console or not
	if (forceAlert) {
		window.alert(theLog)
	} else {
		outputLog(theLog);
	}
}
//--------------------------------------------

function spaceDelimCheckRegExp(theWord) {
	//norcimo September 2010
	//Builds regExp to check for theWord is space separated list
	var buildRegExp="(^|\\s+)("+theWord+")(\\s+|$)";
	var testRegExp=new RegExp(buildRegExp,"g");
	return testRegExp;
}

function checkListForItem(theItem, theList, delim) {
	//norcimo September 2010
	// Checks a list for occurance of an item
	// Optional separator delim
	// theItem - Item to check for
	// theList - List to look in
	// delim - Optional. List deliminator (default: Space)
	if (!delim)
		delim=" ";
	var listArray=theList.split(delim);
	if (DEBUG)
		buglog("Checking "+listArray.length+" items for "+theItem);
	for (i=0; i<listArray.length; i++) {
		if (listArray[i]==theItem) {
			return true;
		}
	}
	return false;
}

document.getElementsByClassName=function(searchClass,node,tag) {
	//Dustin Diaz's implementation of getElementsByClassName
	// Finds elements with a given class
	//searchClass - the class which elements must have to be returned
	// node - start node for search (defaults to document if null)
	// tag - optional: find only elements with tagname tag
	// Returns: Array of elements  decendants of node(optionally of type tag) which have class searchClass
		if (DEBUG) {
			buglog("Finding classname "+searchClass+" in "+node);
			
		}
        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;
}


function addClass(theClass, theNode) {
	// norcimo May 2009
	// Adds a class to an element
	// theClass - class to add to element
	// theNode - element to which to add class
	// Requires: hasClass()
	if (DEBUG) {
		buglog("Adding class "+theClass+" to "+theNode);
	}
	if (!hasClass(theClass, theNode)) { //Don't want it twice if already there!
		var currentClasses=theNode.className;
		// We only do this way to avoid leading spaces---all neat and tidy!
		if (currentClasses)
			currentClasses+=" "+theClass;
		else
			currentClasses=theClass;
		theNode.className=currentClasses;
	}
}

function removeClass(theClass, theNode) {
	// norcimo May 2009
	// Removes a class from an element
	// theClass - the class to be removed
	// theNode - the element from which to remove the class
	if (DEBUG) {
		buglog("Removing class "+theClass+" from "+theNode);
	}
	if (hasClass(theClass, theNode)) {
		currentClasses=theNode.className;
		currentClasses=currentClasses.replace(spaceDelimCheckRegExp(theClass)," ");
		//Gone. Tidy up multiple spaces to leave just one (doesn't matter, but be neat)
		currentClasses.replace(/\s\s+/g," ");
		// We may have a leading space (if it was the first class), or trailing space (if last).
		// This doesn't really matter, but we'll be tidy
		currentClasses.replace(/^\s+/,"");
		currentClasses.replace(/\s+$/,"");
		theNode.className=currentClasses;
	}
}

function hasClass(theClass, theNode) {
	//norcimo September 2010
	//Checks if an element has the given class
	//theClass - the class to be checked for
	//theNode - the element to check
	if (DEBUG) {
		buglog("Checking if "+theNode+" has class "+theClass);
	}
	var nodeClasses=theNode.className;
	return checkListForItem(theClass,nodeClasses);
}

function setOpacity(theOpacity, theNode) {
	// norcimo June 2009
	// Sets opacity of an element, using CSS opacity property and filters for IE
	// theOpacity - required opacity [ 0<=theOpacity<=1 else returns false ]
	// theNode - Element on which to set opacity
	if (theOpacity<0 || theOpacity >1)
		return false;
	theNode.style.opacity=theOpacity;
	if (theNode.filters) {
		theNode.filters.item("DXImageTransform.Microsoft.Alpha").opacity=theOpacity*100;
	}
}

function findPos(obj) {
	// Find actual position of object obj
	// From quirksmode.org
	//Returns left, top as array
	var curLeft=curTop=0;
		do {
			curLeft+=obj.offsetLeft;
			curTop+=obj.offsetTop;
		} while (obj=obj.offsetParent);
	return [curLeft,curTop];
}

function randomInRange(low, high) {
	// Return a (pseudo)random integer from low to high inclusive
	return Math.floor(Math.random()*(high-low+1)+low);
}

function randomInRangeWithExclude(low, high, excluded) {
	//Return a (pseudo) random integer from low to high inclusive,
	//excluding the numbers in the passed array
	high-=excluded.length;
	if (high<low) {// We haven't left ourselves a number!
		return null;
	}
	var tempRand=randomInRange(low,high);
	//Sort array numerically
	excluded.sort(function(a,b){return a - b})
	for (var r=0; r<excluded.length;r++) {
		if (tempRand>=excluded[r]) {
			tempRand++;
		}
	}
	return tempRand;
}
	

function getFileName() {
	//Return the filename of the current file
	//this gets the full url
	var url = document.location.href;
	//this removes the anchor at the end, if there is one
	url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
	//this removes the query after the file name, if there is one
	url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
	//this removes everything before the last slash in the path
	url = url.substring(url.lastIndexOf("/") + 1, url.length);
	return url;
}

function getWindowSize() {
	// Return width and height of current window, as array[width,height]
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return [myWidth,myHeight];
}

function removeElement(theElem) {
	//removes the given element (and all children) from the DOM
	if (!theElem || !theElem.parentNode)
		return null;
	theElem.parentNode.removeChild(theElem);
}
