
// Version 1.0
// Author: Agustin Bosso

/*

USO:
************************************************************
USO 1: Un solo id de objeto

En el script:
	var ajx = new AJAX();
	ajx.req("url?con=variables","id_del_objeto",'alert("javascript que se ejecutara al terminar")');

En el HTML:	
	<div id="id_del_objeto">
			AQUI SE PONDRA EL CONTENIDO DEL RETORNO DEL AJAX
	</div>

************************************************************
USO 2: Retornando Javascript: Para usarlo poner como id "json"
En el script:
	var ajx = new AJAX();
	ajx.req("test.php","json");
	
Contenido de test.php:
<?
	echo "alert('hola')";
?>

************************************************************
USO 3: Poniendo XML en el retorno del AJAX

	var ajx = new AJAX();
	ajx.req("test.php");
	
Contenido de test.php:
<?
	echo "
<json>
	alert('hola')
</json>

<ajax destination_id='id_objeto_1'>
	<h1>TEXTO 1</h1>
</ajax>

<ajax destination_id='id_objeto_2'>
	<h1>TEXTO 2</h1>
</ajax>";
?>

En el HTML:	
	<div id="id_objeto_1">
			AQUI SE PONDRA EL CONTENIDO DEL RETORNO DEL AJAX QUE SERA <h1>TEXTO 1</h1>
	</div>
	
	<div id="id_objeto_2">
			AQUI SE PONDRA EL CONTENIDO DEL RETORNO DEL AJAX QUE SERA <h1>TEXTO 2</h1>
	</div>
	
	Y se ejecutara el codigo javascript que haya entre <json> y </json>

*/



// Object Declaration
function AJAX(){
	this.claseprefix = "";
	this.clasesufix = "";
	this.exec = f_exec;
	this.sendForm = f_sendForm;
	this.sendThis = f_sendThis;
	this.req = f_request;

//Functions
/***********************************/	
	
	//f_exec: Call to the claseprefix+clase php file to bring the content
	function f_exec(clase, action, place, params, noaction, func){
		if (params==undefined){params = "";}
		if (noaction==undefined){
				noaction = "&action=";
			}else{
				noaction = "";
			}
		f_request(this.claseprefix+clase+this.clasesufix+noaction+action+params,place,func);
	}
	
	
	// f_sendForm: Call sendThis with a Form in the parameters
	function f_sendForm(clase,action,place,formId){
		f = document.getElementById(formId);
		this.sendThis(clase,action,place,f);
	}

	//f_sendThis: If There is a form, walk its fields to use them as GET vars, then call exec 
	function f_sendThis(clase,action,place,Tform){
		sendurl = "";
		for(i=0;i<Tform.elements.length;i++){
			if (verifyField(Tform[i])){
				sendurl += "&"+Tform[i].name+"="+Tform[i].value;
			}
		}
		this.exec(clase,action,place,sendurl);		
	}
	
/****************************/
	
	//verifyField: Verify if a field is cappable to be sended in a GET var
	function verifyField(field){
		if (!field.name){return false;}
		if (field.name=="action"){return false;}
		if ((field.type=="checkbox")&&(!field.checked)){return false;}
		return true;
	}
	
//cargarpagina: Procedure attached to the XML Socket when loading is complete
function cargarpagina (pagina_requerida, id_contenedor, funcion){
	  	if (pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1)){	
	
	
	/************parsers********************/
	
	/*
	<json>
		JAVASCRIPT CODE
	</json>
	*/
	function parseJSON(content){
		content_b = content.split("<json>");
		if (content_b != content){
			for(var i=0; i<content_b.length; i++){
				jsoncode = content_b[i].split("</json>");
				eval (jsoncode[0]);
			}
			return true;
		}else{
			return false;
		}
	}
	
	/*
	<ajax [destination_id="ID_OF_DESTINATION"]>
		HTML/XHTML CODE
	</ajax>
	*/
	function parseXML(content, destination){
		content_b = content.split("<ajax");
		if (content_b != content){
			for(var i=0; i<content_b.length; i++){
				ajaxtext = content_b[1].split("</ajax>");
				parameters = ajaxtext[0].split(">",1);
				ajaxtext = ajaxtext[0].replace(parameters+">","");
			
				var myregexp = new RegExp(/destination_id=[\"']([a-zA-Z0-9_-]+)[\"']/);
				var match = myregexp.exec(parameters);
				if (match != null) {
					dest = match[1];
				} else {
					dest = destination;
				}
				document.getElementById (dest).innerHTML = ajaxtext;
			}
			return true;					
		}else{
			return false;
		}
	}
	/****************************************/
			
			content = pagina_requerida.responseText;
			parsed = false;
			parsed = parseXML(content, id_contenedor) || parsed;
			parsed = parseJSON(content) || parsed;
			
			if (!parsed){
				if (id_contenedor=="json"){
					eval(content);
				}else{
					document.getElementById (id_contenedor).innerHTML = content;
				}
			}
		
		eval(funcion)
		
		}		
	}
	
	//f_request: Main Ajax procedure, make the XML Socket, use it and waits response
	function f_request (url, id_contenedor, funcion)
	{

		var pagina_requerida = false;
	    if (window.XMLHttpRequest)
	    {
	        // If is Mozilla, Safari etc
	        pagina_requerida = new XMLHttpRequest ();
	
	    } else if (window.ActiveXObject)
	    {
	        // but if is IE
	        try 
	        {
	            pagina_requerida = new ActiveXObject ("Msxml2.XMLHTTP");
	        }
	        catch (e)
	        {
	            // Old version
	           try
	            {
	                pagina_requerida = new ActiveXObject ("Microsoft.XMLHTTP");
	            }
	           catch (e)
	            {
	            }
	        }
	    } 
	    else
	    return false;
	    pagina_requerida.onreadystatechange = function ()
	    {
	        // response procedure
	        cargarpagina (pagina_requerida, id_contenedor, funcion);
	
	    }
		

		
	    pagina_requerida.open ('GET', url, true); // assign open and send

		pagina_requerida.send (null);
	    return true;

}
}