// formata valor digitado
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 ) ;}
	}		
}

// permite só caracteres números
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;
	}
}

// Remove os espaços antes e depois do texto
function trim(texto){
    while(texto.indexOf(" ") != -1){
        texto = texto.replace(" ","");
	}
    return texto;
}

// Limpa um campo
function clearField(param,id){
	var field = document.getElementById(id);	
	if(field.value == param){		
		field.value = "";			
	}    
}

// Exibe legenda no campo
function showField(param,id){
	var field = document.getElementById(id);
	if(field.value == ""){
		field.value = param;
	}
}

// Escolhe a cidade
function setaCidade(path,cidade){
    if (cidade!=0){
        location.href = path+cidade;
    }
}

// float
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;
}


// ------------------------------ PIZZA ---------------------------------
function pegaValorTamanho(tamanhoEscolhido){
	if (document.getElementById('pizza_tamanho_id').value == 0){
		alert("Selecione o tamanho da pizza.");
		document.getElementById('valorTotalPrato').innerHTML = '------'
		return; 
    }
	atualizaDisplayValor(tamanhoEscolhido);
}

function permiteDivisao(){
	var tamanhoPizza = document.getElementById('pizza_tamanho_id').value;
	var permite_divisao_array = tamanhoPizza.split(",");
	if(permite_divisao_array[1] == 1){
		return true;
	}else{
		return false;
	}
}

function atualizaDisplayValor(obj){
	posicao = document.getElementById('pizza_tamanho_id').selectedIndex;

    //dados do sabor 1
	sabor_1 = document.getElementById('sabor_1_id').value;
	sabor_1_array = sabor_1.split(",");
	valorSabor1= sabor_1_array[posicao]/2;
	maiorValor = sabor_1_array[posicao];
    
    valorSabor2 = valorSabor1;
    valorSabor3 = 0;
    valorSabor4 = 0;
	if(permiteDivisao() == true){
		//dados do sabor 2
		sabor_2 = document.getElementById('sabor_2_id').value;
		sabor_2_array = sabor_2.split(",");
		valorSabor2= sabor_2_array[posicao]/2;
		if (sabor_2_array[posicao]>maiorValor){
			maiorValor = sabor_2_array[posicao];
		}
			
		//verifica se a pizza é de 4 sabores
		if (document.getElementById('pizzaFatia').value==4){
			//atualiza os valores das partes 1 e 2
			valorSabor1= sabor_1_array[posicao]/4;
			valorSabor2= sabor_2_array[posicao]/4;
			
			//dados do sabor 3
			sabor_3 = document.getElementById('sabor_3_id').value;
			sabor_3_array = sabor_3.split(",");
			valorSabor3= sabor_3_array[posicao]/4;
			if (sabor_3_array[posicao]>maiorValor){
				maiorValor = sabor_3_array[posicao];
			}
	
			//dados do sabor 4
			sabor_4 = document.getElementById('sabor_4_id').value;
			sabor_4_array = sabor_4.split(",");
			valorSabor4= sabor_4_array[posicao]/4;
			if (sabor_4_array[posicao]>maiorValor){
				maiorValor = sabor_4_array[posicao];
			}
		}
	}else{
		if (document.getElementById('pizzaFatia').value==4){
			if(obj.name == "sabor_2_id"){
		        document.getElementById("sabor_1_id").selectedIndex = obj.options[obj.selectedIndex].index;
		        document.getElementById("sabor_1_id").options[document.getElementById("sabor_1_id").selectedIndex].selected;   
		        document.getElementById("sabor_3_id").selectedIndex = obj.options[obj.selectedIndex].index;
        		document.getElementById("sabor_3_id").options[document.getElementById("sabor_3_id").selectedIndex].selected;     		
        		document.getElementById("sabor_4_id").selectedIndex = obj.options[obj.selectedIndex].index;
        		document.getElementById("sabor_4_id").options[document.getElementById("sabor_4_id").selectedIndex].selected;
		    }else if(obj.name == "sabor_3_id"){
		    	document.getElementById("sabor_1_id").selectedIndex = obj.options[obj.selectedIndex].index;
		        document.getElementById("sabor_1_id").options[document.getElementById("sabor_1_id").selectedIndex].selected;		        
		        document.getElementById("sabor_2_id").selectedIndex = obj.options[obj.selectedIndex].index;
        		document.getElementById("sabor_2_id").options[document.getElementById("sabor_2_id").selectedIndex].selected;       		
        		document.getElementById("sabor_4_id").selectedIndex = obj.options[obj.selectedIndex].index;
        		document.getElementById("sabor_4_id").options[document.getElementById("sabor_4_id").selectedIndex].selected;
		    }else if(obj.name == "sabor_4_id"){
		    	document.getElementById("sabor_1_id").selectedIndex = obj.options[obj.selectedIndex].index;
		        document.getElementById("sabor_1_id").options[document.getElementById("sabor_1_id").selectedIndex].selected;		        
		        document.getElementById("sabor_2_id").selectedIndex = obj.options[obj.selectedIndex].index;
        		document.getElementById("sabor_2_id").options[document.getElementById("sabor_2_id").selectedIndex].selected;      		
        		document.getElementById("sabor_3_id").selectedIndex = obj.options[obj.selectedIndex].index;
        		document.getElementById("sabor_3_id").options[document.getElementById("sabor_3_id").selectedIndex].selected;
		    }else{
		    	document.getElementById("sabor_2_id").selectedIndex = document.getElementById("sabor_1_id").selectedIndex;
        		document.getElementById("sabor_2_id").options[document.getElementById("sabor_2_id").selectedIndex].selected;        		
        		document.getElementById("sabor_3_id").selectedIndex = document.getElementById("sabor_1_id").selectedIndex;
        		document.getElementById("sabor_3_id").options[document.getElementById("sabor_3_id").selectedIndex].selected;      		
        		document.getElementById("sabor_4_id").selectedIndex = document.getElementById("sabor_1_id").selectedIndex;
        		document.getElementById("sabor_4_id").options[document.getElementById("sabor_4_id").selectedIndex].selected;
		    }
		}else{            
			if(obj.name == "sabor_2_id"){
		        document.getElementById("sabor_1_id").selectedIndex = obj.options[obj.selectedIndex].index;
		        document.getElementById("sabor_1_id").options[document.getElementById("sabor_1_id").selectedIndex].selected;
		    }else{
		    	document.getElementById("sabor_2_id").selectedIndex = document.getElementById("sabor_1_id").selectedIndex;
        		document.getElementById("sabor_2_id").options[document.getElementById("sabor_2_id").selectedIndex].selected; 
		    }
		}
	}

	//verifica se a pizza é proporcional ou pelo maior valor
	if (parseInt(document.getElementById('pizzaProporcional').value) == 1){
		total = valorSabor1 + valorSabor2 + valorSabor3 + valorSabor4;
	}else{
		total = maiorValor;
	}
	total = parseFloat(total);
	total += parseFloat(pegaValoresAcompanhamento())+parseFloat(pegaValoresBorda()); 
	document.getElementById('valorTotalPrato').innerHTML = float2moeda(total);
	document.getElementById('valorPrato').value = parseFloat(total);
}

