// JavaScript Document

function tryEvent(secao, acao, evento, args)
{
	try
	{
		command = secao + "_" + acao + "_" + evento + "(args[0]";

		for (i = 1; i < args.length; i++)
			command = command + ', args[' + i + ']';

		command = command + ");"
		return(eval(command));
	}
	catch(err)
	{
		return true;
	}
}

function tryFunction(func, args)
{
	try
	{
		command = func + "(args[0]";

		for (i = 1; i < args.length; i++)
			command = command + ', args[' + i + ']';

		command = command + ");"
		var res = eval(command);
		return(res);
	}
	catch(err)
	{
		return true;
	}
}

function getpk(botao, pk)
{
	nel = botao.form.elements.length;
	
	for (i = 0; i < nel; i++)
	{
		if (botao.form.elements[i].id == "primaryKeys[" + db + "." + pk + "][]")
		{
			return(i)
		}
	}
}

function logininternas()
{
	abrirlayer();
	document.getElementById('aguardedivtexto').innerHTML = '<table class=login><tr><td colspan=2>Informe os seus dados:</td></tr><tr><td>Usuário</td><td><input type=text id=login name=login></td></tr><tr><td>Senha</td><td><input type=password id=senha name=senha></td></tr><tr><td colspan=2 align=center><input type=button value=Cancelar onclick=\'fecharlayer();\'><input type=button value=Enviar onclick=\'enviarlogin(document.getElementById("login"), document.getElementById("senha"));\'></td></tr></table>';
	document.getElementById("login").focus();
}

function enviarlogin(usuobj, senobj)
{
	if ((usuobj != "") && (senobj != ""))
	{
		var xmlHttp = criaAjaxHttp();
		xmlHttp.onreadystatechange=function()
		{
		if(xmlHttp.readyState==4)
			{
				ret = xmlHttp.responseText;
				if (ret == "ok")
				{
					location.reload(true);
				}
				else if (ret == "uso")
				{
					alert('ESTE USUÁRIO JÁ ESTÁ EM USO EM OUTRO COMPUTADOR.\\n\\nNão é permitida a entrada em vários locais com o mesmo login.');
					logininternas();
				}
				else
				{
					alert('Usuário ou Senha incorretos');
					logininternas();
				}
			}
		}
		hora = new Date();
		engana = hora.getTime();
		xmlHttp.open("GET","login.php?dh="+engana+"&usuario="+usuobj.value+"&senha="+senobj.value+"&origem=internas",true);
		xmlHttp.send(null);
		document.getElementById('aguardedivtexto').innerHTML = '<table><tr><td>Aguarde, carregando...</td></tr></table>';
	}
}

function fecharlayer()
{
	document.getElementById('transpdiv').style.display = 'none';
	document.getElementById('aguardediv').style.display = 'none';
	document.body.style.overflow='';
	document.getElementById('aguardedivtexto').innerHTML = 'Aguarde, carregando...';
}

function abrirlayer()
{
	document.getElementById('transpdiv').style.display = 'block';
	document.getElementById('aguardediv').style.display = 'block';
	document.getElementsByTagName("body")[0].style.overflow = "hidden";
//	document.html.style.overflow='hidden';
	document.getElementById('transpdiv').focus();
}

function email(gercodigo)
{
	abrirlayer();
	document.getElementById('aguardedivtexto').innerHTML = '<table class=email><tr><td colspan=2><u>Escreva uma mensagem para o vendedor</u><br><br></td></tr><tr><td align=right>Título </td><td align=left><input size=39 type=text id=titulo name=titulo></td></tr><tr><td align=right>Mensagem </td><td align=left><textarea cols=30 rows=10 id=mensagem name=mensagem></textarea></td></tr><tr><td colspan=2 align=center><input type=button value=Cancelar onclick=\'fecharlayer();\'><input type=button value=Enviar onclick=\'enviaremail('+gercodigo+', document.getElementById("titulo"), document.getElementById("mensagem"));\'></td></tr></table>';
	document.getElementById("titulo").focus();
}

