// Firefox bug
// If you do an RPC call from a popup window, you CAN NOT work asynchronous
// Ex. opener.selectHandler(id, title); (opener is the opening window of the popup)
// The popup creates the XMLHttpRequest object and is then closed (note that in this case normally it should be opener eg. not the popup that creates and ownes the XMLHttpRequest)
// By the time the response arrives the XMLHttpRequest object is removed together with the popup window
// By some this is caused by the fact that firefox shares XMLHttpRequest objects

function doRequest(method, request, args, callbackFunction, callbackArgument)
{
	if ((method != "GET") && (method != "POST"))
	{
		alert("Invalid request method: " + method);
		return null;
	}
	var url = request;
	var postData = "";
	if (args)
	{
		var argIndex = 0;
		for (var key in args)
		{
			if (argIndex > 0) postData += "&";
			postData += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]);
			argIndex ++;
		}
		if (method == "GET")
		{
			url += "?" + postData;
		}
	}
	// Create request
	var request = null;
	if (window.XMLHttpRequest) // Firefox, Opera, iCab
	{
        request = new XMLHttpRequest();
	}
    else if (window.ActiveXObject) // IE5.5,6,7
	{
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
	if (!request)
	{
		alert("Failed to load XMLHttpRequest");
		return;
	}
	// Do request
	if (callbackFunction)
	{
		request.onreadystatechange = function() {
			if (request.readyState == 4)
			{
				var data = processResponse(request);
				callbackFunction(data, callbackArgument);
			}
		}
	}
	var async = callbackFunction != null;
	request.open(method, url, async);
	if (method == "POST")
	{
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.send(postData);
	}
	else
	{
		request.send(null);
	}
	// Process response
	if (!callbackFunction)	// Async
	{
		return processResponse(request);
	}
}

function processResponse(request)
{
	if ((request.status) && (request.status != 200) && (request.status != 201))
	{
		alert("RPC failure: HTTP error\r\nHTTP status: " + request.status + "\r\nBody:\r\n" + request.responseText);
		return null;
	}
	try
	{
		var data = eval(request.responseText);
		return data;
	}
	catch (e)
	{
		alert("JSON parsing failure: JSON data\r\n" + request.responseText);
		return null;
	}
}

