$(document).ready(function(){
	$("#institucional li:last").css({backgroundImage: "none"});
	$("#institucional2 li:last").css({backgroundImage: "none"});
	$("#inst li:last").css({backgroundImage: "none"});
	$("#televendas li:last").css({backgroundImage: "none"});
	//ControleRevendedor();
	CriaMenuBaixo();
});

function chop(str){
	var strHash = new String(str);
	strHash = strHash.substring(0,(strHash.length-1));
	return strHash;
}

function limpaCampo(campo){
	// Verifica se o campo possui a mesma string da tag "alt" se tiver ele limpa o campo para o novo valor
	if(campo.value ==  campo.alt){
		campo.value = "";
	}
}
function verificaCampo(campo){
	// Se sair do campo com ele em branco, ele preenche denovo com o valor do "alt" como mensagem padrÃ£o
	if(campo.value == ""){		
		document.getElementById(campo.id).value = campo.alt;
	}
}
function formataData(e,campo){
	// Formata a data no formato "dd/mm/aaaa"
	// Captura a tecla pressionada, se nÃ£o for "Backspace" e nem "Delete" ele formata o campo
	var tecla = e.keyCode;				
	var data = campo.value;
	if (tecla != 8) {
		if (tecla != 46) {
			if (data.length == 2 || data.length == 5) {
				data = data + "/";
				document.getElementById(campo.id).value = data;
			}
		}
	}
}

function remover_espacos(str){
	r = "";
	for(i = 0; i < str.length; i++){
	  if(str.charAt(i) != ' ')
	    r += str.charAt(i);
	}
	return r;
}

function ValidaEmail(email){
	var re2 = /^([a-z0-9\.\-\_]+)\@([a-z0-9\-\_]+\.{1})*?([a-z0-9]{2,3}){1}$/;
	email = email.toLowerCase();

	if (!re2.test(email)){
		return 0;
	}
	return 1;
}

function trocaMenu(campos){				
// 	for(x=0;x<document.getElementsByName(campos.name).length;x++){
// 		document.getElementsByName(campos.name)[x].className = "";
// 	}
// 	document.getElementById(campos.id).className = "ativo";
    document.formMenu.passo.value = campos;
    document.formMenu.submit();
}

function validaCampos(){
	var erro = 0;
	if(document.frmLogin.idInputEmail.value == ''){
		alert("Digite o seu email.");
		document.getElementById('idInputEmail').focus();
		erro = 1;
	}else if(!ValidaEmail(document.frmLogin.idInputEmail.value)){
		alert("Email inválido");
		document.getElementById('idInputEmail').focus();
		erro = 1;
	}else if(document.frmLogin.idInputSenha.value == ''){
		alert("Digite sua senha.");
		document.getElementById('idInputSenha').focus();
		erro = 1;
	}

	if(erro == 1){
		return;
	}else{
		document.frmLogin.submit();
	}
}

function manupulaImagem(campo){
	if (campo.alt == "adicionar") {
		// Soltar uma requisição AJAX para subir a nova imagem e trazer o endereço da mesma
		document.getElementById(campo.id).alt = "excluir";
		document.getElementById(campo.id).value = "Excluir Foto";
		var imagemId = campo.id;
		imagemId = imagemId.substring(6);
		imagemId = "img" + imagemId;
		document.getElementById(imagemId).src = "imagens/fotoExemplo.jpg";
		var imagemId = campo.id;
		imagemId = imagemId.substring(6);
		imagemId++;
		var novaFoto = "foto" + imagemId;
		var novoCampo = "<div id='" + novaFoto + "' class='minhasFotos'>";
		novaFoto = "grFoto" + imagemId;
		novoCampo += "<input type='button' alt='adicionar' value='Adicionar foto' id='" + novaFoto + "' onclick='manupulaImagem(this);' /><br />";
		novaFoto = "img" + imagemId;
		novoCampo += "<img src='imagens/addImg.jpg' id='" + novaFoto + "' width='150px' height='100px' /></div>";
		document.getElementById("painelFotos").innerHTML += novoCampo;
	}else{
		if(confirm("Deseja excluir a foto?")){
			var campoDel = campo.id;
			campoDel = campoDel.substring(6);
			campoDel = "#foto"+campoDel; 
			$(campoDel).fadeOut("slow");
		}
	}
}

function addDelImg(campo){
	if (campo.alt == "adicionar") {
		// Soltar uma requisição AJAX para subir a nova imagem e trazer o endereço da mesma
		document.getElementById(campo.id).alt = "excluir";
		document.getElementById(campo.id).value = "Excluir Foto";
		var imagemId = campo.id;
		imagemId = imagemId.substring(7);
		imagemId = "img" + imagemId;
		document.getElementById(imagemId).src = "imagens/fotoExemplo.jpg";
		var imagemId = campo.id;
		imagemId = imagemId.substring(7);
		imagemId++;
		var novaFoto = "foto" + imagemId;
		var novoCampo = "<div class='fotoPrinc' id='"+novaFoto+"'>";
		novaFoto = "btnFoto" + imagemId;
		novoCampo += "<input type='button' value='Adicionar foto' id='"+novaFoto+"' alt='adicionar' onclick='addDelImg(this);' /><br />";
		novaFoto = "img" + imagemId;
		novoCampo += "<img src='imagens/addImg.jpg' id='"+novaFoto+"' width='200px' height='150px' /></div>";
		document.getElementById("colFotos").innerHTML += novoCampo;
	}else{
		if(confirm("Deseja excluir a foto?")){
			var campoDel = campo.id;
			campoDel = campoDel.substring(7);
			campoDel = "#foto"+campoDel; 
			$(campoDel).fadeOut("slow");
		}
	}
}

function habilitaFormAltEndereco(vlrStatus){
	var status;
	if(vlrStatus == 0){
		status = false;
	}else{
		status = true;
	}
	document.frmAltEndereco.altEndereco.disabled = status;
	document.frmAltEndereco.altComplemento.disabled = status;
	document.frmAltEndereco.altBairro.disabled = status;
	document.frmAltEndereco.altCidade.disabled = status;
	document.frmAltEndereco.altEstado.disabled = status;
	document.frmAltEndereco.altCep.disabled = status;
	if(status == false){
		document.frmAltEndereco.btnAlt.disabled = true;
		document.frmAltEndereco.btnSave.disabled = false;					
	}else{
		document.frmAltEndereco.btnAlt.disabled = false;
		document.frmAltEndereco.btnSave.disabled = true;
	}
}

