function extraiScript(texto){
        // inicializa o inicio ><
        var ini = 0;
        // loop enquanto achar um script
        while (ini!=-1){
                // procura uma tag de script
                ini = texto.indexOf('<script', ini);
                // se encontrar
                if (ini >=0){
                        // define o inicio para depois do fechamento dessa 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
                        eval(codigo);
                }
        }
}

//------------------------------------------

   function ExecAjaxComboFamilia(valor,pagina) {
	   
	   //alert(valor);
	   //alert(pagina);
      //verifica se o browser tem suporte a ajax
	  try {
         ajax = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 document.forms[0].idFamilia.options.length = 1;
	     
		 idOpcao  = document.getElementById("opcoesFamilia");
		 Div      = document.getElementById("DivCarregando");
		 
	     ajax.open("POST", pagina, true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
				Div.innerHTML = "<table align='center' cellpadding='2' cellspacing='1'>";
				Div.innerHTML = Div.innerHTML + " <tr>";
				Div.innerHTML = Div.innerHTML + "   <td align='center'>";
				Div.innerHTML = Div.innerHTML + " 		<img src='../images/load.gif' width=32 height=32  align=absmiddle>";
				Div.innerHTML = Div.innerHTML + " 		&nbsp;&nbsp; Aguarde. Carregando...</td>";
				Div.innerHTML = Div.innerHTML + " </tr>";
				Div.innerHTML = Div.innerHTML + "</table>";
				Div.className = "DivCarregando";  
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processXMLFamilia(ajax.responseXML);
				  Div.innerHTML = "";   
				  Div.className = "";  


			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   //idOpcao.innerHTML = "--Primeiro selecione o Solicitante--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "idCategoria="+valor;
         ajax.send(params);
      }
   }

//---------------------------------------------------------------------------------------------------------------------------------

function processXMLFamilia(obj){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("Categoria");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length ; i++) {
            var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var idFamilia    =  item.getElementsByTagName("idFamilia")[0].firstChild.nodeValue;
			var Familia      =  item.getElementsByTagName("Familia")[0].firstChild.nodeValue;
			
	        //idOpcao.innerHTML = "--Selecione uma das opções abaixo--";
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", "opcoes");
				//atribui um valor
			    novo.value = idFamilia;
				//atribui um texto
			    novo.text  = Familia;
				//finalmente adiciona o novo elemento
				document.forms[0].idFamilia.options.add(novo);
				document.Form.idFamilia.options[1].selected = true;
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		//idOpcao.innerHTML = "--nao processado--";
	  }	  
   }

//---------------------------------------------------------------------------------------------------------------------------------

function ExecAjaxComboCategoria(valor,pagina) {
	   
	   //alert(valor);
	   //alert(pagina);
      //verifica se o browser tem suporte a ajax
	  try {
         ajax = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 document.forms[0].idCategoria.options.length = 1;
	     
		 idOpcao  = document.getElementById("opcoes");
		 Div      = document.getElementById("DivCarregando");
		 
	     ajax.open("POST", pagina, true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
				Div.innerHTML = "<table align='center' cellpadding='2' cellspacing='1'>";
				Div.innerHTML = Div.innerHTML + " <tr>";
				Div.innerHTML = Div.innerHTML + "   <td align='center'>";
				Div.innerHTML = Div.innerHTML + " 		<img src='../images/load.gif' width=32 height=32  align=absmiddle>";
				Div.innerHTML = Div.innerHTML + " 		&nbsp;&nbsp; Aguarde. Carregando...</td>";
				Div.innerHTML = Div.innerHTML + " </tr>";
				Div.innerHTML = Div.innerHTML + "</table>";
				Div.className = "DivCarregando";  
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processXMLCategoria(ajax.responseXML);
				  Div.innerHTML = "";   
				  Div.className = "";  


			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   //idOpcao.innerHTML = "--Primeiro selecione o Solicitante--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "idFabricante="+valor;
         ajax.send(params);
      }
   }

//---------------------------------------------------------------------------------------------------------------------------------

   function processXMLCategoria(obj){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("Fabricante");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length ; i++) {
            var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var idCategoria    =  item.getElementsByTagName("idCategoria")[0].firstChild.nodeValue;
			var Categoria      =  item.getElementsByTagName("Categoria")[0].firstChild.nodeValue;
			
	        //idOpcao.innerHTML = "--Selecione uma das opções abaixo--";
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", "opcoes");
				//atribui um valor
			    novo.value = idCategoria;
				//atribui um texto
			    novo.text  = Categoria;
				//finalmente adiciona o novo elemento
				document.forms[0].idCategoria.options.add(novo);
				document.Form.idCategoria.options[1].selected = false;
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		//idOpcao.innerHTML = "--nao processado--";
	  }	  
   }

