/* Este fichero se encagar de la conexión AJAX. Tiene compatibilidad con todos los navegadores */
/* Código original extraido de librosweb.es (Introducción a AJAX). Modificado para añadir compatibilidad con clases JS */

var net = new Object();

// Constantes estado de la consulta 
net.READY_STATE_UNINITIALIZED = 0;
net.READY_STATE_LOADING = 1;
net.READY_STATE_LOADED = 2;
net.READY_STATE_INTERACTIVE = 3;
net.READY_STATE_COMPLETE = 4;
 
// Constructor
// url:			Es la ruta de la funciión del servidor que queremos 'preguntar'.
// func:		Es la función que se ejecutará (con los datos del servidor) si todo va bien.
// funcError:	Es la función que se ejecutará si hay algún error (si no damos ninguna, la función por defecto).
// msg:			Son los argumentos con los que llamamos a la función del servidor.
// obj:			Objecto (this) de la clase desde la que se llama.
net.ContentLoader = function(url, func, funcError, msg, obj) 
{
	if(obj)
		this.obj = obj;
	else
		this.obj = false;

	// Inicializa los valores.
	this.url = url;
	this.req = null;
	this.onload = func;
	this.onerror = (funcError) ? funcError : this.defaultError;
	
	// Llamada al servidor.
	this.loadXMLContent(url, msg);
}
 
net.ContentLoader.prototype = 
{
	// Hace la llamada al servidor
	// Utiliza la url que le dimos y los argumentos (msg)
	loadXMLContent: function(url, msg) 
	{
		if(window.XMLHttpRequest) 
		{
			this.req = new XMLHttpRequest();
		}
		else if(window.ActiveXObject) 
		{
			this.req = new ActiveXObject("Microsoft.XMLHTTP");
		}
 
		if(this.req) 
		{
			try 
			{
				var loader = this;
				this.req.onreadystatechange = function() 
				{
					loader.onReadyState.call(loader);
				}
				this.req.open('POST', url, true);
				this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				this.req.send(msg);
			} catch(err) {
				this.onerror.call(this);
			}
		}
	},

	// La función que se ejecutará cuando el servidor nos devuelva una respuesta.
	onReadyState: function() 
	{
		var req = this.req;
		var ready = req.readyState;

		// Servidor listo.
		if(ready == net.READY_STATE_COMPLETE) 
		{
			var httpStatus = req.status;

			// Respuesta correcta: llamamos a nuestra función con la respuesta
			if(httpStatus == 200 || httpStatus == 0) 
			{
				if(this.obj)
					this.onload.call(this.obj, this.req);
				else
					this.onload.call(this);
			}
			// Respueseta incorrecta: llamamos a la función de error.
			else 
			{
				this.onerror.call(this);
			}
		}
	},

	// Función de error por defecto.
	defaultError: function() 
	{
	
	}
}
