
// guarda a versao HTTPREQUEST do IE usado
var _ms_XMLHttpRequest_ActiveX = ""; // Holds type of ActiveX to instantiate
var strNomLog = "status_area";

// array que controlo a requisicao ajax
var gArrLiberaRequisicao = new Array();
/**
* Construtor da classe AjaxRequest
* Essa classe tem como objetivo executar os metodos ajax
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest = function(metodo,url,parametros,strMetodoCarregando,strMetodoAposExecucao,strMetodoErro,bolAjax)
{	
	// verificando parametros
	if(parametros == undefined)
	{
		parametros = '';
	}
	
	if(strMetodoCarregando == undefined)
	{
		strMetodoCarregando = '';
	}
	
	if(strMetodoAposExecucao == undefined)
	{
		strMetodoAposExecucao = '';
	}
	
	if(strMetodoErro == undefined)
	{
		strMetodoErro = '';
	}
	
	// gerando senha de acesso
	var strSenhaAcesso = metodo+url+parametros+strMetodoCarregando+strMetodoAposExecucao+strMetodoErro;
//	var objBase64 = new Base64();
//	strSenhaAcesso = objBase64.encode(strSenhaAcesso);
	
	if (gArrLiberaRequisicao[strSenhaAcesso] || (gArrLiberaRequisicao[strSenhaAcesso]==undefined))
	{
		// iniciando ajax
		this.objAreaLog = document.getElementById(strNomLog);	
		if(this.objAreaLog)
		{
			this.bolGeraLog = true;		
		}
		else
		{
			this.bolGeraLog = false;
		}
		
		// montando parametros
		this.senhaAcesso = strSenhaAcesso;
		this.strMetodoCarregando = strMetodoCarregando;
		this.strMetodoAposExecucao = strMetodoAposExecucao;
		this.strMetodoErro = strMetodoErro;
		this.objAjax = this.getGeraAjax();
		gArrLiberaRequisicao[this.senhaAcesso] = false;
		
		// recuperando metodo
		    if (!metodo) {
			metodo = "POST";
		    }
		    metodo = metodo.toUpperCase();
		
		// criando evento de mudanca de estado
		var objTemp = this;
		this.objAjax.onreadystatechange = function()
		{
			objTemp.executarRetornoAjax();
		}
		
		parametros +='&HTTP_REFERER='+self.location+'&BOLAJAX=1';
		
		this.executaAjax(metodo,url,parametros);
	}	
}

/**
* Metodo para criar objeto XMLHttpRequest
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest.prototype.getGeraAjax = function()
{
	var objAjax;
	
	// metodo carregando
	if(this.strMetodoCarregando!=undefined && this.strMetodoCarregando!='')
	{
		indStatus = 'I'; //status inicial
		eval(this.strMetodoCarregando);
	}	
	
	// instanciando a class XMLHTTPRequest
	if (window.XMLHttpRequest) 
	{
	       objAjax  = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) 
    {
	    if (_ms_XMLHttpRequest_ActiveX) 
	    {
            objAjax = new ActiveXObject(_ms_XMLHttpRequest_ActiveX);
            if(!objAjax)
            {
            	// loops through the various versions of XMLHTTP to ensure we're using the latest
		    	var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
	                        "Microsoft.XMLHTTP"];
	
	            // buscando versao HTTPRequest
	            for (var i = 0; i < versions.length ; i++) 
	            {
	                try 
	                {
			            objAjax = new ActiveXObject(versions[i]);
		                if (objAjax) {
	        	            _ms_XMLHttpRequest_ActiveX = versions[i];
	            	        break;
	                    }
	                }
	                catch (objException) 
	                {
	                	this.debug("Erro inexperado. Objeto ajax não conseguiu ser criado !");
	                };
	            };
            }
        } else 
        {
	    	// loops through the various versions of XMLHTTP to ensure we're using the latest
	    	var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
                        "Microsoft.XMLHTTP"];

            // buscando versao HTTPRequest
            for (var i = 0; i < versions.length ; i++) 
            {
                try 
                {
		            objAjax = new ActiveXObject(versions[i]);
	                if (objAjax) {
        	            _ms_XMLHttpRequest_ActiveX = versions[i];
            	        break;
                    }
                }
                catch (objException) 
                {
                	this.debug("Erro inexperado. Objeto ajax não conseguiu ser criado !");
                };
            };
        }
    }
    return objAjax;  
}

/**
* Metodo para debugar codigo
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest.prototype.debug = function(texto)
{
	if(this.bolGeraLog)
	{
		textoAnterior = this.objAreaLog.innerHTML;
		this.objAreaLog.innerHTML = texto + ((textoAnterior) ? "\r\n" : "") + textoAnterior;
	}
}

/**
* Metodo para executar o retorno do ajax
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest.prototype.executarRetornoAjax = function()
{
	if(this.objAjax.readyState == 4)
	{
		if(this.objAjax.status == 200)
		{
			// liberando acesso ajax
			gArrLiberaRequisicao[this.senhaAcesso] = true;
			
			this.debug('AJAXRequest is complete: ' + this.objAjax.readyState + "/" + this.objAjax.status + "/" + this.objAjax.statusText);
			if (trim(this.objAjax.responseText)!='') 
			{
				this.debug(this.objAjax.responseText);
		    	this.debug("-----------------------------------------------------------");
			
				//verifica o tipo de retorno
				if (this.objAjax.getResponseHeader("content-type")=='UTF-8')
				{
					//retorno é um script
					eval(this.objAjax.responseText);
				}
				else
				{
					//retorno é um html
					objRetornoAjax = new RetornoAjax('',null,this.objAjax.responseText);
				}
				
		    	if(objRetornoAjax)
		    	{
		    		if(objRetornoAjax.getErro())
					{
						this.debug("Retornou erro !");
						if(this.strMetodoErro!=undefined && this.strMetodoErro != '')
						{							
							eval(this.strMetodoErro);
						}
						else
						{
							alert(objRetornoAjax.getMsgErro());
						}		
					}
					else
					{	
						this.debug("Ajax completado com sucesso !");
						// metodo executado apos a execucao do ajax
						if(this.strMetodoAposExecucao!=undefined && this.strMetodoAposExecucao!='')
						{
							eval(this.strMetodoAposExecucao);
						}
					}
		    	}
		    	else
		    	{	
		    		alert('Erro inesperado. Favor entrar em contato com o suporte.');
		    	}
		    	objRetornoAjax = '';
	    	}
	    	// metodo carregando
			if(this.strMetodoCarregando!=undefined && this.strMetodoCarregando!='')
			{
				indStatus = 'F'; //status final do processamento				
				eval(this.strMetodoCarregando);
			}
		}
	}	
}

/**
* Metodo para executar o ajax
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest.prototype.executaAjax = function(metodo,url,parametros)
{
    this.debug("----------------------------------------------------------------------");
    this.debug("AJAX Request: Async " + metodo + ": URL: " + url + ", Data: " + parametros);

    // eviando requisição ajax
    this.objAjax.open(metodo, url, true);

    if (metodo == "POST") {
        this.objAjax.setRequestHeader("Connection", "close");
        this.objAjax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.objAjax.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
    }
    
	// finalizando envio
	if(parametros!=undefined && parametros!= '')
    	this.objAjax.send(parametros);
    else
    	this.objAjax.send(null);
}

/**
* Metodo para retornar os dados XML
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest.prototype.getXML = function()
{
	return this.objAjax.responseXML.cloneNode(true);
}

/**
* Metodo para retornar o texto gerado
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest.prototype.getTextoRetorno = function()
{
	return this.objAjax.responseText;
}

/**
* Metodo para retornar o objeto ajax
*
* @since 07/06/2006
* @author Erix Henrique Morato <emorato@unibh.br>
* @access public
*/
AjaxRequest.prototype.getAjax = function()
{
	return this.objAjax;
}
