/**
 * Clase para trabajar con AJAX
 * Fernando Pascua García
 * 9 Mayo 2008
*/ 

var net = new Object();

// Constantes para saber el estado de la comunicacion con el servidor
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 de la clase
net.AJAX = function(url,parametros) {
	this.url = url;
	this.req = null;
	opciones = arguments[2] || {};
	this.metodo = opciones.metodo || 'POST';
	this.contentType = opciones.contentType || 'application/x-www-form-urlencoded';
	this.sincrona = (opciones.sincrona)? ((opciones.sincrona == true)? true : false): true;  //por defecto true
	this.result = opciones.result || 'innerHtml'; // 'innerHtml'|'XML'
	this.div = opciones.div || '';
	this.cargador = opciones.cargador || '';	//Si deseas un elemento loading
	this.evalBefore = opciones.evalBefore || false;
	this.onload = opciones.funcion || '';
	this.onerror = opciones.funcionerror || this.errorDefecto;
	this.cargaContenidoXML(this.metodo, parametros, this.contentType, this.sincrona);
}

net.AJAX.prototype = { 
	cargaContenidoXML: function(metodo, parametros, contentType, sincrona) {
		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.leerEstado.call(loader); 
				} 
				this.req.open(metodo, this.url, (sincrona===false)?false:true);
				
				if(contentType) {
					this.req.setRequestHeader("Content-Type", contentType);
				}
				this.req.send(parametros);
			} catch (err) { 
				this.onerror.call(this);
			} 
		}
	},

	leerEstado: function() {
		if (this.req.readyState == net.READY_STATE_COMPLETE) { 
			var httpStatus = this.req.status;
			if(httpStatus == 200 || httpStatus == 0) {
				if (this.result == 'innerHtml'){
					document.getElementById(this.div).innerHTML = this.req.responseText;
					if (this.cargador != '')
	            		hide_div(this.cargador);
					eval(this.evalBefore); 
				} else {
					//if (this.cargador != '') Dehabilitado porque en ocasiones la creación el Dom tarda demasiado y el cargador ya no está y confunde .. Se debe deshabilitar a mano: hide_div('id_DIV');
	            	//	hide_div(this.cargador);
					this.onload.call(this);
				}
			}
			else { 
				this.onerror.call(this);
			} 
		} else {
			if (this.cargador != '')
            	show_div(this.cargador);
        } 
	}, 

	errorDefecto: function() { 
		alert("Se ha producido un error al obtener los datos" 
				+ "\n\nreadyState:" + this.req.readyState 
				+ "\nHTTPestado: " + this.req.status 
				+ "\nCabeceras: " + this.req.getAllResponseHeaders()); 
	}
}

