$(function() {
	$("#cart tr .remove input").click(function() {
		var orderCode = $(this).val();
		$.ajax({
			type: "GET",
			url: "cart_action.php",
			data: "remove[]=" + orderCode,
			success: function() {
				$("#cart tr .remove input[value=" + orderCode + "]").parent().parent().fadeOut(500, function() {
					$(this).remove();
					calcPrice();
				});
			},
			error: function() {
				window.location("cart_action.php?remove[]="+orderCode);
			}
		});
	});

	$("#cart tr .quantity input").change(function() {
		var orderCode = $(this).attr("name").slice(9, -1);
		var quantity = $(this).val();
		$.ajax({
			type: "GET",
			url: "cart_action.php",
			data: "quantity[" + orderCode + "]=" + quantity,
			success: function() {
				var startColor = $("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().hasClass("odd") ? "#eee" : "#fff";
				calcPrice();
				$("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().find("td").animate({ backgroundColor: "#ff8" }, 100).animate({ backgroundColor: startColor }, 800);
			},
			error: function() {
				window.location("cart_action.php?quantity[" + orderCode + "]=" + quantity);
			}
		});
	});
});
function number_format (number, decimals, dec_point, thousands_sep) {
	// Formats a number with grouped thousands
	//
	// version: 906.1806
	// discuss at: http://phpjs.org/functions/number_format
	var n = number, prec = decimals;

	var toFixedFix = function (n,prec) {
		var k = Math.pow(10,prec);
		return (Math.round(n*k)/k).toString();
	};

	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) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

	var abs = toFixedFix(Math.abs(n), 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);
	}

	var decPos = s.indexOf(dec);
	if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
		s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
	}
	else if (prec >= 1 && decPos === -1) {
		s += dec+new Array(prec).join(0)+'0';
	}
	return s;
}

function calcPrice() {
	var totalPrice = 0;
	$("#cart tr .quantity").parent().each(function() {
		var quantity = $(".quantity input", this).val();
		var unitPrice = $(".unit_price", this).text().slice(0);
		var extendedPrice = quantity*unitPrice;
		totalPrice += extendedPrice;

		$(".unit_price", this).html("" + unitPrice);
		$(".extended_price", this).html("" + extendedPrice.toFixed(2));
		$("#total_price").html("R$ <b>" + number_format(totalPrice.toFixed(2), 2, ',', '.')+"</b>");
	});
	if ( totalPrice == 0 ) {
		$("#cart").parent().replaceWith("<p class='center'>Carrinho vazio</p>");
	}
}
function so_numero(field){
	field.value = field.value.replace(/[^0-9.]/g,'');
}

function soma_quantidade(field){
	document.getElementById(''+field+'').value = parseInt(document.getElementById(''+field+'').value)+1;
	document.frm.submit();
}
function subtrai_quantidade(field){
	document.getElementById(''+field+'').value = parseInt(document.getElementById(''+field+'').value)-1;
	document.frm.submit();
}
function atualiza_quantidade(field){
	if(document.getElementById(''+field+'').value != document.getElementById('x'+field+'').value){
		document.getElementById('update').style.display = 'none';
		document.getElementById('carregando_atualizar').style.display = 'block';
		document.getElementById(''+field+'').style.background = 'url(/img/loading.gif)';
		document.getElementById(''+field+'').style.backgroundPosition = 'center';
		document.getElementById(''+field+'').style.backgroundRepeat = 'no-repeat';
		document.getElementById(''+field+'').style.backgroundColor = '#FFFFFF';
		document.frm.submit();
	}
}
function trim(v){
	// Passa o valor ou objeto recebido pela função para uma variável temporária,
	// pois se for objeto, a variável "v" só poderá ser alterada no final da função.
	var x = v
	// Cria uma varíavel temporária com o valor recebido convertido para string em minúsculas.
	// Essa variável será usada para testar se o valor recebido é uma string ou um objeto.
	var test = v.toString().toLowerCase()
	// Verifica se o valor recebido é um objeto
	if(test.indexOf("object") == 1){
		// Se v é um objeto, x recebe o valor do objeto v.
		x = v.value
	}
	// Enquanto o primeiro caractere de x (que tem índice 0) for espaço em branco,
	// x receberá um novo valor, que será o valor anterior sem o primeiro caractere.
	while(x.charAt(0) == " "){
		x = x.substr(1,x.length - 1)
	}
	// Enquanto o último caractere de x (onde o índice é definido pela quantidade de
	// carateres de x menos um) for espaço em branco, x receberá um novo valor, que
	// será o valor anterior sem o último caractere.
	while(x.charAt(x.length - 1) == " "){
		x = x.substr(0,x.length-1)
	}
	// Se o valor recebido é um objeto, o objeto recebe o valor de x, sem espaços
	// em branco à direita e à esquerda.
	if(test.indexOf("object") == 1){
		v.value = x
	} else {
		// Se não for objeto, a função retorna o valor de x sem espaços
		// em branco à direita e à esquerda.
		return x
	}
}
