/* AJAX stuff */
/* Inspired by:
 * http://dkpinteractive.ath.cx/scripts/AJAXRequest.js
 */

function AJAX(callBack) {
	// Variables
	this.xmlHttp = null;
	this.callback = callBack;
	this.data = null;
	this.busy = false;
	
	// Member functions
	this.stop = function() {
		this.callback = function() {};
		this.xmlHttp.abort();
		this.xmlHttp = null;
		this.data = null;
		this.busy = false;
	};

	this.get = function(data) {
		var url;
		url = 'http://' + document.domain + '/ajax.php';
		
		// See if we can take the request
		if (this.busy) {
			var obj = new AJAX(this.callback);
			return obj.get(data);
		}

		// Indicate that we're doing something
		this.busy = true;

		// IE?
		if (window.ActiveXObject) {
			var xmlObjPrefixes = ['Microsoft', 'MSXML3', 'MSXML2', 'MSXML'];
			for (var i = 0; i < this.xmlObjPrefixes.length; i++) {
				try {
					this.xmlHttp = new ActiveXObject(this.xmlObjPrefixes[i] + '.XMLDOM');
					break;
				}
				catch(ex) {};
			}
		} else if (window.XMLHttpRequest) {
			try {
				this.xmlHttp = new XMLHttpRequest();
			}
			catch (ex) {};
		}

		if (this.xmlHttp == null) {
			alert('AJAX request aborted: unsupported browser detected.');
			return null;
		}
		
		var xh = this.xmlHttp;
		var cb = this.callback;
		this.xmlHttp.onreadystatechange = function() {
			if (xh.readyState == 4 && xh.status == 200) {
				// We want to hit the callback with the response data
				// Is this JSON data?
				if (xh.getResponseHeader('Content-type') == 'application/x-json') {
					// Treat as JSON
					cb(eval('(' + xh.responseText + ')'));
				} else {
					// Treat as text
					cb(xh.responseText, xh.getAllResponseHeaders());
				}
			}
		};
		this.xmlHttp.open('POST', url, true);
		this.xmlHttp.send(JSON.stringify(data));
		return this;
	};
}

function ajax_rpc(callback, name, params) {
	var aj;
	ajax = new AJAX(function(obj) {
		if (obj.error) {
			alert("Error in AJAX call.\n\n" + obj.error);
			return;
		}
		callback(obj);
		});
	ajax.get({
		"method": name,
		"params": params
		});
}

