/*
	myAjax.js
*/

// Create a new XMLHttpRequest for all browsers
function createREQ()
{
	try
	{
		req = new XMLHttpRequest(); /* Firefox, Safari etc */
	}
	catch(e)
	{
		try
		{
			req = new ActiveXObject("Msxm12.XMLHTTP"); /* For some IE versions */
		}
		catch(e)
		{
			try
			{
				req = new ActiveXObject("Microsoft.XMLHTTP"); /* For rest of IE */
			}
			catch(E)
			{
				req = false;
			}
		}
	}
	return req;
}

// Send a request using the GET method
function requestGET(url, query, req)
{
	// To stop browers loading page from cache
	myRand = parseInt(Math.random() *9999999999);
	// Opens new request, and adds the query
	req.open("GET", url + '?' + query + '&=rand=' + myRand, true);
	req.send(null);
}

// Send a request using POST method
function requestPOST(url, query, req)
{
	// Opens the new request
	req.open("POST", url, true);
	// Sets the header
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	// Sends the query
	req.send(query)
}

// Uses item created by doAjax and applys the callback method
function doCallback(callback, item)
{
	eval(callback + '(item)');
}

// Performs everything you need to call ajax to your page
function doAjax(url, query, callback, reqtype, getxml, pageElement, loadImage)
{
	// Feedback to user that something is happening
	if(loadImage == 1)
	{
		document.getElementById(pageElement).innerHTML = 'checking';
	}
	else
	{
		document.getElementById(pageElement).innerHTML = '<center><img src="./res/loading.gif" alt="loading" width="35" height="35" /></center>';
	}
	
	// Create a new XMLHttpRequest object instance
	var myreq = createREQ();
	
	// When the page loads
	myreq.onreadystatechange = function()
	{
		// Once page had loaded
		if(req.readyState == 4)
		{
			// If everything is working
			if(req.status == 200)
			{
				// Display as responseText object
				var item = myreq.responseText;
				// Override myreq with responseXML object
				if(getxml == 1)
				{
					item = myreq.responseXML;
				}
				doCallback(callback, item);
			}
			else
			{
				// if page did not load
				alert(req.status + ": " + req.statusText + "\nSorry but there seems to be a problem.");
			}
		}
	}
	if(reqtype == 'post')
	{
		requestPOST(url, query, myreq);
	}
	else
	{
		requestGET(url, query, myreq);
	}
}

function cbackPlain(text)
{
	document.getElementById('bodyText').innerHTML = text;
}