// ------------------------------------------------------------------------------------------------------------
// Usage:
//
// ajax(url[,method][,httpheaders][,cache][,callback])
//
// url: (string): have a guess :-)
// method: (string or false): GET/POST (default GET)
// httpheader: (array or false): headers to be sent e.g. new Array("Connection: Close", "Cookie: firstName=John") - use false if not wanted
// cache: (bool): same guess! - note: seting to false may yield errors due to forged parameter on some websites
// callback: (function or false): ommit if no callback is required, else use function(h,t) { } where h are the headers returned and t is the text returned
//
// notes:
//	if server yield a 302 or 304 header (found, moved, ...) ajax will stop
//	results longer than 32k will go bananas
// ------------------------------------------------------------------------------------------------------------

var http = new Array();
var pid=0;

function ajax() {
	a = arguments;
	if (a.length == 0) return; else url = a[0];
	var method = "GET"; if (a.length >= 2) method = a[1];
	var extraheaders = false; if (a.length >= 3) extraheaders = a[2];
	var cache = false; if (a.length >= 4) cache = a[3];
	var callback = false; if (a.length >= 5) callback = a[4];
	params = ""; if (method == "POST" && url.indexOf("?") != -1) { s = url.split("?"); url = s[0]; params = s[1]; }
	if (!cache) url = url + ((url.indexOf("?") != -1) ? "&" : "?") + "randomajax=" + new Date().getTime();
	var o = http[pid];
	o = getHTTPObject();
	o.open(method, url, true);
	if (extraheaders) {
		for (var i = 0; i < extraheaders.length; i++) {
			h = extraheaders[i].split(": ");
			o.setRequestHeader(h[0], h[1]);
		}
	}
	if (method == "POST") o.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	o.setRequestHeader("Accept-Charset", "ISO-8859-1");
	o.onreadystatechange = function() {
		if (o.readyState == 4) {
			if (o.status > 0) {
				if (callback) {
					t = typeof callback;
					txt = o.responseText.replace(/^\s+/,'').replace(/\s+$/,'');
					head = "HTTP/1.1 " + o.status + " " + o.statusText + "\r\n" + o.getAllResponseHeaders();
					if (t == "function") callback(head, unescape(txt));
					if (t == "string") eval(eval("callback")+"(head,unescape(txt))");
				}
			} else self.status = "AJAX error: " + o.statusText + " (" + o.status + ")";
		}
	}
	o.send(method == "GET" ? null : params);
	pid++;
}


function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) {
			try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch (E) { xmlhttp = false; }
		}
	@else
	xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }
	}
	return xmlhttp;
}

/*
ajax("File:\\\\C:\\test.doc", "GET", new Array("Connection: Keep-alive"), true, function(h,t) {
	alert(h+t);
});
*/
