function contarAcesso(contou) {
	jQuery.ajax(
		{
			type: "POST",
			url: "usuario/acesso/acesso_exe.php",
			data: "contou=" + contou,
			beforeSend: function() {},
			success: function(txt) {},
			error: function(txt) {}
		}
	);
}		
	

window.setVariableInterval = function(callbackFunc, timing) {
  var variableInterval = {
    interval: timing,
    callback: callbackFunc,
    stopped: false,
    runLoop: function() {
      if (variableInterval.stopped) return;
      var result = variableInterval.callback.call(variableInterval);
      if (typeof result == 'number')
      {
        if (result === 0) return;
        variableInterval.interval = result;
      }
      variableInterval.loop();
    },
    stop: function() {
      this.stopped = true;
      window.clearTimeout(this.timeout);
    },
    start: function() {
      this.stopped = false;
      return this.loop();
    },
    loop: function() {
      this.timeout = window.setTimeout(this.runLoop, this.interval);
      return this;
    }
  };

  return variableInterval.start();
};

function banner_proximo(){
	if(banner_atual == banner_array.length-1){
		var proximo = 0;
	}else{
		var proximo = banner_atual+1;
	}	
	banner_atual = proximo;
	banner_mostrar_atual();
}

function banner_mostrar_atual(){
	banner_apagar_todos();
	jQuery('#'+banner_array[banner_atual]).show();
}

function banner_apagar_todos(){
	for ( var a in banner_array) {
		jQuery('#'+banner_array[a]).hide();
	}
}

function validar_cadastro(){
	var cep = document.getElementById('cep').value;
	var nome = document.getElementById('nome').value;
	
	if(cep.length != 8){
		alert("Seu Cep deve conter 9 caracteres!");
		return false;
	}else if(nome == ""){
		alert("Seu Nome esta em branco!");
		return false;
	}else{
		return true;
	}
}

function frete_mostrar(VALOR){
	if(VALOR != 0){
		frete_apagar_todos();
		jQuery('#div_frete_'+VALOR).show('slow');
	}else{
		frete_apagar_todos();
	}
}

function frete_apagar_todos(){

	jQuery('#div_frete_1').hide();
	jQuery('#div_frete_2').hide();
	jQuery('#div_frete_3').hide();
}


function validar_pagamento_status(){
	var id_forma_pagamento = document.getElementById('id_forma_pagamento').value;
	var id_pedido_status = document.getElementById('id_pedido_status').value;
	
	if(id_forma_pagamento != "" && id_pedido_status != ""){
		if(id_forma_pagamento==1 && id_pedido_status != 2){
			alert("Quando a forma de pagamento for PAGUE SEGURO o status deve ser em AGUARDADNO PAGAMENTO");
			document.getElementById('id_pedido_status').selectedIndex = 2;
		}
	}
	
}

function calcule_o_frete(MENSAGEM){
	$('#valor_frete').val("0");
	$('#prazo').val("0");
	$('#erro').html(MENSAGEM);
	$('#calculou_frete').val("0");
}

function calcular_frete(){
	$.blockUI({ overlayCSS: { backgroundColor: '#00466C' } }); 
	var id_frete_tipo = document.getElementById('id_frete_tipo').value;
	
	$.ajax(
			{
				type: "POST",
				url: "../frete/frete_exe.php",
				data: "action_real=calcular_frete&"+$('#form1').serialize(),
				beforeSend: function() {},
				success: function(txt) {
					variaveis_json = eval("("+txt+")");
					
					if(variaveis_json.erro!=0){
						calcule_o_frete(variaveis_json.msg_erro);
					}else{
						$('#valor_frete').val(variaveis_json.valor_frete);
						$('#prazo').val(variaveis_json.prazo);
						$('#erro').html("");
						$('#calculou_frete').val("1");
					}
					
					calcular_valor_total();
					$.unblockUI(); 
				},
				error: function(txt) {
					return txt;
				}
			}
	);
}

function frete_sedex(FRETE_TIPO){
	calcular_valor_total();
	if(FRETE_TIPO != ""){
		calcule_o_frete("");
		jQuery('#div_frete').show();
	}else{
		calcule_o_frete("");
		jQuery('#div_frete').hide();
	}
}

