﻿function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num))
		num = "0";
		
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10)
		cents = "0" + cents;
		
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + ',' + cents);
}

function CalulaTotal()
{
	var totalItens = document.getElementById("ctl00_ContentPlaceHolder1_hdTotalItens").value;
	var totalFinal = 0;
	var precoFrete = 0;
	var totalFinalFrete = 0;
	
	document.getElementById("ctl00_ContentPlaceHolder1_hdQuantidades").value = "";
	
	for (i = 0; i < totalItens; i++)
	{
		
		//alert(i + " - " + totalItens);
		var quantidade = eval("document.getElementById('ctl00_ContentPlaceHolder1_dtlCarrinho_ctl0"+ i +"_txQuantidade').value");		
		var preco = eval("document.getElementById('ctl00_ContentPlaceHolder1_dtlCarrinho_ctl0"+ i +"_hdPreco').value");
		preco = preco.replace(/,/, ".");
		var total = preco*quantidade;
		
		eval("document.getElementById('ctl00_ContentPlaceHolder1_dtlCarrinho_ctl0"+ i +"_txTotalProduto').value = \""+ formatCurrency(total) +"\"");
		
		totalFinal = totalFinal + total;
		
		//ATUAliZA HIDDENFIELD COM TOTAL DE QUANTIDADES
		document.getElementById("ctl00_ContentPlaceHolder1_hdQuantidades").value += "qtd" + quantidade + "|";
	}
	
	document.getElementById("ctl00_ContentPlaceHolder1_hdTotalSemFrete").value = formatCurrency(totalFinal);
	
	//CHECA SE O FRETE JA FOI CALCULADO
	if (document.getElementById("ctl00_ContentPlaceHolder1_hdCustoFrete").value == 0)
	{
		//ATUALIZA TOTAL FINAL SEM O FRETE
		document.getElementById("ctl00_ContentPlaceHolder1_txTotalFinal").value = "R$ " + formatCurrency(totalFinal);
	}
	else
	{
		precoFrete = document.getElementById("ctl00_ContentPlaceHolder1_hdCustoFrete").value;
		document.getElementById("ctl00_ContentPlaceHolder1_txTotalFinal").value = "R$ " + formatCurrency(totalFinal) + " + R$ " + precoFrete + "(frete)";
	}
	
	//ATUALIZA TOTAL FINAL COM FRETE	
	totalFinalFrete = parseFloat(totalFinal) + parseFloat(precoFrete);
	
	document.getElementById("ctl00_ContentPlaceHolder1_hdTotalComFrete").value = formatCurrency(totalFinalFrete);
	document.getElementById("ctl00_ContentPlaceHolder1_txTotalFinalComFrete").value = "R$ " + formatCurrency(totalFinalFrete);
}

function OpenTrans(x)
{
	if (x== 1)
	{
		window.open("TransacaoVisa.aspx","mywindow");
	}
	else if (x == 2)
	{
		window.open("TransacaoMaster.aspx","mywindow");
	}
	else
	{
		window.open("TransacaoItau.aspx","mywindow");
	}
}
