function carregaEndereco(campo){
		document.getElementById('cliente_telefone_entrega_entrega').value = eval('document.getElementById("cliente_telefone_entrega_end'+campo+'").value');
		document.getElementById('cliente_endereco_entrega').value = eval('document.getElementById("cliente_end_end'+campo+'").value');
		document.getElementById('cliente_end_compl_entrega').value = eval('document.getElementById("cliente_complemento_end'+campo+'").value');
		//document.getElementById('cliente_bairro_entrega').value = eval('document.getElementById("cliente_bairro_end'+campo+'").value');	
		//document.getElementById('cliente_cidade_entrega').value = eval('document.getElementById("cliente_cidade_end'+campo+'").value');
		//document.getElementById('cliente_estado_entrega').value = eval('document.getElementById("cliente_estado_end'+campo+'").value');
		document.getElementById('cliente_cep_entrega').value = eval('document.getElementById("cliente_cep_end'+campo+'").value');
		document.getElementById('cliente_ref_entrega').value = eval('document.getElementById("cliente_ref_end'+campo+'").value');
}

function vota(){
	valor_id = 0;
	campoProcurado = document.getElementsByName('id_resp');
	total_respostas = document.getElementById('total_resp').value;
    encontrou = false;
	for (var i=0;i<total_respostas;i++){
  		if (campoProcurado[i].checked == true){
			valor_id = campoProcurado[i].value;
			encontrou = true;
		}
	}
	if (!encontrou){
	  	alert("Selecione uma opção.");
	  	campoProcurado[0].focus();
        return;
	}
	temp = "enquete_resultado.php?id=" + valor_id;
	enviaRequisicao('enqueteBox',temp,'Efetuando votação...');
}

function FormataValor(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = campo.value;
	while (vr.indexOf(".")!=-1){
		   vr=vr.replace(".","");
	}
	while (vr.indexOf(",")!=-1){
		   vr=vr.replace(",","");
	}
	tam = vr.length;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	if (tecla == 8 ){	tam = tam - 1 ; }
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
 			campo.value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
 		if ( (tam >= 6) && (tam <= 8) ){
	 		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
 			campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	}		
}
function enviaEsqueceuSenha(caminho){
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('esqueceuSenha').value))){ 
       	alert("Email inválido.");
        document.getElementById('esqueceuSenha').focus(); 
   	    return;
    } 
    parametro = "?email="+encodeURI(document.getElementById('esqueceuSenha').value);
	enviaRequisicao('enviandoEsqueceuSenha',caminho+parametro,'Validando email...');
}
function formataCep(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = campo.value;
	while (vr.indexOf("-")!=-1){
		   vr=vr.replace("-","");
	}
	tam = vr.length;
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	if (tecla == 8 ){	tam = tam - 1 ; }
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 5 ){ 
 			campo.value = vr ; }
	 	if (tam > 5){
	 		campo.value = vr.substr(0,5) + "-" + vr.substr(5,3); 
	 	}
	}		
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

var ns=(document.layers);
var ie=(document.all);
var w3=(document.getElementById && !ie);
var calunit=ns? "" : "px"

function initEsqueceuSenha(caminho){
    if(!ns && !ie && !w3) return;
    if (ie||w3){
        if (document.getElementById("exibindoEsqueceuSenha").value==0){
           document.getElementById("exibindoEsqueceuSenha").value=1;
      	   document.getElementById("verEsqueceuSenha").style.display="block";
      	   document.getElementById("verEsqueceuSenha").style.visibility="visible";
           enviaRequisicao('verEsqueceuSenha',caminho+'esqueceu_senha.php','Carregando...');
        }else{
       	   document.getElementById('verEsqueceuSenha').innerHTML = '';
           document.getElementById("exibindoEsqueceuSenha").value=0;
      	   document.getElementById("verEsqueceuSenha").style.display="none";
        }
    }else{
        document.getElementById("verEsqueceuSenha").style.visibility ="show";
    }
}


//FUNÇÕES DO DIV FLUTUANTE E OPACIDADE DA PÁGINA
function initAd(){
    varRand = Math.ceil(Math.random()*2);
    frameSelecionado = "document.all.sponsorAdDiv.style";
    tamanho = screen.height;
    if (tamanho<document.body.offsetHeight){
    	tamanho = document.body.offsetHeight;
    }
    document.getElementById("sponsorAdDiv").style.height = tamanho + 'px';
    if(!ns && !ie && !w3) return;
	if(ie)		adDiv=eval(frameSelecionado);
	else if(ns)	adDiv=eval('document.layers["sponsorAdDiv"]');
	else if(w3)	adDiv=eval('document.getElementById("sponsorAdDiv").style');
    if (ie||w3){
    	adDiv.display="block";
        adDiv.visibility="visible";
    }else{
        adDiv.visibility ="show";
    }
}
function closeAd(){
	if (ie||w3)
		adDiv.display="none";
	else
		adDiv.visibility ="hide";
}
//FUNÇÕES DO DIV FLUTUANTE E OPACIDADE DA PÁGINA
function initAdObs(){
    varRand = Math.ceil(Math.random()*2);
    frameSelecionado = "document.all.caixaObs.style";
    tamanho = screen.height;
	posicaoCaixa = parseInt(document.body.offsetWidth/2) - 158;
    if (tamanho<document.body.offsetHeight){
    	tamanho = document.body.offsetHeight;
    }
    document.getElementById("caixaObs").style.height = tamanho + 'px';
    document.getElementById("carregandoObs").style.left = posicaoCaixa + 'px';
    if(!ns && !ie && !w3) return;
	if(ie)		adDiv2=eval(frameSelecionado);
	else if(ns)	adDiv2=eval('document.layers["caixaObs"]');
	else if(w3)	adDiv2=eval('document.getElementById("caixaObs").style');
    if (ie||w3){
   	    document.getElementById("carregandoObs").style.display="block";
   	    document.getElementById("carregandoObs").style.visibility="visible";
    	document.getElementById("caixaObs").style.display="block";
        document.getElementById("caixaObs").style.visibility="visible";
    }else{
        document.layers["caixaObs"].visibility ="show";
        document.getElementById("carregandoObs").style.visibility="show";
    }
}
function closeAdObs(){
	if (ie||w3){
		document.getElementById("carregandoObs").style.display="none";
		document.getElementById("caixaObs").style.display="none";
	}else{
		document.layers["caixaObs"].visibility ="hide";
		document.getElementById("carregandoObs").visibility="hide";
	}
}

function redirecionaCidade(cidade,caminho){
	if (cidade!=0){
		location.href=caminho+"index1.php?cidade="+cidade;
	}
}

function chamaComoUsar(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Como Usar...');	
}
function chamaQuemSomos(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Quem Somos...');	
}
function chamaColuna(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Coluna...');	
}
function chamaNovidades(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando...');	
}

function chamaNovidadesSelecionada(caminho,id){
	enviaRequisicao('meioPagina',caminho+'?id='+id ,'Carregando...');	
}function chamaDicasChef(caminho,id){	enviaRequisicao('meioPagina',caminho+'?id='+id ,'Carregando...');	}
function chamaDicasSaude(caminho,id){	enviaRequisicao('meioPagina',caminho+'?id='+id ,'Carregando...');	}
function buscaDetalhada(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Busca Detalhada...');	
}
function formCadCliente(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Cadastro de Cliente...');	
}
function formCadClienteLogado(caminho){
	enviaRequisicao('cadClienteLogado',caminho,'Carregando Seus Dados...');	
}
function minhasCompras(caminho){
	enviaRequisicao('cadClienteLogado',caminho,'Carregando Minhas Compras...');	
}
function chamaMinhasCompras(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Minhas Compras...');	
}
function chamaParceiro(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Cadastro de Parceiros...');	
}
function chamaPromocao(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Promoção...');	
}
function chamaContato(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Página de Contato...');	
}
function pratosMaisComprados(caminho){
	enviaRequisicao('cadClienteLogado', caminho, "Carregando...");	
}
function chamaFranquia(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando...');	
}
function chamaPromocoes(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando...');
}
function chamaAnuncie(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando...');
}

