var sajax_debug_mode = false;
var sajax_request_type = "GET";

function sajax_debug (text)
{
	if (!sajax_debug_mode)
		return false;

	var e = document.getElementById('sajax_debug');

	if (!e)
	{
		e = document.createElement("p");
		e.className = 'debug';
		e.id = 'sajax_debug';

		var b = document.getElementsByTagName("body")[0];

		if (b.firstChild)
			b.insertBefore (e, b.firstChild);
		else
			b.appendChild (e);
	}

	var m = document.createElement("div");
	m.appendChild (document.createTextNode(text));

	e.appendChild (m);

	return true;
}

/* compatibility wrapper for creating a new XMLHttpRequest object. */
function sajax_init_object()
{
	sajax_debug ("sajax_init_object() called..");
	
	var returnValue;
	
	try
	{ // Firefox, Opera 8.0+, Safari
		returnValue = new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{ // Internet Explorer 6.0+
			returnValue = new ActiveXObject ("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{ // Internet Explorer 5.5+
				returnValue = new ActiveXObject ("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				returnValue = null;
			}
		}
	}
	if (!returnValue)
		sajax_debug ("Could not create connection object.");

	return returnValue;
}

/*
* Perform an ajax call. Calls are handeled by AjaxDispatcher.php
*   func_name - the name of the function to call.
*   args - an array of arguments to that function
*   target - the target that will handle the result of the call. If this is a function,
*            if will be called with the XMLHttpRequest as a parameter; if it's an input
*            element, its value will be set to the resultText; if it's another type of
*            element, its innerHTML will be set to the resultText.
*
* Example:
*    sajax_do_call ('doFoo', [1, 2, 3], document.getElementById("showFoo"));
*
* This will call the doFoo function, with
* (1, 2, 3) as the parameter list, and will show the result in the element
* with id = showFoo
*/
function sajax_do_call (func_name, args, target)
{
	var i, httpRequest, n;
	var uri;
	var post_data;
	uri = "api.php";
	if (sajax_request_type == "GET")
	{
		if (uri.indexOf("?") == -1)
			uri = uri + "?f=" + encodeURIComponent (func_name);
		else
			uri = uri + "&f=" + encodeURIComponent (func_name);
		for (i = 0; i < args.length; i++)
			uri = uri + "&args[]=" + encodeURIComponent (args[i]);
		//uri = uri + "&rsrnd=" + new Date().getTime();
		post_data = null;
	}
	else
	{
		post_data = "f=" + encodeURIComponent (func_name);
		for (i = 0; i < args.length; i++)
			post_data = post_data + "&args[]=" + encodeURIComponent (args[i]);
	}
	httpRequest = sajax_init_object();
	if (!httpRequest)
	{
		sajax_debug ("AJAX not supported");
		return false;
	}

	try
	{
		httpRequest.open (sajax_request_type, uri, true);
	}
	catch (e)
	{
		if (window.location.hostname == "localhost")
			sajax_debug ("Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing.");
		throw e;
	}
	if (sajax_request_type == "POST")
	{
		httpRequest.setRequestHeader ("Method", "POST " + uri + " HTTP/1.1");
		httpRequest.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
	}
	httpRequest.setRequestHeader ("Pragma", "cache=yes");
	httpRequest.setRequestHeader ("Cache-Control", "no-transform");
	httpRequest.onreadystatechange = function()
	{
		if (httpRequest.readyState != 4)
			return;

		sajax_debug ("received (" + httpRequest.status + " " + httpRequest.statusText + ") " + httpRequest.responseText);

		//if (httpRequest.status != 200)
		//	sajax_debug ("Error: " + httpRequest.status + " " + httpRequest.statusText + ": " + httpRequest.responseText);
		//else

		if (typeof (target) == 'function')
			target (httpRequest);
		else
			if (typeof (target) == 'object')
			{
				if (target.tagName == 'INPUT')
				{
					if (httpRequest.status == 200)
						target.value = httpRequest.responseText;
					//else
					//	sajax_debug ("Error: " + httpRequest.status + " " + httpRequest.statusText + " (" + httpRequest.responseText + ")");
				}
				else
				{
					if (httpRequest.status == 200)
						target.innerHTML = httpRequest.responseText;
					else
						target.innerHTML = "<div class='error'>Error: " + httpRequest.status + " " + httpRequest.statusText + " (" + httpRequest.responseText + ")</div>";
				}
			}
			else
				sajax_debug ("No target for sajax_do_call: not a function or object: " + target);

			return;
	}

	sajax_debug (func_name + " uri = " + uri + " / post = " + post_data);
	httpRequest.send (post_data);
	sajax_debug (func_name + " waiting..");
	delete httpRequest;

	return true;
}

/* @return boolean whether the browser supports XMLHttpRequest */
function wfSupportsAjax()
{
	var request = sajax_init_object();
	var supportsAjax = request ? true : false;
	delete request;

	return supportsAjax;
}