function habilitaFormDadosPessoais(vlrStatus){
	var status;
	if(vlrStatus == 0){
		status = false;
	}else{
		status = true;
	}
	document.frmDadosPessoais.dpTipoLista.disabled = status;
	document.frmDadosPessoais.dpNome.disabled = status;
	document.frmDadosPessoais.dpEmail.disabled = status;
	document.frmDadosPessoais.dpNomePai.disabled = status;
	document.frmDadosPessoais.dpNomeMae.disabled = status;
	if(status == false){
		document.frmDadosPessoais.dpBtnAlt.disabled = true;
		document.frmDadosPessoais.dpBtnSave.disabled = false;					
	}else{
		document.frmDadosPessoais.dpBtnAlt.disabled = false;
		document.frmDadosPessoais.dpBtnSave.disabled = true;
	}
}

function habilitaFormDadosCasamento(vlrStatus){
	var status;
	if(vlrStatus == 0){
		status = false;
	}else{
		status = true;
	}
	
	document.frmDadosCasamento.dcNome.disabled = status;
	document.frmDadosCasamento.dcEmail.disabled = status;
	document.frmDadosCasamento.dcNomePai.disabled = status;
	document.frmDadosCasamento.dcNomeMae.disabled = status;
	if(status == false){
		document.frmDadosCasamento.dcBtnAlt.disabled = true;
		document.frmDadosCasamento.dcBtnSave.disabled = false;					
	}else{
		document.frmDadosCasamento.dcBtnAlt.disabled = false;
		document.frmDadosCasamento.dcBtnSave.disabled = true;
	}
}

function habilitaFormDadosEvento(vlrStatus){
	var status;
	if(vlrStatus == 0){
		status = false;
	}else{
		status = true;
	}
	
	document.frmDadosEvento.deLocal.disabled = status;
	document.frmDadosEvento.deEndEvt.disabled = status;
	document.frmDadosEvento.deBairroEvt.disabled = status;
	document.frmDadosEvento.deCidadeEvt.disabled = status;				
	document.frmDadosEvento.deEstadoEvt.disabled = status;
	document.frmDadosEvento.deNumEvt.disabled = status;
	document.frmDadosEvento.deComplEvt.disabled = status;
	document.frmDadosEvento.deCidadeEvt.disabled = status;				
	document.frmDadosEvento.deDtEvento.disabled = status;
	document.frmDadosEvento.deHrEvento.disabled = status;
	document.frmDadosEvento.deObsEvento.disabled = status;
	document.frmDadosEvento.deRefEvt.disabled = status;
	if(status == false){
		document.frmDadosEvento.deBtnAlt.disabled = true;
		document.frmDadosEvento.deBtnSave.disabled = false;					
	}else{
		document.frmDadosEvento.deBtnAlt.disabled = false;
		document.frmDadosEvento.deBtnSave.disabled = true;
	}
}


function validaOpcao(opcao){
	if(opcao == 'casamento'){
		$('#caixaCasamento').fadeIn('slow');
	}else{
		$('#caixaCasamento').fadeOut('slow');
	}
}

// Tratamento do Ajax para a Home

var ajx_HTTPObject = criaHTTPObject();

function salvaDescricaoImg(textArea){
	
	var img_id =  textArea.id.substr(4);
	var txt = escape(textArea.value);
	var parametros = {
		loja:document.formMenu.loja.value,
		imgId:img_id,
		lista:document.formMenu.lista_id.value,
		acao:'salvaDescricaoImg',
		desc:txt
	};
	chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, '', 'txt');
}

function salvaTituloImg(inputTxt){
	var img_id =  inputTxt.id.substr(3);
	var txt = escape(inputTxt.value);
	var parametros = {
		loja:document.formMenu.loja.value,
		imgId:img_id,
		lista:document.formMenu.lista_id.value,
		acao:'salvaTituloImg',
		titleImg:txt
	};
	chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, '', 'txt');
}


function salvaDescricaoEvento(textArea){

	var txt = escape(textArea.value);
	var parametros = {
		loja:document.formMenu.loja.value,
		lista:document.formMenu.lista_id.value,
		acao:'salvaDescricaoEvento',
		descEvt:txt
	};
	chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, '', 'txt');
}

function configuraTela(origCampo){
	
	var tpListaSel = document.getElementById(origCampo).value;
	document.getElementById('origTrocaCss').value = origCampo;
	document.getElementById('tpSelecionado').value = tpListaSel;
	var loja_id = document.getElementById('loja_id').value;
	var classeMiolo = "#" + document.getElementById('classemiolo').value;
    
	if (tpListaSel != 'none') {
		$(classeMiolo).css({background:"url(../imagens/"+loja_id+"-bgMiolo"+tpListaSel+".jpg) no-repeat left bottom"});
		$("#mioloCabecalhoImg img").attr("src","../imagens/"+loja_id+"-logoLista"+tpListaSel+".gif");
		$("#ico01").attr("src","../imagens/"+loja_id+"-ico01-"+tpListaSel+".gif");
		$("#ico02").attr("src","../imagens/"+loja_id+"-ico02-"+tpListaSel+".gif");
		
		
		var parametros = {
			acao: 'configTelaHome',
			loja: loja_id,
			tp_lista: tpListaSel
		};
		
		chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, 'trataNovaTela', 'txt');
	}
	else{
		$(classeMiolo).css({background:"url(../imagens/"+loja_id+"-bgMioloPadrao.jpg) no-repeat left bottom"});
		$("#mioloCabecalhoImg img").attr("src","../imagens/"+loja_id+"-logoListaPadrao.gif");
	}
}

function alteraFolhaEstilo(title) {
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if (a.getAttribute("title") == title) {
				a.disabled = false;
			}
		}
	}
}