function contaAcomp(total,ultima){
  opcoesSelecionadas=0;
  for (var i=0;i<document.getElementById("totalAcompanhamentosFree").value;i++) {
  	cb = eval('document.getElementById("acompanhamento_id_free' + i + '").checked');
  	if (cb) {
  		opcoesSelecionadas++;
  		if (opcoesSelecionadas>total){
  			opcoesSelecionadas--;
  			alert('A quantidade máxima de acompanhamentos é de '+total+'.\nInclusão não permitida.')
			eval('document.getElementById("acompanhamento_id_free' + (ultima-1) + '").checked=false');
  		}
	}
  }
  idSelecionados='0';  
  for (var i=0;i<document.getElementById("totalAcompanhamentosFree").value;i++) {
  	cb = eval('document.getElementById("acompanhamento_id_free' + i + '").checked');
  	if (cb) {
  		valor = eval('document.getElementById("acompanhamento_id_free' + i + '").value');
  		idSelecionados = idSelecionados + "," + valor;
  	}
  }
  
}
function contaBebida(total,ultima){
  opcoesSelecionadas=0;
  for (var i=0;i<document.getElementById("totalBebidas").value;i++) {
	cb = eval('document.getElementById("bebida_id' + i + '").checked');
  	if (cb) {
  		opcoesSelecionadas++;
  		if (opcoesSelecionadas>total){
  			opcoesSelecionadas--;
  			alert('A quantidade máxima de bebidas é de '+total+'.\nInclusão não permitida.')
  			idAtual = ultima-1;
  			eval('document.getElementById("bebida_id' + (ultima-1) + '").checked=false');
  		}
	}
  }
  idSelecionados='0';  
  for (var i=0;i<document.getElementById("totalBebidas").value;i++) {
  	cb = eval('document.getElementById("bebida_id' + i + '").checked');
  	if (cb) {
  		valor = eval('document.getElementById("bebida_id' + i + '").value');
  		idSelecionados = idSelecionados + "," + valor;
  	}
  }
}
function adicionaValorPratoDetalhe(campo,valor){
	if (campo.checked){
		valorAdicionais = parseFloat(document.getElementById("valorAdicionais").value) + parseFloat(valor);
	}else{
		valorAdicionais = parseFloat(document.getElementById("valorAdicionais").value) - parseFloat(valor);
	}
	document.getElementById("valorAdicionais").value = valorAdicionais;
	valorAtual = parseFloat(document.getElementById("valorAdicionais").value) + parseFloat(document.getElementById("valorPrato").value);
	document.getElementById('valorTotalPrato').innerHTML =float2moeda(valorAtual)+'&nbsp;&nbsp;';	
}
function adicionaPratoJapones(pratoId, caminho){
	if (document.getElementById("quantAcompPermitida").value != document.getElementById("acomp_quantidade_atual").value){
		alert("Você deve selecionar o equivalente a " + document.getElementById("quantAcompPermitida").value + " itens");
		return;
	}
	//verifica se possui acompanhamento free
	acompIdFreeSelecionados='0';  
	acompIdQuantFreeSelecionados='0';  
	if (document.getElementById("possuiAcompFree").value == 1){
		  quantSelecionada=0;
		  for (var i=1;i<=document.getElementById("totalAcompanhamentosFree").value;i++) {
		  	cb = eval('document.getElementById("acomp_quant_' + i + '").value');
		  	if (cb>0) {
		  		acomp_id = eval('document.getElementById("acomp_id_' + i + '").value');
		  		acomp_id_quant = eval('document.getElementById("acomp_quant_' + i + '").value');
		  		
		  		acompIdFreeSelecionados = acompIdFreeSelecionados + "," + acomp_id;
		  		acompIdQuantFreeSelecionados = acompIdQuantFreeSelecionados + "," + acomp_id_quant;
		  	}
		  }
	}
	//verifica se possui acompanhamento pago
    acompIdPagoSelecionados='0';  
	if (document.getElementById("possuiAcompPago").value == 1){
	  for (var i=0;i<document.getElementById("totalAcompanhamentosPagos").value;i++) {
	  	cb = eval('document.getElementById("acompanhamento_id_pago' + i + '").checked');
		if (cb) {
			valor = eval('document.getElementById("acompanhamento_id_pago' + i + '").value');
	  		acompIdPagoSelecionados = acompIdPagoSelecionados + "," + valor;
	  	}
	  }
	}
	//verifica se possui bebida free
    bebidaIdFreeSelecionados='0'; 
    if (document.getElementById("possuiBebidaFree").value == 1){ 	
		  quantSelecionada=0;		  
		  for (var i=0;i<document.getElementById("totalBebidas").value;i++) {
		  	cb = eval('document.getElementById("bebida_id' + i + '").checked');
		  	if (cb) {
		  		quantSelecionada++;
		  		valor = eval('document.getElementById("bebida_id' + i + '").value');
		  		bebidaIdFreeSelecionados = bebidaIdFreeSelecionados + "," + valor;
		  	}
		  }
		  if (parseInt(quantSelecionada) < parseInt(document.getElementById("quantBebidasPermitida").value)){
		  	alert("Você deve selecionar " + document.getElementById("quantBebidasPermitida").value + " bebidas.");
		  	return;
		  }
	}
	document.getElementById('textoSponsor').innerHTML ='Adicionando';
	initAd();
	parametros = "?prato_id="+pratoId;
	parametros = parametros + "&acompIdFree="+acompIdFreeSelecionados;	
	parametros = parametros + "&acompIdQuantFree="+acompIdQuantFreeSelecionados;	
	parametros = parametros + "&acompIdPago="+acompIdPagoSelecionados;	
	parametros = parametros + "&bebidaIdFree="+bebidaIdFreeSelecionados;	
	parametros = parametros + "&obsPrato="+encodeURI(document.getElementById('obs_prato').value);	
	setTimeout("enviaRequisicao('pedidos','"+caminho+parametros+"','Adicionando produto...')",100);
}

function adicionaPratoAcomp(pratoId, caminho){
	//verifica se possui acompanhamento free
	acompIdFreeSelecionados='0';  
	if (document.getElementById("possuiAcompFree").value == 1){
		  quantSelecionada=0;
		  for (var i=0;i<document.getElementById("totalAcompanhamentosFree").value;i++) {
		  	cb = eval('document.getElementById("acompanhamento_id_free' + i + '").checked');
		  	if (cb) {
		  		quantSelecionada++;
		  		valor = eval('document.getElementById("acompanhamento_id_free' + i + '").value');
		  		acompIdFreeSelecionados = acompIdFreeSelecionados + "," + valor;
		  	}
		  }
		  
		  if (parseInt(quantSelecionada) < parseInt(document.getElementById("quantAcompPermitida").value)){
		  	alert("Você deve selecionar " + document.getElementById("quantAcompPermitida").value + " acompanhamentos inclusos.");
		  	return;
		  }
	}
	//verifica se possui acompanhamento pago
    acompIdPagoSelecionados='0';  
	if (document.getElementById("possuiAcompPago").value == 1){
	  for (var i=0;i<document.getElementById("totalAcompanhamentosPagos").value;i++) {
	  	cb = eval('document.getElementById("acompanhamento_id_pago' + i + '").checked');
		if (cb) {
			valor = eval('document.getElementById("acompanhamento_id_pago' + i + '").value');
	  		acompIdPagoSelecionados = acompIdPagoSelecionados + "," + valor;
	  	}
	  }
	}
	//verifica se possui bebida free
    bebidaIdFreeSelecionados='0'; 
    if (document.getElementById("possuiBebidaFree").value == 1){ 	
		  quantSelecionada=0;		  
		  for (var i=0;i<document.getElementById("totalBebidas").value;i++) {
		  	cb = eval('document.getElementById("bebida_id' + i + '").checked');
		  	if (cb) {
		  		quantSelecionada++;
		  		valor = eval('document.getElementById("bebida_id' + i + '").value');
		  		bebidaIdFreeSelecionados = bebidaIdFreeSelecionados + "," + valor;
		  	}
		  }
		  if (parseInt(quantSelecionada) < parseInt(document.getElementById("quantBebidasPermitida").value)){
		  	alert("Você deve selecionar " + document.getElementById("quantBebidasPermitida").value + " bebidas.");
		  	return;
		  }
	}
	document.getElementById('textoSponsor').innerHTML ='Adicionando';
	initAd();
	parametros = "?prato_id="+pratoId;
	parametros = parametros + "&acompIdFree="+acompIdFreeSelecionados;	
	parametros = parametros + "&acompIdPago="+acompIdPagoSelecionados;	
	parametros = parametros + "&bebidaIdFree="+bebidaIdFreeSelecionados;	
	parametros = parametros + "&obsPrato="+encodeURI(document.getElementById('obs_prato').value);	
	setTimeout("enviaRequisicao('pedidos','"+caminho+parametros+"','Adicionando produto...')",100);
}
function buscaDetalhadaParametros(caminho){
	parametros = "?reset=1";
	if (document.getElementById('pesquisaBusca').value != ''){
		parametros = parametros + "&pesquisa="+document.getElementById('pesquisaBusca').value;	
	}
	if (document.getElementById('statusCardapioBusca').value != ''){
		parametros = parametros + "&statusCardapio="+document.getElementById('statusCardapioBusca').value;	
	}
	if (document.getElementById('categoria_idBusca').value != ''){
		parametros = parametros + "&categoria_id="+document.getElementById('categoria_idBusca').value;	
	}
	if (document.getElementById('loja_idBusca').value != ''){
		parametros = parametros + "&loja_id="+document.getElementById('loja_idBusca').value;	
	}
	if (document.getElementById('precoBusca').value != ''){
		parametros = parametros + "&preco="+document.getElementById('precoBusca').value;	
	}
	enviaRequisicao('meioPagina',caminho+parametros,'Carregando Resultado da Busca ...');	
}
function buscaLoja(valor,caminho){
	if (valor != 0){
		if (document.getElementById('pesquisaCategoriaHome')!=null){
			document.getElementById('pesquisaCategoriaHome').options[0].selected = true;
		}
		if (document.getElementById('pesquisaPalavraHome')!=null){
			document.getElementById('pesquisaPalavraHome').value = '';
		}
		enviaRequisicao('meioPagina',caminho+valor,'Carregando Loja...');
	}
}
function carregaLoja(valor,caminho){
	if (valor != 0){
		enviaRequisicao('meioPagina',caminho+valor,'Carregando Loja...');
	}
}
function buscaParceiros(caminho){
	enviaRequisicao('meioPagina',caminho,'Carregando Lojas...');
}
function buscaRestAberto(caminho){
	enviaRequisicao('meioPagina',caminho,'Pesquisando Lojas Abertas...');
}
function buscaCategoria(valor,caminho){
	if (valor != 0){
		document.getElementById('pesquisaCategoriaHome').options[0].selected = true;
		document.getElementById('pesquisaPalavraHome').value = '';
		enviaRequisicao('meioPagina',caminho+valor,'Carregando Lojas da Categoria...');
	}
}
function buscaCategoriaStatus(valor,categoria_id,procurouParceiro,caminho){
	if (procurouParceiro == 1){
		enviaRequisicao('meioPagina',caminho+'?reset=1&categoria_id='+categoria_id+'&statusLoja='+valor+'&buscaParceiro=1','Carregando...');
	}else{
		enviaRequisicao('meioPagina',caminho+'?reset=1&categoria_id='+categoria_id+'&statusLoja='+valor,'Carregando...');
	}
}

