// 20091117 - Removed use of base_url. @action no longer adds ".php"
// 20091005 - Added GetRemoteResponse (SJAX)

/** Notes
	oncomplete(bool success, data, oncomplete_arg, hash)
		Will call oncomplete(false, msg, oncomplete_arg, hash) on failure
*/

// NOTE: Use urlencode() on 'data' before sending
function PerformRemoteAction(oncomplete, action, data, postdata, oncomplete_arg)
{
	var hash = Math.random();
	var req = NewRequest(oncomplete, oncomplete_arg, hash);
	if (!req)
		return false;
	
	var url = action + '?' + data + '&hash=' + hash;
	if (postdata != undefined && postdata != null && postdata.length > 0)
	{
		req.open('POST', url, true);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(postdata);
		return hash;
	}

	req.open('GET', url, true);
	req.send('');
	return hash;
}

// NOTE: Use urlencode() on 'data' before sending
function GetRemoteResponse(action, data, postdata)
{
	var hash = Math.random();
	var req = NewRequest(null);
	if (!req)
		return false;
	
	var url = action + '?' + data + '&hash=' + hash;
	if (postdata != undefined && postdata != null && postdata.length > 0)
	{
		req.open('POST', url, false);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(postdata);
	}
	else
	{
		req.open('GET', url, false);
		req.send('');
	}

	/* Skip to first XML element */
	var root = req.responseXML;
	if (root == null || root.childNodes.length == 0)
		return req.responseText; // Not XML
	
	var node = root.childNodes[0];
	if (node.nodeName == 'xml')
		node = root.childNodes[1];
	return node;
}

function NewRequest(oncomplete, oncomplete_arg, hash)
{
	var req;
	if (window.XMLHttpRequest)
	{
		try
		{
			req = new XMLHttpRequest();
		}
		catch (e) {}
	}
	else if (ActiveXObject)
	{
		try
		{
			req = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (e)
		{
			try
			{
				req = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e) {}
		}
	}
	
	if (oncomplete != null)
		req.onreadystatechange = function() { processReqChange(req, oncomplete, oncomplete_arg, hash); };
	
	return req;
}

function processReqChange(req, oncomplete, oncomplete_arg, hash)
{
	if (req.readyState != 4)
		return;
	if (req.status == 200)
	{
		if (oncomplete == null)
		{
			document.location.reload();
		}
		else
		{
			/* Skip to first element */
			var root = req.responseXML;
			if (root == null || root.childNodes.length == 0)
			{
				// Not XML
				oncomplete(true, req.responseText, oncomplete_arg, hash);
			}
			else
			{
				var node = root.childNodes[0];
				if (node.nodeName == 'xml')
					node = root.childNodes[1];
				oncomplete(true, node, oncomplete_arg, hash);
			}
		}
	}
	else
	{
		var errMsg = null;
		try
		{
			errMsg = req.statusText;
		}
		catch (ex)
		{
			errMsg = 'Unknown error';
		}
		try
		{
			errMsg += "\r\n" + req.responseText;
		}
		catch (ex)
		{ }
		
		oncomplete(false, 'Request failed: ' + errMsg, oncomplete_arg, hash);
	}
}