
loader = null;

var LoaderFile = function()
{
	this.loadedJS = this.loadedJS.clone();
	this.loadedCSS = this.loadedCSS.clone();
	
	var linkElements = $$('link');
	for (i = 0; i < linkElements.length; ++i)
	{
		var src = this.getAbsoluteURL(linkElements[i].href);
		// don't add multiple keys
		if (this.loadedCSS.contains(src))
			continue;
		this.loadedCSS.push(src);
	}

	var scriptElements = $$('script');
	for (i = 0; i < scriptElements.length; ++i)
	{
		// skip inline script element
		if (!scriptElements[i].src || scriptElements[i].src == '')
			continue;
		var src = this.getAbsoluteURL(scriptElements[i].src);
		// don't add multiple keys
		if (this.loadedJS.contains(src))
			continue;
		this.loadedJS.push(src);
	}
}

/**
 * array with JS files already loaded
 * @type Array
 */
LoaderFile.prototype.loadedJS = new Array();

/**
 * array with CSS files already loaded
 * @type Array
 */
LoaderFile.prototype.loadedCSS = new Array();

LoaderFile.prototype.getAbsoluteURL = function(/** String */ URL)
{
	var hostUrl = window.location.href;
	var index = hostUrl.lastIndexOf("/");

	if (URL.startsWith('http'))
		return URL;
	hostUrl = hostUrl.substring(0, index + 1);
	return hostUrl + URL;
	
}

/**
 * load synchronously files and eval content. doesn't add header entries
 * @param {String} src path of the file
 * @return  {void}
 * @type {Function}
 */
LoaderFile.prototype.addJS = function(/** String */ src)
{
	src = this.getAbsoluteURL(src);
	if (this.loadedJS.contains(src))
		return;
	this.loadedJS.push(src);
	new Ajax.Request(src, {
		'asynchronous': false,
		'parameters': {
			'ms': new Date().getTime()
		},
		'onSuccess': function(){
		}
	});
}

/**
 * load style file if needed
 * @param {String} src path of the file
 * @return {void}
 * @type {Function}
 */
LoaderFile.prototype.addCSS = function(/** String */ src)
{
	src = this.getAbsoluteURL(src);
	if (this.loadedCSS.contains(src))
		return;
	var linkElement = new Element('link', {'rel': 'stylesheet', 'type': 'text/css', 'href': src});
	$$('head')[0].insert(linkElement);
	this.loadedCSS.push(src);
}

document.observe("dom:loaded", function(){
	loader = new LoaderFile();
	document.fire("loader:loaded");
});
