

function round2(x)
{
	return Math.round(x*100)/100.00;
}

function discount_percentage(discountable_total, eff_total, n)
{
	if (n>1 || added_total > 0 && n == 1) {
		var dp = Math.min(eff_total / target_spend, max_discount);
		if (dp * eff_total / discountable_total > max_discount){
			return max_discount * discountable_total / eff_total;
		}else{ 
			return dp;
		}
	}else { return 0; }
}

// globals effective_total and n_items should be set before this func is called
function disc_price(price) 
{
	var new_n_items = (price > 0) ? (n_items + 1) : (n_items - 1);

	return (1 - discount_percentage(discountable_total + price, effective_total + price, new_n_items)) * 
			(effective_total+price)	- (1 - discount_percentage(discountable_total, effective_total, n_items)) *
			effective_total;
}

function get_remaining_percentage(discountable_total, added_total, n_items)
{
	effective_total = added_total + discountable_total;

	if (n_items > 1 || added_total > 0 && n_items == 1){
		eff_percentage = Math.max(1 - effective_total / target_spend, 1 - max_discount);
		discount_value = (1 - eff_percentage) * effective_total;
		percentage = (discountable_total - discount_value) / discountable_total;
		
		if (percentage < 1 - max_discount) {
			percentage = 1 - max_discount;
		}
		return percentage;
	}else{
		return 1;
	}
}

function format2dp(num) 
{
	var tempNum = Math.round(parseFloat(num) * 100).toString()
	tempNum = '000'.substr(0, (tempNum.length < 3) ? 3 - tempNum.length : 0) + tempNum;
	tempNum = tempNum.replace(/(\d*)(\d\d)/, '$1.$2');
	return tempNum.replace(/(\d*\d)(\d\d\d\.\d\d)/, '$1,$2');
}
