function Ajax() { 
    
   var connection = null; 
   var erro = null; 
   var method = null; 
   var url = null; 
   var parameters = null; 
   var mode = null; 
   var status = null;
   var state  = null; 
   var response = null; 
   var responseText = null; 
   var responseType = null; 
   var functionCallBack = null;
   var divNome = null;    
   var textoPuro = null;
   
   this.executaAjax = executaAjax;
   this.executaAjaxForm = executaAjaxForm;

   this.setTextoPuro = setTextoPuro;   
   this.getTextoPuro = getTextoPuro;

   this.getResponseType = getResponseType;
   this.getResponse = getResponse;
   this.getResponseText = getResponseText;
   this.getErro = getErro; 
   this.close = close;  
   this.setFunctionCallBack = setFunctionCallBack;
   this.setFunctionCallBackDiv = setFunctionCallBackDiv;
 
   this.isFinished = isFinished;

   function getTextoPuro(){
	return textoPuro;
   }

   function setTextoPuro(pValor){
	textoPuro = pValor;
   }

   function setFunctionCallBackDiv(pFuncao, pDiv){
	functionCallBack = pFuncao;
	divNome = pDiv;		   
   }
   
   function setFunctionCallBack(pFuncao){
		functionCallBack = pFuncao;   
   }
   
    function executaAjaxForm (pAplicacao, pForm, pParametros, pShowMsg) { 
		//Adiciona os Parametros do Formulario
		addParamForm(pForm);
		return executaAjax(pAplicacao, pParametros, pShowMsg);
	}

	function executaAjax(pAplicacao, pParametros, pShowMsg) { 
		//Inicia a Conexao
		if (init()) {
			//Adiciona os Parametros da Aplicacao
			addParams(pParametros);		

			if (open('POST',pAplicacao,'false')){
				return true;
			}else{	
				if (pShowMsg)
					alert(getErro());			
			}
		}else		
			if (pShowMsg)
				alert('Erro2: ' + getErro());
		return false;
	}

	//*******************************************
	//Inicia uma Conexao Ajax
	//*******************************************
	function init(){ 
	    
	   connection = false; 
	     
	   try{
	        connection = new XMLHttpRequest();
	    }catch(ee){
	        try{
	            connection = new ActiveXObject("Msxml2.XMLHTTP");
	        }catch(e){
	            try{
	                connection = new ActiveXObject("Microsoft.XMLHTTP");
	            }catch(E){
					connection = null; 
					erro = 'Seu browser não suporta o objeto XMLHTTP.'; 
	                return false;
	            }
	        }
	    }

	    return true;   
	} 

	function isFinished() {
	    if (connection.readyState == 4) {
	        return true;
	    }
	}


	//*******************************************
	//Veririca o Estado da Conexao Ajax
	//*******************************************
	function isBusy () {     
		return (connection.readyState && (connection.readyState < 4));     
	} 

	//*******************************************
	//Verifica se os parametros não estão vazios
	//*******************************************
	function avalArgument (arg) { 
	    
	   if (arg != null && arg != '' && arg != 'undefined') 
			return true; 
	    
	   erro = arg + ' não pode ser vazio(a)'; 
	   return false;    
	} 

	//*******************************************
	//Adiciona parametro para o submit do ajax
	//*******************************************
	function addParam (name, arg) { 
	    
	   if (avalArgument(arg)) { 
	      if (parameters != null) 
			parameters += '&' + name + '=' + arg; 
	      else 
			parameters = name + '=' + arg; 
	      return true; 
	   }    
	   erro = "O argumento não é válido";
	   return false; 
	} 

	//*******************************************
	//Adiciona parametro para o submit do ajax
	//*******************************************
	function addParams (pParametros) { 
	    
	   if (avalArgument(pParametros)) { 
	      if (parameters != null) 
			parameters = pParametros + '&' + parameters;
	      else 
			parameters = pParametros; 
	      return true; 
	   }    
	   erro = "O valor do parametro não é válido";
	   return false; 
	} 


	//*******************************************
	//Adiciona os parametros do formulario
	//*******************************************
	function addParamForm (pForm){
		try{
			parameters = null;
			
			for (var wx = 0; wx < pForm.elements.length; wx++){
				var wstr = new String(pForm.elements[wx].type);
				var wAdd = true;
				
				if (wstr.toUpperCase() == "RADIO" || wstr.toUpperCase() == "CHECKBOX"){								
					try{
						if (!pForm.elements[wx].checked)
							wAdd = false;
					}
					catch(Exception){}
				}
				if (wAdd){
					addParam(pForm.elements[wx].name, escape(pForm.elements[wx].value));
				}
			}
		}catch(Exception){
		    erro = "Ñão foi possível adicionar os valores dos formulários";
			return false;	
		}
		return true;
	}

	function addArgument (name, arg) { 
	    
	   try { 
	      eval( name + ' = \'' + arg + '\''); 
	      return true; 
	   } catch (e) { 
	      erro = 'Erro ao tentar criar o atributo ' + name + ' no objeto Ajax\n' + e; 
	      return false; 
	   }    
	} 

	function getResponse () { 
	    
	   if (response != null) return response; 
	   else { 
	      erro = 'Não há nenhuma resposta'; 
	      return false; 
	   } 
	    
	} 

	function getResponseText () { 
	   if (responseText != null) 
			return responseText; 
	   else { 
	      erro = 'Não há nenhuma resposta'; 
	      return false; 
	   } 	    
	} 


	function getResponseType () { 
	    
	   if (responseType != null) return responseType; 
	   else { 
	      erro = 'Não há nenhuma resposta'; 
	      return false; 
	   } 
	    
	} 

	function getErro () { 
		return erro;
	} 

	function close () { 
	   delete connection; 
	   delete erro; 
	   delete method; 
	   delete url; 
	   delete parameters; 
	   delete mode; 
	   delete status; 
	   delete response;     
	}

	function getConnection () { 
		return connection;
	}

	function onChange (){
		 if (avalArgument(functionCallBack)){
			if (divNome !=  null){
				functionCallBack(connection, divNome);
			}else
				functionCallBack(connection);
			return;
		 }
	
	     state = connection.readyState; 
	     if (state == 4) { 
	         
			try{
				if (textoPuro){
					responseText = connection.responseText;
				}
				else{
					responseText = unescape(connection.responseText.replace(/\+/g," "));
				}

			}catch(Exception){}
			
			status = connection.status;
				
	        if (status == 200) { 

	            if (connection.responseXML) {                    
	              responseType = 'xml'; 
	              response = connection.responseXML; 
	              return true; 
	                   
	           } else { 

	              if (connection.responseText) { 
	                 responseType = 'text'; 
	                 response = responseText;
	                 return true; 
	              } else { 
	                 erro = 'A conexão não retornou nenhuma resposta'; 
	                 return false; 
	              } 
	           } 
	                
	        } 
	        else { 
	           erro = status + "-" + connection.statusText;
	           return false; 
	        } 
	     }
	}

	function open (method, url, mode) { 

	   if (avalArgument(method)) 
			addArgument('method',method.toUpperCase()); 
	   else 
			return false; 
	    
	   if (avalArgument(url)) 
			addArgument('url',url); 
	   else 
			return false; 
	    
	   if (avalArgument(mode)) 
			addArgument('mode',mode); 
	   else 
			return false; 
	   if (!connection) { 
	      erro = 'Impossível conectar! Objeto Ajax não foi iniciado.'; 
	      return false; 
	   } 
	          
	   if (!isBusy()) { 
	      if (method == 'GET') { 
	         if (parameters != null) 
				url += '?' + parameters; 			
			 parameters = null;
	         connection.open(method, url, mode); 
	      } else {    
	         if (method == 'POST') { 
	            connection.open(method, url, mode); 
	            connection.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); 
	            connection.setRequestHeader('Cache-Control', 'no-store, no-cache, must-revalidate'); 
	            connection.setRequestHeader('Cache-Control', 'post-check=0, pre-check=0'); 
	            connection.setRequestHeader('Pragma', 'no-cache'); 
	            
				if (!avalArgument(parameters)){
					erro = "O parametro de envio está nulo ou é inválido!";
					return false;
				}
		        
	         } else { 
	            erro = 'Método de envio inválido.'; 
	            return false; 
	         } 
	      }    
		
	      wHandle = this;
	      connection.onreadystatechange = onChange;
	      
		  connection.send(parameters); 		
		  return true;
		  if (isFinished)
			if (!onChange(connection))
				return false;

		  return true;       
	   } else { 
	      erro = 'Impossível completar operação pois este objeto Ajax já está em uso.'; 
	      return false; 
	   } 

	} 	

} 

