function updateCart(cart) {
	updateMiniCart( null, cart.itemCount, cart.total )
}

function updateMiniCart(item, totalItems, cartTotal) {
	setSpanValue('items-in-cart', totalItems);
	setSpanValue('items-label', (totalItems  == 1) ? "item" : "items");
	setSpanValue('items-in-cart-label', totalItems);
	setSpanValue('cart-total', '$' + cartTotal);
	
	if (item) {
		$("#item-preview").show();
		$('#cart-item-name').text(item.name + " (" + item.quantity + ")");
		$("#cart-dropdown-message p.empty").hide();
	} else {
		$("#item-preview").hide();
	}
}

function setSpanValue(id, value) {
	$("span#" + id).text(value);
}

function showMiniCart() {
	$('#cart-dropdown').show();
}

function Cart(endpoint) {
	
	this.endpoint = endpoint;
	
	this.addProduct = function(cid, pid, quantity, callback) {
		$.post(this.getEndPointForAction('add'), { item: cid+":"+pid+":"+quantity }, callback, 'json')
	}
	
	this.deleteProduct = function(cid, pid, callback) {
		$.post(this.getEndPointForAction('delete'), { item: cid+":"+pid }, callback, 'json')
	}
	
	this.updateProduct = function(cid, pid, quantity, callback) {
		$.post(this.getEndPointForAction('update'), { item: cid+":"+pid+":"+quantity }, callback, 'json')
	}
	
	this.updateProducts = function(items, callback) {
		$.post(this.getEndPointForAction('updates'), { items: $.toJSON(items) }, callback, 'json')
	}
	
	this.getProducts = function(callback) {
		$.post(this.getEndPointForAction(''), { }, callback, 'json')
	}
	
	this.updateShipping = function(shippingMethod, callback) {
		$.post(this.getEndPointForAction('shipping'), { shipping_method: shippingMethod }, callback, 'json')
	}
	
	this.getEndPointForAction = function(action) {
		return this.endpoint + action + "/";
	}
	
}

function addProduct(cid, pid, quantity) {
	console.log('addProduct('+cid+', '+ pid +', '+ quantity +')');
	
	cart.addProduct(cid, pid, quantity, function(result) {
		console.log('got result from add: ', result)
		if (result.success) {
			console.log('item added to cart');
			showMiniCart();
			updateMiniCart(result.item, result.cart.itemCount, result.cart.total  );
		} else {
			console.error(result.message);
		}
	});
}