function trataNovaTela(resp){
	var spanTxt;
	var opcoes = new Array();
	var opcao = new Array();
	var formAlvo = document.getElementById('frmAlvo').value;
	opcoes = resp.split('*');	
	var tpCss = opcoes.pop();
	var numCss = document.getElementById('numCss').value;
	alteraFolhaEstilo(tpCss,1);
	//carregaCaixainfo(document.getElementById('loja_id').value,document.getElementById('tpSelecionado').value);
	if (document.getElementById('origTrocaCss').value == 'tpLista') {
		document.getElementById(formAlvo).innerHTML = '';
		//alert(opcoes.length);
		for (x = 0; x < opcoes.length; x++) {
			//alert(x +" e "+opcoes[x]);
			opcao = opcoes[x].split('|');
			var idCampo = "n" + opcao[2];
			if (opcao[1] == 'M') {
				var nameCampo = "Nome do " + opcao[0] + ":";
			}
			else {
				var nameCampo = "Nome da " + opcao[0] + ":";
			}
//			var campoForm = document.createElement("input");
//			campoForm.setAttribute("type", "text");
//			campoForm.setAttribute("id", idCampo);
//			campoForm.setAttribute("name", idCampo);
//			campoForm.setAttribute("size", "20");
//			campoForm.setAttribute("value", "digite o nome...");
//			campoForm.setAttribute("alt", "digite o nome...");
//			campoForm.setAttribute("onclick", "limpaCampo(this);");
//			campoForm.setAttribute("onfocus", "limpaCampo(this);");
//			campoForm.setAttribute("onblur", "verificaCampo(this);");
			var campoForm ="<input type='text' id='"+idCampo+"' name='"+idCampo+"' size='20' value='digite o nome...' alt='digite o nome...' onClick='limpaCampo(this);' onfocus='limpaCampo(this);' onblur='verificaCampo(this);' >";
			if(document.getElementById('resultBusca')){
				spanTxt = "<span style='float:left;'>";
			}else{
				spanTxt = '';
			}			
			document.getElementById(formAlvo).innerHTML += spanTxt+"<p class='txt3'>"+nameCampo+"</p>"+campoForm;
			//if (document.getElementById(formAlvo).appendChild(campoForm)) {
				if (document.getElementById('resultBusca')) {
					document.getElementById(formAlvo).innerHTML += "</span>";
				}
			//}
			//if (x < opcoes.length -1) {
			//	document.getElementById('cxFrm').innerHTML += '<br />ou<br />';
			//}
		}
	}
}
//function enviaHistoriaHTML(){
//	var histHtml;
//	var iframe = document.getElementById('freeRTE');
//	if(iframe.contentWindow) {
//		histHtml = iframe.contentWindow.document.body.innerHTML;
//	} else if(iframe.contentDocument){
//		histHtml = iframe.contentDocument.document.body.innerHTML;
//	}
//	document.frm.rteContent.value = histHtml
//	document.frm.submit();
//}


function salvarArquivoHTML()
{
	var iframe = document.getElementById('freeRTE');
	var histHtml;
	if(iframe.contentWindow) {
		histHtml = iframe.contentWindow.document.body.innerHTML;
	} else if(iframe.contentDocument){
		histHtml = iframe.contentDocument.document.body.innerHTML;
	}
	alert(histHtml);
	//histHtml = eval(histHtml);
	//alert(histHtml);

	var parametros = {
		acao:'salvaHistoriaHTML',
		loja:document.frm.loja.value,
		lista_id:document.frm.lista_id.value,
		sessao:document.frm.sessao.value,
		tipo_id:document.frm.tipo_id.value,
		txtHtml:histHtml
	}

	chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, 'tratarSalvaHistorico', 'txt');
}

function tratarSalvaHistorico(resp)
{
	if(resp == 1){
		document.getElementById('mensagem').innerHTML = 'Arquivo salvo com sucesso';
	}else{
		document.getElementById('mensagem').innerHTML = 'Houve um erro no servidor, tente novamente';
	}
}


function criaNovaLista()
{
	if(document.frmNovaLista.tipo_id.selectedIndex>0){
		document.frmNovaLista.loja.value = document.getElementById('loja_id').value;
		document.frmNovaLista.submit();
    }else{
        alert('Selecione um tipo de lista');
    }
	
}

function carregaCaixainfo(loja_id,tpLista){
	//pegar a quantidade de caixas de informação necessária para a montagem da página
    var parametros = {
			acao: 'pegaCaixas',
   			tipo_id: tpLista,
			loja: loja_id
    };
    chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, 'trataCaixaInfo', 'txt');
}

function trataCaixaInfo(dados){
	var caixas;
    caixas = dados.split('!#FIM_CAIXA#!');
    
	for(i=0;i<caixas.length;i++){
		var numCx = i+1;
        if(document.getElementById('caixa'+numCx)){
			document.getElementById('caixa'+numCx).innerHTML = caixas[i];
        }
    }
}

function enviaLoginHome(){
	var emailLimpo = remover_espacos(document.getElementById('idEmail').value);
	if(emailLimpo == document.getElementById('idEmail').alt || emailLimpo == '' || ValidaEmail(emailLimpo) == 0){
		alert("E-Mail invalido ou incorreto.");
		document.getElementById('idEmail').focus();
		return;
	}
	if(document.getElementById('tpListaadm').value == "none"){
		alert("Selecione um tipo de lista!");
		return;
	}	
	
	if(document.getElementById('idSenha').value == ''){
		alert("Informe a senha");
		document.getElementById('idSenha').focus();
		return;
	}	
	
	var parametros = {
		acao:'validaLogin',
		loja:document.getElementById('loja_id').value,
		email:emailLimpo,
		senha:document.getElementById('idSenha').value,
        tipo_id:document.getElementById('tpListaadm').value
	};
	chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, 'validaLogin', 'txt');
}

function validaLogin (resp){
	var dados = new Array();
	dados = resp.split('|');
	if(dados[0] == 0){
		alert("E-Mail ou senha incorretos");
		return;
	}
	document.frmAdmLista.loja.value = document.getElementById('loja_id').value;
	document.frmAdmLista.lista_id.value = dados[0];
	document.frmAdmLista.tipo_id.value = dados[1];		
	document.frmAdmLista.submit();
}

