// jsonreq by Stefan Powell - released to the public domain
// v1.4 - changed optional call parameters to a single object
// v1.3 - optional loading of jsonreq
// v1.2 - additional parameters to call get passed to the callback
// v1.0 - first release
// v0.1 - testing release

if (typeof jsonreq == "undefined") {
	jsonreqObj=function(){
		callbackObj=function(idx,reqobj,callback) {
			this.idx=idx
			this.reqobj=reqobj
			this.callback=callback
			this.args={};
		}
		callbackObj.prototype.call = function(resp) {
			if (typeof this.callback=="object") {
				// if the call back is an object call its jsonresp method
				this.callback.jsonresp(resp,this.args)
			}
			else {
				this.callback(resp,this.args)
			}
			this.reqobj.tidy(this.idx)
		}
		this.lastidx=0
		this.pendingcount=0
		this.callbacks={}
		this.nonce='&nonce='+(new Date()).getTime()
		this.headEl=document.getElementsByTagName("head").item(0)
	}

	jsonreqObj.prototype.call = function(url,callback) {
if (this.pendingcount > 0) {
  window.setTimeout(function() {jsonreq.call(url, callback) },100);
  return;
}
		try{debuglog('jsonreq '+url)}catch(ex){}
		//check if we should do it the old way
		var oldcode = 0;
		if (callback.id != null) {
		  idx = callback.id;
		} else {
		  oldcode = 1;
		  idx=++this.lastidx; //for old code
		}
		this.callbacks[idx] = new callbackObj(idx,this,callback)
		if (typeof arguments[2] == "object") {
			this.callbacks[idx].args=arguments[2]
		}
		scriptEl=document.createElement("script")
		scriptEl.setAttribute("type","text/javascript")
		scriptEl.setAttribute("charset","utf-8")
		if (oldcode) {
		  scriptEl.setAttribute("src",url+'&callback=jsonreq.callbacks'+escape('['+idx+']')+'.call'+this.nonce+idx)
		} else {
		  scriptEl.setAttribute("src",url+'&callback=' + idx + this.nonce+idx)
		}
		scriptEl.setAttribute("id",'jsonReq'+idx)
		this.callbacks[idx].scriptEl=scriptEl
		this.pendingcount++
		this.headEl.appendChild(scriptEl)
	}

	jsonreqObj.prototype.tidy = function(idx) {
		this.headEl.removeChild(this.callbacks[idx].scriptEl)
		this.pendingcount--
		delete this.callbacks[idx]
	}

	jsonreq = new jsonreqObj()
}
