/**                                                                                                  
*Clase que implementa una llamada mediante AJAX, a travez de los metodos Get y Post                  
*Metodo Constructor                                                                                  
*@version beta                                                                                       
*@copyright Enzo lepe                                                                                
*@author Enzo Lepe                                                                                   
*@param String - direccion : Contiene la URL de la pagina que será llamada                           
*@param String - callback  : Contiene el nombre de la funcion que recibira la respuesta a la peticion
*@link http://www.cristalab.com/tutoriales/178/precarga-preloader--en-ajax                           
*/                                                                                                   
var Request = function(direccion, funcion){                                                          
  this.ajax = this.createXMLHttpRequest();                                                           
  this.async = true;                                                                                 
  this.Method = "GET";                                                                               
  this.callback = funcion;                                                                           
  this.Id = "";                                                                                      
  this.direccion  = direccion;	                                                                     
  this.parametros = "";                                                                              
  this.countParametros = 0;
  this.ajaxCache = true; /**Determina si colocamos una variable aleatoria para engañar la cache*/
  /*Determina si responde texto plano(JSON) o un documento XML
    por defecto es texto PLano*/
  this.response = 0;
}                                                                                                    
/**                                                                                                  
*Metodo que crea el objeto XMLHttpRequest, con el cual se realizan las llamadas                      
*@return XMLHttpRequest object;                                                                      
*/                                                                                                   
Request.prototype.createXMLHttpRequest = function(){                                                 
 var xmlhttp = false;                                                                                
	try                                                                                                
	{xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");}                                                   
	catch (e)                                                                                          
	{                                                                                                  
	 try                                                                                               
	  {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}                                              
	 catch (E)                                                                                         
	  {xmlhttp = false;}                                                                               
	}                                                                                                  
                                                                                                     
 if(!xmlhttp && typeof XMLHttpRequest!='undefined')                                                  
   {xmlhttp = new XMLHttpRequest();}                                                                 
 return xmlhttp; 	                                                                                   
}        
/*Setea la respuesta para texto plano*/
Request.prototype.setAjaxCache = function(){
	this.ajaxCache = false;
}
/*Setea la respuesta para texto plano*/
Request.prototype.setResponseText = function(){
	this.response = 0;	
}
/*Setea la respuesta como documento xml*/
Request.prototype.setResponseXML = function(){
	this.response = 1;	
}
/**                                                                                                  
*Metodo que setea el sincronismo de la peticion                                                      
*@param Bool - Value : Contiene el sincronismo de la peticion true, es asincronico, false sincronico 
*/                                                                                                   
Request.prototype.setAsync = function(value){                                                        
  this.async = value;		                                                                             
}                                                                                                    
/**                                                                                                  
*Metodo que entrega el valor de async                                                                
*@return Bool: true, en caso de ser asincrono, false en caso de ser sincrono                         
*/                                                                                                   
Request.prototype.getAsync = function(){                                                             
  return this.async;		                                                                             
}                                                                                                    
/**                                                                                                  
*Metodo que setea el metodo que es utilizado para hacer la peticion                                  
*@param String - value: Contiene el nombre del metodo puede ser GET o POST                           
*/                                                                                                   
Request.prototype.setMethod = function(value){                                                       
  this.Method = value;		                                                                           
}                                                                                                    
/**                                                                                                  
*Metodo que porporciona el nombre del metodo que es utilizado para hacer la peticion                 
*@return String : Con el nombre del metodo                                                           
*/                                                                                                   
Request.prototype.getMethod = function(){                                                            
  return this.Method;		                                                                             
}                                                                                                    
/**                                                                                                  
*Metodo que setea el id del campo en donde sera recibido la respuesta a la peticion                  
*@param String - value: Contiene el id donde sera depositada la respuesta                            
*/                                                                                                   
Request.prototype.setId = function(value){                                                           
  this.Id = value;		                                                                               
}                                                                                                    
/**                                                                                                  
*Metodo que proporciona el identificador del campo                                                   
*@return String : Contiene el Identificador del campo                                                
*/                                                                                                   
Request.prototype.getId = function(){                                                                
  return this.Id;		                                                                                 
}                                                                                                    
/**                                                                                                  
*Metodo que agrega pares valor a la direccion                                                        
*@param string nombre: Contiene el nombre del parametro                                              
*@param string valor : Contiene el valor que se le asigna al parametro                               
*/                                                                                                   
Request.prototype.addParam = function(nombre, valor){                                                
 if(this.countParametros==0)                                                                         
   {                                                                                                 
    this.parametros = nombre + "=" + valor;	                                                         
   }                                                                                                 
 else                                                                                                
 	 {                                                                                                 
 	 	 this.parametros = this.parametros + "&" + nombre + "=" + valor;	                               
 	 }                                                                                                 
  this.countParametros++;                                                                            
}                                                                                                    
/**                                                                                                  
*Metodo que propororciona un string con el enlace y los parametros para el metodo GET                
*@return String : Con el contenido del string                                                        
*/                                                                                                   
Request.prototype.getLinkGet = function(){                                                           
	var texto = this.direccion;	                                                                       
	if(this.countParametros>0)                                                                         
	 {                                                                                                 
	 	texto = texto + '?' + this.parametros;	 	                                                       
	 }                                                                                                 
	return texto;                                                                                      
 }                                                                                                   
/**                                                                                                  
*Metodo que propororciona un string con los parametros para el metodo POST                           
*@return String : Con el contenido del string                                                        
*/                                                                                                   
Request.prototype.getLinkPost = function(){	                                                         
	return this.parametros;                                                                            
 }                                                                                                   
/**                                                                                                  
*Metodo que porporciona la peticion generica                                                         
*/                                                                                                   
Request.prototype.callRequest= function (){                                                          
  if(this.getMethod().toUpperCase()=="GET")                                                          
  {
   this.callGet();	  	                                                                             
   return;                                                                                           
  }	                                                                                                 
  if(this.getMethod().toUpperCase()=="POST")                                                         
  {                                                                                                  
   this.callPost();	                                                                                 
   return;                                                                                           
  }                                                                                                  
}                                                                                                    
/**                                                                                                  
*Metodo que implementa la peticion a travez del metodo GET                                           
*/                                                                                                   
Request.prototype.callGet = function(){                                                              
  //Creacion del objeto XMLHttpRequest                                                               
  var ajax = this.createXMLHttpRequest();                                                            
  var Id   = this.getId();                                                                           
  var callback = this.callback; 
  var response = this.response;
  //Ingreso de variable aleatoria de manera de engañar el cacheo de internet explorer                
  if(this.ajaxCache==true)
  this.addParam("ajaxCache",Math.random());                                                          
  //Envio de la peticion                                                                             
  ajax.open(this.getMethod(), this.getLinkGet(), this.getAsync());                                   
  ajax.onreadystatechange = function() {                                                             
	if (ajax.readyState==4) {					  		                                                           
	  responseAjaxRequest(ajax, Id, response, callback)                                                          
	}                                                                                                  
  }	                                                                                                 
  ajax.send(null)		                                                                                 
 }                                                                                                   
/**                                                                                                  
*Metodo que implementa la peticion a travez del metodo POST                                          
*/                                                                                                   
Request.prototype.callPost = function(){                                                             
  	//Creacion del objeto XMLHttpRequest                                                             
    var ajax = this.createXMLHttpRequest();                                                          
    var Id   = this.getId();                                                                         
    var callback = this.callback;             
	var response = this.response;
	ajax.open(this.getMethod(), this.direccion ,this.getAsync());                                      
    ajax.onreadystatechange = function() {                                                           
	if (ajax.readyState==4) {					  		                                                           
	  responseAjaxRequest(ajax, Id, response, callback)                                                          
	  }                                                                                                
	}                                                                                                  
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                        
	ajax.send(this.getLinkPost())                                                                      
}                                                                                                    
/**                                                                                                  
*Funcion que analiza la respuesta a la peticion                                                      
*@param XMLHttpRequest - xmlHttp : Contiene el objeto que implementa la peticion                     
*@param String id - Contiene el id del campo en donde se cargara la respuesta                        
*@Param String callback - Contiene el nombre de la funcion que sera ejecutada para acomodar los datos
*/                                                                                                   
function responseAjaxRequest(xmlHttp, Id, resp ,callback){                                                                                                    
 var val = "";                                                                                       
 for(i in xmlHttp) {                                                                                 
	try {                                                                                              
	val+="xmlHttp."+i+"="+xmlHttp[i]+"\n"                                                              
	} catch(e) {}                                                                                      
 }                                                                                                   
 if(xmlHttp.status==404) {                                                                           
	alert("Al parecer la pagina a la cual esta accediendo no existe")                                  
 }                                                                                                   
 try                                                                                                 
	{       
	 if(resp == 0){
	 	var texto = new String(xmlHttp.responseText);
	 	callback(texto, Id) 
	 }
	 else{
	 	var texto = xmlHttp.responseXML;
	 	callback(texto, Id)
	 }	 
	 //alert(texto);                                                     
	 //var contenido = new String();                                                                     
     //contenido = texto.replace(/(·)/g,"\"");    
   	                                                                       
	}                                                                                                  
 catch(e) {alert(e.name+" - "+e.message);}                                                           
}                                                                                                    