// Inicializador Ajax
function ajax() {
};

// Método iniciar
ajax.prototype.iniciar = function() {
    try {
        this.xmlhttp = new XMLHttpRequest();
    }
    catch(ee) {
        try {
            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e) {
            try {
                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(E) {
                this.xmlhttp = false;
            }
        }
    }
    return true;
}


// Metodo Ocupado
ajax.prototype.ocupado = function() {
    estadoAtual = this.xmlhttp.readyState;
    return (estadoAtual && (estadoAtual < 4));
}

// Metodo Processa
ajax.prototype.processa = function() {
    if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
        return true;
    }
}

// Metodo que faz as requisições web
ajax.prototype.enviar = function(url, metodo, modo) {
    // se nao estiver iniciardo vai iniciar dae...
    if(!this.xmlhttp) {
        this.iniciar();
    }
    // se nao estiver ocupado
    if(!this.ocupado()) {
        // se for metodo GET
        if(metodo == "GET") {
            this.xmlhttp.open("GET", url, modo);
            this.xmlhttp.send(null);
        }
        else {
            // se for post
            this.xmlhttp.open("POST", url, modo);
            this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            this.xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            this.xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
            this.xmlhttp.setRequestHeader("Pragma", "no-cache");
            this.xmlhttp.send(url);
        }
        if(this.processa) {
            // recebe o resultado da pagina... php
						var strRes=unescape(this.xmlhttp.responseText.replace(/\+/g," "));
						this.xmlhttp=null;
            return strRes;
        }
    }
    return false;
}

//Funcao AJAX GET
function ajaxGET(url,elemento_retorno,blnCarregaLinks)
{
	ajaxGET_POST("GET",url,elemento_retorno,blnCarregaLinks);
}

//Funcao AJAX POST
function ajaxPOST(url,elemento_retorno,blnCarregaLinks)
{
	ajaxGET_POST("POST",url,elemento_retorno,blnCarregaLinks);
}

//Funcao AJAX
function ajaxGET_POST(modo,url,elemento_retorno,blnCarregaLinks)
{
	var strHTMLLoadingERRO='<div><IMG SRC="imagens/alerta.jpg" BORDER="0">&nbsp;<font class="textoTitulo">Erro de sistema</font></div>';
	var strHTMLLoading='<div id="preloader"></div><div><font class="textoTitulo">a carregar...</font></div>';

	if(modo=="POST")
		strHTMLLoading='<div><IMG SRC="imagens/preloader3.gif" BORDER="0">&nbsp;<font class="textoTitulo">a enviar dados...</font></div>';

     var ajax1 = pegaAjax();
     if(ajax1){
         url = antiCacheRand(url);
         ajax1.onreadystatechange = ajaxOnReady;
				 if(modo=="GET")
				 {
					 ajax1.open("GET", url ,true);
				 }
				 else
				 {
					 ajax1.open("POST", url ,true);
					 ajax1.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					 ajax1.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");//"application/x-www-form-urlencoded");
				 }

				 ajax1.setRequestHeader("Cache-Control", "no-cache");
				 ajax1.setRequestHeader("Pragma", "no-cache");
				 put(strHTMLLoading);
         ajax1.send(null)
         return true;
     }else{
         return false;
     }
     function ajaxOnReady(){
         if (ajax1.readyState==4){
             if(ajax1.status == 200)
							{
                 var texto=ajax1.responseText;
								 texto=texto.replace(/\+/g," ");
                 texto=unescape(texto); //descomentar esta linha se tiver usado o urlencode no php ou asp
                 put(texto);
                 extraiScript(texto);
								 if(blnCarregaLinks){ fCarregaEventos('li',fClickSubMenu,document.getElementById("divAreaSubMenu"));}
             }else{
                 put(strHTMLLoadingERRO+" : "+httpStatus(ajax1.status));
             }
             ajax1 = null;
         }else {//para mudar o status de cada carregando
                 put(strHTMLLoading);
         }
     }
     function put(valor){ //coloca o valor na variavel/elemento de retorno
         if((typeof(elemento_retorno)).toLowerCase()=="string"){ //se for o nome da string
             //if(valor!="Falha no carregamento"){
                 eval(elemento_retorno + '= unescape("' + escape(valor) + '")');
             //}
         }else if(elemento_retorno.tagName.toLowerCase()=="input"){
             valor = escape(valor).replace(/\%0D\%0A/g,"")
             elemento_retorno.value = unescape(valor);
         }else if(elemento_retorno.tagName.toLowerCase()=="select"){        
             select_innerHTML(elemento_retorno,valor)
         }else if(elemento_retorno.tagName){
             elemento_retorno.innerHTML = valor;
         }    
     }
     function pegaAjax(){ //instancia um novo xmlhttprequest
         if(typeof(XMLHttpRequest)!='undefined'){return new XMLHttpRequest();}
         var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
         for(var i=0;i<axO.length;i++){ try{ return new ActiveXObject(axO[i]);}catch(e){} }
         return null;
     }
     function httpStatus(stat){ //retorna o texto do erro http
         switch(stat){
             case 0: return "Erro desconhecido de javascript";
             case 400: return "400: Solicita&ccedil;&atilde;o incompreensível"; break;
             case 403: case 404: return "404: N&atilde;o foi encontrada a URL solicitada"; break;
             case 405: return "405: O servidor n&atilde;o suporta o m&eacute;todo solicitado"; break;
             case 500: return "500: Erro desconhecido de natureza do servidor"; break;
             case 503: return "503: Capacidade m&aacute;xima do servidor alcançada"; break;
             default: return "Erro " + stat + ". Mais informa&ccedil;&otilde;es em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
         }
     }
     function antiCacheRand(aurl){
         var dt = new Date();
         if(aurl.indexOf("?")>=0){// já tem parametros
             return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
         }else{ return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());}
     }
}

function extraiScript(texto){
     // inicializa
     var ini = 0;
     // loop enquanto script
     while (ini!=-1){
         // procura uma tag de script
         ini = texto.indexOf('<script', ini);
         // se encontrar
         if (ini >=0){
             // define o inicio para depois de fechar essa tag
             ini = texto.indexOf('>', ini) + 1;
             // procura o final do script
             var fim = texto.indexOf('</script>', ini);
             // extrai apenas o script
             codigo = texto.substring(ini,fim);
             // executa o script
             novo = document.createElement("script")
             novo.text = codigo;
             document.body.appendChild(novo);
         }
     }
}
