﻿var ajaxNumberOfRequests=0;

function AJAXInteraction(url, callback) {
	var req = init();
	req.onreadystatechange = processRequest;
        
	function init() {
		if (window.XMLHttpRequest) {
			ajaxNumberOfRequests++;
			//show('ajaxRequestActive');
			return new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0",  "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
			for (var i = avers.length -1; i >= 0; i--) {
				try {
					httpObj = new ActiveXObject(avers[i]);
					ajaxNumberOfRequests++;
					//show('ajaxRequestActive');
					return httpObj;
				} catch(e) { }
			}
		}
	}
	
	function processRequest () {
		if (req.readyState == 4) {
			if (req.status == 200) {
				if (callback)
					callback(req.responseText);
				ajaxNumberOfRequests--;
				//if(ajaxNumberOfRequests==0) hide('ajaxRequestActive');
			}
		}
	}
	
	this.doGet = function() {
		req.open("GET", url, ((callback) ? true : false));
		req.send(null);
	}
	
	this.doPost = function(body) {
		req.open("POST", url, ((callback) ? true : false));
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(body);
	}
}

function makeRequest(url, method, data, doeval) {
	if (typeof method == "undefined")
		method = 'GET';
	
	// If we don't pass the fourth argument, assume that this is a conventional AJAX request
	// (i.e. we want a callback where the content returned by the server is evaluated by the JavaScript interpreter)
	if (typeof doeval == "undefined")
		doeval = true;
	
	var ai = new AJAXInteraction(url, ((doeval) ? function(data) { eval(data) } : null));
	
	if (method == 'GET'){
		ai.doGet();
	} else {
		if (method == 'POST'){
			ai.doPost(data);
		}
	}
}
