/**
 * Event driven AJAX object
 */

function AJAX() {
	var self = this;

	/**
	 * Triggered when a request begins
	 */
	this.onRequest = function() { /* override this */ }

	/**
	 * Triggered when a request completes
	 */
	this.onRequestComplete = function() { /* override this */ }

	/**
	 * Process a response
	 */
	this.processResponse = function(response) { /* override this */ }

	/**
	 * Check if the browser is AJAX capable
	 */
	this.capable = function() {
		return (false != this.create) ? true : false;
	}

	this.requestMethod = "GET";

	/**
	 * Create the XMLHTTP object
	 */
	this.create = function() {
		try {
			self.obj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				self.obj = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				self.obj = false;
			}
		}
		if (!self.obj && typeof XMLHttpRequest != 'undefined') {
		  self.obj = new XMLHttpRequest();
		}
		return self.obj;
	}

	/**
	 * The workhorse method. This retreives data from the specified uri
	 * You need to define the self.processResponse function to do something with the response
	 * @return boolean success
	 */
	this.fetch = function(uri) {
		var obj = this.create();
		if (obj !== false) {
			obj.open(self.requestMethod, uri, true);
			obj.onreadystatechange = function() {
				if (obj.readyState == 4) {
					self.processResponse(obj.responseText);
					self.onRequestComplete(); /* Fire the complete request event */
				}
			}
			obj.send(null);
			self.onRequest();
			return true;
		}
		return false;
	}

	/**
	 * Send a page request, don't worry about a response
	 * @return boolean success
	 */
	this.send = function(uri) {
		var obj = this.create();
		if (obj !== false) {
			obj.open(self.requestMethod, uri, true);
			obj.onreadystatechange = function() {
				if (obj.readyState == 4) {
					self.onRequestComplete(); /* Fire the complete request event */
				}
			}
			obj.send(null);
			self.onRequest();
			return true;
		}
		return false;
	}

	/**
	 * Inject content from a uri into a document element
	 */
	this.innerHTML = function(id, uri) {
		if (document.getElementById(id)) {
			self.processResponse = function(response) {
				document.getElementById(id).innerHTML = response;
			}
			return self.fetch(uri);
		}
		return false;
	}
}
