/*
Shopping Cart Code
*/

function updateCart(cart) {
	updateMiniCart()
}


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

function trackCall(trackURL) {
	pageTracker._trackPageview(trackURL);
}

function Cart(endpoint) {
	
	this.endpoint = endpoint;
	
	this.addProduct = function(cid, pid, quantity, code, callback) {
		$.post(this.getEndPointForAction('add'), { item: cid+":"+pid+":"+quantity }, callback, 'json')
		trackCall("/cart/add/" + code);
	}
	
	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 + "/";
	}
	
	this.getMiniCartHTML = function(callback) {
		$.ajax( { url: this.getEndPointForAction('minicart'), cache: false, success: callback} );
	}
	
}

function updateMiniCart() {
	cart.getMiniCartHTML( function(html) {
		$("#cart-loading").hide();
		$("#cart-dropdown-message").html(html); 
		$("#cart-dropdown-message").show();
	});
}

function showMiniCartLoading() {
	//get around IE bug with non animating gifs
	$("#cart-loading").html("<div class='loading'><img src='"+ mediaURL +"images/mini-loader.gif' /><span>Updating Cart</span></div>").show();
	$("#cart-dropdown-message").hide()
	$('#cart-dropdown').show();
}

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