function calcular_valor_total(){
	var valor_total = 0;
	var valor_total_itens = 0;
	var valor_frete = parseFloat(document.getElementById('valor_frete').value);
	var valor_desconto = parseFloat(document.getElementById('valor_desconto').value);
	
	var tamanho = parseInt(document.getElementById('quantidade_item').value);
	var inicio = 0;
	
	while(inicio<=tamanho){
		if(document.getElementById('tem'+inicio+'')){
		
			valor_atual = parseFloat(document.getElementById('valor_unitario'+inicio+'').value);
			quantidade_atual = parseInt(document.getElementById('quantidade'+inicio+'').value);
			valor_atual = valor_atual * quantidade_atual;
			valor_total_itens = valor_total_itens + valor_atual;
		}
		inicio++;
	}
	
	valor_total = (parseFloat(valor_total_itens) - parseFloat(valor_desconto)) + parseFloat(valor_frete);
	document.getElementById('valor_total').value = parseFloat(valor_total).toFixed(2);
}

function verificar_ja_existe(ID_PRODUTO,INDICE){
	
	var tamanho = parseInt(document.getElementById('quantidade_item').value);
	var inicio = 1;
	
	while(inicio<=tamanho){
		if(INDICE!=inicio){
			if(document.getElementById('id_produto'+inicio+'')){
				if(document.getElementById('id_produto'+inicio+'').value == document.getElementById('id_produto'+INDICE+'').value){
					return true;
				}
			}
		}		
		inicio++;
	}
	
	return false;
}

function excluir_item_l(INDICE){
	jQuery('#lista_item'+INDICE).remove();
	calcular_valor_total();
	calcule_o_frete("");
}

function adicionar_item(){
	var quantidade_item = parseInt(document.getElementById('quantidade_item').value);
	quantidade_item = quantidade_item + 1;
	document.getElementById('quantidade_item').value = quantidade_item;
	
	jQuery('#lista').append('<tr id="lista_item'+quantidade_item+'" bgcolor="#F5F5F5" >'+
		'<td width="45%">'+
			'<p>'+  
			'Produto: *'+
				'<select id="id_produto'+quantidade_item+'" name="id_produto'+quantidade_item+'" onchange="buscar_produto_preco(this.value,'+quantidade_item+');calcule_o_frete(\'\');">'+
				'</select>'+
				'<input type="hidden" value="'+quantidade_item+'" id="tem'+quantidade_item+'" name="tem'+quantidade_item+'" >'+
			'</p>'+
		'</td>'+
		
		'<td width="20%">'+
			'<p>'+  
				'Valor Unit: &nbsp;&nbsp;<input READONLY="READONLY"  name="valor_unitario'+quantidade_item+'" id="valor_unitario'+quantidade_item+'"  onKeyPress="Mascara(this,Din);" onKeyUp="Mascara(this,Din);" type="text" size="6" maxlength="10" />'+
			'</p>'+						
		'</td>'+
		
		'<td width="15%">'+
			'<p>'+  
				'Qtd: *&nbsp;&nbsp;'+
				'<select id="quantidade'+quantidade_item+'" name="quantidade'+quantidade_item+'" onchange="calcular_valor_total();calcule_o_frete(\'\');" >'+
				'</select>'+
			'</p>'+
		'</td>'+
		'<td width="10%">'+
			'<p>'+  
				'<input type="button" value="Excluir" id="excluir_item'+quantidade_item+'" name="excluir_item" onclick="excluir_item_l('+quantidade_item+');" >'+
			'</p>'+
		'</td>'+
	'</tr>');
	$.ajax(
		{
			type: "POST",
			url: "../produto/produto_exe.php",
			data: "action=buscar_produtos",
			beforeSend: function() {},
			success: function(txt) {
				jQuery('#id_produto'+quantidade_item).html(txt);
				
			},
			error: function(txt) {
				return txt;
			}
		}
	);
	
	calcule_o_frete("");
}

