/**
 * @author Ed Slocombe
 */

var AJAX = {
	
	LOADING : 1,
	ERROR_PAGE_NOT_FOUND : 2,
	ERROR_UNKNOWN : 3,
	
	READY_STATE_CODE : 200,
	
	request : null,
	callback : null, 
	returnXML : true,
	loadingNotification : false,
	
	call : function (url, callback, returnXML, data, loadingNotification) {
		
		url = url;//+"#"+(new Date()).getTime();
		
		this.callback = callback;
		if (returnXML != null) this.returnXML = returnXML;
		else this.returnXML = true;
		if (loadingNotification) this.loadingNotification = loadingNotification;
		
		if (window.XMLHttpRequest) this.request = new XMLHttpRequest();
		else if (window.ActiveXObject) this. request = new ActiveXObject ("Microsoft.XMLHTTP");
		else return false;
		
		this.request.onreadystatechange = function() { AJAX.handleResponse(); };
		
		if (data) {
			
			var dataString = "";
			
			if (typeof data == "object") {
				for (var variable in data) {
					dataString += variable + "=" + data[variable] + "&";
				}
				dataString = dataString.substr(0, dataString.length-1);
			}
			else dataString = "data=" + data;
			
			this.request.open("POST", url, true);
			this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			this.request.setRequestHeader("Cache-Control", "no-cache");
			this.request.send(dataString);
			
		} else {
			this.request.open("GET", url, true);
			this.request.send(null);
		}
		
	},
	
	handleResponse : function() {
		
		if (this.request.readyState == 1 && this.loadingNotification) this.callback(AJAX.LOADING);
		
		else if (this.request.readyState == 4) {
			if (this.request.status == AJAX.READY_STATE_CODE) {
				if (this.returnXML === false) this.callback(this.request.responseText);	
				else this.callback(this.request.responseXML);
			}
			else if (this.request.status == 404) this.callback(AJAX.ERROR_PAGE_NOT_FOUND);
			else this.callback(AJAX.ERROR_UNKNOWN);	
			
		}
		
	}
	
}
