/**
* @author camilo
* 
* This object makes it possible to easely load javascript files after the page is loaded.
* The main point of this is to draw the page as quickly as possible to the user, and allow parallell download of javascript components.
*/


ExternalScript = function(scriptUrl, scriptOnloadFunctionName)
{
	this.queue = [];
}

ExternalScript.prototype.load = function(scriptUrl, scriptOnloadFunctionName)
{
	var es = document.createElement("script");
	es.type = "text/javascript";
	es.text = scriptOnloadFunctionName;
	es.src = scriptUrl;
	es.onload = function()
	{
		eval(this.innerHTML);
	};
	document.getElementsByTagName("head")[0].appendChild(es);
}

ExternalScript.prototype.addToQueue = function(scriptUrl)
{
	var scritTag = document.createElement("script");
    scritTag.type = "text/javascript";
    scritTag.src = scriptUrl + "?debug="+ Math.random();
    var self = this;
    scritTag.onload = function()
    {
       self.queueLoaded.apply(self);
    };
	scritTag.onreadystatechange = function () {

        if (scritTag.readyState == 'loaded') {
            self.queueLoaded.apply(self);
        }
    }
    this.queue.push(scritTag);
}

ExternalScript.prototype.loadQueue = function(scriptOnloadFunctionName)
{
	this.counter = 0;
	this.scriptOnloadFunctionName = scriptOnloadFunctionName;
	for (var i = 0; i < this.queue.length; i++) 
	{
		document.getElementsByTagName("head")[0].appendChild(this.queue[i]);
	}
}

ExternalScript.prototype.queueLoaded = function()
{
	this.counter++;
	var self = this;
	
	if (this.counter == this.queue.length)
	{
		var isIE6 = navigator.userAgent.match(/MSIE 6\.0/gi) != null;
		
		if (!isIE6) 
		{
			eval(this.scriptOnloadFunctionName);
			this.queue = [];
			this.scriptOnloadFunctionName = "";
		}
		else
		{
			setTimeout(
				function()
				{
					eval(self.scriptOnloadFunctionName);
					self.queue = [];
					self.scriptOnloadFunctionName = "";
				}, 100);
		}
	}
	
}



