
function Broadcaster () {
	
}

Class(Broadcaster);

Broadcaster.prototype._listeners = new Array();

Broadcaster.initialize = function (o, dontCreateArray) {
	if (o.broadcastMessage != undefined) delete o.broadcastMessage;
	o.addListener = Broadcaster.prototype.addListener;
	o.removeListener = Broadcaster.prototype.removeListener;
	
	if (o.broadcastEvent != undefined) delete o.broadcastEvent;
	o.addEventListener = Broadcaster.prototype.addEventListener;
	o.removeEventListener = Broadcaster.prototype.removeEventListener;
	
	if (!dontCreateArray) o._listeners = new Array();
}

Broadcaster.prototype.addListener = function (o) {
	this.removeListener (o);
	
	if (this.broadcastMessage == undefined) {
		this.broadcastMessage = Broadcaster.prototype.broadcastMessage;
	}
	return this._listeners.push(o);
}

Broadcaster.prototype.removeListener = function (o) {
	var a = this._listeners;	
	var i = a.length;
	while (i--) {
		if (a[i] == o) {
			a.splice (i, 1);
			if (!a.length) this.broadcastMessage = undefined;
			return true;
		}
	}
	return false;
}

Broadcaster.prototype.broadcastMessage = function () {
	var e = String(Array.prototype.slice.call(arguments).shift());
	var a = this._listeners.concat();
	var l = a.length;
	
	for (var i=0; i<l; i++) {
		a[i][e].apply(a[i], arguments);
	}
}

Broadcaster.prototype.addEventListener = function (type, listener) {
	
	if (this.broadcastEvent == undefined) {
		this.broadcastEvent = Broadcaster.prototype.broadcastEvent;
	}
	
	var a = this._listeners;	
	var i = a.length;
	var matched = false;
	while (i--) {
		if (a[i].type == type && a[i].listener == listener) {
			matched = true;
			break;
		}
	}
	
	if (!matched) {
		return this._listeners.push({type: type, listener: listener});
	} else {
		return this._listeners;
	}
	
}

Broadcaster.prototype.removeEventListener = function (type, listener) {
	var a = this._listeners;	
	var i = a.length;
	while (i--) {
		if (a[i].type == type && a[i].listener != listener) {
			a.splice (i, 1);
			if (!a.length) this.broadcastEvent = undefined;
			return true;
		}
	}
	return false;
}

Broadcaster.prototype.broadcastEvent = function () {
	var e = String(Array.prototype.slice.call(arguments).shift());
	var a = this._listeners.concat();
	var l = a.length;
	
	for (var i=0; i<l; i++) {
		if (a[i].type == e) {
			a[i].listener.apply(this, arguments);
		}
	}
}