function pegaValoresPizza(obj){
	if (document.getElementById('pizza_tamanho_id').value == 0){
		alert("Selecione o tamanho da pizza.");
		document.getElementById('valorTotalPrato').innerHTML = '------'
		return;
	}
	atualizaDisplayValor(obj);
}

function pegaValoresBorda(){
	if (document.getElementById('existeBorda').value==1){
		if (document.getElementById('borda_id').selectedIndex !=0){
			valores = eval("document.getElementById('borda_id').value.split(',')");
			posicao = document.getElementById('pizza_tamanho_id').selectedIndex;
			valorBorda = parseFloat(valores[posicao]);
		}else{
			valorBorda = 0;
		}
	}else{
		valorBorda = 0;
	}
	return parseFloat(valorBorda);
}

function atualizaAcompsPizza(campo){
	if (document.getElementById('pizza_tamanho_id').value == 0){
		campo.checked = false;
		alert("Selecione o tamanho da pizza.");
		document.getElementById('valorTotalPrato').innerHTML = '------'
		return;
	}
	atualizaDisplayValor(campo);
}

//pega os valores dos acompanhamentos separados por tamanhos
function pegaValoresAcompanhamento(){
	valorAcomps = 0;
	if (document.getElementById('possuiAcompPago').value == 1){
	  for (var i=0;i<document.getElementById('possuiAcompPagoQuant').value;i++) {
	  	campo = eval("document.getElementById('acompanhamento_id_pago" + i + "').checked");
	  	if (campo){
			valores = eval("document.getElementById('acompanhamento_id_pago" + i + "').value.split(',')");
			posicao = document.getElementById('pizza_tamanho_id').selectedIndex;
			valorAcomps = parseFloat(valorAcomps) + parseFloat(valores[posicao]);
	  	}
	  }
	}
	valor =  valorAcomps;
	return parseFloat(valor);
}

