/*
 * XMLhr : simple tool for simpler XMLHttpRequest use
 * michael.lecerf@gmail.com
 * 2006-06-14
*/
function XMLhr()
{
	var xhr, complete = false;
	
	// Tries to create a XMLHttpRequest object
	try
	{
		xhr = new ActiveXObject("Msxml2.XMLHTTP");// IE
	}
	catch (e)
	{
		try
		{
			xhr = new ActiveXObject("Microsoft.XMLHTTP");// IE
		}
		catch (f)
		{
			try
			{
				xhr = new XMLHttpRequest();// other browsers
			}
			catch (g)
			{
				xhr = false;// XMLHttpRequest is not available
			}
		}
	}
	if (!xhr) return false;
	
	/* request() : send data
	 *
	 * url		url to send data to
	 * vars	query string containing variables to send
	 * 		or
	 * 		array with variables names as keys and variables values as values (like  myArray[property] = value;)
	 *		NOTE : if you use an array, values does not need (or more exactly must not) to be url-encoded; the request function takes care of that
	 * fn		a reference to a function that will be called when the HTTP request will be complete
	 *		this function should take a single argument, it will be the XMLHttpRequest object
	 * method	optional parameter specifying the type (GET or POST) of HTTP request to make. "POST" is used if a method is not given
	*/
	this.request = function(url, vars, fn, method)
	{
		if (!xhr) return false;
		complete = false;
		
		if (method == null) method = 'POST';
		else method = method.toUpperCase();
		
		// converts the array in query string
		if (vars instanceof Array)
		{
			var qs = '';
			for (i in vars)
				qs += i+'='+encodeURIComponent(vars[i])+'&';
			vars = qs.substring(0, (qs.length-1));
		}
		
		try
		{
			// sends data using GET
			if (method == 'GET')
			{
				xhr.open('GET', url+'?'+vars, true);
				vars = '';
			}
			// sends data using POST
			else
			{
				xhr.open('POST', url, true);
				xhr.setRequestHeader("Method", "POST "+url+" HTTP/1.1");
				xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			}
			// calls fn function when the HTTP request is complete
			xhr.onreadystatechange = function()
			{
				if (xhr.readyState == 4 && !complete)
				{
					complete = true;
					fn(xhr);
				}
			}
			
			xhr.send(vars);
		}
		catch (h)
		{
			return false;
		}
		
		return true;
	}
	
	return this;
}