function buscaLojaStatus(valor,cep,caminho){
	enviaRequisicao('meioPagina',caminho+'?reset=1&statusLoja='+valor+'&pesquisa='+cep,'Carregando...');
}


function InfoAdicionais(valor,caminho, caminho2){
	if (document.getElementById('exibindoAreaCobertura').value == 0){
		enviaRequisicao('horarioLoja',caminho+valor,'Carregando...');
		document.getElementById('exibindoAreaCobertura').value = 1;
		document.getElementById('maisHorario').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/mais_rest.gif">';
		document.getElementById('maisArea').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/menos_rest.gif">';
	}else{
		if (document.getElementById('exibindoHorario').value == 1){
			enviaRequisicao('horarioLoja',caminho+valor,'Carregando...');
			document.getElementById('exibindoHorario').value = 0;
			document.getElementById('maisHorario').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/mais_rest.gif">';
			document.getElementById('maisArea').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/menos_rest.gif">';
		}else{
			document.getElementById('horarioLoja').innerHTML = '';
			document.getElementById('exibindoAreaCobertura').value = 0;
			document.getElementById('maisHorario').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/mais_rest.gif">';
			document.getElementById('maisArea').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/mais_rest.gif">';
		}
	}
}
function insereCarrinhoPizza(valor, caminho){
	enviaRequisicao('meioPagina',caminho+"?prato_id="+valor+"&obsPrato=''",'Carregando...')
}
function fecharObs(){
	closeAdObs();
	document.getElementById('obs_prato').value = "";
	document.getElementById("flashPromo").style.display="block";
    document.getElementById("flashPromo").style.visibility="visible";

}
function enviaObs(caminho){
	obsPrato = "&obsPrato="+encodeURI(document.getElementById('obs_prato').value);		
	closeAdObs();
	document.getElementById('obs_prato').value = "";
	if(document.getElementById('flashPromo') != null){			
		document.getElementById("flashPromo").style.display="block";
    	document.getElementById("flashPromo").style.visibility="visible";
	}
	initAd();
	setTimeout("enviaRequisicao('pedidos','"+caminho+"?obsPrato="+obsPrato+"&prato_id="+document.getElementById('obsPratoIdTemp').value+"','Adicionando produto...')",100);	
}
function insereCarrinho(valor,possuiAcomp,caminho,nomePrato,permiteObs){
	if (valor != 0){
		if (!possuiAcomp){
			document.getElementById('textoSponsor').innerHTML ='Adicionando';
			document.getElementById('obsNomePrato').innerHTML = '<b>'+nomePrato+'</b>';
			document.getElementById('obsPratoIdTemp').value=valor;
			if (permiteObs){
				if(document.getElementById('flashPromo') != null){
					document.getElementById('flashPromo').style.display = 'none'; 
				}
				initAdObs();
			}else{
				initAd();
				setTimeout("enviaRequisicao('pedidos','"+caminho+"?obsPrato=&prato_id="+valor+"','Adicionando produto...')",100);	
			}
		}else{
			enviaRequisicao('meioPagina',caminho+"?prato_id="+valor+"&obsPrato=''",'Carregando...');
		}
	}else{
		enviaRequisicao2('pedidos',caminho+'redirCarrinho.php','Carregando...');	
	}
}
function insereBebidaCarrinho(valor,caminho){
	if (valor != 0){
		document.getElementById('textoSponsor').innerHTML ='Adicionando';
		initAd();
		setTimeout("enviaRequisicao('pedidos','"+caminho+valor+"','Adicionando bebida...')",100);
	}else{
		enviaRequisicao('pedidos',caminho+valor,'Adicionando bebida...');	
	}
}
function removerCarrinho(campo,caminho,tipo){
	document.getElementById('textoSponsor').innerHTML ='Removendo';
	initAd();
	destino = caminho+"?remover="+campo+'&tipo='+tipo;
	setTimeout("direciona('"+destino+"')",100);
}
function direciona(destino){
	location.href=destino;
}
function atualizarQuantidade(caminho){
	camposGet = 'atualiza=1';
	for (i=0;i<document.getElementById('quantPratoCarrinho').value;i++){
		campo = "document.getElementById('prato_quant_"+i+"').value";
		valor = eval(campo);
		if (eval(campo)=='1/2'){
			valor = 0.5;
		}
		if (eval(campo)=='1/4'){
			valor = 0.25;
		}
		camposGet = camposGet + "&prato_quant_" + i + "=" + valor;
	}
	for (i=0;i<document.getElementById('quantBebidaCarrinho').value;i++){
		campo = "document.getElementById('bebida_quant_"+i+"').value";
		camposGet = camposGet + "&bebida_quant_" + i + "=" + eval(campo);
	}
	camposGet = camposGet + "&areaId=" + document.getElementById('area_id').value;
	document.getElementById('textoSponsor').innerHTML ='Atualizando';
	initAd();
	destino = caminho+camposGet;
	setTimeout("direciona('"+destino+"')",100);
}
function buscaCategoriaStatusProduto(status,palavra,caminho){
	enviaRequisicao('meioPagina',caminho+'?statusCardapio='+status+'&pesquisa='+palavra,'Carregando...');
}
function buscaProdutoPalavra(caminho){
	if (document.getElementById('pesquisaPalavraHome').value.length >= 3){
		enviaRequisicao('meioPagina',caminho+document.getElementById('pesquisaPalavraHome').value,'Carregando Busca por Palavra...');
		document.getElementById('pesquisaCategoriaHome').options[0].selected = true;
	}else{
		alert("A palavra pesquisada deve ter no mínimo 3 caracteres.");
	}
}
function buscaProdutoPalavraLoja(caminho){
	if (document.getElementById('pesquisaPalavraHome').value.length >= 4){
		enviaRequisicao('meioPagina',caminho+document.getElementById('pesquisaPalavraHome').value,'Carregando Busca por Palavra...');
	}else{
		alert("A palavra pesquisada deve ter no mínimo 4 caracteres.");
	}
}

