

/**
 * EarthGL.Events creates an objects handling events
 * @param object object on which events will be handeld
 * @constructor
 */


EarthGL.Events = EarthGL.Class({

	initialize: function(object, element, eventTypes, fallThrough, options) {
	    this.object = object;
	    this.element    = element;
	    this.fallThrough = fallThrough;
	    this.listeners  = {};
	    this.eventTypes = [];    
	},

	/**
	 * register registers an event handler
	 * @param {string} type name of the event
	 * @param object object on which function is invoked
	 * @param {function} function function to execute when event is tiggered
	 */

	register: function (type, obj, func) {
	    //console.log('register ',type);

	    if (! (type in this.listeners)) {
		this.listeners[type] = [];
	    }

	    this.listeners[type].push({obj: obj, func: func});
	},

	/**
	 * unregister unregisters an event handler
	 * @param {string} type name of the event
	 * @param object object on which function is invoked
	 * @param {function} function function to execute when event is tiggered
	 */

	unregister: function (type, obj, func) {
	    if (!this.listeners[type]) {
		return;
	    }

	    this.listeners[type] = this.listeners[type].filter(function(c) {
		    return c.obj != obj || c.func != func;
		});						      
	},


	/**
	 * triggerEvent invokes all register event handlers
	 * @param {string} type name of the event
	 * @param {object} event object passed to event handler
	 */

	triggerEvent: function (type, event) {
	    //console.log('trigger ',type);

	    if (!this.listeners[type]) {
		return;
	    }

	    for (var it in this.listeners[type]) {
		var callback = this.listeners[type][it];
		var cont = callback.func.apply(callback.obj, [event]);

		if (cont === false) {
		    break;
		}
	    }
	}
    });