function adicionaPizzaAcomp(caminho){
	if (document.getElementById('pizza_tamanho_id').value == 0){
		alert("Selecione o tamanho da pizza.");
		document.getElementById('valorTotalPrato').innerHTML = '------'
		return;
	}
	//verifica se tem borda adicional
	idBorda = 0;
	if (document.getElementById('borda_id').selectedIndex !=0){
		valores = eval("document.getElementById('borda_id').value.split(',')");
		idBorda = valores[0];
	}

	//verifica se possui acompanhamento free
	acompIdFreeSelecionados='0';  
	if (document.getElementById("possuiAcompFree").value == 1){
		  quantSelecionada=0;
		  for (var i=0;i<document.getElementById("totalAcompanhamentos").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 apenas " + document.getElementById("quantAcompPermitida").value + " acompanhamentos.");
		  	return;
		  }
	}	
	//verifica se possui acompanhamento pago
	acompIdPagoSelecionados='0';
	if (document.getElementById('possuiAcompPago').value == 1){
	  for (var i=0;i<document.getElementById('possuiAcompPagoQuant').value;i++) {
	  	campo = eval("document.getElementById('acompanhamento_id_pago" + i + "').checked");
	  	if (campo){
			idsAcompanhamentos = eval("document.getElementById('idsAcomp_" + i + "').value.split(',')");
			posicao = document.getElementById('pizza_tamanho_id').selectedIndex;
			acompIdPagoSelecionados += "," + idsAcompanhamentos[posicao];
	  	}
	  }
	}

	//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;
		  }
	}
	
	sabor_1 = document.getElementById('sabor_1_id').value;
	sabor_1_array = sabor_1.split(",");
	prato_id = sabor_1_array[0];
	
	sabor_2 = document.getElementById('sabor_2_id').value;
	sabor_2_array = sabor_2.split(",");
	prato_id2 = sabor_2_array[0];

	if (document.getElementById('pizzaFatia').value==4){	
		sabor_3 = document.getElementById('sabor_3_id').value;
		sabor_3_array = sabor_3.split(",");
		prato_id3 = sabor_3_array[0];

		sabor_4 = document.getElementById('sabor_4_id').value;
		sabor_4_array = sabor_4.split(",");
		prato_id4 = sabor_4_array[0];
	}

	//tamanhoPizza = document.getElementById('pizza_tamanho_id').value;
	tamanhoPizzaArray = document.getElementById('pizza_tamanho_id').value.split(",");
	tamanhoPizza = tamanhoPizzaArray[0];
	
	parametros = "?proporcional=" + document.getElementById('pizzaProporcional').value 
	parametros = parametros + "&pizza=1&tamanhoPizza=" + tamanhoPizza 
	parametros = parametros + "&prato_id="+prato_id+"&prato_id2="+prato_id2;
	if (document.getElementById('pizzaFatia').value==4){
		parametros = parametros + "&prato_id3="+prato_id3+"&prato_id4="+prato_id4;		
	}
	parametros = parametros + "&bordaId="+idBorda;	
	parametros = parametros + "&acompIdFree="+acompIdFreeSelecionados;	
	parametros = parametros + "&acompIdPago="+acompIdPagoSelecionados;	
	parametros = parametros + "&bebidaIdFree="+bebidaIdFreeSelecionados;	
	parametros = parametros + "&obsPrato="+encodeURI(document.getElementById('obs_prato').value);
    
    if(document.getElementById('ofertaId') != null){
        parametros = parametros + "&ofertaId="+document.getElementById('ofertaId').value;
    }
	execute('seusPedidos',caminho+parametros,'Adicionando produto...');
}
// ---------------------------- FIM PIZZA

// Acompanhamento de prato
function contaAcomp(total,ultima){
    opcoesSelecionadas=0;
    var acomp = document.getElementById("totalAcompanhamentosFree");
  
    for(var i=0; i < acomp.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 < acomp.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;
      	}   
    }  
}

// Acompanhamento de bebida
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;
        }
    }
}

// Limitador de caracteres
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;
}

// Insere uma bebida no carrinho
function insereBebidaCarrinho(path){
	execute('seusPedidos',path,'Adicionando bebida...');	
}

// Insere Prato no carrinho
function insereNoCarrinho(prato_id,caminho,contador){  
    qtdPrato = document.getElementById('quantidade_prato_'+contador);
    
    if(qtdPrato != null) {
        if(parseInt(qtdPrato.value) <= 0 || trim(qtdPrato.value) == "") {
            alert("Quantidade inválida");
            qtdPrato.focus();
            return;
        }
    }   
    
	if (prato_id != 0){		
        execute('seusPedidos',caminho+"modulos/carrinho/carrinho.php?prato_id="+prato_id+"&quantidade_prato="+qtdPrato.value+"&obsPrato=",'Carregando...');		
	} else {
		alert('No momento o prato escolhido não está disponível.');	
	}
}

// Insere Prato no carrinho
function insereNoCarrinhoOferta(prato_id,oferta_id,caminho){  
	if (prato_id != 0){		
        var param = "?prato_id="+prato_id+"&quantidade_prato=1&ofertaId="+oferta_id+"&obsPrato=";
        execute('seusPedidos',caminho+"modulos/carrinho/carrinho.php"+param,'Carregando...');		
	} else {
		alert('No momento o prato escolhido não está disponível.');	
	}
}

// Envia prato com observação para o carrinho
function enviaObs(prato_id,caminho,contador){
    qtdPrato = document.getElementById('quantidade_prato_'+contador);
    
    if(qtdPrato != null) {
        if(parseInt(qtdPrato.value) <= 0 || trim(qtdPrato.value) == "") {
            alert("Quantidade inválida");
            qtdPrato.focus();
            return;
        }
    }
    
	obsPrato = "&obsPrato="+encodeURI(document.getElementById('obs_prato').value);	    	    
    
    arquivo = caminho+"modulos/carrinho/carrinho.php?obsPrato="+obsPrato+"&prato_id="+prato_id+"&quantidade_prato="+qtdPrato.value;
    
    // oferta
    if(document.getElementById('ofertaId') != null){
        arquivo += "&ofertaId="+document.getElementById('ofertaId').value;
    }
    
    $.fancybox.close();
	execute('seusPedidos',arquivo,'Adicionando produto...');    
}