function tabAutomatico(origem, destino, motivo){
	if(document.getElementById(origem).value.length == motivo){
		document.getElementById(destino).focus();
	}
}

function buscaLojaCep(caminho){
	if (document.getElementById('buscaCep').value.length >= 5){
		var cep = document.getElementById('buscaCep').value + document.getElementById('buscaCepSufixo').value;
		enviaRequisicao('meioPagina',caminho+cep,'Carregando Busca por Cep...');
	}else{
		alert("Informe no mínimo os 5(cinco) primeiros dígitos do CEP.");
	}
}

function buscaHorario(lojaId,caminho,caminho2){
	if (document.getElementById('exibindoHorario').value == 0){
		enviaRequisicao('horarioLoja',caminho+lojaId,'Carregando Horários...');
		document.getElementById('exibindoHorario').value = 1;
		document.getElementById('maisHorario').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/menos_rest.gif">';
		document.getElementById('maisArea').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/mais_rest.gif">';
	}else{
		if (document.getElementById('exibindoAreaCobertura').value == 1){
			enviaRequisicao('horarioLoja',caminho+lojaId,'Carregando Horários...');
			document.getElementById('exibindoAreaCobertura').value = 0;
			document.getElementById('maisHorario').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/menos_rest.gif">';
			document.getElementById('maisArea').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/mais_rest.gif">';
		}else{
			document.getElementById('horarioLoja').innerHTML = '';
			document.getElementById('exibindoHorario').value = 0;
			document.getElementById('maisHorario').innerHTML = '<img style="cursor:pointer" src="' + caminho2 + 'img/mais_rest.gif">';
			document.getElementById('maisArea').innerHTML = '<img style="cursor:pointer"  src="' + caminho2 + 'img/mais_rest.gif">';
		}
	}	
}
function fechaHorario(lojaId,caminho, destino){
	texto = '<img style="cursor:pointer" onclick="buscaHorario(' + lojaId + ',\''+caminho+destino+'\')" src="'+caminho+'img/ver-todos-dias.gif" border="0"></a>';
	document.getElementById('horarioLoja').innerHTML = texto;
}
function buscaCardapio(cardapioId,caminho,prato,bebida){
	if (cardapioId != 0){
		document.getElementById('cardapioCompleto').style.width = '40px';
		if (cardapioId != 9999){
			enviaRequisicao('cardapio',caminho+prato+cardapioId,'Carregando Produtos...');
		}else{
			enviaRequisicao('cardapio',caminho+bebida+document.getElementById('lojaIdCombo').value,'Carregando Bebidas...');
		}
		document.getElementById("colunaNome").style.width = 65;
		document.getElementById('cardapioCompleto').innerHTML ='&nbsp;&nbsp;CARDÁPIO';		
	}
}
function pegaBebidas(lojaId,caminho){
	if (document.getElementById("exibiuBebida").value==0){
		document.getElementById("exibiuBebida").value=1;
		enviaRequisicao('cardapio',caminho+lojaId,'Carregando Bebidas...');
	}else{
		document.getElementById("exibiuBebida").value=0;
		document.getElementById("cardapio").innerHTML = '';
	}
}
function sonumeros(numero){
	//verifica o enter (13), o delete (46), o backspace (8), o end (35), o home (36) e as setas (37,38,39,40)
	if ((numero.keyCode >= 35 && numero.keyCode <= 40) || (numero.keyCode == 46) ||
		(numero.keyCode == 8) || (numero.keyCode == 13) || (numero.keyCode == 9) ||
		(numero.keyCode >= 48 && numero.keyCode <= 57) || (numero.keyCode >= 96 && numero.keyCode <= 105)){
		return true;
	}else{
		return false;
	}
}
function acrescentar(campo,tipo){
	document.getElementById("alterou_quantidades").value=1;
	campoAtual = eval("document.getElementById('"+tipo+"_quant_"+campo+"')");
	campoHidden = eval("document.getElementById('"+tipo+"_quantidade_"+campo+"')");
	valorAtual = campoAtual.value;
	campoAtual.value = parseInt(valorAtual) + 1;
	campoHidden.value = campoAtual.value;
}
function retirar(campo,tipo){
	campoAtual = eval("document.getElementById('"+tipo+"_quant_"+campo+"')");
	campoHidden = eval("document.getElementById('"+tipo+"_quantidade_"+campo+"')");
	valorAtual = campoAtual.value;
	if (parseInt(valorAtual) > 1){
		campoAtual.value = parseInt(valorAtual) - 1;
		campoHidden.value = campoAtual.value;
		document.getElementById("alterou_quantidades").value=1;
	}else{
		alert("Para excluir o item, clique no botão remover.")
	}
}
function acrescentarJapones(campo,tipo){
	campoAtual = eval("document.getElementById('"+tipo+"_quant_"+campo+"')");
	campoHidden = eval("document.getElementById('"+tipo+"_quantidade_"+campo+"')");
	equivalencia = eval("document.getElementById('"+tipo+"_equivalencia_"+campo+"')");
	totalAtual = eval("document.getElementById('"+tipo+"_quantidade_atual').value");
	valorAtual = campoAtual.value;
	
	//pega a equivalencia
	equivalenciaAtual = equivalencia.value*valorAtual;
	equivalenciaFuturo = equivalencia.value*(parseInt(valorAtual)+1);
	
	totalFuturo = parseInt(totalAtual) - parseInt(equivalenciaAtual) + parseInt(equivalenciaFuturo);
	if (parseInt(totalFuturo)<=parseInt(document.getElementById("quantAcompPermitida").value)){
		campoAtual.value = parseInt(valorAtual) + 1;
		campoHidden.value = campoAtual.value;
		eval("document.getElementById('"+tipo+"_quantidade_atual').value=totalFuturo");
	}else{
		alert("Inclusão não permitida.\nA quantidade de itens ultrapassa o limite de opções.");
	}
}
function retirarJapones(campo,tipo){
	campoAtual = eval("document.getElementById('"+tipo+"_quant_"+campo+"')");
	campoHidden = eval("document.getElementById('"+tipo+"_quantidade_"+campo+"')");
	equivalencia = eval("document.getElementById('"+tipo+"_equivalencia_"+campo+"')");
	valorAtual = campoAtual.value;
	if (parseInt(valorAtual) > 0){
		eval("document.getElementById('"+tipo+"_quantidade_atual').value=document.getElementById('"+tipo+"_quantidade_atual').value-parseInt(equivalencia.value)");
		campoAtual.value = parseInt(valorAtual) - 1;
		campoHidden.value = campoAtual.value;
	}else{
		alert("Não é possível diminuir além deste valor.")
	}
}