function procuraLista(frmCampo){
	frmCampo = eval("document."+frmCampo);
	var erro = 0;
	var numText = 0;
	var valueLimpo,altLimpo;
	for (x=0;x<frmCampo.elements.length;x++){
		if(frmCampo.elements[x].type == 'text'){
			numText++;			
			valueLimpo = remover_espacos(frmCampo.elements[x].value);
			altLimpo = remover_espacos(frmCampo.elements[x].alt);
			if(frmCampo.elements[x].value == frmCampo.elements[x].alt || valueLimpo == ''){
				erro++;
			}
		}
	}
	if(eval("document."+frmCampo.id+".tpLista.value") == "none")
	{
	  alert("Selecione um tipo de lista!");
	  return;
	}

	if(erro >= numText){
		alert("Informe pelo menos um dos campos");
		frmCampo.elements[1].focus();
		return;
	}
	var frmId = frmCampo.id;
	eval("document."+frmId+".loja.value = document.getElementById('loja_id').value");
	//document.frmComprarPresente.loja.value = document.getElementById('loja_id').value;	
	//document.frmComprarPresente.submit();
	for (x = 0; x < frmCampo.elements.length; x++) {
		if(frmCampo.elements[x].value == frmCampo.elements[x].alt){
			frmCampo.elements[x].value = '';
		}
	}
	
	var data = eval("document." + frmId + ".dtEvento.value");
	if (data != "") {		
		var diaMesAno = data.split('/');
		
		var dataValida = validaData(diaMesAno[0], diaMesAno[1], diaMesAno[2]);
		if (dataValida == 0) {
			eval("document." + frmId + ".submit()");
		}
		else {
			alert(dataValida);
			for (x = 0; x < frmCampo.elements.length; x++) {
				frmCampo.elements[x].value = frmCampo.elements[x].alt;
			}
			return;
		}
	}else{
		eval("document." + frmId + ".submit()");
	}
}

function formataHora(e,campo){
	var tecla = e.keyCode;
	if ((tecla > 94 && tecla < 106) || (tecla == 37 || tecla == 39) && !(tecla == 188 || tecla == 190 || tecla == 16)) {
		// Formata a hora no formato "hh:mm"
		// Captura a tecla pressionada, se nao for "Backspace" e nem "Delete" ele formata o campo
		var hora = campo.value;
		if (tecla != 8) {
			if (tecla != 46) {
				if (hora.length == 2) {
					if (hora > 23){
						alert('A hora deverá ser de 00:00 até 23:59');
						campo.value = '';
						return;
					}
					hora = hora + ":";
					document.getElementById(campo.id).value = hora;
				}
				else if (hora.length == 5){
					if (hora.substr(3,2) > 59){
						alert('A hora deverá ser de 00:00 até 23:59');
						campo.value = '';
						return;
					}
				}
			}
		}
	}
	else if ((tecla  < 48 || tecla > 57) && !(tecla == 8 || tecla == 46 || tecla == 9 || tecla == 22)) {
		alert('A hora deve conter apenas números');
		campo.value = '';
		return false
	}
	

}
// ============================================================================================================ //

function goToPagina(formId,destino)
{
	switch (destino){
		//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
		case 'first':
			eval("document."+formId+".limiteBusca.value = 0");
		break;
		//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
		case 'prev':
			var novoNum;
			if ((eval("document." + formId + ".limiteBusca.value"))*1 > 0) {
				if ((eval("document." + formId + ".limiteBusca.value")) * 1 == (eval("document." + formId + ".qtdeTotal.value")) * 1 - 1) {
					novoNum = (eval("document." + formId + ".qtdeTotal.value"))*1 - (eval("document."+formId+".intervalo.value"))*1;
				}else{
					novoNum = (eval("document."+formId+".intervalo.value"))*1;
					novoNum -= (eval("document." + formId + ".limiteBusca.value"))*1;
					novoNum = (novoNum)*(-1);
				}
				
				if(novoNum < 0){
					novoNum = 0;
				}
				eval("document." + formId + ".limiteBusca.value ="+novoNum);
			}
		break;
		//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
		case 'next':
			var novoNum = (eval("document."+formId+".limiteBusca.value"))*1;
			novoNum += (eval("document."+formId+".intervalo.value"))*1;
			
			if(novoNum == (eval("document."+formId+".qtdeTotal.value"))*1)
			{
				novoNum -= (eval("document."+formId+".intervalo.value"))*1;
				novoNum += ((eval("document."+formId+".intervalo.value"))*1)-1;
			}else if(novoNum >(eval("document."+formId+".qtdeTotal.value"))*1){
				novoNum -= eval("document."+formId+".intervalo.value");
				novoNum = ((eval("document."+formId+".qtdeTotal.value"))*1) - 1;
			}			
			eval("document."+formId+".limiteBusca.value="+novoNum);			
		break;
		//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
		case 'last':
// 			alert(eval("document."+formId+".qtdeTotal.value") + "-" + eval("document."+formId+".intervalo.value") +"-"+ eval("document."+formId+".limiteBusca.value ="+novaPag));
// 			var novaPag = ((eval("document."+formId+".qtdeTotal.value"))*1) - (eval("document."+formId+".intervalo.value"))*1;
// 			novaPag = eval("document."+formId+".qtdeTotal.value") - novaPag;
			var novaPag = ((eval("document."+formId+".qtdeTotal.value"))*1) / (eval("document."+formId+".intervalo.value"))*1;
			novaPag = Math.ceil(novaPag); //arredonda o total de links
			novaPag = ((novaPag -1) * eval("document."+formId+".intervalo.value"));
			
			eval("document."+formId+".limiteBusca.value ="+novaPag);
		break;
		//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
	}
	eval("document."+formId+".submit()");
}

