var previousRate = 1;

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function updatePriceFields(newRate) {
	$(".price-field").each(function(i) {
		$(this).find("option").each(function(j) {
			var currentVal = $(this).val();
			if (currentVal != "" && currentVal != 0) {
				var currentValInDollars = currentVal / previousRate;
				$(this).val(currentValInDollars * newRate);
				$(this).text(addCommas((currentValInDollars * newRate).toFixed(0)));
			}
		});
	});
	
	previousRate = newRate;
}

$(document).ready(function() {
	$(".currency-select").bind("change keyup", function(e) {
		var rate = Math.pow(10, Math.round(Math.log($(this).val().split('|')[1])/Math.log(10)));
		updatePriceFields(rate);
	});
	$(".currency-select").each(function(i) {
		var rate = Math.pow(10, Math.round(Math.log($(this).val().split('|')[1])/Math.log(10)));
		updatePriceFields(rate);
	});
});
