/**
 * Event propagation class. Based on jQuery bind and trigger methods
 * @constructor
 */
function PastelEventQueue() {
	var _eventIds = {};
	
	this._queue = $("<div></div>");
	 
	/**
	 * Register an event for triggering.
	 * 
	 * @param {String} eventId - event unique id
	 * @param {Function} callback - event handler function. Signature: function(event, payload){};
	 * @param {Object} sender - the initiator of the event, if context is not passed sender is used 
	 * as context of execution
	 * @param {Object} context - the object which will host the execution of the function
	 */
	this.register = function(eventId, callback, sender, context) {
		this.unregister(eventId);
		if (context !== undefined) {
			callback = $.proxy(callback, context);
		} else {
			callback = $.proxy(callback, sender);
		}
		this._queue.bind(eventId, callback);	
	};
	
	this.unregister = function(eventId) {
		if (this._queue.length != 0) {
			this._queue.unbind(eventId);
		}
	};
	
	/**
	 * Trigger an event.
	 * 
	 * @param {String} eventId
	 * @param {Object} payload - the payload which will be passed to the event handler function
	 */
	this.trigger = function(eventId, payload) {
		this._queue.trigger(eventId, payload);
	};
 
	/**
	 * Generate an unique event id
	 * @param {String} eventId
	 * @return
	 * @type String
	 */
	this.eventId = function(eventId) {
		var milis = (new Date().getTime());
		
		var tempId = eventId + "-" + milis;
		if (_eventIds[tempId] === undefined) {
			_eventIds[tempId] = true;
		} else {
			var i = 0; 
			do {				
				tempId = eventId + "-" + milis + "-" + i;
				i++;
			} while (_eventIds[tempId] !== undefined);
			_eventIds[tempId] = true;
		}
		return tempId;
	};
}