function goToPaginaBusca(formId,destini,destFinal,paginaAtual)
{
	if (destFinal == 0) {
		if(destini == 'anterior'){
			if (eval("document." + formId + ".limiteBusca.value > 11")) {
				eval("document." + formId + ".limiteBusca.value =document." + formId + ".limiteBusca.value - 10");
				eval("document." + formId + ".intervalo.value= document." + formId + ".intervalo.value -10");
			}else{
				eval("document." + formId + ".limiteBusca.value = 0");
				eval("document." + formId + ".intervalo.value = 10");
			}
			eval("document." + formId + ".paginaAtual.value --");
		}else{ // Navegação próxima página
			var totalPag = eval("document." + formId + ".totalPag.value");
			if(eval("document." + formId + ".intervalo.value == "+totalPag*10)){
				eval("document." + formId + ".limiteBusca.value ="+totalPag - 9);
				eval("document." + formId + ".intervalo.value = "+totalPag *10);
			}else{
				
				if (eval("document." + formId + ".limiteBusca.value == 0")) {
					if (formId == 'frmPagFotos') {
						eval("document." + formId + ".limiteBusca.value = (document." + formId + ".limiteBusca.value)*1 + 10");
					}else{
						eval("document." + formId + ".limiteBusca.value = (document." + formId + ".limiteBusca.value)*1 + 11");
					}
				}else{
					eval("document." + formId + ".limiteBusca.value = (document." + formId + ".limiteBusca.value)*1 + 10");
				}
				eval("document." + formId + ".intervalo.value= (document." + formId + ".intervalo.value)*1 + 10");
			}
			eval("document." + formId + ".paginaAtual.value ++");
		}		
	}
	else {
		eval("document." + formId + ".limiteBusca.value =" + destini);
		eval("document." + formId + ".intervalo.value=" + destFinal);
		eval("document." + formId + ".paginaAtual.value =" + paginaAtual);
	}
	eval("document."+formId+".submit()");

}

function defineItensPaginacao(formId)
{
	var limite = eval("document."+formId+".limiteBusca.value")*1;
	var intervalo = eval("document."+formId+".intervalo.value")*1;
	var total = eval("document."+formId+".qtdeTotal.value")*1;
	var soma = limite+intervalo;
	
	if(limite == 0){
		$('#primeiro01').hide();
		$('#anterior01').hide();
		$('#primeiro02').hide();
		$('#anterior02').hide();
		
		$('#proximo01').show();
		$('#ultimo01').show();
		$('#proximo02').show();
		$('#ultimo02').show();
	}else if(soma >= total){ 
		$('#primeiro01').show();
		$('#anterior01').show();
		$('#primeiro02').show();
		$('#anterior02').show();
		
		$('#proximo01').hide();
		$('#ultimo01').hide();
		$('#proximo02').hide();
		$('#ultimo02').hide();
	}else{
		$('#primeiro01').show();
		$('#anterior01').show();		
		$('#proximo01').show();
		$('#ultimo01').show();
		
		$('#primeiro02').show();
		$('#anterior02').show();
		$('#proximo02').show();
		$('#ultimo02').show();
	}
}


function limitaChar(campo,qtde,nomeContador)
{
	var textCampo = campo;
	var texto = textCampo.value;
	if (textCampo.value.length > qtde) {
		textCampo.value = textCampo.value.substring(0, qtde);
	}
	else {
		document.getElementById(nomeContador).innerHTML = qtde - textCampo.value.length;
	}

}

function resetaObrigatorios(formName){

	var frmElTam = eval("document."+formName+".elements.length");
	for (x = 1; x < frmElTam-2; x++) {
		eval("document."+formName+".elements["+x+"].style.background = '#FFFFFF';");
		eval("document."+formName+".elements["+x+"].value = '';");
		//eval("document."+formName+"."+elForm[x].name+".style.background = '#FFFFFF';");
		//eval("document."+formName+"."+elForm[x].name+".value = '';");
		document.getElementById('msgRespEnd').innerHTML= " ";
	}
}


var flag=0;

function mostraDadosCep(retorno){
	var results = retorno.split("|");

	if (results[0] > 0) {
		if (document.getElementById('PESlogradouro')) {
			document.getElementById('PESlogradouro').value = results[1] + ' ' + results[2];
		}
		else if (document.getElementById('ENTlogradouro')) {
			document.getElementById('ENTlogradouro').value = results[1] + ' ' + results[2];
		}

		if (document.getElementById('PESbairro')) {
			document.getElementById('PESbairro').value = results[4];
		}
		else if (document.getElementById('ENTbairro')) {
			document.getElementById('ENTbairro').value = results[4];
		}
		//document.getElementById('cidade').value = results[6];
		if (document.getElementById('PEScidade')) {
			document.getElementById('PEScidade').value = results[6];
		}
		else if (document.getElementById('ENTcidade')) {
			document.getElementById('ENTcidade').value = results[6];
		}
		
		//document.getElementById('uf').value = results[7];
		if (document.getElementById('PESuf')) {
			document.getElementById('PESuf').value = results[7];
		}
		else if (document.getElementById('ENTuf')) {
			document.getElementById('ENTuf').value = results[7];
		}
	}
	else {
		alert("CEP inválido");
	}
	return;
}

function mostraDadosCepCadastro(retorno){
	var results = retorno.split("|");

	if (results[0] > 0) {
		if (document.getElementsByName('PESlogradouro')) {
			document.getElementsByName('PESlogradouro')[0].value = results[1] + ' ' + results[2];
		}
		
		if(document.getElementsByName('PESbairro')){
			document.getElementsByName('PESbairro')[0].value = results[4];
		}

		if(document.getElementsByName('PEScidade')){
			document.getElementsByName('PEScidade')[0].value = results[6];
		}
		if(document.getElementsByName('PESuf')){
			document.getElementsByName('PESuf')[0].value = results[7];
		}
	}
	else {
		alert("CEP inválido");
	}
	return;
}

function preencheFilial(cep) {
	re0 = /^[\d]+$/;
	cep = cep.replace(/[\D]/gm,'');
	
	if (re0.test(cep)){
		$.post(	"ajx_lista.pl",
				{
				acao: 'mostraFilial',
				cep:  escape(cep),
				loja: document.getElementById('loja').value
				},
				function retornoAjax(retorno){
					mostraSelectFilial(retorno);					
				}
		);
	}
	return;
}




function mostraSelectFilial(retorno){
	if (retorno != '.'){
		var results = retorno.split("|");		
		if (results[0]){
			if (results.length == 2) {
				eval("document.getElementById('boxFilial').style.display = 'none'");
				EsvaziarSelectFilial();
				dados = results[0].split('-');
				if (dados[0] != '') {
					eval("document.frmAltEndereco.arrayFilial.options[1] = new Option(dados[1],dados[0])");
					document.frmAltEndereco.arrayFilial.selectedIndex = 1;
				}
			}
			else {
				eval("document.getElementById('boxFilial').style.display = 'block'");
				EsvaziarSelectFilial();
				for (x = 0; x < results.length; x++) {
					dados = results[x].split('-');
					if (dados[0] != '') {
						eval("document.frmAltEndereco.arrayFilial.options[x + 1] = new Option(dados[1],dados[0])");
					}
				}
			}
		}
	}
	else{
		eval("document.getElementById('boxFilial').style.display = 'none'");
	}
	return;
}

