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 validateKeyUp($field, $price) {
	var $value = "",
		$valid = true,
		$decimal = false,
		$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) {
	validateKeyUp($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);
}

var items = [],
	packaging = 'default',
	discount = 0,
	shipping = 0,
	shipoptions = {},
	shipoption = "STD",
	voucher = "",
	currency = "",
	symbol = "",
	quantity = 0,
	total = 0,
	cups = 0;

function updateTotals() {
	var $item_count = 0,
		$shipping_count = 0,
		$subtotal = 0,
		$max_price = 0,
		$max_input = null,
		$max_total = null;
	for(var $i = 0; $i < items.length; $i ++) {
		var $id = items[$i],
			$input = document.form["_" + $id],
			$quantity = parseInt($input.value);
		if(!$quantity) $quantity = 0;
		var $price = $quantity * parseFloat($input.getAttribute("price"));
		var $_price = document.getElementById("total" + $id);
		$_price.innerHTML = symbol + formatPrice($price);
		$item_count += $quantity;
		if(parseInt($input.getAttribute("shipping"))) {
			$shipping_count += $quantity;
			if($quantity > 0 && parseFloat($input.getAttribute("price")) > $max_price) {
				$max_price = parseFloat($input.getAttribute("price"));
				$max_input = $input;
				$max_total = $_price;
			}
		}
		$subtotal += $price;
	}
	var $discount = $subtotal * (discount / 100);
	var $shipping_reduction = 0.02; // 2%
	var $ship_fixedfee = parseFloat(shipoptions[shipoption]['fixedfee']);
	var $ship_peritem = parseFloat(shipoptions[shipoption]['peritem']);
	var $shipping = ($shipping_count == 0) ? 0 : Math.max($ship_fixedfee + ($shipping_count * ($ship_peritem - ($ship_peritem * (($shipping_count-1) * $shipping_reduction)))), $ship_fixedfee + $ship_peritem);
	if(voucher) {
		$('.product_details').removeClass('voucher');
		if($max_input) {
			$price = Math.max((parseFloat($max_input.value) - 1) * $max_price, 0);
			$max_total.innerHTML = symbol + formatPrice($price);
			$shipping = Math.max($shipping - (parseFloat(shipoptions['STD']['fixedfee']) + parseFloat(shipoptions['STD']['peritem'])), 0);
			$subtotal = Math.max($subtotal - $max_price, 0);
			$($max_input).parents('tr:first').find('.product_details').addClass('voucher');
		}
	}
	if(currency == 'YEN') $shipping = Math.round($shipping);
	if(shipping) $shipping = 0;
	var $total = $subtotal - $discount + $shipping,
		$_subtotal = document.getElementById("subtotal"),
		$_discount = document.getElementById("discount"),
		$_shipping = document.getElementById("shipping"),
		$_shipping_label = document.getElementById("shipping_label"),
		$_total = document.getElementById("total");
	$_subtotal.innerHTML = symbol + formatPrice($subtotal);
	if($_discount) $_discount.innerHTML = "-" + symbol + formatPrice($discount);
	$_shipping.innerHTML = symbol + formatPrice($shipping);
	if($shipping > 0) $_shipping_label.innerHTML = 'Shipping (' + shipoptions[shipoption]['label'] + ')';
	else $_shipping_label.innerHTML = 'Shipping';
	$_total.innerHTML = symbol + formatPrice($total);

	if($shipping_count == 0) {
		document.getElementById("shipping_box_content").style.display = 'none';
		document.getElementById("packaging").style.display = 'none';
	} else {
		document.getElementById("shipping_box_content").style.display = 'block';
		document.getElementById("packaging").style.display = 'block';
	}

	// show/hide paypal if total is zero
	if($total == 0) $('#or').hide().next().hide();
	else $('#or').show().next().show();

	quantity = $item_count;
	total = $total;
	cups = $shipping_count;
}

function updateCart() {
	var $vars = [];
	for(var $i = 0; $i < items.length; $i ++) {
		var $id = items[$i];
		$vars.push("_" + $id + "=" + document.form["_" + $id].value);
	}
	$vars.push('packaging=' + packaging);
	$vars.push('shipoption=' + shipoption);
	$vars.push('total=' + total);
	$vars = $vars.join("&");
	ajax("/store/updatecart.php", true, $vars, null, true);
}

function cleanWhitespace($node) {
	for(var $i = 0; $i < $node.childNodes.length; $i++) {
		var $childNode = $node.childNodes[$i];
		if($childNode.nodeType == 3 && /^[\s]*$/.test($childNode.nodeValue)) {
			$node.removeChild($node.childNodes[$i]);
			$i --;
		}
		if($childNode.nodeType == 1) {
			cleanWhitespace($childNode);
		}
	}
}

function encode($string) {
	var chars = [
		{search: "&",	replace: "&amp;"},
		{search: '"',	replace: "&quot;"},
		{search: "<",	replace: "&lt;"},
		{search: ">",	replace: "&gt;"}
	];
	for(var $i = 0; $i < chars.length; $i ++) {
		var $char = chars[$i];
		$string = $string.replace($char.search, $char.replace);
	}
	return $string;
}

function decode($string) {
	$string = $string.replace(/\+/g, " ");
    $string = unescape($string);
	return $string;
}
