function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

var http = getHTTPObject();

/*================================================================================================================================*/

/* Função padrão */
function carrega(url,funcao){
    http.open("GET", url + "?" + Math.random(), true);
    http.onreadystatechange = eval(funcao);
    http.send(null);
}

/*================================================================================================================================*/

/* posta todos os dados do formulario */
function camposForm(oForm){
		var aParams = new Array();
		for (var i=0 ; i < oForm.length; i++) {
			var sParam = oForm[i].id;
			sParam += "=";
			sParam += escape(oForm[i].value);
			aParams.push(sParam);
		}
		return aParams.join("&");
	}

/*================================================================================================================================*/
/* prepara o post */
function enviar(url, funcao){
	
	formulario = document.forms[0].elements;
	param = camposForm(formulario);

    http.open("POST", url + "?" + Math.random(), true);
	http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    http.onreadystatechange = eval(funcao);
    http.send(param);
}

/*================================================================================================================================*/
/* Chama a função acima */
function autenticar(){
    enviar("incs/valida.php", function() { validar(); });
}

function Alterar(){
    enviar("incs/action.php", function() { alterardados(); });
}

function Esqueci(){
    enviar("incs/processa-envia-senha.php", function() { enviasenha(); });
}

/*================================================================================================================================*/
/* Chama a função padrão */

function Minhasenha(){
    carrega("incs/envia-senha.php", function() { senha(); });  /* div onde se encontra login e eaqueci minha senha */
}

function Perfil(){
    carrega("incs/usuarios.php", function() { processado(); });
}

function Logout(){
    carrega("incs/logout.php", function() { processado(); });
}

/*================================================================================================================================*/
/* Chama a função padrão */

function Home(){
    carrega("obj/home.php", function() { processado(); });
}

/*================================================================================================================================*/

function processado(){
    // apenas quando o estado for "completado"
    document.getElementById('loading').innerHTML = "<span style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; color=#FFFFFF; background-color=#6EB2D3;'><b> Carregando </b></span>";
   if (http.readyState == 4) {    
   if (http.status == 200) {
		
		var texto = http.responseText;
		document.getElementById('conteudo').innerHTML = unescape(texto.replace(/\+/g," "));
        ExtraiScript(texto);

		document.getElementById('loading').innerHTML = " ";
        } else {
        alert("Problemas ao carregar o arquivo.");
        }
    }
}

/*================================================================================================================================*/

/* Valida Login */

function validar() {

   document.getElementById("resposta").style.color = 'green';	
   document.getElementById("resposta").innerHTML = "<center><b>Processando Aguarde...</b></center>";
   if (http.readyState == 4) {    
   if (http.status == 200) {
     
   if(http.responseText == 1) {
   document.getElementById("resposta").innerHTML = "<center><b>Redirecionando Aguarde ...</b></center>";
   window.location.href = "inside.php";    // Redireciona para uma pagina....
   } 
   
   else if(http.responseText == 2) {
   document.getElementById("resposta").style.color = 'red';	   
   document.getElementById("resposta").innerHTML = "<center><b>Login Inexistente</b></center>";
   } 
   
   else if(http.responseText == 3) {
   document.getElementById("resposta").style.color = 'red';
   document.getElementById("resposta").innerHTML = "<center><b>Senha Inválida</b></center>";
   } 
	 
   else
   document.getElementById("resposta").innerHTML = unescape(http.responseText.replace(/\+/g," "));
     
       } else {
           alert("Problemas ao carregar o arquivo.");
       }         // fecha http.readyState
   }            //  fecha http.status

} // fecha validalogin

/*================================================================================================================================*/
/* Alterar Senha */

