//**********************************************************************************************
//**********************************************************************************************
//**********************************************************************************************
// funcao que preenche os combo_box com ajax
//**********************************************************************************************

function Dadosajax(nomeidselect,campo1,campo2,campo3,table,id,msgerror,msgsuccess) {
	//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) {
		cpselect = document.getElementById(nomeidselect);
		
		//deixa apenas o elemento 1 no option, os outros são excluídos
		cpselect.options.length = 1;

		ajax.open("POST", "ajax/ajax_xml.php", 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) {
				cpselect.options[0].value= "-1";
				cpselect.options[0].text= "Loading...";
			}
			//após ser processado - chama função processXML que vai varrer os dados
			if(ajax.readyState == 4 ) {
				if(ajax.responseXML) {
					processXML(ajax.responseXML,nomeidselect,msgerror,msgsuccess);
				} else {
					//caso não seja um arquivo XML emite a mensagem abaixo
					cpselect.options[0].value= "-1";
					cpselect.options[0].text= msgerror;
				}
			}
		}
		//passa o código do estado escolhido
		var params = 'campo1='+campo1+'&campo2='+campo2+'&campo3='+campo3+'&table='+table+'&id='+id;
		ajax.send(params);
	}
}

function processXML(obj,nomeidselect,msgerror,msgsuccess){
	//pega a tag cidade
	var dataArray   = obj.getElementsByTagName("item");
	cpselect = document.getElementById(nomeidselect);
	//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 codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			
			cpselect.options[0].value= "-1";
			cpselect.options[0].text= msgsuccess;
			
			//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 = codigo;
			//atribui um texto
			novo.text  = descricao;
			//finalmente adiciona o novo elemento
			cpselect.options.add(novo);
		}
	} else {
		//caso o XML volte vazio, printa a mensagem abaixo
		cpselect.options[0].value= "-1";
		cpselect.options[0].text= msgerror;
	}
}

function limpa_sel(nomeidselect,msg) {
	cpselect = document.getElementById(nomeidselect);
	cpselect.options.length = 1;
	cpselect.options[0].value= "-1";
	cpselect.options[0].text= msg;
}

function limpa_div(nomeidselect,msg) {
	cpselect = document.getElementById(nomeidselect);
	cpselect.innerHTML= msg;
}


function Dadosajaxhtml(id,param,url,formvai,funcreturn){
	//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) {
		//Obtém o objeto HTML
		objetoHTML=document.getElementById(id)

		//Exibe "Carregando..."
		objetoHTML.innerHTML="Loading..."

		ajax.open("POST", url, 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) {
				objetoHTML.innerHTML="Loading..."
			}
			//após ser processado - chama função processXML que vai varrer os dados
			if(ajax.readyState == 4 ) {
				//Mostra o HTML recebido
				retorno=unescape(ajax.responseText.replace(/\+/g," "))
				objetoHTML.innerHTML=retorno
				if(funcreturn)
					eval(funcreturn);
			}
		}
		if(formvai==1){
			//formen = document.getElementById(param);
			//alert(formen.name);
			var params = getstr(param);
		} else {
			var params = 'parametro='+param;
		}
		//alert(params);
		ajax.send(params);
	}
}

function getstr(obj) {
// come from: http://www.captain.at/howto-ajax-form-post-get.php
	var getstr = "";
	obj = document.getElementById(obj);
	
	var obj_input = obj.getElementsByTagName('INPUT');
	
	for(tt=0; tt < obj_input.length; tt++){
		//alert(obj_input[tt].type);
		if (obj_input[tt].type == "text" || obj_input[tt].type == "hidden") {
			getstr += obj_input[tt].name + "=" + obj_input[tt].value + "&";
		}
		if (obj_input[tt].type == "checkbox") {
			if (obj_input[tt].checked) {
				getstr += obj_input[tt].name + "=" + obj_input[tt].value + "&";
			} //else {
				//getstr += obj_input[tt].name + "=&";
			//}
		}
		if (obj_input[tt].type == "radio") {
			if (obj_input[tt].checked) {
				getstr += obj_input[tt].name + "=" + obj_input[tt].value + "&";
			}
		}
		//alert(getstr);
	}
	
	var obj_input = obj.getElementsByTagName('SELECT');
	for(tt=0; tt < obj_input.length; tt++){
		var sel = obj_input[tt];
		getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
	}

	var obj_input = obj.getElementsByTagName('TEXTAREA');
	for(tt=0; tt < obj_input.length; tt++){
		getstr += obj_input[tt].name + "=" + obj_input[tt].value + "&";
	}
	return getstr;
}

