/**
* Wrapper class around AJAX functionality.
*
* @author Richard Downes
* @version 1.0
* @package ajax
*/


/**
* Constructor
*/
function Ajax(listener) {

	/**
	* An instance of XMLHttpRequest (or microsofts activeX object)
	*/
	this.xmlHttpRequest = undefined;

	/**
	* An instance of Function that is listening for a return and accepts 1 single parameter, this xmlHttpRequest object
	*/
	this.listener = listener;

	/**
	* Initialise the XMLHttpRequest object
	*
	* @return XmlHttpRequest
	*/
	this.initialise = function() {
		// check if the mozilla XMLHttpRequest object is defined
		if (window.XMLHttpRequest) {
			// create the object for mozilla
			try {
				this.xmlHttpRequest = new XMLHttpRequest();
				if (this.xmlHttpRequest.overrideMimeType) {
					this.xmlHttpRequest.overrideMimeType("text/xml");
				}
			} catch (e) {
				throw e;
			}
		// check if MS ActiveXObject is defined
		} else if (window.ActiveXObject) {
			// create the newer object for IE
			try {
				// try the new IE version first
				this.xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					// try using the old IE version
					this.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e2) {
					throw e2;
				}
			}
		} else {
			throw "Browser does not support Ajax.";
		}
	}

	/**
	* Send an HTTP GET request
	*/
	this.get = function(url) {
		var request = this.xmlHttpRequest;
		var listener = this.listener;
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				listener(request);
			}
		}
		request.open("GET", url, true);
		request.send("");
	}


	/**
	* Send an HTTP POST request
	*/
	this.post = function(url, queryString) {
		var request = this.xmlHttpRequest;
		request.open("POST", url, true);
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		var listener = this.listener;
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				listener(request);
			}
		}
		request.send(queryString);
	}

	/**
	* Sets the function object that is listening for a return
	*
	*/
	this.setListener = function(listener) {
		this.listener = listener;
	}

	/**
	* Sets the function to call on return
	*//*
	this.addXmlHttpListener = function(listener) {
		this.listeners[this.listeners.length] = listener;
	}*/

	/**
	* Remove the function to call on return
	*
	* @return True if the event was found and was removed, false otherwise
	*//*
	this.removeXmlHttpListener = function(listener) {
		// iterate over the listeners until we find a match
		var gotListener = false;
		for (var i = 0; i < this.listeners.length; i++) {
			if (this.listeners[i] == listener) {
				gotListener = true;
			}
			// once the listener is found, shift the rest down a notch in the list
			if ((gotListener == true) && (i < (this.listeners.length -1))) {
				this.listeners[i] = this.listeners[i + 1];
			}
		}
		return gotListener;
	}*/
	
this.initialise();

}