// envia a senha para o cliente
function submeterEsqueceuSenha(caminho){
    var email = document.getElementById('seu_email');
    
    if(trim(email.value) == ""){
        alert("O campo e-mail é obrigatório.");
        email.focus();
        return;
    }

    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))){
        alert("Seu e-mail é inválido.");
        email.focus();
        return;
    }

    arquivo = caminho+"modulos/recuperasenha/formulario.php?email="+encodeURI(email.value);    
	execute('recuperarSenha',arquivo,'Enviando...');  
    //$.fancybox.close();
    //document.getElementById('formEsqueceuSenha').submit();
}

// Adiciona Prato no carrinho
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;
		  }
	}
    	    
    
	parametros = "modulos/carrinho/carrinho.php?prato_id="+pratoId;
	parametros = parametros + "&acompIdFree="+acompIdFreeSelecionados;	
	parametros = parametros + "&acompIdPago="+acompIdPagoSelecionados;	
	parametros = parametros + "&bebidaIdFree="+bebidaIdFreeSelecionados;	
	parametros = parametros + "&obsPrato="+encodeURI(document.getElementById('obs_prato').value);

    // oferta
    if(document.getElementById('ofertaId') != null){
        parametros = parametros + "&ofertaId="+document.getElementById('ofertaId').value;
    }
    
	execute('seusPedidos', caminho+parametros, 'Adicionando produto...');
}

// Exibe os pratos de uma categoria
function buscaCardapio(cardapioId,path){
	if (cardapioId != 0){		
		if (cardapioId != 9999){
			location.href = path+'cardapio/'+cardapioId;
		} else {
            location.href = path+'cardapio/bebidas/';
			//enviaRequisicao('carregaCardapio',caminho+bebida+document.getElementById('lojaIdCombo').value,'Carregando Bebidas...');
		}			
	}
}

// Busca cardápio na loja
function buscaCardapioLoja(caminho, loja_id){
	var field = document.getElementById('buscaInternaLoja');
	var cardapio_id = document.getElementById("comboCategorias").value;
    if(cardapio_id == 0){
        cardapio_id = 'tudo';
    }
	if (trim(field.value).length >= 3){
		//execute('carregaCardapio',caminho+'modulos/restaurante/cardapio.php?loja_id='+loja_id+'&cardapio_id='+cardapio_id+'&pesquisa='+field.value,'Procurando Prato...');
        location.href = caminho+'restaurante/'+loja_id+'/cardapio/'+encodeURI(field.value);        
	}else{
		alert("A palavra pesquisada deve ter no mínimo 3 caracteres.");
	}
}

/*
// busca avançada
function buscaAvancada(url) {
    var termo = document.getElementById('termoProduto').value;
    var categoria = document.getElementById('categoria').value;
    var loja = document.getElementById('loja').value;
    var status = document.getElementById('status').value;
    var preco = document.getElementById('preco').value;
    
    param = "modulos/busca/resultado.php?termo="+termo+"&categoria="+categoria+"&loja="+loja+"status="+status+"&preco="+preco;
    execute("resultadoBusca",url+param,'');
}
*/



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

// Excluir Avaliação
function excluirAvaliacaoLoja(ponteiro, path){
	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 = path+"cliente/avaliacao/excluir/"+lojaId.value+"/"+pedidoId.value;
        location.href = caminhoCompleto;
    }
}

// Submeter o formulário de indicação
function enviaLojaAvaliacao(ponteiro, path){
	var prazoEntrega = document.getElementById('prazo_entrega'+ponteiro);
	var qualidadeLoja = document.getElementById('qualidade'+ponteiro);
	var avaliacaoGeral = document.getElementById('avaliacao_geral'+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.");
		prazoEntrega.focus();
		return;
	}
	if(qualidadeLoja.value == 0){
		alert("O campo comida é obrigatório.");
		qualidadeLoja.focus();
		return;
	}
	if(avaliacaoGeral.value == 0){
		alert("O campo avaliação geral é obrigatório.");
		avaliacaoGeral.focus();
		return;
	}
    
    var obs = observacao.value;
    if(observacao.value == "Observação"){
        obs = "";
    }
	
	var caminhoCompleto = path+"cliente/avaliacao/avaliar/"+lojaId.value+"/"+pedidoId.value+"/"+prazoEntrega.value+"/"+qualidadeLoja.value+"/"+avaliacaoGeral.value+"/"+encodeURI(obs);
	location.href = caminhoCompleto;
}