function float2moeda(num) {

   x = 0;

   if(num<0) {
      num = Math.abs(num);
      x = 1;
   }   if(isNaN(num)) num = "0";
      cents = Math.floor((num*100+0.5)%100);

   num = Math.floor((num*100+0.5)/100).toString();

   if(cents < 10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
         num = num.substring(0,num.length-(4*i+3))+'.'
               +num.substring(num.length-(4*i+3));   ret = num + ',' + cents;   if (x == 1) ret = ' - ' + ret;return ret;
}

function setarCamposSubmeterParceiros(){
	campos = "parceiro_razao="+encodeURI(document.getElementById('parceiro_razao').value);
	campos +="&parceiro_nome="+encodeURI(document.getElementById('parceiro_nome').value);
	campos +="&parceiro_cnpj="+encodeURI(document.getElementById('parceiro_cnpj').value);
	campos +="&parceiro_email="+encodeURI(document.getElementById('parceiro_email').value);
	campos +="&parceiro_endereco="+encodeURI(document.getElementById('parceiro_endereco').value);
	campos +="&parceiro_end_compl="+encodeURI(document.getElementById('parceiro_end_compl').value);
	campos +="&parceiro_bairro="+encodeURI(document.getElementById('parceiro_bairro').value);
	campos +="&parceiro_cidade="+encodeURI(document.getElementById('parceiro_cidade').value);
	campos +="&parceiro_estado="+encodeURI(document.getElementById('parceiro_estado').value);
	campos +="&parceiro_cep="+encodeURI(document.getElementById('parceiro_cep').value);
	campos +="&parceiro_telefone="+encodeURI(document.getElementById('parceiro_telefone').value);
	campos +="&parceiro_celular="+encodeURI(document.getElementById('parceiro_celular').value);
}

function submeterParceiros(caminho,origem){
    if(tiraEspaco(document.getElementById('parceiro_razao').value) == ""){
		alert("Razão Social inválida.");
		document.getElementById('parceiro_razao').focus();
		return;
    }
    if(tiraEspaco(document.getElementById('parceiro_nome').value) == ""){
		alert("Nome inválido.");
		document.getElementById('parceiro_nome').focus();
		return;
    }
    if(tiraEspaco(document.getElementById('parceiro_nome').value) == ""){
		alert("CNPJ inválido.");
		document.getElementById('parceiro_nome').focus();
		return;
    }
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('parceiro_email').value))){ 
       	alert("Email inválido.");
        document.getElementById('parceiro_email').focus(); 
   	    return;
    } 
	if(tiraEspaco(document.getElementById('parceiro_endereco').value) == ""){	
		alert("Endereço inválido.");
		document.getElementById('parceiro_endereco').focus();
		return;
	}	
	if(tiraEspaco(document.getElementById('parceiro_bairro').value) == ""){	
		alert("Bairro inválido.");
		document.getElementById('parceiro_bairro').focus();
		return;
	}
	if(tiraEspaco(document.getElementById('parceiro_cidade').value) == ""){	
		alert("Cidade inválido.");
		document.getElementById('parceiro_cidade').focus();
		return;
	}
	if(tiraEspaco(document.getElementById('parceiro_estado').value) == 0){	
		alert("Estado inválido.");
		document.getElementById('parceiro_estado').focus();
		return;
	}
	if(tiraEspaco(document.getElementById('parceiro_cep').value) == ""){	
		alert("CEP inválido.");
		document.getElementById('parceiro_cep').focus();
		return;
	}
	if(tiraEspaco(document.getElementById('parceiro_telefone').value) == ""){	
		alert("Telefone inválido.");
		document.getElementById('parceiro_telefone').focus();
		return;
	}
	if(tiraEspaco(document.getElementById('parceiro_celular').value) == ""){	
		alert("Celular inválido.");
		document.getElementById('parceiro_celular').focus();
		return;
	}
	document.getElementById('textoSponsor').innerHTML ='Enviando E-mail';
	initAd();
	setarCamposSubmeterParceiros();
	enviarForm(caminho,campos,'enviarParceiros','',caminho);
}

function setarCamposSubmeterContato(){
	campos = "contato_nome="+encodeURI(document.getElementById('contato_nome').value);
	campos +="&contato_email="+encodeURI(document.getElementById('contato_email').value);
	campos +="&contato_telefone="+encodeURI(document.getElementById('contato_telefone').value);
	campos +="&contato_mensagem="+encodeURI(document.getElementById('contato_mensagem').value);
}

function submeterContato(caminho,origem){
    if(tiraEspaco(document.getElementById('contato_nome').value) == ""){
		alert("Nome inválido.");
		document.getElementById('contato_nome').focus();
		return;
    }
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('contato_email').value))){ 
       	alert("Email inválido.");
        document.getElementById('contato_email').focus(); 
   	    return;
    }
	if(tiraEspaco(document.getElementById('contato_mensagem').value) == ""){
		alert("Mensagem inválida.");
		document.getElementById('contato_mensagem').focus();
		return;
	}
    
	document.getElementById('textoSponsor').innerHTML ='Enviando E-mail';
	initAd();
	setarCamposSubmeterContato();
	enviarForm(caminho,campos,'enviarContato','',caminho);
}


function setarCamposLogin(){
	campos = "email="+encodeURI(document.getElementById('loginEmail').value);
	campos +="&password="+encodeURI(document.getElementById('loginPass').value);
	campos +="&origem=1";	
}

function logar(caminho,origem){
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('loginEmail').value))){ 
       	alert("Email inválido.");
        document.getElementById('loginEmail').focus();
   	    return;
    } 
	if(tiraEspaco(document.getElementById('loginPass').value) == ""){	
		alert("Senha inválida.");
		document.getElementById('loginPass').focus();
		return;
	}	
	document.getElementById('textoSponsor').innerHTML ='Logando';
	initAd();
	setarCamposLogin();
	enviarForm(caminho+'login.php',campos,'idLogar','',caminho);
}
function setarCamposLoginCarrinho(){
	campos = "email="+encodeURI(document.getElementById('loginEmailCarrinho').value);
	campos +="&password="+encodeURI(document.getElementById('loginPassCarrinho').value);
	campos +="&origem=2";
}

function logarSistemaCarrinho(caminho,origem,caminhoLoja){
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('loginEmailCarrinho').value))){ 
       	alert("Email inválido.");
        logarCarrinho.email.focus(); 
   	    return;
    } 
	if(tiraEspaco(document.getElementById('loginPassCarrinho').value) == ""){	
		alert("Senha inválida.");
		logarCarrinho.senha.focus();
		return;
	}	
	document.getElementById('textoSponsor').innerHTML ='Logando';
	initAd();
	setarCamposLoginCarrinho();
	
	enviarForm(caminho+caminhoLoja+'login.php',campos,'idLogar','',caminho);
}
function avancaCarrinho(caminho,destino){
	if (document.getElementById('alterou_quantidades')!=null){
		if (document.getElementById('alterou_quantidades').value == 1){
			alert("A quantidade dos itens foi alterada, clique no botão Atualizar para validar a alteração.");
			return;
		}
	}
	if (document.getElementById('area_id')!=null){
		if (document.getElementById('area_id').value == 0){
			alert("Selecione o Local de Entrega antes de avançar.");
			return;
		}
	}
	enviaRequisicao('carrinhoEtapas',caminho+destino,'Carregando ...');		
}
function ativaTroco(){
	document.getElementById('troco').disabled = false;
}
function desativaTroco(){
	document.getElementById('troco').value = '';
	document.getElementById('troco').disabled = true;
}
function redirecionaCartao(caminhoProcessamento,caminhoAguardaProcessamento,caminhoVerificaProcessamento,tipo){
	caminhoVerificaProcessamentoTemp = caminhoVerificaProcessamento;
	janelaTemp=window.open(caminhoProcessamento+'?tipo='+tipo,'vpos','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=auto,resizable=yes,copyhistory=no,width=320,height=260');
	janelaTemp.moveTo(1,1);
	enviaRequisicao('carrinhoEtapas',caminhoAguardaProcessamento+'?card='+tipo,'Avançando...');
}
function ativaProcessamentoCartao(){
	ourInterval = setInterval("verificaProcessamentoAtual()",5000);
}
function verificaProcessamentoAtual(){
	enviaRequisicao('verificaProcessamento',caminhoVerificaProcessamentoTemp);
}
function redirecionaPaginaFinalCartao(caminho){
	enviaRequisicao('carrinhoEtapas',caminho);
}