function buscar_produto_preco(ID_PRODUTO,INDICE){
	
	var existe = verificar_ja_existe(ID_PRODUTO,INDICE);
	
	if(existe==true){
		document.getElementById('id_produto'+INDICE).selectedIndex =0;
		alert("Produto ja existe na lista");
	}else{
		
		$.ajax(
		{
			type: "POST",
			url: "../produto/produto_exe.php",
		    data: "id_="+ID_PRODUTO+"&action=buscar_produto",
		    beforeSend: function() {},
			success: function(txt) {
				variaveis_json = eval("("+txt+")");
				
				if(variaveis_json.preco !=""){
					document.getElementById('valor_unitario'+INDICE).value = variaveis_json.preco;
				}else{
					document.getElementById('valor_unitario'+INDICE).value = "";
				}
				
				if(variaveis_json.quantidade !=""){
					
					jQuery('#quantidade'+INDICE).html("");
					
					var tamanho = document.getElementById('quantidade'+INDICE).value = variaveis_json.quantidade;
					var indice = 0 ;
					
					while(indice<=tamanho){
						jQuery('#quantidade'+INDICE).append("<option>"+indice+"</option>");
						indice++;
					}
				}else{
					document.getElementById('quantidade'+INDICE).selectedIndex =0;
				}
		    	
				calcular_valor_total();
				
		    },
			error: function(txt) {
				   alert(txt);
			}
		}
		);
		
		
	
	}
}




function mostar_div(CLIENTE_TIPO){
	
	if(CLIENTE_TIPO==1){
		mostar_cpf();
	}else if(CLIENTE_TIPO==2){
		mostar_cnpj();
	}else{
		$("#div_cpf").hide();
		$("#div_cnpj").hide();
	}
	
}

function mostar_cpf(){
	$("#div_cpf").show();
	$("#div_cnpj").hide();
}

function mostar_cnpj(){
	$("#div_cnpj").show();
	$("#div_cpf").hide();
}

function getEndereco2() {
	if($.trim($("#cep").val()) != ""){
			$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
					if(resultadoCEP["resultado"] && resultadoCEP["bairro"] != ""){
							$("#rua").val(unescape(resultadoCEP["logradouro"]));
							$("#bairro").val(unescape(resultadoCEP["bairro"]));
							$("#cidade").val(unescape(resultadoCEP["cidade"]));
							$("#uf").val(unescape(resultadoCEP["uf"]));
					}else{
							alert("Endereco nao encontrado");
							return false;
					}
			});                             
	}
    else
    {
        alert('Antes, preencha o campo CEP!');
	}
	
}

function getEndereco1() {
	if($.trim($("#cep").val()) != ""){
			$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
			if(resultadoCEP["resultado"] && resultadoCEP["bairro"] != ""){
					
			}else{
				alert("Endereco nao encontrado");
				document.getElementById('cep').value = "";
				return false;
			}
		});                             
	}
    else
    {
        alert('Antes, preencha o campo CEP!');
	}
	
}

function getEndereco() {
	if($.trim($("#cep").val()) != ""){
			$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
					if(resultadoCEP["resultado"] && resultadoCEP["bairro"] != ""){
							$("#rua").val(unescape(resultadoCEP["logradouro"]));
							$("#bairro").val(unescape(resultadoCEP["bairro"]));
							$("#cidade").val(unescape(resultadoCEP["cidade"]));
							$("#uf").val(unescape(resultadoCEP["uf"]));
							$("#numero").focus();
					}else{
							alert("Endereco nao encontrado");
							return false;
					}
			});                             
	}
    else
    {
        alert('Antes, preencha o campo CEP!');
	}
	
}

function redireciona_page(CAMINHO) {
	window.location=CAMINHO;
}


function blockui_abre(){
	$.blockUI({ overlayCSS: { backgroundColor: '#00466C' } }); 
}

function blockui_fecha(){
	$.unblockUI(); 
}

function trocar_pagina1(FORMULARIO,DIV){
	trocar_pagina($('#'+FORMULARIO.id).attr("action"),$('#'+FORMULARIO.id).serialize(),DIV);
	
	return false;
}

function enviar_formulario_confirm(FORMULARIO){
	
	var confimou = confirm('Deseja realmente realizar esta operacao?');

	if(confimou==true){
		enviar_formulario(FORMULARIO);
	}
	
	return false;
		
	
}