// Exibe detalhes do pedido
function verDetalhePedido(caminho,divName,pedidoId){
	abreFecha = divName + 'Status';
	imagem = divName + 'imagem';
	abreFechaValor = document.getElementById(abreFecha).value;
	if (abreFechaValor == 0){
		execute(divName,caminho+'modulos/cliente/pedidos_detalhes.php?pedido_id='+pedidoId,'Carregando ...');			
		document.getElementById(abreFecha).value = 1;                
        document.getElementById(imagem).setAttribute("class", 'btmenos') // Para a maioria dos navegadores
        document.getElementById(imagem).setAttribute ("className", 'btmenos') // Para IE; inofensivo para outros navegadores.
            
        //$(imagem).removeClass('btmais');
        //$(imagem).addClass('btmenos');		
	} else {
		document.getElementById(abreFecha).value =0;
		document.getElementById(divName).innerHTML ='';
        document.getElementById(imagem).setAttribute("class", 'btmais') // Para a maioria dos navegadores
        document.getElementById(imagem).setAttribute ("className", 'btmais') // Para IE; inofensivo para outros navegadores.
        //$(imagem).removeClass('btmenos');
        //$(imagem).addClass('btmais');		
	}
}

// Adiciona prato japones no carrinho
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;
		  }
	}
    	    
    
    parametros = "modulos/carrinho/carrinho.php?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);

    if(document.getElementById('ofertaId') != null){
        parametros = parametros + "&ofertaId="+document.getElementById('ofertaId').value;
    }
    
	execute('seusPedidos', caminho+parametros, 'Adicionando produto...');        	
}

// adiciona complemento no prato
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;';	
}

// para o combinado
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.")
	}
}

// Abre a página da promoção da central
function promocaoCentral() {
    path = document.getElementById('urlPagina').value;
    location.href = path+'promocao';
}


// ----------------- CLIENTE -----------------------------

// cadastra cliente
function submeterCliente(div){
    var nome = document.getElementById('nome');
    var sobrenome = document.getElementById('sobrenome');
    var dt_nascimento = document.getElementById('dt_nascimento');
    var cpf = document.getElementById('cpf');
    var rg = document.getElementById('rg');
    var telefone = document.getElementById('telefone');
    var celular = document.getElementById('celular');
    var email = document.getElementById('email');
    var senha = document.getElementById('senha');        
    var confirma = document.getElementById('confirma');        
    var cliente_conheceu = document.getElementById('cliente_conheceu'); 
    var totalEnderecos = document.getElementById('totalEnderecos').value;       

    if(trim(nome.value) == "" || trim(nome.value) == "Nome"){
        alert("O campo Nome é obrigatório");
        nome.focus();
        return;
    }

    if(trim(sobrenome.value) == "" || trim(sobrenome.value) == "Sobrenome"){
        alert("O campo Sobrenome é obrigatório");
        sobrenome.focus();
        return;
    }

    if(trim(dt_nascimento.value) == "" || trim(dt_nascimento.value) == "Data de Nascimento"){
        alert("O campo Data de Nascimento é obrigatório");
        dt_nascimento.focus();
        return;
    }

    if(trim(cpf.value) == "" || trim(cpf.value) == "CPF"){
        alert("O campo CPF é obrigatório");
        cpf.focus();
        return;
    }

    if(trim(rg.value) == "" || trim(rg.value) == "RG"){
        alert("O campo RG é obrigatório");
        rg.focus();
        return;
    }

    if(trim(telefone.value) == "" || trim(telefone.value) == "Telefone"){
        alert("O campo Telefone é obrigatório");
        telefone.focus();
        return;
    }

    if(trim(celular.value) == "" || trim(celular.value) == "Celular"){
        alert("O campo Celular é obrigatório");
        celular.focus();
        return;
    }

    if(trim(email.value) == "" || trim(email.value) == "E-mail"){
        alert("O campo E-mail é obrigatório");
        email.focus();
        return;
    }
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))){ 
        alert("E-mail inválido.");
        email.focus();
        return;
    }       

    if(trim(senha.value) == "" || senha.value == "Senha"){
        alert("O campo Senha é obrigatório");
        senha.focus();
        return;
    }   

    if(trim(confirma.value) == "" || confirma.value == "Senha"){
        alert("O campo Confirma Senha é obrigatório");
        confirma.focus();
        return;
    } 

    if(totalEnderecos == 0){
        alert("Você deve informar ao menos um endereço");
        return;
    }    

    document.getElementById(div).submit();
}

