var gpx = gpx || {};
gpx.utils = gpx.utils || {};

gpx.utils.eventHandler = function() {
	this.eh = {};
}

/**
 * Event Handler
 * @version 1.1
 */
/**
 * Set a handler for a specified event
 * @param <string> event - name of the event;
 * @param <function> handler - function to run on event
 * @param <bool> first - execute this function first
 * @return <bool>
 */
gpx.utils.eventHandler.prototype.add = function(event, handler, first) {
	if(typeof(handler) != 'function') {
		return false;
	}
	var highpriority = first === true;
	if(!this.has(event)) {
		this.eh[event] = [];
	}
	if(highpriority) {
		this.eh[event].splice(0,0, handler);
	}
	else {
		this.eh[event][this.eh[event].length] = handler;
	}
	return true;
}

/**
 * See if handler(s) exists for a specified event
 * @param <string> event - name of the event
 * @return <bool>
 */
gpx.utils.eventHandler.prototype.has = function(event) {
	return typeof this.eh[event] != undefined && this.eh[event] != null;
}

/**
 * Run all the handlers for a specified event
 * @param <string> eventName - name of the event
 * @param <object> e - event object passed to the handler
 * @return <bool>
 */
gpx.utils.eventHandler.prototype.run = function(eventName, e, callback) {
	if(this.has(eventName)) {
		for(var i = 0; i < this.eh[eventName].length; i++) {
			if(this.eh[eventName][i](e) === false) {
				return false;
			}
		}
		return true;
	}
	if(callback) {
		callback();
	}
	return false;
}

/**
 * Reset the handlers for the specified event
 * @param <string> event - name of the event
 * @return <null>
 */
gpx.utils.eventHandler.prototype.reset = function(event) {
	this.eh[event] = null;
	return null;
}
