/* Simple AJAX Code-Kit (SACK) */
/* 2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */

/* This is a modified version of the software indicated above 
 * Modified by Hermann Kaser for Caleio 
 * hermann.kaser@gmail.com 
 * http://www.caleio.com */

 
 /* la clase se inicializa tal que: 
  * var ajax = new sack(); 
  */
 
 
function sack(){
	this.AjaxFailedAlert = "Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one.\n";
	this.URLString = null;		// El script en el servidor al que va el request
	this.object1 = null; 		// El elemento que ha llamado al JS 
	this.object2 = null;        // En caso de tener que rellenar un hidden
	this.object3 = null;        // En caso de tener que poner visible/no visible un elemento relacionado
	this.isRunning = false;     // Determina si se esta realizado peticion.

	/* funciones que se ejecutan en cada paso de la conexion xmlhttprequest */
	this.onLoading = function() { };
	this.onLoaded = function() { };
	this.onInteractive = function() { };
	this.onCompletion = function() { };
	
	/* funcion que crea el objecto xmlhttprequest */
	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	
	this.runAJAX = function(){
	    this.isRunning = true;
		this.responseStatus = new Array(2);
		if(this.failed && this.AjaxFailedAlert)
		{ 
			alert(this.AjaxFailedAlert); 
		} else {
			if (this.xmlhttp) 
			{
				var self = this;
				
				/* no recuerdo bien porque POST, creo que si usamos GET no se puede enviar informacion */
				this.xmlhttp.open("GET", this.URLString, true);
				
				/* cabecera para que el servidor sepa que es xml */
				//this.xmlhttp.setRequestHeader("Content-Type", "text/xml");
				
				/* enviar el xml */
				//document.location.href = this.URLString;
				this.xmlhttp.send(this.URLString);
				
				/* vigilamos los cuatro estados de la conexion, y se van ejecutando las funciones */
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState){
						case 1:
							self.onLoading();
							break;
							
						case 2:
							self.onLoaded();
							break;
							
						case 3:
							self.onInteractive();
							break;
							
						/* el estado cuatro es completado */
						case 4:
							/* el primer response guarda el resultado como texto, este es bueno para debug
							 * se puede hacer un alert() de esta variable y sale todo el reponse */
							self.response = self.xmlhttp.responseText;
							
							/* este response si es XML, con este nos podemos mover por el DOM como si fuesen nodos */
							self.responseXML = self.xmlhttp.responseXML;
							
							/* estas nunca las use, pero me imagino que serÃ¡n utiles para debuging, 
							 * me imagino que son cosas como 404 y Page not found */
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							
							/* la funciÃ³n que se ejecutar una vez terminado todo lo anterior 
							 * aqui se puede asignar una segunda funciÃ³n post-request para que haga algo
							 * con el xml y lo muestre */
							self.onCompletion();
							break;
					}
				};
			}
		}
	};

this.createAJAX();
}


function RellenaDiv(xml, objDiv, objHidden) {
    var texto = "";
    try {
        if (xml.childNodes.length > 0) {
            var nodes = xml.getElementsByTagName('anyType');
            if (nodes.length > 0) {
                objDiv.innerHtml = "";
                for(i=0; i<nodes.length; i++){
			        if (nodes[i].childNodes.length >= 2)
			            texto += "<a href='javascript:selectAddress(\"" + nodes[i].childNodes[0].firstChild.nodeValue + "\", \"" + nodes[i].childNodes[1].firstChild.nodeValue + "\");'>" + nodes[i].childNodes[1].firstChild.nodeValue + "</a><br>";
                }
            }
        }
        if (texto == "") {
            if (document.layers) objDiv.visibility="hide";
            else objDiv.style.visibility="hidden";
        }
        else {
            objDiv.innerHTML = texto;
            if (document.layers) objDiv.visibility="show";
            else objDiv.style.visibility="visible";
        }
        return;
    }
    catch(e) {
    }
};
 
function Gettext(node){
    var isIE = false;
    if (window.ActiveXObject){
        isIE = true;
    }
    if(isIE){
        return node.text;
    }else{
        return node.textContent;
    } 
};
 

function RellenaMapa(xml, objDiv, objHidden) {
	var texto = "";
	try {
		if (xml.childNodes.length > 0) {
			var nodes = xml.getElementsByTagName('string');
			  objDiv.innerHtml = "";
			 if (nodes.length > 0) { 
			   texto+=  Gettext(nodes[0])
						}
					   } 
		
		if (texto == "") { 
		objDiv.style.display = "none";
		objHidden.value = ""
		}
		else {
			objDiv.innerHTML = texto;
			objHidden.value = texto;
			objDiv.style.display = "";
		}
		return;
	}
	catch(e) {
	}
};
 

function RellenaTextBox(xml, objText, objHidden) {
    var texto = "";
    var id = 0;
    try {
        if (xml.childNodes.length > 0) {
	        var nodes = xml.getElementsByTagName('anyType')
            if (nodes.length > 0) {
                for (i=0;i<nodes.length;i++){
                    if ( nodes[i].getElementsByTagName('Key')[0].firstChild.nodeValue > 0){
                        texto =   nodes[i].getElementsByTagName('Value')[0].firstChild.nodeValue
                        id = nodes[i].getElementsByTagName('Key')[0].firstChild.nodeValue
                    }
                }
            }
        }
    }
    catch(e){
        texto = '';
        id = 0;
    }
    if (objText != null)
        if (typeof(objText) != "undefined")
            if (objText.type == "text")
                objText.value = texto;
    if (objHidden != null)
        if (typeof(objHidden) != "undefined")
            if (objHidden.type == "hidden")
                objHidden.value = id;
};

function RellenaSelect(xml, obj, selectText) {
    try {
        if (xml.childNodes.length > 0) {
	        var nodes = xml.getElementsByTagName('anyType') 
	      
            if (nodes.length > 0) {
                obj.options.length = 0;
                
                for(i=0; i<nodes.length; i++){
                    var oOption = document.createElement("OPTION");
                     obj.options.add(oOption);
				    
		            if (nodes[i].childNodes.length >= 2) {
				        oOption.value =  nodes[i].getElementsByTagName('Key')[0].firstChild.nodeValue
				        if (obj.options.length == 0 && nodes[i].childNodes[0].firstChild.nodeValue == 0){
				            oOption.text = '';
				        }
				        else{
				             oOption.text =  nodes[i].getElementsByTagName('Value')[0].firstChild.nodeValue
				        }
				    }
                }
                if(obj.options.length == 2 && obj.options[0].value == 0)
                {
                    obj.remove(0);
                }                
                return;
            }
        }
        obj.options.length = 0;
        var oOption = document.createElement("OPTION");
        obj.options.add(oOption);
        oOption.value = 0;
        oOption.innerText = "";
    }
    catch(e) {
        obj.options.length = 0;
        var oOption = document.createElement("OPTION");
	    obj.options.add(oOption);
	    oOption.value = 0;
	    oOption.innerText = "";
    }
};

function SetVisibleDependentObject(objDependent, visible) {
    try {
        if (objDependent != null)
        {
            objDependent.style.display = (visible) ? "block" : "none";
        }
    }
    catch(e) {
   }
};