// cadastra o endereço
function submeterEndereco(caminho,carrinho){	
    var enderecoId = document.getElementById('endereco_id').value;
    var titulo = document.getElementById('end_titulo');
    var telefone = document.getElementById('end_telefone');
    var endereco = document.getElementById('endereco');    
    var complemento = document.getElementById('end_complemento');        
    var bairro = document.getElementById('end_bairro');
    var cidade = document.getElementById('end_cidade');
    var cep = document.getElementById('cep');
    var estado = document.getElementById('end_estado');
    var referencia = document.getElementById('end_ponto_referencia');
    var clienteId = document.getElementById('clienteIdTemp').value;

    if(trim(titulo.value) == "" || trim(titulo.value) == "Título"){
        alert("O campo Título é obrigatório");
        titulo.focus();
        return;
    }

    if(trim(telefone.value) == "" || trim(telefone.value) == "Telefone"){
        alert("O campo Telefone é obrigatório");
        telefone.focus();
        return;
    }

    if(trim(endereco.value) == "" || trim(endereco.value) == "Endereço"){
        alert("O campo Endereço é obrigatório");
        endereco.focus();
        return;
    }        

    if(trim(complemento.value) == "" || complemento.value == "Complemento (Apt°/Nome do edifício)"){
        alert("O campo Complemento é obrigatório");
        complemento.focus();
        return;
    }
    
    if(trim(referencia.value) == "" || referencia.value == "Ponto de Referência"){
        alert("O campo Ponto de Referência é obrigatório");
        referencia.focus();
        return;
    }
        
    if(trim(bairro.value) == "" || trim(bairro.value) == "Bairro"){
        alert("O campo Bairro é obrigatório");
        bairro.focus();
        return;
    }

    if(trim(cidade.value) == "" || trim(cidade.value) == "Cidade"){
        alert("O campo Cidade é obrigatório");
        cidade.focus();
        return;
    }

    if(trim(cep.value) == "" || trim(cep.value) == "CEP"){
        alert("O campo CEP é obrigatório");
        cep.focus();
        return;
    }

    if(estado.value == "0"){
        alert("O campo Estado é obrigatório");
        estado.focus();
        return;
    }                   

    campos = 'modulos/cliente/endereco.php';
    if(enderecoId == 0){
        campos += "?cadastrarEndereco=1";
    } else {
        campos += "?atualizarEndereco=1";
    }
    if(carrinho == 1){
        campos += '&carrinho=1';
    }
    campos += '&endereco_id='+enderecoId+'&titulo='+titulo.value+'&telefone='+telefone.value+'&endereco='+endereco.value+'&estado='+estado.value;
    campos += '&complemento='+complemento.value+'&bairro='+bairro.value+'&cidade='+cidade.value+'&clienteIdTemp='+clienteId+'&cep='+cep.value+'&referencia='+referencia.value;

    execute('enderecosCliente', caminho+campos,'Registrando endereço...');
}

// Exclui endereço
function excluiEndereco(endereco,cliente,caminho) {
    if(confirm("Deseja realmente deletar este endereço?")){
        campos = "modulos/cliente/endereco.php?excluir=1&cliente_id="+cliente+"&endereco_id="+endereco;
        execute('enderecosCliente',caminho+campos,'Excluindo endereço...');	
    }        
}

// altera endereço do cliente logado
function alteraEndereco(id, url){
	param = "cliente/alterarDados/"+id;	
    location.href = url+param;
}

// limpa os campos do cadastro de endereço do cliente
function limpaCamposEnd(){
	document.getElementById('endereco_id').value = '0';
	document.getElementById('end_titulo').value = 'Título';
	document.getElementById('end_telefone').value = 'Telefone';
	document.getElementById('endereco').value = 'Endereço';
	document.getElementById('end_complemento').value = 'Complemento (Apt°/Nome do edifício)';
	document.getElementById('end_ponto_referencia').value = 'Ponto de Referência';
	document.getElementById('end_cidade').value = 'Cidade';
	document.getElementById('end_bairro').value = 'Bairro';
	document.getElementById('cep').value = 'CEP';
	document.getElementById('end_estado').value = '0';
}

// ---------------- FIM CLIENTE ---------------------------

// Busca
function buscaProdutoPalavra(){
	var termo = document.getElementById('termoPesquisa');
    
    if(termo.value != 'Buscar Prato') {
        if (termo.value.length >= 3){	
            document.getElementById('formBuscaSimples').submit();            
        }else{
            alert("A palavra pesquisada deve ter no mínimo 3 caracteres.");
        }
    }
}

// Acrescentar no carrinho
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;
}

// Retira no carrinho
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.")
	}
}

// Remove produto do carrinho
function removerCarrinho(campo,url,tipo){	
	destino = url+"carrinho/detalhes/remover/"+tipo+"/"+campo;	
    
    location.href = destino;
}

// atualiza quantidade no carrinho
function atualizarQuantidade(caminho){
	campos = '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;
		}
		campos = campos + "&prato_quant_" + i + "=" + valor;
	}
	for (i=0;i<document.getElementById('quantBebidaCarrinho').value;i++){
		campo = "document.getElementById('bebida_quant_"+i+"').value";
		campos = campos + "&bebida_quant_" + i + "=" + eval(campo);
	}
	campos = campos + "&areaId=" + document.getElementById('area_id').value;
	  
    executePost(caminho+'modulos/carrinho/detalhes.php',campos,'loaderCarrinhoCompras','Carregando...',caminho);
}


// login
function logar(caminho){
    var email = document.getElementById('login');
    var senha = document.getElementById('senha');
    var origem = document.getElementById('origem').value;
    
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))){ 
       	alert("Email inválido.");
        email.focus();
   	    return;
    } 
	if(trim(senha.value) == ""){	
		alert("Senha inválida.");
		senha.focus();
		return;
	}	
	
   
    //var quebra = variaveis[1].split("=");
    campos =  "login="+encodeURI(email.value);
    campos += "&senha="+encodeURI(senha.value);
    campos += "&origem="+origem;	
    executePost(caminho+'login.php',campos,'logarCliente','Carregando...',caminho);
}

