function Garbage() 
{ 
}


Garbage.init = function() 
{
	if (!window._OBJECTS_)  {
		
		window._OBJECTS_ = []; 
		window._FUNCTIONS_ = []; 
		window._EVENTS_ = []; 
		window._CLASSES_ = []; 
	}
}

Garbage.release = function() 
{
	if (!window._OBJECTS_) 
		return false; 
	
	Garbage.release_events(); 
	
	for (var index in window._OBJECTS_) {
		var element = window._OBJECTS_[index]; 
		
		if (typeof element == "function") 
			continue; 
		
		window._OBJECTS_[index] = null; 
	}
	
	window._OBJECTS_ = null; 
	
	for (var index in window._FUNCTIONS_) { 
		var funct = window._FUNCTIONS_[index]; 
		
		funct = null; 
	} 
	
	window._FUNCTIONS_ = null
	
	for (var index in window._CLASSES_) {
		var cls = window._CLASSES_[index]; 

		if (cls.dispose)
			cls.dispose(); 
			
		window._CLASSES_[index] = null; 
	}
	
	window._CLASSES_ = null; 
	
	return true; 
}

Garbage.release_events = function () 
{
	var events = window._EVENTS_; 

	for (var i = 0; i < events.length; i++) { 
		var event = events[i]; 

		detach_event(event[0],event[1],event[2]); 
	}
	
	window._EVENTS_ = null; 
}
Garbage.push_event = function(obj, event, f) 
{ 
	Garbage.init(); 

	var length = window._EVENTS_.length; 
	window._EVENTS_[length] = [obj,event,f]; 
}
Garbage.collect = function(obj) {
	
	Garbage.init(); 
	
	var func = this; 
	
	var object_id = obj._OBJID; 
	if (!object_id) {
		object_id = obj_OBJID = window._OBJECTS_.length;
		window._OBJECTS_ [object_id] = obj; 
	}
	
	var funct_id = func._FUNCID; 
	if (!funct_id) {
		funct_id = func._FUNCID = window._FUNCTIONS_.length; 
		window._FUNCTIONS_[funct_id] = obj._FUNCT = func; 
	}

	if (!obj._CLOSURES) 	
		obj._CLOSURES = []; 
	
	var closure = obj._CLOSURES[funct_id]; 
	if (closure) 
		return closure; 
		
	obj = func = null; 
	
	return window._OBJECTS_[object_id]._CLOSURES[funct_id] = function() {
		if (!window._FUNCTIONS_) 
			return; 
			
		return window._FUNCTIONS_[funct_id].apply(window._OBJECTS_[object_id], arguments);
	};	
}


Function.prototype.garbage = Garbage.collect;	

function event_install(obj,event_name,f){

	if (obj.addEventListener){	
		obj.addEventListener(event_name.substr(2), f.garbage(obj),false);
	}else if (obj.attachEvent){	 
		obj.attachEvent(event_name,f.garbage(obj));
	}
	
	Garbage.push_event(obj, event_name, f); 
}

function detach_event(obj,event_name, f){

	if (obj.removeEventListener) { 
		obj.removeEventListener(event_name.substr(2), f,false);
	} else if (obj.detachEvent) { 
		obj.detachEvent(event_name, f.garbage(obj)); 

	}
}

function IMPLEMENT_GARBAGE(f) {
	Garbage.init(); 
	window._CLASSES_[ window._CLASSES_.length ] = f; 
}

event_install(window,"onunload",Garbage.release); 

