/**
 * Ajax driven object
 * 
 * var myRequest = new ajaxObject('http://motte.codigolibre.net');
 * myRequest.update('VAR1=111&VAR2=222', 'POST', 'dato exta 1|dato extra 2');
 * myRequest.callback = function(respuesta, estado, error, datosExtra){
 * 	if(estado == 1){
 * 		alert(respuesta)
 * 	}
 * 	else{
 * 		alert(error);
 * 		}
 * }
 * 
 * @param string url
 * @param string [callbackFunction]
 */
function ajaxObject(url, callbackFunction) {
	var that = this;
	this.updating = false;
	this.extraData = '';
	if(url.indexOf('?') > 0){
		url = url.substring(0, url.indexOf('?')) +'?Q='+ url.substring(url.indexOf('?') + 1, url.length);
		}
	
	
	/**
	 * Cancela la conexión
	 */
	this.abort = function(){
		if(that.updating){
			that.updating = false;
			that.AJAX.abort();
			that.AJAX = null;
			}
		}
  
	/**
	 * Realiza el intercambio de datos
	 * 
	 * @param string passData - Parámetros del GET
	 * @param string postMethod - GET|POST
	 * @param string [extraData] - Puede ser cualquier cosa
	 */
	this.update = function(passData, postMethod, extraData){
		
		// variables
		passData = (/post/i.test(postMethod))?passData:'?'+ passData;
		this.extraData = (extraData != '')?extraData:'';
		that.AJAX = null;
		
		// ya está corriendo?
		if(that.updating){
			return false;
			}
		
		// IE o el mundo?
		if (window.XMLHttpRequest){              
		   that.AJAX = new XMLHttpRequest();              
			}
		else{                                  
		   that.AJAX = new ActiveXObject("Microsoft.XMLHTTP");
			}                                             
		if(that.AJAX == null) {                             
		   return false;                               
			}
		else{
      	
      	// para los avisos
      	var oAviso = new mteNotify(1);
      	
			that.AJAX.onreadystatechange = function(){
      	
	   	  	// terminó la actualización
	      	if(that.AJAX.readyState == 4){
		   	  	that.updating = false;

	          	// algunas variables
		         var mensaje = '';
		         var aviso_texto = '';
		         var error = that.AJAX.responseText;
		         var estado = 0;
		         
		         // vienen datos
		         if(that.AJAX.responseXML){
		         	
		         	var feedback = that.AJAX.responseXML;
					   estado = feedback.getElementsByTagName('status').item(0).firstChild.data;
					   var respuesta = (feedback.getElementsByTagName('result').item(0))?feedback.getElementsByTagName('result').item(0).firstChild.data:'';
					   error = (feedback.getElementsByTagName('error').item(0))?feedback.getElementsByTagName('error').item(0).firstChild.data:'';
		         	
		         	// todo ok
		         	if(estado == 1){
		         		mensaje = respuesta.replace(/\r\n/g, "");
		         		mensaje = mensaje.replace(/\n/g, "");
		         		mensaje = mensaje.replace(/\\r\\n/g, "");
		         		mensaje = mensaje.replace(/\\n/g, "");
		         		mensaje = mensaje.replace(/\t/g, " ");
		         		mensaje = mensaje.replace(/\\t/g, " ");
			 		  		aviso_texto = 'procedimiento OK';
		         		}	         	
		         	}
				  	
					// ups, hay errores, se avisa
				  	if(estado != 1){
				  		error = (error == '')?'Ocurrió un error, vuelva a intentarlo':error;
				  		}
					
					// ups, hay errores, se avisa
				  	if(estado != 1){
				  		error = (error == '')?'Ocurrió un error, vuelva a intentarlo':error;
				  		oAviso.showAlert(error);
				  		}
				  							
		        	// se llama a la función de callback
		        	that.callback(mensaje, estado, error, that.extraData);
		        	that.AJAX = null;
	      		}
      		}
      
	      // para tener la hora                                                        
			that.updating = new Date();
	      
	      // se prepara lo que se va a pasar
			var uri=urlCall+''+passData;
			that.AJAX.open(postMethod.toUpperCase(), uri, true);
	      
	      // si es POST                              
			if (/post/i.test(postMethod)){
				that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				that.AJAX.setRequestHeader("Content-Length", passData.length);
				}
			
			// se hace la llamada
			that.AJAX.send(passData);
			return true;                                             
	    	}                                                                           
		}
	
	var urlCall = url;
	this.callback = callbackFunction || function(){ };
	}

/**
 * Clase mteNotify
 * muestra una aviso en algún lado
 */
var mteNotify = function (id){
	
	if(!id)return;
	this.texto = '';
	this.id = id;

	/**
	 * Define el texto a mostrar
	 * 
	 * @param string texto
	 */	
	this.setText = function(txt){
		
		// ya existe
		if(document.getElementById('mteNotify_'+ this.id)){
			var aviso = document.getElementById('mteNotify_'+ this.id);
			aviso.innerHTML = setHtml(txt);
			}
		else{ // es nuevo
			this.texto = txt;
			}
		}
	
	/**
	 * Se utiliza cuando hay problemas
	 * 
	 * @param string texto
	 */	
	this.showAlert = function(texto){
		
		texto = texto +'';
		texto = texto.split('|');
		if(texto[0] != '0' && texto[0] != ''){
			alert("########################################\n\n"+ texto[0] +"\n\n########################################");
			return;
			}
		if((texto[0] != '0' && trim(texto[0]) == '') || (texto[0] == '0' && texto[1] == '')){
			alert("Ocurrió un error, vuelva a intentarlo.");
			return;
			}
		if(texto[0] == '0' || texto[1] != ''){
			alert("########################################\n\n"+ texto[1] +"\n\n########################################");
			return;
			}		
		}
		
	}

