// JavaScript Document
function adicionar_produto(CD_PRODUTO)
{	
	$.ajax({
		url: "carrinho.php",
		type: 'post',
		cache: false,
		data: {acao: 'adicionarProduto', CD_PRODUTO: CD_PRODUTO},
		dataType: 'json',
		success: function(retorno)
		{
			if (retorno.valido == 1){
				window.location = 'carrinho.php';
			} else {
				//$("#retorno").html(retorno.msg);
				mostra_erro(retorno.msg);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
		}
	});	
}

function remover_produto(CD_PRODUTO)
{
	if (confirm('Tem certeza de que deseja remover esse produto de seu carrinho?'))
	{
		$.ajax({
			url: "carrinho.php",
			type: 'post',
			cache: false,
			data: {acao: 'removerProduto', CD_PRODUTO: CD_PRODUTO},
			dataType: 'json',
			success: function(retorno)
			{
				if (retorno.valido)
				{
					window.location = 'carrinho.php';
				}
				else
				{
					alert(retorno.msg);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				//alert(textStatus);
			}
		});	
	}
}

function atualiza_quantidade_produto(CD_PRODUTO, obj)
{
	var num = parseInt(obj.val());
	if (!num){
		$("#div_erro_cadastro").html('');
		mostra_erro('Digite uma quantidade maior que 0 (zero).');
		obj.val('1');
		obj.focus();
	}
	
	$.ajax({
		url: "carrinho.php",
		type: 'post',
		cache: false,
		data: {acao: 'atualiza_quantidade_produto', CD_PRODUTO: CD_PRODUTO, NM_QUANTIDADE: num},
		dataType: 'json',
		success: function(retorno)
		{
			if (retorno.valido)
			{
				
				atualizar_total();
				
			}else{
				
				$("#div_erro_cadastro").html('');
				mostra_erro(decode(retorno.msg));
				$("#NM_QUANTIDADE_"+retorno.cd_produto).val(retorno.qtd);
				
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			//alert(textStatus);
		}
	});	
}

function calcula_frete(acao_carrinho, cep_destino)
{
	$("#div_frete_entrega").html("Aguarde ...");
	$("#div_endereco_entrega").html("");
	if(cep_destino.length == 8)
	{
		$.ajax({
			url: "carrinho.php",
			type: 'post',
			cache: false,
			data: {acao: 'calcula_frete', cep_destino: cep_destino, acao_carrinho: acao_carrinho},
			dataType: 'json',
			success: function(retorno)
			{
				// cep frete
				$("#div_frete_entrega").html(decode(retorno.html_frete));
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				$("#div_frete_entrega").html("Ocorreu um erro durante o cálculo do frete. Recarregue a página.");
			}
		});	
	} 
	else 
	{
		$("#CEP1").val('');
		$("#CEP2").val('');
	}
}

function novo_endereco(cep_destino)
{
	$("#div_endereco_entrega").html("Carregando novo endereco...");
		
	if (cep_destino.length == 8){
		$.ajax({
			url: "carrinho.php",
			type: 'post',
			cache: false,
			data: {acao: 'calcula_frete_endereco', cep_destino: cep_destino},
			dataType: 'json',
			success: function(retorno)
			{
				$("#div_endereco_entrega").html(decode(retorno.html_endereco_entrega));
			}
		});	
	}
} 

function limpar_carrinho()
{
	if (confirm('Tem certeza de que deseja limpar seu carrinho?'))
	{
		$.ajax({
			url: "carrinho.php",
			type: 'post',
			cache: false,
			data: {acao: 'limpar_carrinho'},
			dataType: 'html',
			success: function(retorno)
			{
				window.location = 'carrinho.php';
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				//alert(textStatus);
			}
		});	
	}
}

function finalizar_compra() 
{
	if (valor_total_carrinho > 0)
	{
		window.location = '?acao=fechar_pedido';
	}
	else
	{
		mostra_erro("Carrinho vazio");
	}
}

function atualizar_total()
{
	$.ajax({
		url: "carrinho.php",
		type: 'post',
		cache: false,
		data: {acao: 'calcula_total'},
		dataType: 'json',
		success: function(retorno)
		{
			//var vlr = retorno.toFixed(2).replace('.', ',');
			var vlr = number_format(retorno, 2, ',', '.');
			$("#valor_total_carrinho").html("R$ "+vlr);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			//alert(textStatus);
		}
	});
}


function concluir_compra()
{
	if($("input[name='VL_FRETE_ENTREGA']:checked").val()){
		mostra_mensagem('Aguarde. Enviando formulario.');
		$("#frm_concluir").submit();
	} else {
		mostra_erro('Selecione a forma de entrega.');
	}
}

function presente(CD_PRODUTO, obj)
{
	var vlr = Number();
	if(obj.attr('checked')){
		vlr = 1;
	} else {
		vlr = 0;
	}
	
	$.ajax({
		url: "carrinho.php",
		type: 'post',
		cache: false,
		data: {acao: 'atualiza_presente', CD_PRODUTO: CD_PRODUTO, vlr_presente: vlr},
		dataType: 'json',
		success: function(retorno)
		{	
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			//alert(textStatus);
		}
	});	
}

function alterar_endereco(obj)
{
	$("#valor_frete").html('R$ --,--');
	$("#entrega_escolhida").val('');	
	$("#vlr_entrega_escolhida").val('');
	
	atualizar_total();
	
	if(obj.val() == 'atual'){
		$("#td_forma").css('padding-top', '0px');
		$("#CEP1").val('');
		$("#CEP1").attr('disabled', 'disabled');
		$("#CEP2").val('');
		$("#CEP2").attr('disabled', 'disabled');
		
		$("#div_endereco_entrega").html('');
		cep = cep.replace('-', '');
		cep = cep.replace('.', '');
		calcula_frete('fechar', cep);
	} else {
		$("#td_forma").css('padding-top', '100px');
		$("#CEP1").attr('disabled', '');
		$("#CEP2").attr('disabled', '');
	}
}

function finalizar_pedido()
{
	$("#retorno_pedido").html('<center>Aguarde enquanto processamos o pedido...</center>');
	$.ajax({
	url: "carrinho.php",
	type: 'post',
	cache: false,
	data: {acao: 'salvar_pedido'},
	dataType: 'json',
	success: function(retorno)
	{	
		var html = "";
		//html += 'Pedido efetuado com sucesso.<br />';
		html += 'Aguarde enquanto carregamos a pop-up com a forma de pagamento desejada, ou clique em <br />';
		html += '<span style="color:#F00;">PROSSEGUIR COM O PAGAMENTO</span> caso você tenha bloqueador de pop-up! <br /><br />';
		html += '<a href="javascript:void(0);" onclick="$(\'#frm_pgto\').submit();">';
		html += '<img src="img/btn_prosseguir_pagamento.jpg" border="0">';
		html += '</a>';
		
		$("#retorno_pedido").html('').append(html);
		
		$('#frm_pgto').submit();
		
	},
	error: function(XMLHttpRequest, textStatus, errorThrown)
	{
		//alert(textStatus);
	}
});	
}

function abre_form()
{
	
	mpg_popup = window.open("", "mpg_popup","toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,screenX=0,screenY=0,left=0,top=0,width=" + $(window).width() + ",height=" + $(window).height());
	
}

function atualiza_total_fechado()
{
	var parcelas = $("#NM_PARCELAS").val();
	var vlr = $("input[name='VL_FRETE_ENTREGA']:checked").val();//adquirindo o INDICE do vetor de frete
	var forma = $("input[name='VL_FRETE_ENTREGA']:checked").attr('alt');
	$.ajax({
		url: "carrinho.php",
		type: 'post',
		cache: false,
		data: {
			acao: 'calcula_total_fechado', 
			indice_frete: vlr, 
			NM_PARCELAS:parcelas
		},
		dataType: 'json',
		success: function(retorno)
		{
			if (retorno.valor_frete) {
				$("#valor_frete").html("R$ " + retorno.valor_frete);
			}
			if(retorno.desconto == '1') {
				$("#lbl_desconto").show();
			} else {
				$("#lbl_desconto").hide();
			}
			$("#subtotal").html("R$ "+(retorno.subtotal));
			$("#valor_total_carrinho").html("R$ "+retorno.total);
			$("#entrega_escolhida").val(retorno.forma_frete);
			$("#vlr_entrega_escolhida").val(retorno.valor_frete);
		}
	});	
}

function fechaParcelas()
{
	$("#NM_PARCELAS").val('1');
	$("#NM_PARCELAS").attr('disabled', true);
	atualiza_total_fechado();
}
function abreParcelas()
{
	$("#NM_PARCELAS").attr('disabled', false);
}


function validaCPF_ajax(cpf)
{
	$.ajax({
		url: "minha_conta.php",
		type: 'post',
		cache: false,
		data: {
			acao: 'valida_cpf', 
			cpf: cpf
		},
		dataType: 'json',
		success: function(retorno)
		{
			if(retorno.ok){
				$("#div_erro_cpf").html('');
				$("#DS_CPF").removeClass('erro');
			} else {
				$("#div_erro_cpf").html(retorno.erro);
				$("#DS_CPF").val('');
				$("#DS_CPF").addClass('erro');
			}
		}
	});	
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // %        nota 1: Para 1000.55 retorna com precisão 1 no FF/Opera é 1,000.5, mas no IE é 1,000.6
    // *     exemplo 1: number_format(1234.56);
    // *     retorno 1: '1,235'
    // *     exemplo 2: number_format(1234.56, 2, ',', ' ');
    // *     retorno 2: '1 234,56'
    // *     exemplo 3: number_format(1234.5678, 2, '.', '');
    // *     retorno 3: '1234.57'
    // *     exemplo 4: number_format(67, 2, ',', '.');
    // *     retorno 4: '67,00'
    // *     exemplo 5: number_format(1000);
    // *     retorno 5: '1,000'
    // *     exemplo 6: number_format(67.311, 2);
    // *     retorno 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}

