/*based on http://codesnippets.joyent.com/posts/show/602*/
function DynamicLoader()
{
	var delegate = this;
	this.loading = false;
	this.urls = new Array();
	this.targets = new Array();
	
	this.requestToTarget = function (request, target) {	  
		if (request.readyState == 4) { // only if req is "loaded"
			if (request.status == 200) { // only if "OK"
				//alert("done Loading " + target + " request: " + request.responseText + " " + document.getElementById(target).innerHTML);
				document.getElementById(target).innerHTML = request.responseText;
			} else {
				//alert("error loading " + target);
				document.getElementById(target).innerHTML=" Error:\n"+ request.status + "\n" +request.statusText;
			}
			this.targets.shift();
			this.urls.shift();
			this.loading = false;
			if( this.urls.length > 0 && this.targets.length >0)
			{
				//alert("clear out");
				this.directLoadInto(this.urls[0], this.targets[0]);
			}
		}
	};
	//Callback uses req to get the request object
	this.loadURL = 
	function (url, target, callBack) {
		document.getElementById(target).innerHTML = ' Fetching data...';
		var req = this.getHttpRequestObject();
		if (req != undefined) {
			req.onreadystatechange = function(){callBack(req, target)};
			req.open("GET", url, true);
			req.send(null);
		}
		else
			throw new Error("This browser does not support XMLHttpRequest.");
	};
	
	this.getHttpRequestObject = function()
	{
		if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			return new XMLHttpRequest();
		}
		if (window.ActiveXObject)
		{
			// code for IE6, IE5
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
		return null;
	}
	
	this.loadInto = function (url, target) {
		this.urls.push(url);
		this.targets.push(target);
		if( !this.loading )
			this.directLoadInto(url, target);
		//else
			//alert("interuptLoading: url: " + url + " target: " + target);
	};
	
	this.directLoadInto = function(url, target) {
		this.loading = true;
		this.loadURL(url,target, function(req, target) {delegate.requestToTarget(req, target);});
		//alert( "startLoading: url: " + url + " target: " + target);
	}
}
