/**
 * AJAX framework for Projection
 * @author Bart
 */

/**
 * Tie an event to an object
 * @param {Object} obj
 * @param {String} eventType
 * @param {Object} fn
 * @param {Boolean} useCapture
 */
function ajax_addEvent(obj, eventType, fn, useCapture)
{
	if(obj.addEventListener)
	{
		obj.addEventListener(eventType, fn, useCapture);
		return true;
	}
	else
	{
		if(obj.attachEvent)
		{
			var r = obj.attachEvent("on"+eventType, fn);
			return r;
		}
	}
}

/**
 * Get the XMLHttpRequest-object in a browser-independent manner.
 */
function ajax_getHTTPHandler()
{
	httphandler = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try
	{
		httphandler = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
	 	try
	 	{
	 		httphandler = new ActiveXObject("Microsoft.XMLHTTP");
	 	} catch(E) {
	 		httphandler = false;
	 	}
	}
	@end @*/
	if(!httphandler && typeof XMLHttpRequest != 'undefined')
	{
		httphandler = new XMLHttpRequest();
	}
	return httphandler;
}

/**
 * Execute a GET-request
 * @param {String} getUrl
 * @return {Mixed} Response or false if failed
 */
function ajax_executeGet(getUrl, element)
{
	var xmlhttpobject = ajax_getHTTPHandler();
	if (typeof xmlhttpobject != 'undefined') {
		xmlhttpobject.open('GET', getUrl, true);
		xmlhttpobject.onreadystatechange = function(){
			if (xmlhttpobject.readyState == 4) {
				element.innerHTML = xmlhttpobject.responseText;
			}
		}
		xmlhttpobject.setRequestHeader("Cache-Control", "no-cache");
		xmlhttpobject.setRequestHeader("X_USERAGENT", "ProjectionFramework");
		
		// Let the magic begin!
		xmlhttpobject.send(null);
	}
	else
	{
		return false;
	}
}

/**
 * Execute a POST-request
 * @param {String} url
 * @param {String} postBody
 * @return {Mixed} Response or false if failed
 */
function ajax_executePost(url, postBody)
{
	var xmlhttpobject = ajax_getHTTPHandler();
	if (xmlhttpobject != false) {
		xmlhttpobject.open('POST', url, true);
		xmlhttpobject.onreadystatechange = function(){
			if (xmlhttpobject.readyState == 4) {
				return xmlhttpobject.responseText;
			}
		}
		xmlhttpobject.setRequestHeader("Cache-Control", "no-cache");
		xmlhttpobject.setRequestHeader("X_USERAGENT", "ProjectionFramework");
		xmlhttpobject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlhttpobject.setRequestHeader("Connection", "close");
		
		// Let the magic begin!
		xmlhttpobject.send(postBody);
	}
	else
	{
		return false;
	}
}
