/*

--USAGE
	
		create new ajax object :
			obj = new ajax(url, callbackFunction)
		
		callback function should (optionally) take response text as first argument, response XML as second;

		send request :
			obj.send([ method [, queryString ] ])
		
		callback function should handle the rest...

*/

function renamedAjax(url, callbackFunction)
{
	this.url = url;
	this.setMethod = setMethod;
	this.setQuery = setQuery;
	this.send = send;
	this.createObject = createObject;
	this.setResponseHandler = setResponseHandler;
	this.callback = callbackFunction || function () { };
}


function send()
{
	// optional arguments: method, queryString
	var method = (arguments.length>0) ? arguments[0] : 'GET';
	var qString = (arguments.length>1) ? arguments[1] : null;
	this.rqstObj = this.createObject();
	if (this.rqstObj)
	{
		this.setMethod(method);
		this.setQuery(qString);
		this.setResponseHandler(this);
		this.rqstObj.open(this.method, this.url, true);
		this.rqstObj.setRequestHeader('Content-Type', this.contentType);
		this.rqstObj.send(this.queryString);
		return true;
	}
	alert('AJAX error - you might consider enabling javascript to experience the full functionality of the web, '
			+ 'or getting a newer browser?');
	return false;
}


function setResponseHandler(ajaxObj)
{
	ajaxObj.rqstObj.onreadystatechange = function()
	{
		var rqstObj = ajaxObj.rqstObj;
		if ((rqstObj.readyState == 4) && (rqstObj.status == 200))
		{
			ajaxObj.callback(rqstObj.responseText, rqstObj.responseXML);
			ajaxObj.rqstObj = null;
		}
	}
}


function createObject()
{
	var req = false;
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{ // IE
		try
		{
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				return false;
			}
		}
	}
	return req;
}


function setMethod(method)
{
	if (method == 'POST')
	{
		this.method = 'POST';
		this.contentType = 'application/x-www-form-urlencoded';
	}
	else
	{
		this.method = 'GET';
		this.contentType = 'text/plain';
	}
}


function setQuery(queryString)
{
	// Be careful with this - AJAX can fail silently if this regex is not matched. It may
	// require modification, but make sure you use EncodeURIComponent on any argument values first
	var qMatch = /^[\w%]+=[\w\-%@\.]*(&[\w\-%]+=[\w%@\.\-]*)*$/;
	this.queryString = (qMatch.test(queryString)) ? queryString : null;
}
