/*  Manager JavaScript framework, version 1.0 beta
 *  (c) 2007 Clément Hallet, from AF83 company
 *
/*--------------------------------------------------------------------------*/


var Resources = new Class({
	counter: [],
	// allocates already loaded resources, avoiding onAllocate callback
	// registers onAllocate and onFree callbacks, if setted in options parameter
  initialize: function(original,options) {
		this.setOptions(options);
		this.counter = [];
		if(original.push) original.each(function(identifier){this.counter[identifier] = 1;},this);
	},
	// creates or increments counter related to the specified identifier, and fires the onAllocate event
	// return flag meaning if the resource has been allocated (no matter the result of onAllocate callback)
	increment: function(identifier) {
		if(!this.counter[identifier]) {
			this.counter[identifier] = 1;
			this.fireEvent("onAllocate",identifier); // if exists, call the onAllocate callback
			return true;
		} else {
			this.counter[identifier]++;
			return false;
		}
	},
	// decrements counter related to the specified identifier, and fires the onFree event
	// return flag meaning if the resource has been freed (no matter the result of onFree callback)
	decrement: function(identifier) {
		this.counter[identifier]--;
		if(this.counter[identifier] <= 0) {
			this.counter[identifier] = 0;
			this.fireEvent("onFree",identifier); // if exists, call the onFree callback
			return true;
		} else {
			return false;
		}	
	}

});

Resources.implement(new Options,new Events);  

// On window initialization, register originally loaded scripts and css files
var StyleSheetManager = null;
var ScriptManager = null;
 
window.addEvent('domready', function(){
	var header = document.getElement('head');
	
	var scripts = new Array();
	header.getElements('script[type=text/javascript]').each(function(el) {	
		scripts.push(el.src);
	});
	// This is the javascript files manager 
	ScriptManager = new Resources(scripts,{
		onAllocate : function(url) {
			new Asset.javascript(url);
		}
	});
	
	var styleheets = new Array();
	header.getElements('link[rel=stylesheet]').each(function(el) {	
		styleheets.push(el.href);
	});
	// This is the css files manager
	StyleSheetManager = new Resources(styleheets,{
		onAllocate : function(url) {
			new Asset.css(url);
		}
	});
 
});         




