/*	VERSION:	1.2
	1.2		Attempt component event listener before asBroadcaster listener
	1.1		Remove events before adding them  (just in case they were already assigned)

	USAGE:
		AsBroadcaster.initialize( _this );
		_this.onUnload = function(){
			_this.broadcastMessage( "unload" );
			_this.dispatchEvent( {type:"unload", target:_this} );
		}
		
		#include "functions/selfCleanupEvents.as"
		var mapEvents = selfCleanupEvents( _this );
		
		mapEvents._this = mapEvents.reactTo( _this );
		mapEvents.map_mc = mapEvents.reactTo( map_mc, null, "change" );
		mapEvents.map_mc = mapEvents.reactTo( map_mc, mapEvents.map_mc, "unload" );
		mapEvents.reactTo( fileBrowser_mc, "openFile" ).openFile = function(){};
*/
#include "once.as"
function selfCleanupEvents( parentUnloader ){
	var inter = {};		// interface
	var cleanup = {};
	var cleanupList = [];
	
	// upon parent's "unload" event
	cleanup.unload = once( function(){
		for(var e=0; e<cleanupList.length; e++){
			cleanupList[e]();		// call this listener's cleanup function
		}// for:  each listener
		cleanupList = [];
		parentUnloader.removeListener( cleanup );
	});// onUnload once()
	
	// listen to parent's "unload" event
	parentUnloader.addListener( cleanup );
	parentUnloader.addEventListener( "unload", cleanup );
	
	// create a listener Obj  &  automatically un-listen upon parent's "unload"
	inter.reactTo = function( eventSrc, existingReactions, eventName ){
		var reaction = existingReactions || {};
		
		// un-listen  (upon parent's "unload" event)
		var unload_reaction = function(){
			if(eventSrc.removeEventListener){
				// components
				eventSrc.removeEventListener(eventName, reaction);
			}else{
				// AsBroadcaster
				eventSrc.removeListener( reaction );
			}
		}// unload_reaction()
		cleanupList.push( unload_reaction );// unload once()
		
		// listen
		if(eventSrc.addEventListener && eventName){
			// components
			eventSrc.removeEventListener(eventName, reaction);
			eventSrc.addEventListener(eventName, reaction);
		}else{
			// AsBroadcaster
			eventSrc.removeListener( reaction );
			eventSrc.addListener( reaction );
		}
		
		// return self-cleaning event object
		return reaction;
	};// reactTo()
	return inter;
}// selfCleanupEvents()