function enviaremail(gercodigo, titulo, mensagem)
{
	var xmlHttp = criaAjaxHttp();
	xmlHttp.onreadystatechange=function()
	{
	if(xmlHttp.readyState==4)
		{
			ret = xmlHttp.responseText;
			if (ret == "ok")
			{
				document.getElementById('aguardedivtexto').innerHTML = '<table width=400><tr><td>O seu email foi enviado com sucesso.<br><br><input type=button value=Fechar onclick=\'fecharlayer();\'></td></tr></table>';
			}
			else
			{
				document.getElementById('aguardedivtexto').innerHTML = '<table width=400><tr><td>Houve um erro ao enviar o e-mail.<br>Desculpe-nos o transtorno, tente mais tarde.<br><br><input type=button value=Fechar onclick=\'fecharlayer();\'></td></tr></table>';
			}
		}
	}
	hora = new Date();
	engana = hora.getTime();
	xmlHttp.open("GET","enviaremail.php?engana="+engana+"&gercodigo="+gercodigo+"&titulo="+titulo.value+"&mensagem="+mensagem.value,true);
	xmlHttp.send(null);
	document.getElementById('aguardedivtexto').innerHTML = '<table><tr><td>Aguarde, carregando...</td></tr></table>';
}

function atualizaAtividadeHora()
{
		var xmlHttp = criaAjaxHttp();
		xmlHttp.onreadystatechange=function()
		{
		if(xmlHttp.readyState==4)
			{
				ret = xmlHttp.responseText;
				if (ret == "ok")
				{
				}
				else
				{
					alert('Problemas com o controle de horas de atividade. Informe seu superior.' + ret);
				}
			}
		}

		hora = new Date();
		engana = hora.getTime();
		url = "helpatividadehoraops.php?dh="+engana+"&submeter=atualizar";
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
}

//********************************* EVENTOS DE OBJETOS *********************************\\

function pj_buscarcep_onclick()
{
	buscarcep("_pjcep", "_loc_nu_sequencial", "_pjendereco", "_pjbairro", "_pjnumero");
}

function pj_buscarcobcep_onclick()
{
	buscarcep("_pjcobcep", "_cobloc_nu_sequencial", "_pjcobendereco", "_pjcobbairro", "_pjcobnumero");
}

function buscarcep(cep, cidade, endereco, bairro, numero)
{
	var xmlHttp = criaAjaxHttp();
	xmlHttp.onreadystatechange=function()
	{
	if(xmlHttp.readyState==4)
		{
			ret = xmlHttp.responseText;
			div = document.getElementById('aguardedivtexto');
			
			if (ret != "falha")
			{
				res = ret.split(";");
				html = '<input type=button value=Fechar onclick=fecharlayer()><br>'; 
				html += '<table cellpadding=0 cellspacing=0 border=0 class=buscacep width=700><tr class=buscaceptitulo><td colspan=2>CLIQUE SOBRE UMA LINHA PARA SELECIONAR O LOGRADOURO</td></tr><tr class=buscacepheader><td width=500>Logradouro</td><td width=200>Bairro</td></tr>';
				
				for (i=0; i<res.length;i++)
				{
					dados = res[i].split('|');
					
					lin = i%2;
					
					html += "<a href=\"javascript:document.getElementById('" + cep + "').value='" + dados[3] + "';document.getElementById('" + endereco + "').value='" + dados[0] + "';document.getElementById('" + bairro + "').value='" + dados[2] + "';document.getElementById('"+ numero +"').focus();fecharlayer();\"><tr class=buscaceplin" + lin + " onmouseover=\"this.style.fontWeight='bold'\" onmouseout=\"this.style.fontWeight='normal'\">";
					html += "<td>" + dados[1] + "</td>";
					html += "<td>" + dados[2] + "</td>";
					
					html += "</tr></a>";
				}
				
				html += '</table>';
				html += '<br><input type=button value=Fechar onclick=fecharlayer()>'; 
				
				div.innerHTML = html;
				$("#"+numero).focus();
			}
			else
			{
				html = 'A consulta não retornou resultado.<br><br><input type=button value=Fechar onclick=\'fecharlayer();$("#' + endereco + '").focus();\'>'; 
				div.innerHTML = html;
			}
		}
	}
	abrirlayer();
	hora = new Date();
	engana = hora.getTime();
	cidadeobj = document.getElementById(cidade).value;
	alert(cidade);
	enderecovalor = document.getElementById(endereco).value;
	if (endereco.length > 3)
	{
		xmlHttp.open("GET","buscarcep.php?cidade="+cidadeobj+"&endereco="+enderecovalor,true);
		xmlHttp.send(null);
		document.getElementById('aguardedivtexto').innerHTML = '<table><tr><td>Aguarde, carregando...</td></tr></table>';
	}
	else
	{
		fecharlayer();
		alert("O campo endereço deve ser preenchido com 4 caracteres ou mais");
	}
}

function pj_consultarcep_onclick()
{
	consultarcep("_pjcep", "_loc_nu_sequencial", "_pjendereco", "_pjbairro");
	document.getElementById("_pjnumero").focus();
}