function EsvaziarSelectFilial() {

	eval("document.frmAltEndereco.arrayFilial.selectedIndex=0");

	eval("tam = document.frmAltEndereco.arrayFilial.length");
	if (tam > 1) {
		for(x=tam-1;x>=0;x--) {
			eval("document.frmAltEndereco.arrayFilial.options[x] = null");
		}
	}
	eval("document.frmAltEndereco.arrayFilial.options[0] = new Option('selecione','')");

}

function preencheTela(){
	var hashLista = stringToHash(document.frmBusca.hashListaPresentes.value);
    //alert(hashLista);
    
	var saldo = new Number();	
	for(var x in hashLista){
        var qtdeEscolhida = document.getElementById('qtd'+x);
		if(document.getElementById('recebe'+x)){											
			if (hashLista[x]['receber'] == 's') {
				document.getElementById('recebe'+x).checked = true;
			}else{
				document.getElementById('recebe'+x).checked = false;
			}
            
			qtdeEscolhida.options[hashLista[x]['qtd']].value = hashLista[x]['qtd'];
            qtdeEscolhida.options[hashLista[x]['qtd']].selected = true;
			saldo = (hashLista[x]['prdSaldo'])*1;
			document.getElementById("sld" + x).value = saldo.toFixed(2);
		}
	}
	calculaSaldoTotal();										
}
									
function receberProduto(campo){
	var codBarra = campo.substr(6);
	var vlrCampo = document.getElementById(campo).checked;
	
    var qtdeEscolhida = document.getElementById('qtd'+codBarra);
    
	//Usuário QUER RECEBER
	if (vlrCampo == true) {
		qtdeEscolhida.disabled = false;
		var qtdFinal = qtdeEscolhida.length;
		qtdeEscolhida.selectedIndex=qtdFinal-1;
		if (qtdeEscolhida.options[qtdeEscolhida.selectedIndex].value == document.getElementById('qtdTotal' + codBarra).value) {
			document.getElementById('sld'+codBarra).value = '0.00';
		}else{
			var precoUnit = document.getElementById('vlrtotal'+codBarra).value/document.getElementById('qtdTotal'+codBarra).value;
			document.getElementById('sld'+codBarra).value = precoUnit*qtdeEscolhida.options[qtdeEscolhida.selectedIndex].value;
		}
        qtdeEscolhida.options[0].disabled = true;
	//Usuário não quer receber
	}else{
		qtdeEscolhida.selectedIndex = 0;
		qtdeEscolhida.disabled= true;
	}
    calculaSaldo(qtdeEscolhida);
}

function calculaSaldo(campo){
    var idCampo = campo.id;
    var qtde    = campo.options[campo.selectedIndex].value;
    
	var codBarra = idCampo.substr(3);
	var vlrFinal;
	var qtdTotal = document.getElementById('qtdTotal'+codBarra).value;
	// Definindo o preço unitário do produto
	var precoUnit =document.getElementById('vlrtotal'+codBarra).value/document.getElementById('qtdTotal'+codBarra).value;
	precoUnit = precoUnit.toFixed(2);
    //alert(precoUnit);
	
	if(qtde == 0){
		document.getElementById('sld'+codBarra).value = document.getElementById('vlrtotal'+codBarra).value;  
	}else if(qtde == 1){
		vlrFinal = document.getElementById('vlrtotal'+codBarra).value - precoUnit;
		 document.getElementById('sld'+codBarra).value = vlrFinal.toFixed(2);
	}else if(qtde == qtdTotal){
		document.getElementById('sld'+codBarra).value = 0;
	}
	else{
		vlrFinal = document.getElementById('vlrtotal'+codBarra).value - (precoUnit*qtde);
		document.getElementById('sld'+codBarra).value = vlrFinal.toFixed(2);
	}
    
	preparaNovoHash(codBarra);
	//calculaSaldoTotal();
}

function preparaNovoHash(codBarra)
{    
	var hashLista = stringToHash(document.frmBusca.hashListaPresentes.value);
	
	if(document.getElementById('recebe'+codBarra).checked == true){
		hashLista[codBarra]['receber'] = 's';
	}else{
		hashLista[codBarra]['receber'] = 'n';
	}	
   
    hashLista[codBarra]['qtd'] = document.getElementById('qtd'+codBarra).options[document.getElementById('qtd'+codBarra).selectedIndex].value;
	hashLista[codBarra]['prdSaldo'] = document.getElementById('sld'+codBarra).value;
    
	hashToString(hashLista,document.frmBusca.hashListaPresentes);
    calculaSaldoTotal();
}
// VERIFICAR POR QUE O valorPrd ESTÁ INDO COMO undefined DEPOIS QUE MARCA QUERO RECEBER...
function stringToHash(strHash)
{
    
	var hashLista = new Array();
	var aux = new Array();
	var codbarra;										
	aux = strHash.split(',');
    for(var x=0;x<aux.length;x++){
        //alert(aux[x]);
		var valores = aux[x].split(':');
		if (codbarra != valores[0]) {
			hashLista[valores[0]] = new Array();
		}
		hashLista[valores[0]][valores[1]] = valores[2];
		codbarra = valores[0];
	}
	return hashLista;
}

function hashToString(hashLista,campoDestino)
{
	// Atualiza a nova string de hash dos produtos
	campoDestino.value = '';
	for(var x in hashLista){
		for(var y in hashLista[x])
		{
 			campoDestino.value += x+":"+y+":"+hashLista[x][y]+","; 
		}
	}
	campoDestino.value = chop(campoDestino.value);
}

