//funcao para capturar o objeto xmlhttprequest do browser
function getXMLHttp(){
	var xmlhttp=null;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");//para i.e.
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//para i.e.
		} catch (E) {
			xmlhttp = null;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  		xmlhttp = new XMLHttpRequest();//padrao
	}
	return xmlhttp;
}
//função para detectar o browser do cliente
function verificaBrowser(){
if (window.showHelp)
	return "ie"; 
if (!window.attachEvent) 
	return "mac";
if (document.createElementNS) 
	return "dom";
if (navigator.userAgent.indexOf("afari")>-1) 
	return "safari";
if (window.opera) 
	return "opera";
}
//função para usar AJAX e reflexao de metodo
function processaAjax(minhaFuncao,url){
	var xmlhttp = getXMLHttp();
	xmlhttp.open("POST", url+"&_flagAjax=1", true);
  
  xmlhttp.onreadystatechange = function() {
  	document.getElementById('status').innerHTML += '.';
  	if (xmlhttp.readyState == 4) {
  		document.getElementById('status').innerHTML = ' ';
  		if(xmlhttp.status == 200) {
  			//função usada para internet explorer
  			var texto = new String(xmlhttp.responseText).replace(/^\s+|\s+$/, '');
  			if(verificaBrowser() == "ie") {
  				xmlhttp.responseXML.loadXML(texto);
  			}
  			try {
	  			funcao = eval(minhaFuncao);	  			
	  		} catch(e) {
	  			alert("Erro ao atualizar os dados na página. " + e);
	  		}
  		}
  		if(xmlhttp.status == 500) {
  			alert('Erro no processamento.');
  		}
   	}
  }
  
  document.getElementById('status').innerHTML = 'Aguarde...';
  xmlhttp.send();
}

//função para usar AJAX e reflexao de metodo
function processaAjaxSincrono(minhaFuncao,url){
	var xmlhttp = getXMLHttp();
	xmlhttp.open("POST", url+"&_flagAjax=1", false);
  
  xmlhttp.onreadystatechange = function() {
  	document.getElementById('status').innerHTML += '.';
  	if (xmlhttp.readyState == 4) {
  		document.getElementById('status').innerHTML = ' ';
  		if(xmlhttp.status == 200) {
  			//função usada para internet explorer
  			var texto = new String(xmlhttp.responseText).replace(/^\s+|\s+$/, '');
  			if(verificaBrowser() == "ie") {
  				xmlhttp.responseXML.loadXML(texto);
  			}
  			try {
	  			funcao = eval(minhaFuncao);	  			
	  		} catch(e) {
	  			alert("Erro ao atualizar os dados na página. " + e);
	  		}
  		}
  		if(xmlhttp.status == 500) {
  			alert('Erro no processamento.');
  		}
   	}
  }
  
  document.getElementById('status').innerHTML = 'Aguarde...';
  xmlhttp.send();
}

function getDescricao(url,attr,funcao){
    processaAjax(
  	'processaDescricao(xmlhttp.responseXML)',
  	url
  	+'&attr='+attr
  	+'&opcao=funcao'
  	+'&funcao='+funcao
  );
}

/*
  Recebe um respondeXML  com o formato abaixo e 
  executa a funcao passada com o valor que 
  esta em descricao.
  
  <funcao>setDescricaoCID</funcao>
  <descricao>FISIOLOGIA DA DENGUE E PATOLOGIA ESTRANHA</descricao>
*/
function processaDescricao(ajaxResponse){  
  var msgErro = ajaxResponse.getElementsByTagName("erro")[0];
  if(msgErro != null && msgErro != ""){
  	alert(msgErro);
  }  
  else{
  	  var funcao = ajaxResponse.getElementsByTagName("funcao")[0].text;
	  var valor = ajaxResponse.getElementsByTagName("descricao")[0].text;
	  if(
	  	funcao != "" && funcao != "null" && funcao != undefined /*&&
	  	valor != "" && valor != "null" && valor != undefined*/
	  ) {
		  eval(funcao+"('"+valor+"');");
		} else {
			alert('Nenhum valor retornado.');
		}
	}
}

/* 

Modelo:

  onblur=getDescricao(
  	'/executarConsulta.do?cmd=getDescricaoCID&CID='document.formulario.CID.value,
  	'DESC_CID', 
  	'setDescricaoCID'
  );

 function setDescricaoCID(valor){
	if(valor==null || valor==""){
		alert('Nenhum registro encontrado');
		document.getElementById('divCid').innerHTML="";
	} else document.getElementById('divCid').innerHTML=attr;
 }

*/

//função para popular combo
function montaCombo(ajaxResponse,id,compls){
 var data = ajaxResponse.getElementsByTagName("option");
 var htmlText="<select "+compls+" >";
 htmlText=htmlText+"<option value=''>[Selecione uma opção]</option>";
 if(data!=null && data.length==0){
 	alert('Nenhum registro encontrado');
 }else{
 	for(i=0;i<data.length;i++){
      		var value = data[i].getElementsByTagName("value").item(0).text;
      		var option = data[i].getElementsByTagName("desc").item(0).text;
      		htmlText=htmlText+"<option value='"+value+"'>"+option+"</option>";
    	}
 }
 htmlText=htmlText+"</select>";
 document.getElementById(id).innerHTML=htmlText;
}
