/**
 * CustomEvent.js		Date created: 6.04.2007
 * Copyright (c) 2007 Exadel Inc.
 * @author Denis Morozov <dmorozov@exadel.com>
 */
ClientUILib.declarePackage("ClientUI.common.utils");

if(!ClientUI.common.utils.CustomEvent) {
ClientUILib.declarePackage("ClientUI.common.utils.CustomEvent");

ClientUI.common.utils.CustomEvent = Class.create({
	// Constructor
	initialize: function(event) {
		this._eventName = event;
		// WARNING: If too many events will be in system with dynamic 
		// observation/stop observation than integer idGenerator can be overflowed
		this._id = ClientUI_common_utils_CustomEvent_idGenerator++;
	},
	getName: function() {
		return this._eventName;
	},
	getId: function() {
		return this._id;
	},
	
	// Fire this event and notifies the subscribers.
	fire: function() {
        if (!Event.subscribers || !Event.subscribers.length) {
            return true;
        }

		var id = this.getId();
		var subscribers = Event.subscribers;
		var subscribersToNotify = Event.subscribers.findAll( 
			function(subscriber) {
				return subscriber.event.getId()===id; 
			});

		var args = $A(arguments);
		subscribersToNotify.unbreakableEach(function(subscriber) {
			subscriber.callback.apply(subscriber.callback, args);
		});
	}
});

Object.extend(ClientUI.common.utils.CustomEvent, {
	_eventName: 'undefined',
	_id: -1	
});

Event._observe = Event.observe;
Event.observe  = function( element, name, observer, useCapture ) {
	if(element && element.getName && element.getId) {
		var customEvent = element;
		if (!this.subscribers) {
			this.subscribers = [];	
		}
		
		this.subscribers.push({
			event: customEvent,
			desc: name,
			callback: observer
		});
	}
	else {
		Event._observe(element, name, observer, useCapture);	
	}
};

Event._stopObserving = Event.stopObserving;
Event.stopObserving  = function( element, name, observer, useCapture ) {
	if(element && element.getName && element.getId) {
		var customEvent = element;
		if (this.subscribers && this.subscribers.length && this.subscribers.length!==0) {
			var id = customEvent.getId();
			this.subscribers = this.subscribers.select(
				function(subscriber) {
					return subscriber.event.getId()!==id; 
				});
		}
	}
	else {
		Event._stopObserving(element, name, observer, useCapture);	
	}
};

Event._unloadCache = Event.unloadCache; 
Event.unloadCache = function() {
    if (Event.subscribers) {
	    for (var i = 0, length = Event.subscribers.length; i < length; i++) {
	      Event.stopObserving.apply(this, Event.subscribers[i]);
	      Event.subscribers[i][0] = null;
	    }
	    Event.subscribers = false;
	}
	Event._unloadCache();
};
  
var ClientUI_common_utils_CustomEvent_idGenerator = 0;

};
 