/*
	Humanique AJAX request handler
*/



var __hua_httprequests = new Array();
var __hua_inforequests = new Array();
var __hua_outstanding = 0;

/*
	initialise an http-request object and set the callback function for the request
*/
function huajax_init(callback_func,updatedocument)
{
	httpreq = false;

	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
		httpreq = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e) {
		try {
			httpreq = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) {
			httpreq = false;
		}
	}
	@end @*/
	if (!httpreq && typeof XMLHttpRequest!='undefined') {
		httpreq = new XMLHttpRequest();
	}


	// determine the index in the request array

	len = __hua_httprequests.length;
	idx = len;				// we can always add a request at the end

	if (len > 0) {
		// trying to put the request in an unused entry in the array
		for(l=0; l < len; l++) {
			if (__hua_inforequests[l].hua_outstanding == 0) {
				idx = l;
				break;
			}
		}
	}

	// store the request in our array
	__hua_httprequests[idx] = httpreq;
	__hua_inforequests[idx] = new Array();

	// set the callback
	__hua_inforequests[idx].hua_ondispatch     = callback_func;
	__hua_inforequests[idx].hua_updatedocument = updatedocument;

	// set the dispatcher
	__hua_httprequests[idx].onreadystatechange = function() { if (__hua_httprequests[idx].readyState == 4) { huajax_dispatcher() } };

	huajax_requestopened(idx);


	return httpreq;
}

/*
	the dispatcher
	
	once a request is finished we get a signal and we find out what requests are finished and call
	the callbacks for that request
*/
function huajax_dispatcher()
{
	var l, len = __hua_httprequests.length;

	for(l=0; l < len; l++) {
		if ((__hua_inforequests[l].hua_outstanding) && (__hua_httprequests[l].readyState == 4)) {
			if (__hua_inforequests[l].hua_updatedocument) {
				huajax_updatedocument(l, __hua_httprequests[l]);
			}
			if (__hua_inforequests[l].hua_ondispatch != "") {
				eval(__hua_inforequests[l].hua_ondispatch + "(" + l + ",__hua_httprequests[" + l + "])");
			}
			huajax_requestfinished(l);
		}
	}
}

/*
	
*/
function huajax_requestopened(idx)
{
	__hua_outstanding++;
	__hua_inforequests[idx].hua_outstanding = 1;

	//__huajax_log("outstanding = " + __hua_outstanding + " (+1)");

	ajax_statechange();
}

/*
*/
function huajax_requestfinished(idx)
{
	__hua_outstanding--;
	__hua_inforequests[idx].hua_outstanding = 0;

	//__huajax_log("outstanding = " + __hua_outstanding + " (-1)");

	ajax_statechange();
}

/*
	schedule a GET request and get called back
*/
function huajax_get(url,callback_func)
{
	httpreq = huajax_init(callback_func,0);

	httpreq.open("GET",url,true);
	httpreq.send(null);
}

/*
	schedule a GET request and only let hu-ajax do a screenupdate
*/
function huajax_get_screenupdate(url)
{
	httpreq = huajax_init("",1);

	httpreq.open("GET",url,true);

	httpreq.send(null);
}

/*
	schedule a POST request and get called back
*/
function huajax_post(url,postdata,callback_func)
{
	httpreq = huajax_init(callback_func,0);

	httpreq.open("POST",url,true);
	httpreq.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=utf-8");
	//httpreq.setRequestHeader("Content-type","multipart/form-data");

	httpreq.send(postdata);
}

function huajax_updatedocument(idx, request)
{
	root = request.responseXML;

	if (!root) {
		// alert("huajax_updatedocument(): request has no root element");
		return;
	}

	reps = root.getElementsByTagName("replacement");
	var r, c, rep_id, el, r_el;
	for(r=0; r < reps.length; r++) {
		rep_id = reps[r].getAttribute("id");

		el = document.getElementById(rep_id);
		if (el) {
			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}
			for(c=0; c < reps[r].childNodes.length; c++) {
				r_el = reps[r].childNodes[c];
				if (r_el.nodeType == 1) {	// doesn't work in MSIE 5.0
					//el.appendChild(r_el);
					__huajax_copy_tree(el,r_el);
				}
			}

			__huajax_log("replaced: " + rep_id);
		}
		else {
			alert("huajax_updatedocument(): no original for replacement " + rep_id);
		}
	}
}