// CARRINHO -------------------------------------------------
// login no passo carrinho
function logarCarrinho(caminho){
    var email = document.getElementById('login_carrinho');
    var senha = document.getElementById('senha_carrinho');
    
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))){ 
       	alert("Email inválido.");
        email.focus(); 
   	    return;
    } 
    
	if(trim(senha.value) == ""){	
		alert("Senha inválida.");
		senha.focus();
		return;
	}	
    
    campos = "login="+encodeURI(email.value);
	campos +="&senha="+encodeURI(senha.value);
	campos +="&origem=2";	
       
    executePost(caminho+'login.php',campos,'logarCliente','Carregando...',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;
		}
	}
    location.href = caminho+'carrinho/'+destino;		
}

// carrega os dados no passo de compra de confirmação do endereço
function carregaEndereco(campo){
    document.getElementById('cliente_telefone_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_complemento_entrega').value = eval('document.getElementById("cliente_complemento_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 setarCamposEnderecoEntrega(){
	campos ="tipoEnderecoEntrega=2&cliente_endereco="+encodeURI(document.getElementById('cliente_endereco_entrega').value);
	campos +="&cliente_bairro="+encodeURI(document.getElementById('cliente_bairro_entrega').value);
	campos +="&cliente_cidade="+encodeURI(document.getElementById('cliente_cidade_entrega').value);
	
	if (trim(document.getElementById('cliente_complemento_entrega').value) != ''){
		campos +="&cliente_end_compl="+encodeURI(document.getElementById('cliente_complemento_entrega').value);
	}else{
		campos +="&cliente_end_compl=''";
	}
	campos +="&cliente_estado="+encodeURI(document.getElementById('cliente_estado_entrega').value);
	campos +="&cliente_cep="+encodeURI(document.getElementById('cliente_cep_entrega').value);
	
	if (trim(document.getElementById('cliente_ref_entrega').value) != ''){
		campos +="&cliente_ref="+encodeURI(document.getElementById('cliente_ref_entrega').value);
	}else{
		campos +="&cliente_ref=''";
	}
	if (trim(document.getElementById('observacao').value) != ''){
		campos +="&observacao="+encodeURI(document.getElementById('observacao').value);
	}else{
		campos +="&observacao=''";
	}
	campos += "&cliente_telefone_entrega="+encodeURI(document.getElementById('cliente_telefone_entrega').value);
}

function submeterEnderecoEntrega(url){
	if(trim(document.getElementById('cliente_telefone_entrega').value) == ""){	
		alert("Informe o Telefone do local que será entregue o pedido.");
		document.getElementById('cliente_telefone_entrega').focus();
		return;
	}
	if(trim(document.getElementById('cliente_endereco_entrega').value) == ""){	
		alert("Informe o Endereço.");
		document.getElementById('cliente_endereco_entrega').focus();
		return;
	}
	if(trim(document.getElementById('cliente_complemento_entrega').value) == ""){	
		alert("Informe o Complemento.");
		document.getElementById('cliente_complemento_entrega').focus();
		return;
	}
	if(trim(document.getElementById('cliente_bairro_entrega').value) == ""){	
		alert("Informe o Bairro.");
		document.getElementById('cliente_bairro_entrega').focus();
		return;
	}
	if(trim(document.getElementById('cliente_cidade_entrega').value) == ""){	
		alert("Informe a Cidade.");
		document.getElementById('cliente_cidade_entrega').focus();
		return;
	}
	if(document.getElementById('cliente_estado_entrega').value == ''){	
		alert("Informe o Estado.");
		document.getElementById('cliente_estado_entrega').focus();
		return;
	}
	if(trim(document.getElementById('cliente_cep_entrega').value) == ""){	
		alert("Informe o CEP.");
		document.getElementById('cliente_cep_entrega').focus();
		return;
	}
	var faixa_cep1_ini = parseInt(document.getElementById('faixa_cep1_ini').value);
	var faixa_cep1_fim = parseInt(document.getElementById('faixa_cep1_fim').value);
	var faixa_cep2_ini = parseInt(document.getElementById('faixa_cep2_ini').value);
	var faixa_cep2_fim = parseInt(document.getElementById('faixa_cep2_fim').value);
	var cep_usuario = document.getElementById('cliente_cep_entrega').value;
	cep_usuario = parseInt(cep_usuario.replace("-",""));
	if((cep_usuario >= faixa_cep1_ini && cep_usuario <= faixa_cep1_fim) || (cep_usuario >= faixa_cep2_ini && cep_usuario <= faixa_cep2_fim)){
		if(cep_usuario == 0){
			alert("CEP não encontrado na cidade informada.");
			document.getElementById('cliente_cep_entrega').focus();
			return;
		}
	}else{
		alert("CEP não encontrado na cidade informada.");
		document.getElementById('cliente_cep_entrega').focus();
		return;
	}
	if(trim(document.getElementById('cliente_ref_entrega').value) == ""){	
		alert("Informe o Ponto de Referência.");
		document.getElementById('cliente_ref_entrega').focus();
		return;
	}
    
    //document.getElementById('formCarrinhoEndereco').submit();
	setarCamposEnderecoEntrega();
	executePost(url+'modulos/carrinho/salva_endereco.php',campos,'loaderCarrinhoCompras','Enviando dados...',url);
}
// FIM CARRINHO -------------------------------------------------

// PAGAMENTO ----------------------------------------------------
function ativaTroco(){
	document.getElementById('troco').disabled = false;
    document.getElementById('concluirCompra').style.display = "block";
}

function desativaTroco(){
	document.getElementById('troco').value = '';
	document.getElementById('troco').disabled = true;
    document.getElementById('concluirCompra').style.display = "block";
}

function chamaCartao(valor){
	desativaTroco();

    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;
    document.getElementById('concluirCompra').style.display = "block";
}

// concluir a compra com cartao
function concluirComCartao(cartaoId,caminho,mes,ano){
    var mes_validade = document.getElementById('mes_validade');
    var ano_validade = document.getElementById('ano_validade');
    var nome_cartao = document.getElementById('nomeCartao');    
    var num_cartao = document.getElementById('numeroCartao');    
    var codigo_cartao = document.getElementById('codigoCartao');    
    
	if (parseFloat(ano_validade.value) == parseFloat(ano)){
		if (parseFloat(mes_validade.value) < parseFloat(mes)){
			alert("Data de Validade inválida.");
			return;			
		}
	}
    
	if(trim(nome_cartao.value) == ''){
		alert("Nome inválido.");
		nome_cartao.focus();
		return;
	}

	if(cartaoId == 4){ // artao Hiperc
		if(num_cartao.value.length != 13 && num_cartao.value.length != 16){
			alert("Cartão inválido.");
			num_cartao.focus();
			return;
		}
	} else {
		if (cartaoId > 4){
			if (!isCreditCard(num_cartao.value)){
				alert("Cartão inválido.");
				num_cartao.focus();
				return;
			}
		} else {
			if (!isValidCreditCardNumber(num_cartao.value,cartaoId)){
				alert("Cartão inválido.");
				return;
			}
		}
	}
    
	if(codigo_cartao.value.length < 3){
		alert("Código de Segurança inválido.");
		codigo_cartao.focus();
		return;
	}
	if ((mes_validade.value == 0) || (ano_validade.value == 0)) {
		alert("Data de Validade incorreta.");
		mes_validade.focus();
		return;
	}
    
	document.getElementById('enviandoDados').value=1;	
	campos = setarCamposCartao();
	execute('conexaoSegura',caminho+'ler_pagina_remota_post.php?cartaoTipo='+cartaoId+campos,'');
	
}

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);    
    return campos;
}

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;
}

