/*!
 * Js do portal Amazon Color
 *
 * Copyright 2010, Jônatan Fróes
 *
 */
$(document).ready(function() {
	
	$("a[rel^='prettyPhoto']").prettyPhoto({
		hideflash: true
	});
	
	
	$("a[rel=external]").attr('target', '_blank');
	
	$(".ajax_form").submit(function(){
		var alvo = $('#resultado');
		$(alvo).empty().append('processando').show();
		$.ajax({
			url: $(this).attr('action'),
			type: 'POST',
			data: $(this).serialize(),
			
			success: function(result) {
				$(alvo).empty().append(result);
			}
		});		
		return false;
	});
	
	
	$('#resultado').click(function() {
		$(this).hide();
	});
	
   // formata moeada
	$(".real").priceFormat({
		prefix: '',
		centsSeparator: ',',
		thousandsSeparator: '.'
	});
	//taxas
	$(".taxas").priceFormat({
		prefix: '',
		centsSeparator: ',',
		thousandsSeparator: ''
	});
	
	//formata outros campos
	$(".datas").mask("99/99/9999");
	$(".cnpj").mask("99.999.999/9999-99");
	$(".mask_cpf").mask("999.999.999-99");
	$(".cep").mask("99.999-999");
	$(".horario").mask("99:99");
	$(".fone").mask("(99) 9999-9999");
	$(".inteiro").mask("99");
	
	var quantidade;
	var frete;
	var preco_atual;
	var preco_total;
	var cep;
	var peso;
	
	$('#hidden_result_ajax').click(function() { $(this).hide(); });




	//atualiza valor dos produtos no carrinho e frete
	$('#cep-carrinho, #quantidade-carrinho').blur(function() {
		quantidade = $('#quantidade-carrinho').val();
		peso = $('#peso-item').val();
		$('#hidden_result_ajax').show();

		if( quantidade >= 1) {
			//atualiza subtotal
			preco_atual = tira_virg($('#preco-carrinho').text() ) * quantidade;
			$('#subtotal-carrinho').text( number_format(preco_atual, 2, ',', '.') );
			
			//calcula o cep
			cep = $('#cep-carrinho').val();
			
			if(cep == '')
				cep = '00.000-000';
			$.ajax({
				url: 'seja_um_distribuidor/calcula_cep/' + cep + '/' + quantidade + '/' + peso,
				type: 'POST',
				data: 'cep=' + cep + '&quantidade=' + quantidade + '&peso=' + peso,
					
				success: function(result) {
					frete = result;
					$('#frete-carrinho').text( number_format(frete, 2, ',', '.') );
					$('#input_cep').val(frete);
					preco_total = parseFloat(preco_atual) + parseFloat(frete);
					$('#total-carrinho').text( number_format(preco_total, 2, ',', '.') );
					$('#cep').val(cep);
					$('#hidden_result_ajax').hide();
				}
			});
		} else
			alert('informe uma quantidade válida');

		return false;
	});
/*	$('#recalcular_frete').click(function() {
		cep = $('#cep-carrinho').val();
		quantidade = $('#quantidade-carrinho').val();
		peso = $('#peso-item').val();
		
		if(quantidade > 0) {
			if(cep == '') {
				cep = '00.000-000';
				alert('CEP Inválido');
			} else {
				$.ajax({
					url: 'calcula_cep/' + cep + '/' + quantidade + '/' + peso,
					type: 'POST',
					data: 'cep=' + cep + '&quantidade=' + quantidade + '&peso=' + peso,
						
					success: function(result) {
						if(result == 0)
							alert('CEP Inválido');
					}
				});
			}
		}
	});
*/








/*
	
	//atualiza valor dos produtos no carrinho
	$('#recalcular_vl').click(function() {
		quantidade = $('#quantidade-carrinho').val();
//		frete = tira_virg( $('#frete-carrinho').text() ) * 1;
		if( quantidade >= 1) {			
			preco_atual = tira_virg($('#preco-carrinho').text() ) * quantidade;
			$('#subtotal-carrinho').text( number_format(preco_atual, 2, ',', '.') );
			
			cep = $('#cep-carrinho').val();
			frete = vl_frete(cep, quantidade);
			
			preco_total = parseFloat(preco_atual) + parseFloat(frete);
			$('#total-carrinho').text( number_format(preco_total, 2, ',', '.') );
			
		} else
			alert('informe uma quantidade válida');

		return false;
	});
	
	// atualiza o valor do frete
	$('#recalcular_frete').click(function() {
		cep = $('#cep-carrinho').val();
		quantidade = $('#quantidade-carrinho').val();
		frete = vl_frete(cep, quantidade);
		if(frete == 0)
			alert('CEP Inválido');
		else {
			quantidade = $('#quantidade-carrinho').val();
			if( quantidade >= 1) {
				preco_atual = tira_virg($('#preco-carrinho').text() ) * quantidade;
				preco_total = parseFloat(preco_atual) + parseFloat(result);
				
				$('#frete-carrinho').text( number_format(result, 2, ',', '.') );
				$('#total-carrinho').text( number_format(preco_total, 2, ',', '.') );
			} else
				alert('informe uma quantidade válida');
		}
		return false;
	});
*/	
	$('#carrinho_form').submit(function() {
		
		//verifica quantidade e frete
		quantidade = $('#quantidade').val();
		frete = Number($('#frete-carrinho').text());
		
		if(quantidade < 1) {
			alert('informe uma quantidade válida');
			$(quantidade).focus();
			return false;
		}
		if(frete < 1) {
			alert('Calcule o cep primeiro');
			$('#cep-carrinho').focus();
			return false;
		}
		
		//verifica o meio de pagamento
		var forma_pgt = $("input[type=radio][name=forma_pgto]:checked").val();
		if( ! forma_pgt ) {
			alert('Selecione o meio de pagamento');
			return false;
		}

	});
	
/*	
	
		  $(function() {
			$('#submit').click(function() {
			$('#container').append('<img src="img/loading.gif" alt="Currently Loading" id="loading" />');
			
				var name = $('#name').val();
				var email = $('#email').val();
				var comments = $('#comments').val();
				
				$.ajax({
					url: 'submit_to_db.php',
					type: 'POST',
					data: 'name=' + name + '&email=' + email + '&comments=' + comments,
					
					success: function(result) {
						$('#response').remove();
						$('#container').append('<p id="response">' + result + '</p>');
						$('#loading').fadeOut(500, function() {
							$(this).remove();
						});
						
					}
				});
				
				return false;
			});
			
		  });
*/
	
});
Cufon.replace('h2, h3, h4');

//frete
function vl_frete(cep, quantidade)
{
	var resultado_frete;
	if(cep == '')
		cep = '00.000-000';
	$.ajax({
		url: 'calcula_cep/',
		type: 'POST',
		data: 'cep=' + cep + '&quantidade=' + quantidade,
			
		success: function(result) {
			alert('completo');
			return result;
		}
	});
}

// mascara js
function formatar(src, mask) {
	var i = src.value.length;
	var saida = mask.substring(0,1);
	var texto = mask.substring(i);
	if (texto.substring(0,1) != saida)
		src.value += texto.substring(0,1);
}

function tira_virg(valor)
{
	return valor = valor.replace(',','.') ;
}
function tira_ponto(valor)
{
	return valor = valor.replace('.',',') ;
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