function calculaSaldoTotal(){
	//var hashLista = stringToHash(document.frmBusca.hashListaPresentes.value);
	var saldoLista = new Number();
	//for(x in hashLista){
	//	saldoLista += (hashLista[x]['prdSaldo'])*1;
	//}
    //saldo total é soma de todos os valores calculados
	//alert(saldoLista.toFixed(2));
    for(i=0;i<document.formProdutos.elements.length;i++){
		if(document.formProdutos.elements[i].name.indexOf('sld') > -1 && document.formProdutos.elements[i].value > 0){
            saldoLista +=parseFloat(document.formProdutos.elements[i].value)
        }
    }
    
    //alert('SALDO ATUAL ' + saldoLista);
    
	document.frmFechaLista.saldoTotal.value = saldoLista.toFixed(2);
}

function submeterFecharLista(){
	calculaSaldoTotal();	
	//document.frmFechaLista.hashListaFinal.value = document.frmBusca.hashListaPresentes.value;
	
	//document.frmFechaLista.saldoTotalLista.value = document.frmFechaLista.saldoTotal.value;
	document.formProdutos.submit();
	
	//var totalPrd = document.frmFechaLista.totalPrd.value;
	//for(x=0;x<totalPrd;x++){
	//	var recebeChk;
	//	if(document.getElementsByName('recebe')[x].checked){
	//		recebeChk = "s";
	//	}else{
	//		recebeChk = "n";
	//	}
	//	var qtdPrd = eval("document.getElementsByName('qtdePrd')["+x+"].value");
	//	eval("document.frmFechaLista.receber"+x+".value="+recebeChk);
	//	eval("document.frmFechaLista.qtd"+x+".value="+qtdPrd);
	//	if(recebeChk == "s"){
	//		eval("document.frmFechaLista.valorPrd"+x+".value=value=document.getElementsByName('vlrTotal')["+x+"].value/"+qtdPrd);
	//	}
	//	eval("document.frmFechaLista.prdSaldo"+x+".value=document.getElementsByName('prdSaldo')["+x+"].value");
	//}
	//eval("document.frmFechaLista.saldoTotalLista.value=document.frmFechaLista.saldoTotal.value");
	
}

function verificaListaPagina()
{
	var confPrd;
	var totalPrd = document.frmFechaLista.totalPrd.value;
	for(x=0;x<totalPrd;x++){		
		var prod_id = eval("document.frmBusca.buscaprd"+x+".value");
		if(eval("document.getElementById('recebe"+prod_id+"')")){
			var recebeChk;
			if(eval("document.getElementById('recebe"+prod_id+"').checked")){
				recebeChk = "s";
			}else{
				recebeChk = "n";
			}
			var qtdPrd = eval("document.getElementById('qtd"+prod_id+"').value");
			eval("document.frmBusca.buscareceber"+x+".value='"+recebeChk+"'");
			eval("document.frmBusca.buscaqtd"+x+".value="+qtdPrd);
			if(recebeChk == "s"){
				eval("document.frmBusca.buscavalorPrd"+x+".value=value=document.getElementById('vlrtotal"+prod_id+"').value/"+qtdPrd);
			}
			eval("document.frmBusca.buscaprdSaldo"+x+".value=document.getElementById('sld"+prod_id+"').value");
		}
	}	
	calculaSaldoTotal();
	document.frmBusca.buscasaldoTotalLista.value = document.frmFechaLista.saldoTotal.value;

}

function buscaEnderecoComCep(cepOrigem,funcaoPreenchimento){
	cepOrigem = cepOrigem.replace(/[\D]/gm,'');		// deixa apenas os digitos
	if (cepOrigem != ""){
		$.post(	"ajx_lista.pl",
				{
				cep : cepOrigem,
				acao : "cep"
				},
				function retornoAjx(retorno){
					eval(funcaoPreenchimento + "(retorno)");					
				}
		);
	}
}


function preencheEndLoginLista(retorno){
	var dados = retorno.split("|");
	if (dados[0] > 0) {		
		document.formCadastroNovo.PESlogradouro.value = dados[1] + ' ' + dados[2];
		document.formCadastroNovo.PESbairro.value = dados[4];
		document.formCadastroNovo.PEScidade.value = dados[6];
		document.formCadastroNovo.PESuf.value = dados[7];
		document.formCadastroNovo.PEScep.value = dados[12];
	} else {
		alert("CEP inválido");
	}
}


function logoff(){
	document.formMenu.acao.value='logoff';
    document.formMenu.submit();
}

function salvaDataEntrega(data)
{
    //alert(data);
	var diaMesAno = data.split("/");
	$.post(	"ajx_lista.pl",
			{
				acao:"salvaDataEntrega",
				loja:document.formMenu.loja.value,
				lista:document.formMenu.lista_id.value,
				tipo_id:document.formMenu.tipo_id.value,
				dtDia:diaMesAno[0],
				dtMes:diaMesAno[1],
				dtAno:diaMesAno[2]
			},
			function retornoAjx(retorno){
//                 alert(retorno);
				if(retorno == 1){
					document.getElementById('respostaAgendamento').innerHTML = document.getElementById('agendamentoAceito').value;
				}else{
					document.getElementById('respostaAgendamento').innerHTML = document.getElementById('agendamentoRecusado').value;
				}
			}
	);
	return;
}

function fechaCaixa(nomeCaxia,display)
{
	if (display == 0) {
		document.getElementById(nomeCaxia).style.display = 'none';
	}else{
		document.getElementById(nomeCaxia).style.display = 'block';
	}
}

