var xmlRequests = {};

function getData(serviceUrl, dataIn, dataHandler, key) {
	window.console.log('getData(), ' + key + ':');
	window.console.log(dataIn);
	try {
		var xmlRequest = getXmlRequest(key);
		var readyState = xmlRequest.readyState;
		if (readyState != 0 && readyState != 4) { // 0: uninitialized, 4: complete
			xmlRequest.abort();
		}
		xmlRequest['key'] = key;
		xmlRequest['dataHandler'] = dataHandler;
		xmlRequest.onload = function() { onloadHandler(xmlRequest); }
		xmlRequest.open("POST", serviceUrl, true);
		xmlRequest.setRequestHeader("Cache-Control", "no-cache");
		xmlRequest.send(dataIn);
	} catch(e) {
		alert('Service is currently unavailable');
	}
}

function getXmlRequest(key) {
	var ret = xmlRequests[key];
	if (typeof ret == 'undefined') {
		ret = new XMLHttpRequest();
		xmlRequests[key] = ret;
	}
	return ret;
}

function onloadHandler(xmlRequest) {
	var rootNode = null;
	if (xmlRequest.status == 200) {
		window.console.log('dataHandler() status 200, ' + xmlRequest.key + ':');
		//window.console.log(xmlRequest.responseText);
		if (xmlRequest.responseXML) {
			rootNode = xmlRequest.responseXML.documentElement;
		}
	} else {
		window.console.log('dataHandler() status ' + xmlRequest.status);
		alert('Server error ' + xmlRequest.status);
	}
	xmlRequest.dataHandler(rootNode, xmlRequest['key']);
}

function findChild(element, nodeName, namespace)
{
    var child;

	if (element) {
		for (child = element.firstChild; child != null; child = child.nextSibling) {
			if (child.localName == nodeName) {
				if (namespace == null || child.namespaceURI == namespace)
					return child;
			}
		}
	}

    return null;
}

function allData(node)
{
    var data = "";
    if (node && node.firstChild) {
        node = node.firstChild;
        if (node.data) data += node.data;
        while (node = node.nextSibling) {
            if (node.data) data += node.data;
        }
    }

    return data;
}


