﻿		function updateCartCount(){
			J$.getJSON(
				"/ajaxhelper/index/cartCount",
				function(data) {
					J$("#cartcount").html('(' + data.cartcount + ')');
				}
			);
		};
		
		function updateCart(){
			J$('#cartlist_busy').show();
			J$('#cartlist').empty();
			J$.getJSON(
				"/cundari_ajaxservice/cart/",
				function(data) {
					J$('#cartlist_busy').hide();
					var productHtml = "";
					var items = data.items;
					if (items.length > 0){
						for(i=0;i<items.length;i++){
							productHtml = productHtml
											+ "<li class=\"clearfix\" id=\"item_" + items[i].product_id + "\">"
											+ "<a href=\"" +  items[i].productURL + "\"><img src=\"" + items[i].thumbnailURL + "\" width=\"50\" alt=\"" + items[i].product_id
											+ "\" class=\"left summary-cart-img\" /></a>"
											+ "<div class=\"left summary-cart-info\"><span class=\"green-text\">"
											+ items[i].name + "</span><br />"
											+ items[i].price +"<br />Quantity: "
											+ "<input type=\"text\" value=\"" + items[i].qty + "\" id=\"qty_" + items[i].product_id + "\" style=\"width:20px;\" />"
											+ "</div>"
											+ "<div class=\"left summary-cart-links\">"
											+ "<a href=\"\" class=\"remove\" onclick=\"removeItem(" + items[i].product_id + "," + items[i].item_id + "); return false;\" title=\"Remove\"></a>"
											+ "<a href=\"\" class=\"update\" onclick=\"updateItem(" + items[i].product_id + "," + items[i].item_id + "); return false;\" title=\"Update\"></a>"
											+ "</div>"
											+ "</li>";
						}
						J$("#viewCart").show();
						J$("#emptyCart").hide();
					}
					else {
						J$("#viewCart").hide();
						J$("#emptyCart").show();					
					}
					J$("#cartlist").html(productHtml);
				}
			);
		};
		
		function removeItem(pid, iid){
			J$.getJSON(
				"/ajaxhelper/index/addToCart",
				{pId: pid, qty: 0, iId: iid},
				function(data) {
					if(data.result == "success"){
						updateCartCount();
						updateCart();
					}
					else {
						alert(data.msg);
						var inputId = "#qty_"+pid;
						J$(inputId).focus();
					}
				}
			);
		};
		
		
		function updateItem(pid, iid){	
			var inputId = "#qty_"+pid;
			
			if (J$(inputId).val() == 0){
				removeItem(pid);
			}
			else {			
				J$.getJSON(
					"/ajaxhelper/index/addToCart",
					{pId: pid,	qty: function(){ return J$(inputId).val();}, iId: iid},
					function(data) {
						if (data.result == "success"){
							updateCartCount();
							updateCart();
						}
						else {
							alert(data.msg);
							J$(inputId).focus();
						}
					}
				);
				
			}
		};
				

		J$(document).ready(function () {
			updateCart();
			
			J$("div.cart").hover(
				function () { J$("div.cart-rollover").slideDown(50).show();},
				function () { J$("div.cart-rollover").slideUp(50).show();}
			);
		});