function finalizaCompra(caminho,caminhoProcessamento,caminhoAguardaProcessamento,caminhoVerificaProcessamento,caminhoFinalizaCartao,valorTotal){
	if (document.getElementById('abriuDadosCartao').value==1){
		alert("Sua compra está sendo realizada com Cartão de Crédito.\nCancele a janela de dados do cartão para prosseguir.");
		return;
	}
	formaSelecionada = 0;
	caminhoFinalizaCartaoAtual = caminhoFinalizaCartao;
	if (document.getElementById('totalTiquete').value > 0){
	    for(i=1;i<=document.getElementById('totalTiquete').value;i++) {  
		  	cb = eval('document.getElementById("tiquete' + i + '")');
		  	if (cb.checked) {
            	formaSelecionada =cb.value;
	        }
	    }
	}
	if (formaSelecionada!=0){
		enviaRequisicao('carrinhoEtapas',caminho+'?troco=0&cheque=0&tiquete='+formaSelecionada,'Finalizando ...');				
		return;		
	}
	
	if (formaSelecionada==0){
		var todasOpcaoPag = document.getElementsByTagName('input');
	    for(i=0;i<todasOpcaoPag.length;i++) {  
	        if(todasOpcaoPag[i].type=='radio' && todasOpcaoPag[i].id != 'pagCheque'&& todasOpcaoPag[i].id != 'pagDinheiro'){
	            if (todasOpcaoPag[i].checked){
	            	formaSelecionada =todasOpcaoPag[i].value;
	            }
	        }
	    }
	}
	//se a formaSelecionada é algum número diferente de zero é sinal q ele selecionou um cartao do tipo wireless, então
	//não existe a necessidade de conexão segura pois os dados serão colhidos no momento da entrega com maquineta wireless
	if (formaSelecionada!=0){
		//redirecionaCartao(caminhoProcessamento,caminhoAguardaProcessamento,caminhoVerificaProcessamento,formaSelecionada);
		enviaRequisicao('carrinhoEtapas',caminho+'?troco=0&cheque=0&cartao=1&wireless=1&id='+document.getElementById('cartaoIdHidden').value,'Finalizando ...');
		return;
	}
	//se o pagamento é com dinheiro
	if (document.getElementById('pagDinheiro').checked){
		trocoValor = document.getElementById('troco').value;
		trocoValor = trocoValor.replace(",",".");
		if (trocoValor!=''){
			if (parseFloat(trocoValor) < parseFloat(valorTotal)){
				alert('O valor para o troco deve ser maior que o valor da compra.');
				return;
			}
		}else{
			trocoValor = 0;
			if(!confirm('Você não indicou o valor para troco. está correto?\nSe quiser informar o valor para troco, clique em "cancelar".')){
				return;
			}
		}
		enviaRequisicao('carrinhoEtapas',caminho+'?cheque=0&troco='+trocoValor,'Finalizando ...');		
		return;
	}
	if (document.getElementById('pagCheque')!=null){
		if (document.getElementById('pagCheque').checked){
			enviaRequisicao('carrinhoEtapas',caminho+'?troco=0&cheque=1','Finalizando ...');				
			return;
		}
	}
	alert('Selecione uma das opções disponíveis de pagamento.');
}
function verDetalhePedido(caminho,origem,divName,pedidoId){
	abreFecha = divName + 'Status';
	imagem = divName + 'imagem';
	abreFechaValor = document.getElementById(abreFecha).value;
	if (abreFechaValor == 0){
		enviaRequisicao(divName,caminho+'?pedido_id='+pedidoId,'Carregando ...');			
		document.getElementById(abreFecha).value =1;
		document.getElementById(imagem).innerHTML ='<img border=0 src="'+origem+'img/menos_bebidas.gif">';
	}else{
		document.getElementById(abreFecha).value =0;
		document.getElementById(divName).innerHTML ='';
		document.getElementById(imagem).innerHTML ='<img border=0 src="'+origem+'img/mais_bebidas.gif">';		
	}
}
function buscaCardapioCompleto(caminho,lojaId){
	document.getElementById("colunaNome").style.width = 133;
	document.getElementById("comboCategorias").options[0].selected = true;
	document.getElementById('cardapioCompleto').style.width = '120px';
	document.getElementById('cardapioCompleto').innerHTML ='&nbsp;&nbsp;CARDÁPIO COMPLETO';
	enviaRequisicao('cardapio',caminho+'?reset=1&loja_id='+lojaId,'Carregando...');
	
}
function textCounter(field, countfield, maxlimit) {
	campo = eval('document.getElementById("'+field+'")') ;
	tamCampo = eval('document.getElementById("'+countfield+'")') ;
	if (campo.value.length > maxlimit) 
		campo.value = campo.value.substring(0, maxlimit);
	else 
		tamCampo.value = maxlimit - campo.value.length;
}


// Indica site
function indicaSite(){
	// Esconde o Banner
	if(document.getElementById('flashPromo') != null){
		document.getElementById('flashPromo').style.display = 'none'; 
	}
	
	varRand = Math.ceil(Math.random()*2);
	frameSelecionado = 'document.all.boxIndicaSite.style';
	tamanho = screen.height;
	posicaoCaixa = parseInt(document.body.offsetWidth/2) - 158;
	
	if(tamanho < document.body.offsetHeight){
		tamanho = document.body.offsetHeight;
	}
	
	document.getElementById('boxIndicaSite').style.height = tamanho + 'px';
	document.getElementById('carregandoIndicaSite').style.left = posicaoCaixa + 'px';
	
	if(!ns && !ie && !w3){
		return;
	}
	
	if(ie){
		adDiv2 = eval(frameSelecionado);
	}else if(ns){
		adDiv2 = eval('document.layers["boxIndicaSite"]');
	}else if(w3){
		adDiv2 = eval('document.getElementById("boxIndicaSite").style');
	}
	
	if(ie || w3){
		document.getElementById('carregandoIndicaSite').style.display = 'block';
		document.getElementById('carregandoIndicaSite').style.visibility = 'visible';
		document.getElementById('boxIndicaSite').style.display = 'block';
		document.getElementById('boxIndicaSite').style.visibility = 'visible';
	}else{
		document.layers['boxIndicaSite'].visibility = 'hide';
		document.getElementById('carregandoIndicaSite').style.visibility = 'show';
	}
}

function fecharIndicaSite(){
	if(ie || w3){
		document.getElementById('carregandoIndicaSite').style.display = 'none';
		document.getElementById('boxIndicaSite').style.display = 'none';
	}else{
		document.layers['boxIndicaSite'].visibility = 'hide';
		document.getElementById('carregandoIndicaSite').visibility = 'hide';
	}
	
	document.getElementById('flashPromo').style.display = 'block';
	document.getElementById('flashPromo').style.visibility = 'visible';
}

function getKey(event) {
    return event?(event.keyCode?event.keyCode:(event.which?event.which:event.charCode)):null;
}

function enviaIndicaSite(caminho){
   if(tiraEspaco(document.getElementById('seuNome').value) == ''){
   	alert("Digite seu nome.");
   	document.getElementById('seuNome').focus();
   	return;
   }
   
   if(tiraEspaco(document.getElementById('seuNome').value).length < 4){
   	alert("Digite um nome com mais de 3 caracteres.");
   	document.getElementById('seuNome').focus();
   	return;
   }
	if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('seuEmail').value))){ 
   	alert("Seu e-mail é inválido.");
      document.getElementById('seuEmail').focus(); 
   	return;
   } 

   if(tiraEspaco(document.getElementById('nomeAmigo1').value) == ''){
   	alert("Digite o nome do seu amigo!");
   	document.getElementById('nomeAmigo1').focus();
   	return;
  	}
  	if(tiraEspaco(document.getElementById('nomeAmigo1').value).length < 4){
   	alert("Digite um nome com mais de 3 caracteres.");
   	document.getElementById('nomeAmigo1').focus();
   	return;
   }
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('emailAmigo1').value))){ 
   	alert("O e-mail do seu amigo é inválido.");
      document.getElementById('emailAmigo1').focus(); 
   	return;
   } 
	
   if((tiraEspaco(document.getElementById('nomeAmigo2').value) != '') || (tiraEspaco(document.getElementById('emailAmigo2').value) != '')){
   	if(tiraEspaco(document.getElementById('nomeAmigo2').value) == ''){
   		alert("Digite o nome do seu segundo amigo!");
   		document.getElementById('nomeAmigo2').focus();
   		return;
  		}
  		if(tiraEspaco(document.getElementById('nomeAmigo2').value).length < 4){
	   	alert("Digite um nome com mais de 3 caracteres.");
	   	document.getElementById('nomeAmigo2').focus();
	   	return;
	   }
   	if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('emailAmigo2').value))){ 
	   	alert("O e-mail do seu segundo amigo é inválido.");
	      document.getElementById('emailAmigo2').focus(); 
	   	return;
   	} 
	}
	
	if((tiraEspaco(document.getElementById('nomeAmigo3').value) != '') || (tiraEspaco(document.getElementById('emailAmigo3').value) != '')){
   	if(tiraEspaco(document.getElementById('nomeAmigo3').value) == ''){
   		alert("Digite o nome do seu terceiro amigo!");
   		document.getElementById('nomeAmigo3').focus();
   		return;
  		}
  		if(tiraEspaco(document.getElementById('nomeAmigo3').value).length < 4){
	   	alert("Digite um nome com mais de 3 caracteres.");
	   	document.getElementById('nomeAmigo3').focus();
	   	return;
	   }
   	if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('emailAmigo3').value))){ 
	   	alert("O e-mail do seu terceiro amigo é inválido.");
	      document.getElementById('emailAmigo3').focus(); 
	   	return;
   	} 
	}
	
   parametro = "?seuNome="+encodeURI(document.getElementById('seuNome').value)+"&seuEmail="+encodeURI(document.getElementById('seuEmail').value)+"&nomeAmigo1="+encodeURI(document.getElementById('nomeAmigo1').value)+"&emailAmigo1="+encodeURI(document.getElementById('emailAmigo1').value)+"&nomeAmigo2="+encodeURI(document.getElementById('nomeAmigo2').value)+"&emailAmigo2="+encodeURI(document.getElementById('emailAmigo2').value)+"&nomeAmigo3="+encodeURI(document.getElementById('nomeAmigo3').value)+"&emailAmigo3="+encodeURI(document.getElementById('emailAmigo3').value);
  
	enviaRequisicao('enviandoIndicaSite',caminho+parametro,'Aguarde...');
} 

