/* 
Classe AJAX - para simples requisições ajax
Irei incrementando conforme necessidade
Data: 14/4/2008
*/


/*CONSTRUTOR*/
function Ajax(url,dados,method){

	this.url = url;
	this.dados = dados;
	this.method = method;
	this.errorCode = 0;
	this.errorMessage = "";
	this.call = loadHTTP;
	this.explodeResult = quebraResultado;
	this.req = false;
	this.returnedText = "";
	this.returnedXML = "";
	this.onSucess;
	this.onError;
}



/*PRIVATE*/
function loadHTTP() {

	this.req = false;

	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest) {
		try {
			this.req = new XMLHttpRequest();
		} catch(e) {
			this.req = false;
		}
	// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			this.req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				this.req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				this.req = false;
			}
		}
	}

	if(this.req) {
		try{

			var thisObj = this;

			this.req.onreadystatechange = function(){

				// apenas quando o estado for "completado"
				if (thisObj.req.readyState == 4) {

					// apenas se o servidor retornar "OK"
					if (thisObj.req.status==200) {

						thisObj.returnedText = thisObj.req.responseText;
						thisObj.returnedXML = thisObj.req.responseXML;
						thisObj.onSucess();

					}else{
						this.errorCode = 3;
						this.errorMessage = "Retornou status != 200. Nao foi possivel atualizar dados";
						thisObj.onError();
					}
				}				
			}			

			if(this.method == 'GET'){
				this.req.open(this.method,this.url+'?'+this.dados,true);
				this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				this.req.send(null);
			} else {
				this.req.open(this.method,this.url,true);
				this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				this.req.send(this.dados);
			}
			
		}catch(e){
			this.errorCode = 2;
			this.errorMessage = "Erro ao enviar informações ao servidor.\nTente novamente!\nErro: "+e;
			this.onError();
			/*
			Este erro ocorre nos seguintes casos: (Conforme for encontrando mais erros, irei adicionando nesta lista)
			1) Voce está chamando uma url de outro dominio (este js está num dominio e fazendo chamada ajax em outro dominio)
			2) Voce está fazendo chamada usando URL Absotuta. Tipo http://www.irex.com.br
			*/
		}
	}else{
		this.errorCode = 1;
		this.errorMessage = "Nao encontrou o XMLHttpRequest do browser!";
		this.onError();
	}
}



/* PUBLIC */
function quebraResultado(){
	if(this.returnedText != ""){
		var array_opcoes = this.returnedText.split("#");
		return array_opcoes;
	}else{
		return false;
	}
}