/*
Autor: César Caetano Neto
Descrição: Classe para utilização da tecnologia Ajax.
Licença: LGPL.
*/
function Ajax() {
 	this.objXMLHttpRequest = null;
 	this.request = request;
 	this.isSuccess = isSuccess;
 	this.getResponseText = getResponseText;
 	this.getResponseXML = getResponseXML;

	if(this.objXMLHttpRequest==null){
		if(window.XMLHttpRequest) {
	    	this.objXMLHttpRequest = new XMLHttpRequest();
	    	if (this.objXMLHttpRequest.overrideMimeType) {
	      		this.objXMLHttpRequest.overrideMimeType('text/xml');
	    	}
		}else if (window.ActiveXObject) { 
	    	try {
	      		this.objXMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	    	} catch (e) {
	      		try {
	        		this.objXMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	      		} catch (e) {}
	    	}
	  	}
	  
		if (this.objXMLHttpRequest==null) {
	    	alert('Não foi possível uma instância.');
	  	}
	}
	
	this.setFuncaoDeResposta = function(funcaoDeResposta){
		this.objXMLHttpRequest.onreadystatechange = funcaoDeResposta;
	}
	
	function request(method, URL, valores){
		//ESTE TRECHO FAZ COM QUE O NEVEGADOR SEMPRE ACESSE 
		//UMA NOVA URL, INDEPENDENTE DO QUE ESTA NO CACHE
		//---------------------------------------------------------
		var nRand=parseInt(Math.random()*99999999); // cache buster
		if(URL.indexOf('?')>-1){
			URL += '&rand=' + nRand;
		}else{
			URL += '?rand=' + nRand;
		}
		//---------------------------------------------------------
		try{
			if(method == 'GET'){
				this.objXMLHttpRequest.open(method, URL, true);
				this.objXMLHttpRequest.send(null);
			}else{
				this.objXMLHttpRequest.open(method, URL, true);
				this.objXMLHttpRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
				this.objXMLHttpRequest.send(valores); 
			}
		}catch(e){
			alert('A função de resposta não foi setada.');
		}	
	}
	
	function isSuccess(){
		try {
            if(this.objXMLHttpRequest.readyState == 4){
            	if(this.objXMLHttpRequest.status == 200){
            		return true;
	            }else{
    	        	return false;
        	    }
            }else{
            	return false;
            } 
        } catch(e) {
        	alert("Ocorreu um problema com a requisição.");
            return false;
        }
	}
	
	function getResponseText(){
		if(this.isSuccess()){
			return this.objXMLHttpRequest.responseText;
		}else{
			alert('Atenção, a requisição ainda não foi concluída.');
			return null;
		}
	}
	
	function getResponseXML(){
		if(this.isSuccess()){
			return this.objXMLHttpRequest.responseXML;
		}else{
			alert('Atenção, a requisição ainda não foi concluída.');
			return null;
		}
	}
	
}