function pj_consultarcobcep_onclick()
{
	consultarcep("_pjcobcep", "_cobloc_nu_sequencial", "_pjcobendereco", "_pjcobbairro");
	document.getElementById("_pjcobnumero").focus();
}

function consultarcep(cep, cidade, endereco, bairro)
{
	var xmlHttp = criaAjaxHttp();
	xmlHttp.onreadystatechange=function()
	{
	if(xmlHttp.readyState==4)
		{
			ret = xmlHttp.responseText;
			if (ret != "falha")
			{
				info = ret.split("|");

				cidadeAC = cidade + "AC";
				cidadeLast = cidade + "Last";
				
				$('#' + cidade).val(info[0]);
				$('#' + cidadeAC).val(info[1]);
				$('#' + cidadeLast).val(info[1]);
				$("#" + endereco).val(info[2]);
				$("#" + bairro).val(info[3]);
				
				fecharlayer();
				return true;
			}
			else
			{
				alert("CEP inexistente na base de dados.");
				fecharlayer();
				return false;
			}
		}
	}
	abrirlayer();
	hora = new Date();
	engana = hora.getTime();
	cep = document.getElementById(cep).value;

	url = "consultacep.php?engana="+engana+"&cep="+cep;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
	document.getElementById('aguardedivtexto').innerHTML = '<table><tr><td>Aguarde, carregando...</td></tr></table>';
}

function pj__pjcnpj_onkeyup(obj)
{
	checarCNPJ(obj, "pj", "pjcnpj");
}

function pj__pjcnpj_validate(obj)
{
	return validaCNPJ(obj);
}

function pj__pjcep_onblur(obj)
{
	if (($("#_pjcep").val() != "") && ($("#_loc_nu_sequencial").val() == "") && ($("#_pjendereco").val() == "") && ($("#_pjbairro").val() == ""))
	{
		consultarcep("_pjcep", "_loc_nu_sequencial", "_pjendereco", "_pjbairro");
		$("#_pjnumero").focus();
	}
}

function pj__pjcobcep_onblur(obj)
{
	if (($("#_pjcobcep").val() != "") && ($("#_cobloc_nu_sequencial").val() == "") && ($("#_pjcobendereco").val() == "") && ($("#_pjcobbairro").val() == ""))
	{
		consultarcep("_pjcobcep", "_cobloc_nu_sequencial", "_pjcobendereco", "_pjcobbairro");
		if ($("#_pjcobcep").val() == $("#_pjcep").val())
		{
			$("#_pjcobnumero").val($("#_pjnumero").val());
			$("#_pjcobcomplemento").val($("#_pjcomplemento").val());
		}
		$("#_pjcobnumero").focus();
	}
}

function pj__pjendereco_onblur(obj)
{
	if (($("#_pjcep").val() == "") && ($("#_loc_nu_sequencial").val() != "") && ($("#_pjendereco").val() != ""))
	{
		pj_buscarcep_onclick();
	}
}

function pj__pjcobendereco_onblur(obj)
{
	if (($("#_pjcobcep").val() == "") && ($("#_cobloc_nu_sequencial").val() != "") && ($("#_pjcobendereco").val() != ""))
	{
		pj_buscarcobcep_onclick();
	}
}

function sitecontatoenviar() {
	if (($("#nome").val() == "") || ($("#fone").val() == "") || ($("#cidade").val() == "") || ($("#email").val() == "") || ($("#mensagem").val() == "")){
		alert("TODOS OS CAMPOS são obrigatórios");
		return(false);
	}
	else {
		return(true);
	}
}

function sitecontatohomeenviar() {
	if (($("#nome").val() == "") || ($("#email").val() == "")){
		alert("Preencha o seu nome e e-mail para cadastrar-se");
		$("#nome").focus();
	}
	else {
		var xmlHttp = criaAjaxHttp();
		xmlHttp.onreadystatechange=function()
		{
		if(xmlHttp.readyState==4)
			{
				ret = xmlHttp.responseText;

				switch(ret) {
					case "falha":
						$("#sitecontatohomeenviado").html("Falha no envio");
						return false;
					break;

					case "cadastrado":
						$("#sitecontatohomeenviado").html("Já cadastrado!");
						return true;
					break;

					case "incluido":
						$("#sitecontatohomeenviado").html("Cadastrado com sucesso!");
						return true;
					break;
				}
			}
		}
		$("#sitecontatohomeenviado").html("Aguarde...");
		hora = new Date();
		engana = hora.getTime();

		url = "sitecontatohomeenviar.php?engana="+engana+"&nome="+$("#nome").val()+"&email="+$("#email").val();
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}
	return(false);
}