var __huajax_attr_to_copy = new Array ( "id", "href", "value", "name", "for", "type" );
function __huajax_copy_tree(dst,src)
{
	var c;
	var dst_node;

	switch (src.nodeType) {
		case 1:
			// copy node element
			dst_node = document.createElement(src.nodeName);

			// copy specific node attributes
			if ((src.getAttribute("class") != null) && (src.getAttribute("class") != "")) {
				dst_node.className = src.getAttribute("class");
			}
			if ((src.getAttribute("type") != null) && (src.getAttribute("type") != "")) {
				//alert(dst_node.getAttribute("type"));
				dst_node.setAttribute("type",src.getAttribute("type"));
			}

			if (src.nodeName == "TEXTAREA") {
				//alert(src.nodeName + ": " + src.nodeValue + ", " + src.nodeType);
			}

			// copy node attributes (w/o events)
			for(a=0; a < __huajax_attr_to_copy.length; a++) {
				value = src.getAttribute(__huajax_attr_to_copy[a]);
				if ((value != null) && (value != "")) {
					if (__huajax_attr_to_copy[a] == "id") {
						//alert("trying id:" + value);
					}
					if ((__huajax_attr_to_copy[a] != "type") && (1)) {
						dst_node.setAttribute(__huajax_attr_to_copy[a],value);
					}
					if (__huajax_attr_to_copy[a] == "type") {
						//alert("tryed type");
					}
				}
			}

			// copy node events
			if ((src.getAttribute("onclick") != null) && (src.getAttribute("onclick") != "")) {
				huajax_seteventhandler(dst_node,"onclick",src.getAttribute("onclick"));
			}
			if ((src.getAttribute("onsubmit") != null) && (src.getAttribute("onsubmit") != "")) {
				huajax_seteventhandler(dst_node,"onsubmit",src.getAttribute("onsubmit"));
			}
			if ((src.getAttribute("onmouseover") != null) && (src.getAttribute("onmouseover") != "")) {
				huajax_seteventhandler(dst_node,"onmouseover",src.getAttribute("onmouseover"));
			}

			dst.appendChild(dst_node);

			// copy node children
			if (src.childNodes.length > 0) {
				for(c=0; c < src.childNodes.length; c++) {
					__huajax_copy_tree(dst_node,src.childNodes[c]);
				}
			}
			break;

		case 2:
			break;

		case 3:
			value = new String(src.nodeValue);
			if (dst.nodeName == "TEXTAREA") {
				// fix for MSIE; newlines are ignored without this fix
				value = value.replace(/\r\n/g,"\n");
				value = value.replace(/\r/g,"\n");
				value = value.replace(/\n/g,"\r");
			}
			dst_node = document.createTextNode(value);
			dst.appendChild(dst_node);
			break;
	}
}

function huajax_sharedeventhandler(e)
{
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

	code = targ.getAttribute("hua_on" + e.type);

	//alert(e + "/" + e.type + "\n" + targ + "\n" + code);

	ret = false;

	eval(code);

	return ret;
}

function huajax_seteventhandler(node, eventtype, code)
{
	switch (eventtype) {
		case "onclick":
			node.onclick = huajax_sharedeventhandler;
			break;
		case "onsubmit":
			node.onsubmit = huajax_sharedeventhandler;
			break;
		case "onmouseover":
			node.onmouseover = huajax_sharedeventhandler;
			break;

		default:
			alert("huajax_seteventhandler(): event not supported (" + eventtype + ")");
	}
	node.setAttribute("hua_" + eventtype,code);
}

function __huajax_dump()
{
	for(l=0; l < len; l++) {
		if (__hua_inforequests[l].hua_outstanding) {
			_-huajax_log("outstanding #" + l + ": " + __hua_inforequests[l].hua_ondispatch + "/" + __hua_inforequests[l].hua_updatedocument);
		}
	}
}

var __huajax_logcounter = 0;
function __huajax_log(msg)
{
	el = document.getElementById("ajaxdebug");

	if (el) {
		el.style.display = "block";

		el.innerHTML = __huajax_logcounter + ": " + msg + "<br />\n" + el.innerHTML;
		__huajax_logcounter++;
		//el.innerHTML += msg + "<br />\n";
	}
}