// finaliza compra com cartao wireless, tiquete, cheque ou dinheiro
function finalizaCompra(caminho,valorTotal){	
		   
    if (document.getElementById('cartaoDigitados').value > 0){
	    for(i=1;i<=document.getElementById('cartaoDigitados').value;i++) {  
		  	cb = eval('document.getElementById("cartaoDebito' + i + '")');
		  	if (cb.checked) {
            	alert("Informe os dados do seu cartão");
                return;
	        }
	    }
	}    
    
    formaSelecionada = 0;
	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){
        // FINALIZA COM TIQUETE        
		execute('loaderCarrinhoCompras',caminho+'modulos/carrinho/finalizar.php?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){		
		execute('loaderCarrinhoCompras',caminho+'modulos/carrinho/finalizar.php?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;
			}
		}
		execute('loaderCarrinhoCompras',caminho+'modulos/carrinho/finalizar.php?cheque=0&troco='+trocoValor,'Finalizando ...');		
		return;
	}
	if (document.getElementById('pagCheque')!=null){
		if (document.getElementById('pagCheque').checked){
            execute('loaderCarrinhoCompras',caminho+'modulos/carrinho/finalizar.php?cheque=1&troco=0','Finalizando ...');				
			return;
		}
	}
	alert('Selecione uma das opções disponíveis de pagamento.');
}

function marcaCartao(id) {
    document.getElementById(id).checked = true;
    document.getElementById('concluirCompra').style.display = "none";
}
// FIM PAGAMENTO ----------------------------------------------------



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

function buscaLojaCep(){
	if (document.getElementById('buscaCep').value.length >= 5){	
        if(document.getElementById('buscaCep').value != "Digite seu CEP"){
            document.getElementById('formCep').submit();
        } else {
            return;
        }
	}else{
		alert("Informe no mínimo os 5(cinco) primeiros dígitos do CEP.");
        return;
	}
}


function buscaLoja(valor, url){
	if (valor != 0){
        location.href = url+'restaurante/'+valor;
	}
}


// calcular cupom
function calcularCupom(caminho){
    var cupom = document.getElementById('cupom');
    	
    if(trim(cupom.value) == "") {
        alert("Informe o código do cupom");
        return;
    }    
    campos = "cupom=" + cupom.value;
	  
    executePost(caminho+'modulos/carrinho/detalhes.php',campos,'loaderCarrinhoCompras','Carregando...',caminho);
}




