/* ***********************************************
 *	Implementación de AJAX
 *	Inmedia Web Builder Engine.
 *	Comunicación asícrona con el servidor para enviar
 *	una petición y procesar una url.
 * ***********************************************
 */

/*
 * Clase que realiza las funciones de ajax comunicación
 * asíncrona.
 */
function WBE_AjaxClass()
{

	this.parameters = new Array();
	this.httpReq;
	this.url = "NO_OUTPUT.wbe";
	this.xml_resource = "XML_DOCUMENT.wbe";
	//this.url = window.document.location.toString();
	this.params;
	this.async = false;	// Indica si se utilizará una comunicación asíncrona
	this.skip_edit_mode = false;	// Indica si se realizará la operación evitando el entorno de edición
	this.hasErrors = (!this.httpReq || this.httpReq.status != 200);

	this.waitResponseHandler = function() {};

	/* Inizializa Ajax para nuevas llamadas */
	this.clear = function () {
		this.parameters = new Array();
	}
	
	/* Añade un nuevo parámetro para enviar.
	   Sólo lo añade si llega un parámetro */
	this.addEventPostParameter = function(sName, sValue) {
		if (sName!=null && sValue!=null) {
		
			sValue += "";
			if (sValue.indexOf('&') > 0) {
				a_sValue = sValue.split('&');
				sValue = a_sValue[0];
				var sAuxName = a_sValue[1].substring(0, a_sValue[1].indexOf('='));
				var sAuxValue = a_sValue[1].substring(a_sValue[1].indexOf('=')+1);
				this.addPostParameter(sAuxName, sAuxValue);
			}
			
			this.parameters[this.parameters.length] = sName + "=" + encodeURIComponent(sValue);
		}
	}	

	/* Añade un nuevo parámetro para enviar.
	   Sólo lo añade si llega un parámetro */
	this.addPostParameter = function(sName, sValue) {
		if (sName!=null && sValue!=null) {
			this.parameters[this.parameters.length] = sName + "=" + encodeURIComponent(sValue);
		}
	}	
	
	/* Devuelve el valor de un nodo del XML que se le pasa */
	this.getXMLNodeValue = function (oXMLNode, sTagName) {
		var value = oXMLNode.getElementsByTagName(sTagName);
		return (value!=null && value.length>0 && value[0].firstChild!=null)
			? value[0].firstChild.nodeValue
			: '';
	}
	
	// Esta función envía una petición AJAX al servidor a la
	// Url que se le pasa enviando un POST con la cadena de parámetros.
	this.call = function ()  {

		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			this.httpReq = new XMLHttpRequest();
			if (this.async)
				this.httpReq.onreadystatechange = this.waitResponseHandler;
		} else if (window.ActiveXObject) { // IE
			try {
				this.httpReq = new ActiveXObject("Msxml2.XMLHTTP");
				if (this.async)
					this.httpReq.onload = this.waitResponseHandler;
			} catch (e) {
				try {
				this.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
				if (this.async)
					this.httpReq.onreadystatechange = this.waitResponseHandler;
				} catch (e) {}
			}
		}

		if (!this.httpReq) {
			alert('No puedo crear una instancia AJAX');
			return false;
		}

		/*
		// Crea la instancia para crear llamadas.
		if (window.ActiveXObject != undefined) { // IE
			this.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
			// Inicializa la función que comprobará la request
			this.httpReq.onreadystatechange = this.waitResponseHandler;
				
		} else {	// Mozilla
			this.httpReq = new XMLHttpRequest();
			// Inicializa la función que comprobará la request
			this.httpReq.onload = this.waitResponseHandler;
		}
		*/
		
		this.url=this.url.replace('#','');
		//alert(this.params);
		
		if (this.skip_edit_mode) this.addPostParameter("switch_off_edit_environment", "1");
		
		// Llamada a la URL
		this.httpReq.open("POST", this.url, this.async);	// Comunicación síncrona por el flag: false
		this.httpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		this.httpReq.send(this.params);

		// Sólo para comunicación sícrona
		if (!this.async)
			this.responseText = this.httpReq.responseText;
	
	};

	// Lanza un evento Ajax.
	// Recibe como entradas:
	//	Evento para lanzar.
	//	Parámetros para enviar en un array de strings.
	//	booleano indicando si la salida es un XMLDocument o como un string.
	this.throwEvent = function (sEvent, asParams, bDoXmlOutput, sUrl)
	{
		var xmlDoc;

		if (sUrl) this.url = sUrl;

		this.params = "event=" + sEvent;
		if (asParams) {
			for (var i=0; i<asParams.length; i++)
				this.params += "&" + asParams[i];
		}
		// alert(this.params);

		// Llamada Ajax
		this.call();

		//alert(this.responseText);
		// Salida de texto
		if (!bDoXmlOutput) return this.responseText;

		// La salida es XML Document.
		if (this.responseText=="") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, this.responseText);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(this.responseText);
			}
		}
		return xmlDoc.documentElement;
	};

	// Lanza una llamada a una url.
	this.throwCall2 = function (sUrl) {
		var xmlDoc;

		if (sUrl) this.url = sUrl;

		this.params = "";
		for (var i=0; i<this.parameters.length; i++) {
		  if (this.params!="") this.params += "&";
		  if (this.parameters[i]!=undefined)	this.params += this.parameters[i];
		}
		//alert(this.params);
		//alert(sUrl);
		
		//return;
		// Llamada Ajax
		this.call();
   }

	/* Lanza un evento Ajax que devuelve un objeto XML DOM
	// Recibe como entradas:
	//  Pgina que recoger�. */
	this.throwEventXML = function (sEvent)  {
    return this.throwEvent2(sEvent, true, this.xml_resource);
  }

	/* Lanza un evento Ajax.
	// Recibe como entradas:
	//	Evento para lanzar.
	//	booleano indicando si la salida es un XMLDocument o como un string.
	//  P�gina que recoger�. */
	this.throwEvent2 = function (sEvent, bDoXmlOutput, sUrl)
  {

		this.addEventPostParameter("event", sEvent);
		this.throwCall2(sUrl);
	    
   		// Salida de texto
		if (!bDoXmlOutput) return this.responseText;

		// La salida es XML Document.
		if (this.responseText=="") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, this.responseText);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(this.responseText);
			}
		}

		return xmlDoc.documentElement;
	};
		
	// Para Mozilla.
	// Carga el XML a partir de un string.
	this.LoadXMLMozilla = function (oDoc, s)
	{
		// parse the string to a new doc   
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
		      
		// remove all initial children
		while (oDoc.hasChildNodes())
			oDoc.removeChild(this.lastChild);
		         
		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			oDoc.appendChild(oDoc.importNode(doc2.childNodes[i], true));
		}
	};	

	// Lanza una llamada a una url.
	this.throwCall = function (asParams, bDoXmlOutput, sUrl)
	{
		var xmlDoc;

		if (sUrl) this.url = sUrl;
		if (asParams) {
			for (var i=0; i<asParams.length; i++)
				this.params += "&" + asParams[i];
		} else {
			this.params = "";
			for (var i=0; i<this.parameters.length; i++) {
				if (this.params!="") this.params += "&";
				if (this.parameters[i]!=undefined)	this.params += this.parameters[i];
			}
		}
		// alert(this.params);

		// Llamada Ajax
		this.call();

		// Salida de texto
		if (!bDoXmlOutput) return this.responseText;
		//alert(this.responseText);

		// La salida es XML Document.
		if (this.responseText=="") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, this.responseText);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(this.responseText);
			}
		}
		//alert(xmlDoc.documentElement);
		return xmlDoc.documentElement;
	};

	// Lanza una llamada a una url.
	this.createXmlDoc = function (sXml)
	{
		var xmlDoc;

		if (sXml=="") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, sXml);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(sXml);
			}
		}
		//alert(xmlDoc.documentElement);
		return xmlDoc.documentElement;
	};
	
};

