// 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) {
		//one request per time
		if (this.pendingcount > 0) {
			window.setTimeout(function() { jsonreq.call(url, callback) }, 100);
			return;
		}

		//idx = ++this.lastidx;
		idx = "c" + hex_md5(url); // equal urls will have unique callback function call
		this.callbacks[idx] = new callbackObj(idx, this, callback);

		if (typeof arguments[2] == "object") {
			this.callbacks[idx].args = arguments[2]
		}

		var fullurl = url + '&callback=jsonreq.callbacks.' + idx + '.call' + this.nonce + idx;
		try { debuglog('jsonreq: <a href="' + fullurl + '" target="_blank">' + fullurl + '</a>') } catch (ex) { }

		scriptEl = document.createElement("script")
		scriptEl.setAttribute("type", "text/javascript")
		scriptEl.setAttribute("charset", "utf-8")
		scriptEl.setAttribute("src", fullurl)
		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();
}

