//*************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 = "../includes/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...');
        }
    }
}
//função que retorna o banner
function GM_Banner(url,Campo)
{
		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;
							//alert(vRetorno);
							//var vId_Nome = vRetorno.split('*');
						  //insere os novos valores
							 //for(var i=0; i < vId_Nome.length-1; i++) 
							 //{
								 var Banner = vRetorno.split('*'); //separa os dados pelo *
								 var vId = Banner[0];
								 var vNome = Banner[1];
								 var vTipo = Banner[2];
								 var vTarget = Banner[3];
								 var vURL = Banner[4];
								 var vTamanho = Banner[5];
								 var vCorpo = "";
								 //alert(vNome);
								 //opcoes = document.createElement("option");
								 //opcoes.value = vId;
								 //opcoes.text = vNome;
								 //if (Selecionado == vId)
								 //{
										//opcoes.setAttribute("selected", "true");
								 //}
								 //document.getElementById(Campo).options.add(opcoes);
								 if (vNome != "")
								 {
									 	if (vTipo == "1")
										{
											if (vTarget == "1")
											{
												vCorpo = vCorpo + "<a href='" + vURL + "' target='_blank' >";
											}
											else
											{
												vCorpo = vCorpo + "<a href='" + vURL + "' target='_self' >";
											}
											vCorpo = vCorpo + "<img src='arquivos/banners/" + vNome + "' border='0'>";
											vCorpo = vCorpo + "</a>";
										}
										else
										{
											vCorpo = "../arquivos/banners/" + vNome
											if (vTamanho == "1")
											{
												flash(468,60,vCorpo);
											}
											else
											{
												flash(120,60,vCorpo);
											}
										}
								 }
								 document.getElementById(Campo).innerHTML = vCorpo;
								 //alert(vCorpo);
								 
							 //}
							 //GM_Aviso(2,150,20,'avisoCarregando','');
            }
						else
						{
                alert("Carregamento falhou!");
								document.getElementById(campo).innerHTML = "";
            }
            ajax = null
        }
				else
				{
					//GM_Aviso(1,150,20,'avisoCarregando','Carregando...');
        }
    }
}
//função que retorna os dados sdo cliente
function GM_Combo_cliente(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 SeparaDados = vRetorno.split('###');
							var dadosCliente = SeparaDados[0];
							var opcoesPagto = SeparaDados[1];
							//alert(dadosCliente);
							//alert(opcoesPagto);
							
							var vInfo = dadosCliente.split('|||');
							var Codigo_cad = vInfo[0];
							var Razao_social = vInfo[1];
							var CNPJ = vInfo[2];
							var CPF = vInfo[3];
							var IE = vInfo[4];
							var Endereco = vInfo[5];
							var Numero = vInfo[6];
							var UF = vInfo[7];
							var Cidade = vInfo[8];
							var Bairro = vInfo[9];
							var CEP = vInfo[10];
							var DDD = vInfo[11];
							var Fone = vInfo[12];
							var Email = vInfo[13];
							var Nome_fantasia = vInfo[14];
							
							document.formulario_cadastro.Codigo_cad.value = Codigo_cad;
							document.formulario_cadastro.Razao_social.value = Razao_social;
							document.formulario_cadastro.CNPJ.value = CNPJ;
							document.formulario_cadastro.CPF.value = CPF;
							document.formulario_cadastro.IE.value = IE;
							document.formulario_cadastro.Endereco.value = Endereco;
							document.formulario_cadastro.Numero.value = Numero;
							document.formulario_cadastro.UF.value = UF;
							document.formulario_cadastro.Cidade.value = Cidade;
							document.formulario_cadastro.Bairro.value = Bairro;
							document.formulario_cadastro.CEP.value = CEP;
							document.formulario_cadastro.DDD.value = DDD;
							document.formulario_cadastro.Fone.value = Fone;
							document.formulario_cadastro.Email.value = Email;
							document.formulario_cadastro.nome_fantasia.value = Nome_fantasia;
							//alert(Nome_fantasia);
							
							document.getElementById("campo_codigo").innerHTML = Codigo_cad;
							document.getElementById("campo_razao_social").innerHTML = Razao_social;
							document.getElementById("campo_cnpj").innerHTML = CNPJ;
							document.getElementById("campo_cpf").innerHTML = CPF;
							document.getElementById("campo_ie").innerHTML = IE;
							document.getElementById("campo_endereco").innerHTML = Endereco + " nº " + Numero;
							document.getElementById("campo_cidade").innerHTML = Cidade;
							document.getElementById("campo_uf").innerHTML = UF;
							document.getElementById("campo_bairro").innerHTML = Bairro;
							document.getElementById("campo_cep").innerHTML = CEP;
							document.getElementById("campo_telefone").innerHTML = "(" + DDD + ") " + Fone;
							document.getElementById("campo_email").innerHTML = Email;
							
							//alert(Cidade);
							
							var vId_Nome = opcoesPagto.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...');
        }
    }
}


