/**
 * @author Camilo at bronson id dot com
 */

if ((typeof Bronson) == "undefined") { var Bronson = {}; }

Bronson.ExternalScript = function(scriptUrl, scriptOnloadFunctionName)
{
	this.queue = [];
	this.debug = false;
	this.callback = null;
}

Bronson.ExternalScript.prototype.load = function(scriptUrl, callback)
{
	var self = this;
	var es = document.createElement("script");
	es.type = "text/javascript";
	es.src = scriptUrl + (!this.debug ? "" : (scriptUrl.indexOf("?") > -1 ? "&" : "?") + "seed=" + Math.random());
	es.onload = function()
	{
		callback();
	};
	es.onreadystatechange = function () 
	{
        if (es.readyState == 'loaded') 
		{
			callback(); 
        }
    }
	document.getElementsByTagName("head")[0].appendChild(es);
}

Bronson.ExternalScript.prototype.addToQueue = function(scriptUrl)
{
	var es = document.createElement("script");
	es.type = "text/javascript";
	es.src = scriptUrl + (!this.debug ? "" : (scriptUrl.indexOf("?") > -1 ? "&" : "?") + "seed=" + Math.random());
	var self = this;
	es.onload = function()
	{
		self.queueLoaded.apply(self);
	};
	es.onreadystatechange = function () 
	{
        if (es.readyState == 'loaded') 
		{
            self.queueLoaded.apply(self);
        }
    }
	this.queue.push(es);
}

Bronson.ExternalScript.prototype.loadQueue = function(callback)
{
	this.counter = 0;
	this.caller = arguments.length > 1 ? arguments[1] : null;
	this.callback = callback;

	for (var i = 0; i < this.queue.length; i++) 
	{
		document.getElementsByTagName("head")[0].appendChild(this.queue[i]);
	}
}

Bronson.ExternalScript.prototype.queueLoaded = function()
{
	this.counter++;
	if (this.counter == this.queue.length)
	{
		if (this.caller != null) 
			this.callback.call(this.caller);
		else
			this.caller();
		this.caller = null;
		this.queue = [];
		this.callback = null;
	}
	
}



