function calculaAcessorio(id) {
	if(document.getElementById("produto_acessorio_" + id).checked == true){
		var qtde = document.getElementById("valor_" + id).value;
		if(isNaN(qtde) || qtde == 0){
			document.getElementById("valor_" + id).value = 1;
			document.getElementById('acessories_qtd[' + id + ']').value = 1;			
		}
		else{
			var qtdAtual = document.getElementById("valor_" + id).value;
			qtdAtual = parseInt(qtdAtual);
			document.getElementById('acessories_qtd[' + id + ']').value = qtdAtual;
		}
	}
	else {
		if(isNaN(document.getElementById("valor_" + id).value)){
			document.getElementById("valor_" + id).value = 1;
			document.getElementById('acessories_qtd[' + id + ']').value = 1;			
		}
		else {
			document.getElementById("valor_" + id).value = 0;
			document.getElementById('acessories_qtd[' + id + ']').value = 0;
		}	
	}
	calculaTotal();		
}

function calculaTotal() {
	//recalcula o total do carrinho com base nos acessorios atuais
	ids = $("#acessorios_ids").attr("value").split('.');
	var total = 0;
	for (var i = 0; i < ids.length; i++) {
		
		qtdAtual = parseInt($("#valor_" + ids[i]).attr("value"));
		precoAtual = converteInt($("#preco_" + ids[i]).attr("value")) * qtdAtual;
		total += precoAtual;
	}
	preco_produto = converteInt($("#preco_produto").attr("value")) + total;
	total = "R$" + addCommas(total);
	$("#total_preco").text(total);
	preco_produto = "R$" + addCommas(preco_produto);
	$("#total_preco_prod").text(preco_produto);
}

function limpaEventos(){
	if(document.getElementById('acessorios_ids')) {
		ids = $("#acessorios_ids").attr("value").split('.');
		for (var i = 0; i < ids.length; i++) {
			$("#valor_" + ids[i]).unbind();
		}
	}
}

//////////////////////
//conversores de unidade
function converteInt(valor) {
	//pega valores como string, com separador de dezena e converte para int para calculos
	var dec = valor.charAt(valor.length-2);
	dec = dec + valor.charAt(valor.length-1);
	valor = parseInt(valor) * 100;
	valor = valor + parseInt(dec);
	valor = valor/100;
	return valor;
}
function addCommas(nStr) {
//adiciona virgulas no lugar de ponto
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	if (x.length > 1) {
		var x2 = ',' + x[1];
		if (x2.length < 3) {
			x2 = x2 + 0;
		}
		if (x2.length > 3) {
			x2 = x2.slice(0,3);
		}
	}
	else {
		var x2 = ',00';
	}
	return x1 + x2;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

$(document).ready(function() {
	limpaEventos();
});

