// utils.js
// Some standard JavaScript utility functions
// by Greg Poole | greg@webengine.com.au | www.webengine.com.au

// Add a function which is to be called upon a certain event being fired. The process is one of
// essentially stacking events so that more than one can be assigned to an object.
function addEventHandler(obj,event,handler) {
	if(!obj)
		throw new Exception("Cannot add handler for " + event + " to null object.");
	
	if(!obj.__eventStack)
		obj.__eventStack = new Array();
	
	if(!obj.__eventStack[event]) {
		obj.__eventStack[event] = new Array();
		var existingFunc = eval("obj." + event);
		if(existingFunc)
			obj.__eventStack[event][0] = existingFunc;
		eval("obj." + event + "=function() { for(var i=0;i<this.__eventStack['" + event + "'].length;i++) { var tmp = this.__eventStack['" + event + "'][i]; if(tmp) tmp(); } }");
	}
	
	obj.__eventStack[event][obj.__eventStack[event].length] = handler;
}

// Generate a random 32-character name
function generateRandomName() {
	var length = 32;
	var name = "";
	for(var l=1;l<=length;l++)
		name += String.fromCharCode((Math.random() * 96) + 32);
	return name;
}

// Add an endswith method to the strign class, to allow for testing against the end of a string.
String.prototype.endsWith = function(string) {
	if(this.length < string.length)
		return false;
	
	var end = this.substring(this.length - string.length);
	if(string == end)
		return true;
	return false;
}