function clearBuscaInternaLoja(){
	var field = document.getElementById("buscaInternaLoja");
	if(field.value == "Busca prato na loja"){
		field.value = "";		
	}
}
function showBuscaInternaLoja(){
	var field = document.getElementById("buscaInternaLoja");
	if(field.value == ""){
		field.value = "Busca prato na loja";
	}
}

function buscaCardapioLoja(caminho, loja_id){
	var field = document.getElementById('buscaInternaLoja');
	var cardapio_id = document.getElementById("comboCategorias").value;
	if (tiraEspaco(field.value).length >= 3){
		enviaRequisicao('cardapio',caminho+'?reset=1&loja_id='+loja_id+'&cardapio_id='+cardapio_id+'&pesquisa='+field.value,'Procurando Prato...');
	}else{
		alert("A palavra pesquisada deve ter no mínimo 3 caracteres.");
	}
}
function initAdCartao(){
	document.getElementById("abriuDadosCartao").value=1;
    varRand = Math.ceil(Math.random()*2);
    frameSelecionado = "document.all.caixaCartao.style";
    tamanho = screen.height;
	posicaoCaixa = parseInt(document.body.offsetWidth/2) - 158;
    if (tamanho<document.body.offsetHeight){
    	tamanho = document.body.offsetHeight;
    }
    document.getElementById("caixaCartao").style.height = tamanho + 'px';
    document.getElementById("carregandoCartao").style.left = posicaoCaixa + 'px';
    if(!ns && !ie && !w3) return;
	if(ie)		adDiv2=eval(frameSelecionado);
	else if(ns)	adDiv2=eval('document.layers["caixaCartao"]');
	else if(w3)	adDiv2=eval('document.getElementById("caixaCartao").style');
    if (ie||w3){
   	    document.getElementById("carregandoCartao").style.display="block";
   	    document.getElementById("carregandoCartao").style.visibility="visible";
    	document.getElementById("caixaCartao").style.display="block";
        document.getElementById("caixaCartao").style.visibility="visible";
   	    document.getElementById("conexaoSegura").style.display="block";
   	    document.getElementById("conexaoSegura").style.visibility="visible";
    }else{
        document.layers["caixaCartao"].visibility ="show";
        document.layers["conexaoSegura"].visibility ="show";
        document.getElementById("carregandoCartao").style.visibility="show";
        document.getElementById("conexaoSegura").style.visibility="show";
    }
    intervalo = setInterval("chamaFormDadosCartao()",7000);
}
function chamaFormDadosCartao(){
	clearInterval(intervalo);
	if (ie||w3){
		document.getElementById("conexaoSegura").style.display="none";
	}else{
		document.layers["conexaoSegura"].visibility ="hide";
		document.getElementById("conexaoSegura").visibility="hide";
	}
	if (ie||w3){
   	    document.getElementById("formDadosCartao").style.display="block";
   	    document.getElementById("formDadosCartao").style.visibility="visible";
    }else{
        document.layers["formDadosCartao"].visibility ="show";
        document.getElementById("formDadosCartao").style.visibility="show";
    }
}
function closeAdCartao(){
	if (ie||w3){
		document.getElementById("carregandoCartao").style.display="none";
		document.getElementById("caixaCartao").style.display="none";
		document.getElementById("conexaoSegura").style.display="none";
		document.getElementById("formDadosCartao").style.display="none";
	}else{
		document.layers["caixaCartao"].visibility ="hide";
		document.getElementById("carregandoCartao").visibility="hide";
		document.getElementById("conexaoSegura").visibility="hide";
		document.getElementById("formDadosCartao").visibility="hide";
	}
}
function chamaCartao(valor,campo,caminho,wireless){
	desativaTroco();
	if (wireless==0){
		document.getElementById("wirelessHidden").value=0;
		document.getElementById("cartaoIdHidden").value='';
		cartaoSelecionado = valor;
		inicio = '<img src="'+caminho+'img/setinha.gif" style="margin-bottom:3px" width="15" height="15" align="absmiddle" />&nbsp;';
		if (valor==1){
			imagem = 'master-cod.jpg'
			fim = 'MASTERCARD';
		}
		if (valor==2){
			fim = 'VISA';
			imagem= 'visa-cod.jpg';
		}
		if (valor==3){
			fim = 'AMERICAN EXPRESS';
			imagem = 'amex-cod.jpg';
		}
		if (valor==4){
			fim = 'HIPERCARD';
			imagem = 'hiper-cod.jpg';
		}
		if (valor==5){
			fim = 'DINERS CLUB';
			imagem = 'diners-cod.jpg';
		}
		document.getElementById("nomeCartaoExtenso").innerHTML = inicio+fim;
		document.getElementById("imagemCartao").innerHTML = '<img src="'+caminho+'img/'+imagem+'" width="200" height="179" hspace="13" />';
		campoSelecionado = campo;
		initAdCartao();
	}else{
		alert("Os dados do cartão serão coletados na entrega com a maquineta da operadora.\nClique em \"Concluir a Compra\" para efetivar sua compra.");
		document.getElementById("wirelessHidden").value=1;
		document.getElementById("cartaoIdHidden").value=valor;
	}
}
function finalizaCompraCartao(caminho){
	clearInterval(newInterval);
	closeAdCartao();
	enviaRequisicao('carrinhoEtapas',caminho+'?troco=0&cheque=0&cartao=1','Finalizando ...');	
}
function enviaDadosCartao(numero,caminho,mes,ano){
	if (parseFloat(document.getElementById('ano_validade').value)==parseFloat(ano)){
		if (parseFloat(document.getElementById('mes_validade').value)<parseFloat(mes)){
			alert("Data de Validade inválida.");
			return;			
		}
	}
	if(tiraEspaco(document.getElementById('nomeCartao').value) == ''){
		alert("Nome inválido.");
		document.getElementById('nomeCartao').focus();
		return;
	}

	if(cartaoSelecionado == 4){ // cartao Hiper
		if(numero.length != 13){
			alert("Cartão inválido.");
			document.getElementById('numeroCartao').focus();
			return;
		}
	}else {
		if (cartaoSelecionado>4){
			if (!isCreditCard(numero)){
				alert("Cartão inválido.");
				document.getElementById('numeroCartao').focus();
				return;
			}
		}else{
			if (!isValidCreditCardNumber(numero,cartaoSelecionado)){
				alert("Cartão inválido.");
				return;
			}
		}
	}
	if(document.getElementById('codigoCartao').value.length < 3){
		alert("Código de Segurança inválido.");
		document.getElementById('codigoCartao').focus();
		return;
	}
	if ((document.getElementById('mes_validade').value == 0)||(document.getElementById('ano_validade').value == 0)){
		alert("Data de Validade incorreta.");
		document.getElementById('mes_validade').focus();
		return;
	}
	mensagem = '<br/><br/><img src="http://www.centraldodelivery.com.br/img/loading_bm.gif"><br/>Enviando dados do cartão...';
	document.getElementById("conexaoSegura").innerHTML = mensagem;
	if (ie||w3){
		document.getElementById("formDadosCartao").style.display="none";
   	    document.getElementById("conexaoSegura").style.display="block";
   	    document.getElementById("conexaoSegura").style.visibility="visible";
	}else{
		document.layers["formDadosCartao"].visibility ="hide";
		document.getElementById("formDadosCartao").visibility="hide";
        document.getElementById("conexaoSegura").style.visibility="show";
	}
	document.getElementById('enviandoDados').value=1;
	document.getElementById('botaoCancelarCartao').innerHTML='';
	setarCamposCartao();
	enviaRequisicao('conexaoSegura',caminho+'ler_pagina_remota_post.php?'+campos,'');
	
}
function cancelaDadosCartao(){
	if(document.getElementById('enviandoDados').value==1){
		alert("Sua transação está em andamento.\nCancelamento não permitido.");
	}else{
		document.getElementById("abriuDadosCartao").value=0;
		document.getElementById('nomeCartao').value = '';		
		document.getElementById('numeroCartao').value = '';		
		document.getElementById('codigoCartao').value = '';		
		document.getElementById('mes_validade').options[0].selected=true; 
		document.getElementById('ano_validade').options[0].selected=true; 
		document.getElementById(campoSelecionado).checked=false; 
		closeAdCartao();
	}
}
function setarCamposCartao(){
	campos = "nomeCartao="+encodeURI(document.getElementById('nomeCartao').value);
	campos += "&numeroCartao="+encodeURI(document.getElementById('numeroCartao').value);
	campos += "&codigoCartao="+encodeURI(document.getElementById('codigoCartao').value);
	campos += "&mes_validade="+encodeURI(document.getElementById('mes_validade').value);
	campos += "&ano_validade="+encodeURI(document.getElementById('ano_validade').value);
	campos += "&cartaoId="+encodeURI(document.getElementById('cartaoId').value);
	campos += "&cartaoTipo="+cartaoSelecionado;
}
function isCreditCard(st) {
	if (st.length > 19)
		return false;

	sum = 0; mul = 1; l = st.length;
	for (i = 0; i < l; i++) {
		digit = st.substring(l-i-1,l-i);
		tproduct = parseInt(digit ,10)*mul;
		if (tproduct >= 10)
			sum += (tproduct % 10) + 1;
		else
			sum += tproduct;
		if (mul == 1)
			mul++;
		else
			mul--;
	}
	if ((sum % 10) == 0)
		return true;
	else
		return false;
}
function isValidCreditCardNumber(cardNumber, cardType){
    var isValid = false;
    var ccCheckRegExp = /[^\d ]/;
    isValid = !ccCheckRegExp.test(cardNumber);
    if (isValid){
        var cardNumbersOnly = cardNumber.replace(/ /g,"");
        var cardNumberLength = cardNumbersOnly.length;
        var lengthIsValid = false;
        var prefixIsValid = false;
        var prefixRegExp;      
	    switch(cardType){
	        case 1:
	        	//marter
	            lengthIsValid = (cardNumberLength == 16);
	            prefixRegExp = /^5[1-5]/;
	        break;
	        case 2:
	        	//visa
	            lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
	            prefixRegExp = /^4/;
	        break;
	        case 3:
	        	//amex
	            lengthIsValid = (cardNumberLength == 15);
	            prefixRegExp = /^3(4|7)/;
	        break;
	        default:
	            prefixRegExp = /^$/;
	            alert("Card type not found");
    }
    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
    }
    if (isValid){
        var numberProduct;
        var numberProductDigitIndex;
        var checkSumTotal = 0;
        for (digitCounter = cardNumberLength - 1; digitCounter >= 0; digitCounter--){
            checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
            digitCounter--;
            numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
            for (var productDigitCounter = 0; productDigitCounter < numberProduct.length; productDigitCounter++){
                checkSumTotal += parseInt(numberProduct.charAt(productDigitCounter));
            }
        }
        isValid = (checkSumTotal % 10 == 0);
    }
    return isValid;
}