function validaHora(hora){
	//recebe as horas 12:00
    if(hora.indexOf(':') == -1){
		return("Digite a hora no formato válido");
    }
    else{
        var auxHora = hora.split(':');
        auxHora[0] =  parseInt(auxHora[0]);
        auxHora[1] =  parseInt(auxHora[1]);
        if ((auxHora[0] > 24) || (auxHora[1] > 60)) {
            
            return('Hora inválida.');
        }
        
        return ;
    }
    
    //verificar se a hora
    
}
// ################################################################################################
//  nome: validaData
// 	parametros:
// 			valor dia (tipo string ou inteiro)
// 			valor mes (tipo string ou inteiro)
// 			valor ano	(tipo string ou inteiro)
//  retorno:
//  		retorna uma mensagem de erro caso a Data esteja incoerente
//  		retorna 0 (zero) se a Data estiver correta
//  mensagens:
// 		"Dia Incorreto"
// 		"Mês Inexistente"
// 		"Data Inválida"
//  descrição:
//  		função para validação de Data, verifica se: o campo contém caracteres não-numéricos,
// 		se os dias se relacionam corretamente com seu mês, se o mês esta na faixa correta.
// ################################################################################################
function validaData(dia,mes,ano){
	dia = parseInt(dia,10);
	mes = parseInt(mes,10);
	ano = parseInt(ano,10);

	if (!isNaN(dia) && !isNaN(mes) && !isNaN(ano)){		//validação do tipo de caracter
        if((ano < 1900 ) || (ano >2099)){
			return ("O ano é inválido");
        }
        
		if ((mes > 0) && (mes < 13)){		//verifica se o mes esta na faixa correta
			switch (mes){
				case 2:
					if (ano % 4){
						if ((dia < 1) || (dia > 28))
							return ("Dia do Evento Incorreto");
					} else {
						if ((dia < 1) || (dia > 29))
							return ("Dia do Evento Incorreto");
					}
				break;
				case 4:
				case 6:
				case 9:
				case 11:
					if ((dia < 1) || (dia > 30))
						return ("Dia do Evento Incorreto");
				break;
				default:
					if ((dia < 1) || (dia > 31))
						return ("Dia do Evento Incorreto");
				break;
			}
		}else {
			return ("Mês do Evento Inexistente")
		}
	} else {
		return ("Data do Evento Inválida");
	}
	return 0;
}

function EsqueciSenha(email,urlLoja,loja) {

    if (email == "") {
        alert('Preencha o seu e-mail para ser enviada a dica da senha.');
    } else {
        esqsenha = window.open('', 'esqsenha', 'menubar=no,toolbar=no,status=no,directories=no,location=no,scrollbars=0,resizable=no,width=300,height=150,top=1,left=1');
        esqsenha.window.location = urlLoja+'?acao=ESQSENHA&loja=' + loja + '&email=' + email;
    }
}

function EsqueciSenhaLista(email,loja) {

    if (email == "") {
        alert('Preencha o seu e-mail para ser enviada a dica da senha.');
    } else {
        esqsenha = window.open('', 'esqsenha', 'menubar=no,toolbar=no,status=no,directories=no,location=no,scrollbars=0,resizable=no,width=300,height=150,top=1,left=1');
        esqsenha.window.location = 'lista.pl?acao=ESQSENHA&loja=' + loja + '&email=' + email;
    }
}
function exibePagina(pagina, largura, altura){
	if (!largura) largura = 200;
	if (!altura) altura = 200;
	if (!($("#exibePagina").attr("id"))){
		$("body").append('<div id="exibePagina" style="display:none; width:100px; height:100px"></div>');
	}
	$("#exibePagina").load(pagina).ready(function(){
		$("#exibePagina").html("");
		$("#exibePagina").css({width: largura + 'px', height:altura+'px'});
		showObjeto($("#exibePagina"),{corFundo:"black", opacityFundo: "0.4", idObjFechar: "btnFechar"});
	});	
}

function caixalogin(){
	//mostrar a caixa para o login do vendedor
	var display = document.getElementById('caixalogin').style.display;

    if(display == 'block'){
    	document.getElementById('caixalogin').style.display = 'none';
        document.getElementById('vendedorlogado').style.display = 'block';
    }else{
		document.getElementById('caixalogin').style.display = 'block';
        document.getElementById('vendedorlogado').style.display = 'none';
        $("#matrvendedor").focus();
    }
    
}
function loginVendedor(){
	var matricula = document.getElementById('matrvendedor').value;
    var senha = document.getElementById('senhavendedor').value;
	    
    if(!matricula){
		alert('digite a matrícula do vendedor');
    }else if(!senha){
		alert('digite a senha do vendedor');
    }else{
        var parametros = {
		loja:document.getElementById('loja_id').value,
  		matricula:matricula,
		senha:senha,
  		acao:'loginvendedor'
        	};
	chamaProcedimentoRemoto(ajx_HTTPObject, 'ajx_lista.pl', parametros, 'trataLoginVendedor', 'txt');
    }
}

function trataLoginVendedor(dados){
	var array;
    array = dados.split('|');
    if(array[0] == 0){
		document.getElementById('errologin').innerHTML = array[1];
    }else{
        caixalogin();
        $('#vendedorlogado').html("Olá, "+array[1]+" - <a href='javascript:logoutVendedor();'>clique aqui</a> para deslogar.");
    	$(".txtBtVendedor").hide();
	}

}

function GetCookie(n) {
	var i,x,y,AC=document.cookie.split(";");
	for (i=0;i<AC.length;i++) {
		x=AC[i].substr(0,AC[i].indexOf("="));
		y=AC[i].substr(AC[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==n)
		{
			return unescape(y);
		}
	}
}

function ControleRevendedor() {
	var loja = parseInt($("#loja_id").val() - 0);
	if (loja > 0) {
		var vend = '__vendedorlista' + loja;
		vend = GetCookie(vend);
		if ( (vend != undefined) && (vend != '') ) {
			$("#caixalogin").hide();
			$("#vendedorlogado").show();
			$(".txtBtVendedor").hide();
		} else {
			$("#caixalogin").hide();
			$("#vendedorlogado").hide();
			$(".txtBtVendedor").show();
		}
	} else {
		$("#caixalogin").hide();
		$("#vendedorlogado").hide();
		$(".txtBtVendedor").hide();
	}
}

function logoutVendedor(){
	var vendUrl = "http://" + document.domain + "/cgi-bin/ajx_lista.pl";
	var lojaId = parseInt($("#loja_id").val() - 0);
	if (lojaId > 0) {
		$.ajax({
			url: vendUrl,
			type: 'POST',
			data: {
				acao: 'logoutvendedor',
				loja: lojaId
			},
			dataType: 'html',
			success: function(retorno) {
				if (retorno == '1') {
					$("#caixalogin").hide();
					$("#vendedorlogado").hide();
					$(".txtBtVendedor").show();
				} else {
					$('#errologin').html("não foi possível deslogar o vendedor");
				}
			},
			error: function(){
				setTimeout('logoutVendedor()', 2000);
			}
		} );
	}
}

function CriaMenuBaixo () {
	if ( ($("#botMenu")[0]) && ($("#topMenu")[0]) ) {
		$("#botMenu").html( $("#topMenu").html() );
		$("#botMenu li a").removeAttr('id');
		$("#botMenu li:last").remove();
	}
}