function alterardados() {

   document.getElementById("resposta").style.color = 'green';	
   document.getElementById("resposta").innerHTML = "<center><b>Processando Aguarde...</b></center>";
   if (http.readyState == 4) {    
   if (http.status == 200) {
     
   if(http.responseText == 1) {
   document.getElementById("resposta").style.color = 'red';
   document.getElementById("resposta").innerHTML = "<center><b>Login e Senha são Obrigatórios ...</b></center>";
   } 

   else if(http.responseText == 2) {
   document.getElementById("resposta").innerHTML = "<center><b>Redirecionando Aguarde ...</b></center>";
   window.location.href = "index.php";    // Redireciona para uma pagina....
   } 

   else
   document.getElementById("resposta").innerHTML = unescape(http.responseText.replace(/\+/g," "));
     
       } else {
           alert("Problemas ao carregar o arquivo.");
       }         // fecha http.readyState
   }            //  fecha http.status

} // fecha validalogin

/*================================================================================================================================*/
/* Envia senha */

function enviasenha() {

   document.getElementById("resposta").style.color = 'green';	
   document.getElementById("resposta").innerHTML = "<center><b>Processando Aguarde...</b></center>";
   if (http.readyState == 4) {    
   if (http.status == 200) {
     
   if(http.responseText == 1) {
   document.getElementById("resposta").style.color = 'red';
   document.getElementById("resposta").innerHTML = "<center><b>E-mail inválido ...</b></center>";
   } 
  
   else if(http.responseText == 2) {
   document.getElementById("resposta").style.color = 'red';
   document.getElementById("resposta").innerHTML = "<center><b>E-mail não cadastrato ...</b></center>";
   } 
   
   else if(http.responseText == 3) {
   document.getElementById("resposta").style.color = 'green';	   
   document.getElementById("resposta").innerHTML = "<center><b>E-mail enviado com sucesso ...</b></center>";
   window.location.href = "index.php";    // Redireciona para uma pagina....
   } 

   else
   document.getElementById("resposta").innerHTML = unescape(http.responseText.replace(/\+/g," "));
     
       } else {
           alert("Problemas ao carregar o arquivo.");
       }         // fecha http.readyState
   }            //  fecha http.status

} // fecha enviasenha

/*================================================================================================================================*/

function senha() {

   document.getElementById("conteudo").style.color = 'green';	
   document.getElementById("conteudo").innerHTML = "<center><b>Processando Aguarde...</b></center>";
   if (http.readyState == 4) {    
   if (http.status == 200) {
     
	 document.getElementById("conteudo").innerHTML = unescape(http.responseText.replace(/\+/g," "));
     
       } else {
           alert("Problemas ao carregar o arquivo.");
       }         // fecha http.readyState
   }            //  fecha http.status

} // fecha enviasenha

/*================================================================================================================================*/

function ExtraiScript(texto){
    var ini, pos_src, fim, codigo;
    var objScript = null;
    ini = texto.indexOf('<script', 0)
    while (ini!=-1){
        var objScript = document.createElement("script");
        //Busca se tem algum src a partir do inicio do script
        pos_src = texto.indexOf(' src', ini)
        ini = texto.indexOf('>', ini) + 1;

        //Verifica se este e um bloco de script ou include para um arquivo de scripts
        if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, esta e um include de um arquivo script
            //Marca como sendo o inicio do nome do arquivo para depois do src
            ini = pos_src + 4;
            //Procura pelo ponto do nome da extencao do arquivo e marca para depois dele
            fim = texto.indexOf('.', ini)+4;
            //Pega o nome do arquivo
            codigo = texto.substring(ini,fim);
            //Elimina do nome do arquivo os caracteres que possam ter sido pegos por engano
            codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");
            // Adiciona o arquivo de script ao objeto que sera adicionado ao documento
            objScript.src = codigo;
        }else{//Se nao encontrou um "src" dentro da tag script, esta e um bloco de codigo script
            // Procura o final do script
            fim = texto.indexOf('</script>', ini);
            // Extrai apenas o script
            codigo = texto.substring(ini,fim);
            // Adiciona o bloco de script ao objeto que sera adicionado ao documento
            objScript.text = codigo;
        }

        //Adiciona o script ao documento
        document.body.appendChild(objScript);
        // Procura a proxima tag de <script
        ini = texto.indexOf('<script', fim);

        //Limpa o objeto de script
        objScript = null;
    }
}

/*================================================================================================================================*/
