function add_product_item(id) 
{
    var lbl_cart = $('cart-count').innerHTML;
	$('cart-count').innerHTML = 'Please Wait...';
	var myRequest = new Request(
	{
		method: 'get',
		url: '/cart/add_item/' + id,
		onComplete : function(response) 
		{
			var json = JSON.decode(response);
			if(lbl_cart.search("View") >= 0)
			{
    			$('cart-count').innerHTML = "View your cart (" + json.total_count + ")";
			}
			else
			{
    			$('cart-count').innerHTML = json.total_count + ' items in your cart';
			}
			$('body-message-box').innerHTML = json.product.title + ' is added to your cart. <a href="/cart">Checkout now?</a>';
			$('message-box').style.display = "block";			
		}
	});
	
	myRequest.send();
}

function remove_product(id)
{
	if(confirm('Are you sure want to delete these products from your cart?'))
	{
		show_wait_image('total-price');

		var myRequest = new Request(
		{
			method: 'get',
			url: '/cart/remove_items/' + id,
			onComplete : function(response) 
			{
				var json = JSON.decode(response);
				if(json.items_count > 0)
				{
					$('product-row-' + id).dispose();
				}
				else
				{
					$('product-row-' + id).innerHTML = '<p>Your cart is empty. <a href="/store">Click here</a> to continue shopping.</p>';
					$('checkout-top').dispose();
					$('checkout-bottom').dispose();
					$('updatecart-top').dispose();
					$('updatecart-bottom').dispose();							
				}
				$('total-price').innerHTML = ('$' + format_currency(json.total));
			}
		});
		
		myRequest.send();
	}
}

function show_wait_image(element) 
{
    $(element).innerHTML = "<img style='float: right;' src='/img/bg-wait.gif' alt='' />";
}

function format_currency(num) {
    num = parseFloat(num);
    return isNaN(num) ? 0.00 : num.toFixed(2);
}

function update_product_count(id) 
{
	var count = parseInt($('product-count-' + id).value);
	
	if(isNaN(count) || count < 0)
	{
		$('product-count-' + id).style.backgroundColor = "red";
		return false;
	}
	else
	{
		$('product-count-' + id).style.backgroundColor = "white";
	}
	
    show_wait_image('product-total-price-' + id);
    show_wait_image('total-price');	
    
    $('checkout-top').disabled = true;
    $('checkout-bottom').disabled = true;

	var myRequest = new Request(
	{
		method: 'get',
		url: '/cart/update_count/' + id + '/' + count,
		onComplete : function(response) 
		{
			var json = JSON.decode(response);
		    $('checkout-top').disabled = false;
		    $('checkout-bottom').disabled = false;
		    
			$('product-total-price-' + id).innerHTML = ('$' + format_currency(count * json.price));
			$('total-price').innerHTML = ('<strong>$' + format_currency(json.total) + '</strong>');
		}
	});

	myRequest.send();
}