function enviar_formulario(FORMULARIO){
	$.blockUI({ overlayCSS: { backgroundColor: '#00466C' } }); 
	
	$.ajax(
			{
				type: "POST",
				url: $('#'+FORMULARIO.id).attr("action"),
				data: $('#'+FORMULARIO.id).serialize(),
				beforeSend: function() {},
				success: function(txt) {
					$.unblockUI(); 
					variaveis_json = eval("("+txt+")");
					
					if(variaveis_json.mensagem!=""){
						
						$.blockUI({ 
							overlayCSS: { 
								backgroundColor: '#00466C' 
							}, 
							message: '<div style="padding:10px;margin:0px;text-align : left;" ><h2 style="text-align : left;">'+variaveis_json.mensagem+'</h2></div><div style="padding:10px;margin:0px;text-align : center;" ><input type="button" value="   OK   " onclick="$.unblockUI();" ></div>'
						}); 
					}
					
					if(variaveis_json.exe_metodo==1){
						var metodo = variaveis_json.metodo;
						eval(metodo);
					}						
						
				},
				error: function(txt) {
					alert(txt);
				}
			}
	);

	return false;
}

function trocar_pagina(URL,DADOS,DIV){
		$('#'+DIV).animate({
			    opacity: 0
		}, 500, function() {
			carregar(URL,DADOS,DIV);
		});

}

function carregar(URL,DADOS,DIV){
	blockui_abre();
    $.ajax(
			{
				type: "POST",
				url: URL,
				data: DADOS,
				beforeSend: function() {},
				success: function(txt) {
					blockui_fecha();
					
					jQuery('#'+DIV).html(txt);
					
					$('#'+DIV).animate({
						    opacity: 100
					}, 500, function() {
						if(jQuery.browser.msie==true){
							 this.style.removeAttribute('filter'); 
						}	
					});					
					
				},
				error: function(txt) {}
			}
	);
}
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}


function horizontal() {
	 
	   var navItems = document.getElementById("menu_dropdown").getElementsByTagName("li");
	    
	   for (var i=0; i< navItems.length; i++) {
	      if(navItems[i].className == "submenu")
	      {
	         if(navItems[i].getElementsByTagName('ul')[0] != null)
	         {
	            navItems[i].onmouseover=function() {this.getElementsByTagName('ul')[0].style.display="block";this.style.backgroundColor = "#000000";}
	            navItems[i].onmouseout=function() {this.getElementsByTagName('ul')[0].style.display="none";this.style.backgroundColor = "#000000";}
	         }
	      }
	   }
	 
	}	

//GERAIS
function Trim(str){return str.replace(/^\s+|\s+$/g,"");}

function Mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function Hora(v){                
	v=v.replace(/\D/g,"")                 
	v=v.replace(/(\d{2})(\d)/,"$1:$2")                 
	v=v.replace(/(\d{2})(\d)/,"$1:$2")                 
	return v        
}

function Data(v){                
	v=v.replace(/\D/g,"")                 
	v=v.replace(/(\d{2})(\d)/,"$1/$2")                 
	v=v.replace(/(\d{2})(\d)/,"$1/$2")                 
	return v        
}

function Din(v){
    v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
    v=v.replace(/^([0-9]{3}\.?){3}-[0-9]{2}$/,"$1.$2");
    //v=v.replace(/(\d{3})(\d)/g,"$1,$2")
    v=v.replace(/(\d)(\d{2})$/,"$1.$2") //Coloca ponto antes dos 2 últimos digitos
    return v
}

function Integer(v){
    return v.replace(/\D/g,"")
}


function Cpf(v){
    v=v.replace(/\D/g,"")                    
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       
                                             
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") 
    return v
}

function Cnpj(v){
    v=v.replace(/\D/g,"")                   
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")     
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") 
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              
    return v
}

function pulacampo(idobj, idproximo)        
		{                
		var str = new String(document.getElementById(idobj).value);                
		var mx = new Number(document.getElementById(idobj).maxLength);                        
		
		if (str.length == mx)                {                        
			document.getElementById(idproximo).focus();                
		}        
		
}