function setarCamposSubmeterFranquia(){
	campos = "franquia_nome="+encodeURI(document.getElementById('franquia_nome').value);
	campos +="&franquia_email="+encodeURI(document.getElementById('franquia_email').value);
	campos +="&franquia_profissao="+encodeURI(document.getElementById('franquia_profissao').value);
	campos +="&franquia_endereco="+encodeURI(document.getElementById('franquia_endereco').value);
	campos +="&franquia_cidade="+encodeURI(document.getElementById('franquia_cidade').value);
	campos +="&franquia_estado="+encodeURI(document.getElementById('franquia_estado').value);
	campos +="&franquia_cep="+encodeURI(document.getElementById('franquia_cep').value);
	campos +="&franquia_telefone="+encodeURI(document.getElementById('franquia_telefone').value);
	campos +="&franquia_celular="+encodeURI(document.getElementById('franquia_celular').value);
	campos +="&franquia_regiao="+encodeURI(document.getElementById('franquia_regiao').value);
	campos +="&franquia_comentarios="+encodeURI(document.getElementById('franquia_comentarios').value);
	campos +="&franquia_sugestoes="+encodeURI(document.getElementById('franquia_sugestoes').value);
}

function submeterFranquia(caminho,origem){
    if(tiraEspaco(document.getElementById('franquia_nome').value) == ""){
		alert("Nome inválido.");
		document.getElementById('franquia_nome').focus();
		return;
    }
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('franquia_email').value))){ 
       	alert("Email inválido.");
        document.getElementById('franquia_email').focus(); 
   	    return;
    }
    if(tiraEspaco(document.getElementById('franquia_regiao').value) == ""){
    	alert("Região de Interesse inválido.");
    	document.getElementById('franquia_regiao').focus();
    	return;
    }
    
	document.getElementById('textoSponsor').innerHTML ='Enviando E-mail';
	initAd();
	setarCamposSubmeterFranquia();
	enviarForm(caminho,campos,'enviarFranquia','',caminho);
}

function chamaAvaliarLoja(caminho){
	enviaRequisicao('cadClienteLogado', caminho, "Carregando...");	
}

function avaliarLojaVotacao(campo, valor){
	if(valor != 0){
		document.getElementById(campo).value = valor;
	}
}

function enviaLojaAvaliacao(div, ponteiro, caminho){
	var prazoEntrega = document.getElementById('prazoEntrega'+ponteiro);
	var qualidadeLoja = document.getElementById('qualidadeLoja'+ponteiro);
	var avaliacaoGeral = document.getElementById('avaliacaoGeral'+ponteiro);
	var lojaId = document.getElementById('loja_id'+ponteiro);
	var pedidoId = document.getElementById('pedido_id'+ponteiro);
	var observacao = document.getElementById('avaliarObservacao'+ponteiro);
	
	if(prazoEntrega.value == 0){
		alert("O campo prazo de entrega é obrigatório.");
		document.getElementById('prazo_entrega'+ponteiro).focus();
		return;
	}
	if(qualidadeLoja.value == 0){
		alert("O campo comida é obrigatório.");
		document.getElementById('qualidade'+ponteiro).focus();
		return;
	}
	if(avaliacaoGeral.value == 0){
		alert("O campo avaliação geral é obrigatório.");
		document.getElementById('avaliacao_geral'+ponteiro).focus();
		return;
	}
	
	var caminhoCompleto = caminho+"?avaliar=1&prazoEntrega="+prazoEntrega.value+"&qualidadeLoja="+qualidadeLoja.value+"&avaliacaoGeral="+avaliacaoGeral.value+"&lojaId="+lojaId.value+"&pedidoId="+pedidoId.value+"&avaliarObservacao="+encodeURI(observacao.value);
	enviaRequisicao(div, caminhoCompleto, "Carregando...");
}


function excluirAvaliacaoLoja(div, ponteiro, caminho){
	var lojaId = document.getElementById('loja_id'+ponteiro);
	var pedidoId = document.getElementById('pedido_id'+ponteiro);

	if(confirm('Você tem certeza que não quer avaliar seu pedido?')){
		var caminhoCompleto = caminho+"?excluir=1&lojaId="+lojaId.value+"&pedidoId="+pedidoId.value;
		enviaRequisicao(div, caminhoCompleto, "Carregando...");
	}
}

function buscaDetalhadaCategoria(caminho,valor){
	query = "?buscaCategoriaId="+valor;
	enviaRequisicao('buscaDetalhadaLoja',caminho+query,'Carregando...');
}


function botaoAreaUsuarioOver(div){
	if(document.getElementById(div) != undefined){
		document.getElementById(div).style.backgroundPosition = '0 -19px';
	}
}

function botaoAreaUsuarioOut(div){
	if(document.getElementById(div) != undefined){
		document.getElementById(div).style.backgroundPosition = '';
	}
}


function menuAreaUsuario(id, caminho){
	if(id == 'meusDados')
	{
		botaoAreaUsuarioOver('meusDados');		
		botaoAreaUsuarioOut('meusPedidos');
		botaoAreaUsuarioOut('maisPedidos');
		botaoAreaUsuarioOut('avaliarLoja');
		formCadClienteLogado(caminho);
	}
	else if(id == 'meusPedidos')
	{
		botaoAreaUsuarioOver('meusPedidos');		
		botaoAreaUsuarioOut('meusDados');
		botaoAreaUsuarioOut('maisPedidos');
		botaoAreaUsuarioOut('avaliarLoja');
		minhasCompras(caminho);
	}
	else if(id == 'maisPedidos')
	{
		botaoAreaUsuarioOver('maisPedidos');		
		botaoAreaUsuarioOut('meusDados');
		botaoAreaUsuarioOut('meusPedidos');
		botaoAreaUsuarioOut('avaliarLoja');
		pratosMaisComprados(caminho);
	}
	else if(id == 'avaliarLoja'){
		botaoAreaUsuarioOver('avaliarLoja');		
		botaoAreaUsuarioOut('meusDados');
		botaoAreaUsuarioOut('meusPedidos');
		botaoAreaUsuarioOut('maisPedidos');
		chamaAvaliarLoja(caminho);
	}
}



