//*************random para ser usado no final da url para evitar cache do navegador****************
function GM_Random() 
{
	today = new Date();
	num= Math.abs(Math.sin(today.getTime()));
	return num;  
}
//*************verifica se o navegador tem suporte ao AJAX****************
function GM_Verifica_ajax()
{ 
	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;
}
//*************exibe avisos para campos em div durante o carregamento das informações utilizando AJAX****************
function GM_Aviso(valor,largura,altura,campo,mensagem)
{
	
	if (valor == "1")
	{
		var corpo = "<table width='"+ largura +"' height='"+ altura +"' border='0' cellpadding='0' cellspacing='0' bgcolor='#FFFFFF'>"
		corpo = corpo + "<tr>"
		corpo = corpo + "<td><div align='center'><strong><font face='Verdana, Arial, Helvetica, sans-serif' size='1' color='#FF0000'>&nbsp;"+ mensagem +"&nbsp;</font> </strong></div></td>"
		corpo = corpo + "</tr>"
		corpo = corpo + "</table>"
		document.getElementById(campo).innerHTML = corpo;
	}
	else
	{
		document.getElementById(campo).innerHTML = "";
	}
}
//*************busca endereco pelo CEP****************
function GM_CEP(CEP) 
{
	 ajax = GM_Verifica_ajax();

	//se tiver suporte ajax
	if(ajax) 
	{
		 GM_Aviso(1,150,20,'avisoCep','Procurando endereço...');
		 var url = "../include/cep.asp"
		 ajax.open("POST", url, true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		 ajax.onreadystatechange=function() 
		 {
				if (ajax.readyState == 4) 
				{
					 if (ajax.status == 200) 
					 {
							var aDados = ajax.responseXML;
							var categorias = aDados.getElementsByTagName("resposta");
							//alert(categorias.length);
							for (var i = 0; i < categorias.length; i++) 
							{
								// Atribui a cat cada elemento da matriz
								cat = categorias[i];
								var bairro =  cat.getElementsByTagName("bairro")[0].firstChild.nodeValue;
								var cidade =  cat.getElementsByTagName("cidade")[0].firstChild.nodeValue;
								var UF = cat.getElementsByTagName("estado")[0].firstChild.nodeValue;
								var endereco =  cat.getElementsByTagName("logradouro")[0].firstChild.nodeValue;
								var erro = cat.getElementsByTagName("erro")[0].firstChild.nodeValue;
							}
							if (erro == "0")
							{
								document.formulario_endereco.bairro.value = bairro;
								document.formulario_endereco.cidade.value = cidade;
								document.formulario_endereco.UF.options.value = UF;
								document.formulario_endereco.endereco.value = endereco;
								document.formulario_endereco.numero.value = "";
								document.formulario_endereco.complemento.value = "";
							}
							else
							{
								document.formulario_endereco.cep.value = "";
								document.formulario_endereco.bairro.value = "";
								document.formulario_endereco.cidade.value = "";
								document.formulario_endereco.UF.options.value = "";
								document.formulario_endereco.endereco.value = "";
								document.formulario_endereco.numero.value = "";
								document.formulario_endereco.complemento.value = "";
								alert(erro);
							}
							GM_Aviso(2,150,20,'avisoCep','');
					 }
				}
		 }
		 var params = "CEP="+CEP;
		 ajax.send(params)
	}
	else
	{
		alert("Erro ao carregar os dados!");
	}
}

//função que retorna para o combo desejado os valores retornados do link da var url
function GM_Combo(url,Campo,Selecionado)
{
		var ajax = GM_Verifica_ajax();
    if(ajax)
		{
				var Rnd = GM_Random();
        if(url.indexOf("?")>=0)
				{
					// já tem parametros vindos na url
        	url = url + "&" + Rnd;
        }
				else
				{ 
					url = url + "?" + Rnd;
				}
        ajax.onreadystatechange = GM_Status_ajax
        ajax.open("GET", url ,true);
        ajax.setRequestHeader("Cache-Control", "no-cache");
        ajax.setRequestHeader("Pragma", "no-cache");
        //GM_Aviso(1,150,20,'avisoCarregando','Carregando...');
        ajax.send(null);
        return true;
   }
		else
		{
        alert("Este navegador não tem suporte ao AJAX!");
				return false;
    }
    function GM_Status_ajax()
		{
        if (ajax.readyState==4)
				{
            if(ajax.status == 200)
						{
							//alert(document.getElementById(Campo).value);
							document.getElementById(Campo).options.length = 1;
							var vRetorno = ajax.responseText;
							var vId_Nome = vRetorno.split('*');
						  //insere os novos valores
							 for(var i=0; i < vId_Nome.length-1; i++) 
							 {
								 var Lista = vId_Nome[i].split('|'); //separa ID do Nome pela Barra(|)
								 var vId = Lista[0];
								 var vNome = Lista[1];
								 opcoes = document.createElement("option");
								 opcoes.value = vId;
								 opcoes.text = vNome;
								 if (Selecionado == vId)
								 {
										opcoes.setAttribute("selected", "true");
								 }
								 document.getElementById(Campo).options.add(opcoes);
							 }
							 //GM_Aviso(2,150,20,'avisoCarregando','');
            }
						else
						{
                alert("Carregamento falhou!");
            }
            ajax = null
        }
				else
				{
					//GM_Aviso(1,150,20,'avisoCarregando','Carregando...');
        }
    }
}


