$(function() {
	$('#cart_update').remove();
	$('input.quantity').each(function() {
		$(this).before('<img src="' + STATIC + 'icons/16x16/remove.png" class="clickable q_down" />')
		.after('<img src="' + STATIC + 'icons/16x16/add.png" class="clickable q_up" />');
	});
	$('.q_down').click(function() {
		var q = $(this).next()
		q.val(Number(q.val()) - 1);
		q.keyup();
	});
	$('.q_up').click(function() {
		var q = $(this).prev()
		q.val(Number(q.val()) + 1);
		q.keyup();
	});
	$('input.quantity').keyup(function() {
		var o = $(this);
		var item = $(this).attr('id').split('-')[1];
		var quantity = $(this).val();
		loading('Updating quantity...');
		$.ajax({
			url: '/cart/',
			type: 'POST',
			data: {'update_item': item, 'quantity': quantity, 'milk_token': milk_token},
			success: function(ret) {
				var item_q = Number(ret.split('|')[0]);
				var item_t = ret.split('|')[1];
				var total_q = Number(ret.split('|')[2]);
				var total_t = ret.split('|')[3];
				update_minicart(total_q);
				if (total_q == 0) {
					$('#cart_form').slideUp('normal', function() {
						o.parents('li').remove();
						$('#cart_empty').slideDown();
					});
				} else {
					if (item_q == 0) {
						o.parents('li').slideUp('slow', function() {
							o.parents('li').remove();
						});
					} else {
						o.parent().siblings('span.total').fadeOut('normal', function() {
							$(this).empty().append('$' + item_t).fadeIn('normal');
						});
					}
					$('#cart_total').fadeOut('normal', function() {
						$(this).empty().append('Total: $' + total_t).fadeIn('normal');
					});
				}
				done('Quantity updated');
			},
			error: function() {
				done("We're really sorry, there was a problem updating the quantity of your item");
			}
		});
		return false;
	});
});

function refreshTotal() {
	var xmlhttp = getReqObject();
	ct = document.getElementById('cart_total');
	cf = document.getElementById('cart_form');
	cen = document.getElementById('cart_empty_notice');
	if (!ct || !cf || !cen || ! xmlhttp) {
		return true;
	}
	xmlhttp.open("GET", "/js?refresh_total=1", true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.responseText.substr(0, 2) == "OK") {
				bits = xmlhttp.responseText.split('-');
				ct.innerHTML = 'Total: $'+String(Number(bits[1]).toFixed(2));
			} else {
				cf.style.display = 'none';
				cen.style.display = 'block';
				emptyButton.style.display = 'none'
				checkoutButton.style.display = 'none'
			}
		}
	}
}
function empty_cart() {
}
