var total;

function formatPrice($price) {
	$price = Math.round($price * 100) / 100;
	$price = String($price);
	if($price.indexOf(".") < 0) {
		$price += ".";
	}
	while($price.indexOf(".") > $price.length - 3) {
		$price += "0";
	}
	return $price;
}

function validateKey($field, $price) {
	var $value = "";
	var $valid = true;
	var $decimal = false;
	var $decimals = 2;
	for(var $i = 0; $i < $field.value.length; $i ++) {
		var $character = $field.value.charAt($i);
		if(/^\d$/.test($character) && $decimals) {
			$value += $character;
			if($decimal) $decimals --;
		} else {
			if(!$decimal && $character == "." && $price) {
				if(!$i) {
					$value += "0";
					$valid = false;
				}
				$value += $character;
				$decimal = true;
			} else {
				$valid = false;
			}
		}
	}
	if(!$valid) $field.value = $value;
}

function validateFocus($field) {
	if(/^[0.]*$/.test($field.value)) $field.value = "";
}

function validateBlur($field, $price) {
	validateKey($field, $price);
	while($field.value.charAt(0) == "0") $field.value = $field.value.substring(1);
	if(/^[0.]*$/.test($field.value)) $field.value = "0";
	if($price) $field.value = formatPrice($field.value);
}

function addItem($id) {
	$quantity = parseInt(document.form["quantity" + $id].value);
	if($quantity) {
		document.cart.product.value = $id;
		document.cart.quantity.value = $quantity;
		document.cart.submit();
	}
}

function updateTotals() {
	var $postage = false;
	var $items = 0;
	var $subtotal = 0;
	for(var $i = 0; $i < items.length; $i ++) {
		var $id = items[$i];
		var $input = document.form["_" + $id];
		var $quantity = $input.value;
		var $price = $quantity * $input.getAttribute("price");
		var $_price = document.getElementById("total" + $id);
		$_price.innerHTML = "$" + formatPrice($price);
		if($quantity && parseInt($input.getAttribute("postage"))) $postage = true;
		$items += $quantity;
		$subtotal += $price;
	}
	var $shipping = $postage ? 10 : Math.min($items * 5, 10);
	var $registered = document.form.regpost.checked ? 3 : 0;
	var $total = $subtotal + $shipping + $registered;
	var $_subtotal = document.getElementById("subtotal");
	var $_shipping = document.getElementById("shipping");
	var $_registered = document.getElementById("registered");
	var $_total = document.getElementById("total");
	$_subtotal.innerHTML = "$" + formatPrice($subtotal);
	$_shipping.innerHTML = "$" + formatPrice($shipping);
	$_registered.innerHTML = "$" + formatPrice($registered);
	$_total.innerHTML = "$" + formatPrice($total);
	total = $total;
}