// Ajax functions

///////////////////////////////////////////////////////////////////////////
//
//	this is the only function you'd typically need

function ajax_Post (url, params, callback, iconId, callerId)
{
	new AjaxHandler (url, params, callback, iconId, callerId);
	
	return true;
}

///////////////////////////////////////////////////////////////////////////

var ajax_AlertGiven = false;
var ajax_List = new Array;

///////////////////////////////////////////////////////////////////////////


AjaxHandler = function (url, params, callback, iconId, callerId)
{
	var xmlHttp = this.getXmlHttpObject();
	if (!xmlHttp)
	{
		if (!ajax_AlertGiven)
		{
			alert ("Error: el navegador no tiene soporte para AJAX.");
			ajax_AlertGiven = true;
		}
		this.ok = false;
		return false;
	}
	
	// init member variables
	this.xmlHttp = xmlHttp;
	this.userCallback = callback;
	this.iconId = iconId;
	this.loadingIconTimer = null;
	this.callerId = callerId;
	
	if (typeof (params) == "string")
		paramString = params;
	else
	{
		paramString = "";
		for (key in params)
		{
			if (paramString != "")
				paramString += "&";
			paramString += key + "=" + encodeURIComponent(params[key]);
		}
	}
	
	this.ShowLoadingIcon (true);

	ajax_List.push (this);
	
	var me = this;
	
	xmlHttp.open ("POST",url,true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", paramString.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.onreadystatechange = function() { me.Callback() };
	xmlHttp.send (paramString);
}


AjaxHandler.prototype.getXmlHttpObject = function()
{
	var xmlHttp = null;
	try { xmlHttp = new XMLHttpRequest(); /* Firefox, Opera 8.0+, Safari */ }
	catch (e)
	{
		try	{ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); /* Internet Explorer */ }
		catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
	}

	return xmlHttp;
}


AjaxHandler.prototype.Callback = function()
{
	if (this.xmlHttp.readyState == 4)
	{
		this.ShowLoadingIcon (false);

		if (this.userCallback)
			this.userCallback (this.xmlHttp.responseText, this.callerId);

		ajax_List.removeByValue (this);
	}
}


AjaxHandler.prototype.ShowLoadingIcon = function (show)
{
	if (this.iconId)
	{
		// initial delay before showing the icon
		if (show && this.loadingIconTimer == null)
		{
			var me = this;
			this.loadingIconTimer = setTimeout (function() { me.ShowLoadingIcon(true) }, 1);
			return;
		}
		
		// clean up after initial delay
		if (this.loadingIconTimer)
		{
			clearTimeout (this.loadingIconTimer);
			this.loadingIconTimer = null;
		}

		// show or hide the icon
		obj = document.getElementById (this.iconId);
		if (obj)
			obj.style.display = show ? '' : 'none';
	}
}