//---------------------------------------------------------------------------------------------------------------------------------

function ExecAjaxCombo(valor,pagina) {
	   
	    //alert(valor);
	   //alert(pagina);
      //verifica se o browser tem suporte a ajax
	  try {
         ajax = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 document.forms[0].idSubCategoria.options.length = 1;
	     
		 idOpcao  = document.getElementById("opcoes");
		 Div      = document.getElementById("DivCarregando");
		 
	     ajax.open("POST", pagina, true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
				Div.innerHTML = "<table align='center' cellpadding='2' cellspacing='1'>";
				Div.innerHTML = Div.innerHTML + " <tr>";
				Div.innerHTML = Div.innerHTML + "   <td align='center'>";
				Div.innerHTML = Div.innerHTML + " 		<img src='../images/load.gif' width=32 height=32  align=absmiddle>";
				Div.innerHTML = Div.innerHTML + " 		&nbsp;&nbsp; Aguarde. Carregando...</td>";
				Div.innerHTML = Div.innerHTML + " </tr>";
				Div.innerHTML = Div.innerHTML + "</table>";
				Div.className = "DivCarregando";  
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processXML(ajax.responseXML);
				  Div.innerHTML = "";   
				  Div.className = "";  


			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   //idOpcao.innerHTML = "--Primeiro selecione o Solicitante--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "idFabricante="+valor;
         ajax.send(params);
      }
   }
   
//--------------------------------------------------------------------------------------------------------
function AlternaDiv(div1, div2) {
	
if(document.getElementById(div1).style.display == "none"){
		document.getElementById(div1).style.display = "";
		document.getElementById(div2).style.display = "none";
	}else{
		document.getElementById(div1).style.display = "none";
		document.getElementById(div2).style.display = "";
	}
}


function ExecAjax(valor, dest, TrocaTexto) {


  try {
	 ajax = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(e) {
	 try {
		ajax = new ActiveXObject("Msxml2.XMLHTTP");
	 }
	 catch(ex) {
		try {
		   ajax = new XMLHttpRequest();
		}
		catch(exc) {
		   alert("Esse browser não tem recursos para uso do Ajax");
		   ajax = null;
		}
	 }
  }
  if(ajax) {
	 
	 idOpcao  = document.getElementById("opcoes");
	 Div      = document.getElementById("DivCarregando");
	 //idOpcao.style.zIndex  = 100;
	 ajax.open("POST", dest, true);

	 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
	 
	 ajax.onreadystatechange = function() {
		if(ajax.readyState == 1) {

		Div.innerHTML = "<table align='center' cellpadding='2' cellspacing='1'>";
		Div.innerHTML = Div.innerHTML + " <tr>";
		Div.innerHTML = Div.innerHTML + "   <td align='center'>";
		Div.innerHTML = Div.innerHTML + " 		<img src='images/load.gif' width=32 height=32  align=absmiddle>";
		Div.innerHTML = Div.innerHTML + " 		&nbsp;&nbsp; Aguarde. Carregando...</td>";
		Div.innerHTML = Div.innerHTML + " </tr>";
		Div.innerHTML = Div.innerHTML + "</table>";
		Div.className = "DivCarregando";  

		}
		if(ajax.readyState == 4 ) {

			  idOpcao.style.visibility = "visible"; //Mostra a DIV caso esteja ocultada
			  idOpcao.innerHTML = ajax.responseText ;
			  Div.innerHTML = "";   
			  Div.className = "";  
			  if (TrocaTexto == 1 ) {
			  AlternaDiv ("EnviaRequisicao", "MostraRequisicao");
			  }
			   
		}
	 }

	 var params = "varID="+valor;
	 ajax.send(params);
  }
}


function ExecAjaxNew(valor, dest, TrocaTexto, divRetorno) {


  try {
	 ajax = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(e) {
	 try {
		ajax = new ActiveXObject("Msxml2.XMLHTTP");
	 }
	 catch(ex) {
		try {
		   ajax = new XMLHttpRequest();
		}
		catch(exc) {
		   alert("Esse browser não tem recursos para uso do Ajax");
		   ajax = null;
		}
	 }
  }
  if(ajax) {
	 
	 alert(divRetorno)
	 idOpcao  = document.getElementById(divRetorno);
	 Div      = document.getElementById("DivCarregando");
	 //idOpcao.style.zIndex  = 100;
	 ajax.open("POST", dest, true);

	 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
	 
	 ajax.onreadystatechange = function() {
		if(ajax.readyState == 1) {

		Div.innerHTML = "<table align='center' cellpadding='2' cellspacing='1'>";
		Div.innerHTML = Div.innerHTML + " <tr>";
		Div.innerHTML = Div.innerHTML + "   <td align='center'>";
		Div.innerHTML = Div.innerHTML + " 		<img src='images/load.gif' width=32 height=32  align=absmiddle>";
		Div.innerHTML = Div.innerHTML + " 		&nbsp;&nbsp; Aguarde. Carregando...</td>";
		Div.innerHTML = Div.innerHTML + " </tr>";
		Div.innerHTML = Div.innerHTML + "</table>";
		Div.className = "DivCarregando";  

		}
		if(ajax.readyState == 4 ) {

			  idOpcao.style.visibility = "visible"; //Mostra a DIV caso esteja ocultada
			  idOpcao.innerHTML = ajax.responseText ;
			  Div.innerHTML = "";   
			  Div.className = "";  
			  if (TrocaTexto == 1 ) {
			  AlternaDiv ("EnviaRequisicao", "MostraRequisicao");
			  }
			   
		}
	 }

	 var params = "varID="+valor;
	 ajax.send(params);
  }
}


//---------------------------------------------------------------

//----------------------------------------------------------------

function ExecPopUpAjax(valor, dest, w , h) {


  try {
	 ajax = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(e) {
	 try {
		ajax = new ActiveXObject("Msxml2.XMLHTTP");
	 }
	 catch(ex) {
		try {
		   ajax = new XMLHttpRequest();
		}
		catch(exc) {
		   alert("Esse browser não tem recursos para uso do Ajax");
		   ajax = null;
		}
	 }
  }
  if(ajax) {
	 
	 Face  = document.getElementById("divPopup");
	 Texto = document.getElementById("divPopupConteudo");
	 Div   = document.getElementById("DivCarregando");
	 //idOpcao.style.zIndex  = 100;
	 ajax.open("POST", dest, true);

	 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
	 
	 ajax.onreadystatechange = function() {
		if(ajax.readyState == 1) {

		Div.innerHTML = "<table align='center' cellpadding='2' cellspacing='1'>";
		Div.innerHTML = Div.innerHTML + " <tr>";
		Div.innerHTML = Div.innerHTML + "   <td align='center'>";
		Div.innerHTML = Div.innerHTML + " 		<img src='images/load.gif' width=32 height=32  align=absmiddle>";
		Div.innerHTML = Div.innerHTML + " 		&nbsp;&nbsp; Aguarde. Carregando...</td>";
		Div.innerHTML = Div.innerHTML + " </tr>";
		Div.innerHTML = Div.innerHTML + "</table>";
		Div.className = "DivCarregando";  

		}
		if(ajax.readyState == 4 ) {

			  
			  Texto.style.width 	 = w;
			  Texto.style.height 	 = h;
			  if (w != 'auto') {
			  Texto.style.marginLeft = - (w / 2) ;
			  }
			  if (h != 'auto') {
			  Texto.style.marginTop  = - h ;
			  }
			  
			  if (dest == 'VisualizaMapa.asp') {
			  Texto.style.top = "600px";
			  //alert(Texto.style.top )				 
			  }
			  
			  Face.style.visibility  = "visible"; //Mostra a DIV caso esteja ocultada
			  Texto.style.visibility = "visible"; //Mostra a DIV caso esteja ocultada

			  Texto.innerHTML = ajax.responseText ;
			  Div.innerHTML   = "";   
			  Div.className   = "";  
			 // AlternaDiv ("divConteudo", "divPopup");
			   
		}
	 }

	 var params = "varID="+valor;
	 ajax.send(params);
  }
}

function ExecPopUpAjaxClose() {
	 Face   = document.getElementById("divPopup");
	 Texto  = document.getElementById("divPopupConteudo");
	 Face.style.visibility  = "hidden";
	 Texto.style.visibility = "hidden"; 

}

function ExecAjaxClose() {
	 idOpcao  = document.getElementById("opcoes");
	 idOpcao.style.visibility  = "hidden";

}


var Ajax = false;

function AjaxRequest()
{
    Ajax = false;
    if(window.XMLHttpRequest) // mozilla
    {
        Ajax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) // ie
    {
        try
        {
            Ajax = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                Ajax = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {}
        }
    }
}

function carregaAjax()
{
    var indice = document.getElementById('cmbEscolaridade').selectedIndex;
    var sigla = document.getElementById('cmbEscolaridade').options[indice].getAttribute('value');

    AjaxRequest();
    Ajax.onreadystatechange = processaResposta;
    Ajax.open('GET', 'cmbCursos.asp?Tipo='+sigla, true);
    Ajax.send(null);
}



function adicionar(texto)
{
var xmlDoc;
var value;
document.getElementById('cmbCurso').options.length = 0;

if (window.ActiveXObject)
{
      //crate xml docuemnt object in IE
     xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
     xmlDoc.async="false";
     xmlDoc.loadXML(texto);
     var x = xmlDoc.documentElement;
     //navigate the xml docuemnt object
     //take notice: firstly, we assign 0 to i, then i adds 1 each time
    for (var i=0;i<x.childNodes.length;i++)
   {
          value = x.childNodes[i].childNodes[0].nodeValue;

          var tmp = value.split(",")

          //add the city to the list one by one
          //document.frmCadVagEst.cmbCurso.options[i] = new Option(tmp[1],tmp[0]);
          document.getElementById('cmbCurso').options[i] = new Option(tmp[1],tmp[0]);
   }    
}
 //for Firefox
else
{
    //create the xml docuemnt object in firefox
    var parser=new DOMParser();
    xmlDoc=parser.parseFromString(texto,"text/xml");
    var x = xmlDoc.documentElement;
    var num = 0;
    //take notice: firstly, we assign 1 to i, then i adds 2 each time
    for (var i=0;i<x.childNodes.length;i++)
    {
          value = x.childNodes[i].childNodes[0].nodeValue;

          var tmp = value.split(",")

          //add the city to the list one by one
          //document.frmCadVagEst.cmbCurso.options[num] = new Option(tmp[1],tmp[0]);
	  document.getElementById('cmbCurso').options[num] = new Option(tmp[1],tmp[0]);
          num++;
     }   
}       
}


function processaResposta()
{
    if(Ajax.readyState==4)
    {
	//document.getElementById('divCursos').innerHTML = "<strong>Carregando...</strong>";
        if(Ajax.status==200)
        {
            adicionar(Ajax.responseText);
        }
    }
}

function carregaAjaxCidades(sCid)
{
    var indice = document.getElementById('cmbEstado').selectedIndex;
    var sigla = document.getElementById('cmbEstado').options[indice].getAttribute('value');

    AjaxRequest();
    Ajax.onreadystatechange = processaRespostaCidades;
	Ajax.open('GET', '../cmbCidades.asp?Estado='+sigla+'&Cidade='+sCid, true);
    //Ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    Ajax.send(null);
}

function processaRespostaCidades()
{
    if(Ajax.readyState==4)
    {
        if(Ajax.status==200)
        {
            adicionarCidades(Ajax.responseText);
        }
    }
}

function adicionarCidades(texto)
{
var xmlDoc;
var value;
document.getElementById('cmbCidades').options.length = 0;

if (window.ActiveXObject)
{
      //crate xml docuemnt object in IE
     xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
     xmlDoc.async="false";
     xmlDoc.loadXML(texto);
     var x = xmlDoc.documentElement;
     //navigate the xml docuemnt object
     //take notice: firstly, we assign 0 to i, then i adds 1 each time
    for (var i=0;i<x.childNodes.length;i++)
   {
          value = x.childNodes[i].childNodes[0].nodeValue;

          var tmp = value.split(",")

          //add the city to the list one by one
		  if (tmp[2] == 1)
		  {
			document.getElementById('cmbCidades').options[i] = new Option(tmp[1],tmp[0],false,true);
		  } else {
			document.getElementById('cmbCidades').options[i] = new Option(tmp[1],tmp[0],false,false);
		  }
          //document.frmCadVagEst.cmbCidades.options[i] = new Option(tmp[1],tmp[0]);
   }    
}
 //for Firefox
else
{
    //create the xml docuemnt object in firefox
    var parser=new DOMParser();
    xmlDoc=parser.parseFromString(texto,"text/xml");
    var x = xmlDoc.documentElement;
    var num = 0;
    //take notice: firstly, we assign 1 to i, then i adds 2 each time
    for (var i=0;i<x.childNodes.length;i++)
    {
          value = x.childNodes[i].childNodes[0].nodeValue;

          var tmp = value.split(",")

          //add the city to the list one by one
		  if (tmp[2] == 1)
		  {
			document.getElementById('cmbCidades').options[num] = new Option(tmp[1],tmp[0],false,true);
		  } else {
			document.getElementById('cmbCidades').options[num] = new Option(tmp[1],tmp[0],false,false);
		  }
          //document.frmCadVagEst.cmbCidades.options[num] = new Option(tmp[1],tmp[0]);
          num++;
     }   
}
}
