/*--------------------------------------------------------

COOKIES USED:

**PER ITEM**

cart-item-[IDX]-name : DESCRIPTION
cart-item-[IDX]-sku : SKU
cart-item-[IDX]-image : IMAGE PATH
cart-item-[IDX]-quantity : QUANTITY
cart-item-[IDX]-price : ITEM PRICE

**PER CART**

cart-unique-items : # OF UNIQUE ITEMS IN CART
cart-subtotal : TOTAL DOLLAR AMOUNT OF ITEMS IN CART
cart-quantity : TOTAL # OF ITEMS IN CART

---------------------------------------------------------*/

var emptyMessage = "<a href='#' class='empty'><span class='inline-block'></span> 0 items</a>";
var loadingMessage = "<p class='loading-cart'>Loading <a href='/store/cart/display.do'>cart</a></p>";
var cartTotal;
var theFreeShipMin;
var items;
var cartQuantity;
var uniqueItems;
var cartCounter;
var f;
var u;

function deleteTheCartCookies() {
	uniqueItems = $j.cookie("cart-unique-items");
	if (uniqueItems != null){
		uniqueItems = parseInt(uniqueItems);
	}
	//delete existing cart cookies
	$j.cookie("cart-unique-items",null);
	$j.cookie("cart-subtotal",null);
	$j.cookie("cart-freeship",null);
	$j.cookie("cart-quantity",null);
	//delete existing item cookies
	for (u=0;u<uniqueItems;u++){
		$j.cookie("cart-item-"+u+"-name",null);
		$j.cookie("cart-item-"+u+"-sku",null);
		$j.cookie("cart-item-"+u+"-image",null);
		$j.cookie("cart-item-"+u+"-quantity",null);
		$j.cookie("cart-item-"+u+"-price",null);
	}
}

function setTheCartItemCookies(item,itemIdx,properties) {
	var thisItemQuantity = item.find("input[name*='quantity']").val();
	thisItemQuantity = parseInt(thisItemQuantity);
	var thisItemImage = item.find(".cart-small-image img").attr("src");
	var thisItemSku = item.find("h2 a").text().replace(/\s/g,"");
	var thisItemDescription = item.find(".item-details dd").text();
	var thisItemPrice = item.find(".item-total").text();
	$j.cookie("cart-item-"+itemIdx+"-name",thisItemDescription,{path:"/",expires: 365});
	$j.cookie("cart-item-"+itemIdx+"-sku",thisItemSku,{path:"/",expires: 365});
	$j.cookie("cart-item-"+itemIdx+"-image",thisItemImage,{path:"/",expires: 365});
	$j.cookie("cart-item-"+itemIdx+"-quantity",thisItemQuantity,{path:"/",expires: 365});
	$j.cookie("cart-item-"+itemIdx+"-price",thisItemPrice,{path:"/",expires: 365});
	
	properties.push(thisItemSku); // 0
	properties.push(thisItemDescription); // 1
	properties.push(thisItemQuantity); // 2
	properties.push(thisItemPrice); // 3
	properties.push(thisItemImage);	// 4

	//testing :: alert cookies
	//alert($j.cookie("cart-item-"+itemIdx+"-name")+'\n'+$j.cookie("cart-item-"+itemIdx+"-sku")+'\n'+$j.cookie("cart-item-"+itemIdx+"-image")+'\n'+	$j.cookie("cart-item-"+itemIdx+"-quantity")+'\n'+$j.cookie("cart-item-"+itemIdx+"-price"));

	cartCounter = cartCounter + thisItemQuantity;

}

function getTheCart(callback,promote) {
	var url = window.location.pathname.split("/");
	//for the cart itself, pull directly from the markup
	if (url[2] == "cart") {
		//delete existing cookies
		deleteTheCartCookies();

		cartTotal = parseFloat($j("#master-subtotal span").text()).toFixed(2);
		theFreeShipMin = parseInt($j("#free-shipping-query .bottom").text().replace(/\$/g,""));
		items = $j(".item-container");
		uniqueItems = items.length;

		//testing :: alert total and items
		//alert("Total: "+cartTotal+"\nUnique Items: "+uniqueItems);

		//if there are items in the cart
		if (uniqueItems > 0) {
			$j("#cart-summary").empty().html(loadingMessage);

			cartCounter = 0;
			//iterate through the items in the cart and set cookies
			for (f=0;f<uniqueItems;f++){
				var thisItem = items.eq(f);
				var thisItemProperties = [];
				setTheCartItemCookies(thisItem,f,thisItemProperties);
			}

			//set global cart cookies
			$j.cookie("cart-subtotal",cartTotal,{path:"/",expires: 365});
			$j.cookie("cart-freeship",theFreeShipMin,{path:"/",expires: 365});
			$j.cookie("cart-unique-items",uniqueItems,{path:"/",expires: 365});
			$j.cookie("cart-quantity",cartCounter,{path:"/",expires: 365});

			//testing :: alert global cookies
			//alert($j.cookie("cart-subtotal")+'\n'+$j.cookie("cart-unique-items")+'\n'+$j.cookie("cart-quantity")+'\n'+$j.cookie("cart-freeship"));

			cartQuantity = cartCounter;
			//populate the summary
			$j("#cart-summary").empty().html("<a href='/store/cart/display.do' onclick='$j(this).blur();return false;'><span class='inline-block'></span>"+cartQuantity+" <em>/</em> $"+cartTotal+"</a>");
		} else {
			$j("#cart-summary").empty().html(emptyMessage);
		}
	}
	//for sessionID-driven pages, use cookie cart
	else if (url[1] == "user" || url[2] == "checkout") {
		
		$j("#cart-summary").empty().html(loadingMessage);
		$j("div.cart-details").remove();
		$j("#the-mini-cart").remove();
		
		//grab the values of the cookies
			
		if ($j.cookie("cart-unique-items") != null && $j.cookie("cart-unique-items").length > 0) {
			uniqueItems = $j.cookie("cart-unique-items");
			cartTotal = $j.cookie("cart-subtotal");
			cartQuantity = $j.cookie("cart-quantity");
			theFreeShipMin = $j.cookie("cart-freeship");
		
		
		
		
			if (parseInt(uniqueItems) > 0) {
							
				//set up the div and the form for holding these items
				var downStatus;
				var clipHeight;
				if (uniqueItems > 2){
					downStatus = "down-active";
					clipHeight = 260;
				} else {
					downStatus = "down-inactive";
					clipHeight = 130*uniqueItems;
				}
				var shipStatus;
				var differenceForFreeShipping = (theFreeShipMin-(parseFloat(cartTotal))).toFixed(2);
				if (parseInt(cartTotal) >= theFreeShipMin){
					shipStatus = "\n\t\t<span class='yes-shipping'>Your order qualifies for</span>\n\t\t<span class='yes-shipping emphasize'>Free U.S. Ground Shipping</span>";
				} else {
					shipStatus = "\n\t\t<span class='no-shipping'>Add $"+differenceForFreeShipping+" to qualify for</span>\n\t\t<span class='no-shipping emphasize'>Free U.S. Ground Shipping</span>";
				}
				
				var offset = $j("#container").offset();
				var right = offset.left + 670;
				
				/*\n\t\t<input id='mini-cart-checkout-input' type='image' value='Checkout' class='outtaHere' name='checkout'>\n\t\t<a href='#' class='mini-cart-button checkout-button' onclick='$j(\"#mini-cart-checkout-input\").click();return false;'>Checkout</a>*/
				
				$j("<div id='the-mini-cart' style='left: "+right+"px;'>\n\t<h2>Currently In Your Cart</h2>\n\t<span class='arrow up-inactive'></span>\n\t<form action='/store/cart/updateCart.do' method='post' name='cartForm'>\n\t\t<div class='clip' style='height: "+clipHeight+"px;'>\n\t\t\t<ul style='margin-top: 0'></ul>\n\t\t</div>\n\t\t<span class='arrow "+downStatus+"'></span>\n\t\t<h3>Total: $"+cartTotal+"</h3>\n\t\t<a class='mini-cart-button' href='/store/cart/display.do'>view cart</a>\n\t</form>\n\t<div class='shipping'>"+shipStatus+"</div></div>").appendTo("body");
				
				
				var miniCartList = $j("#the-mini-cart ul");
				
				cartCounter = 0;
				//iterate through the items in the cart and set cookies
				for (f=0;f<uniqueItems;f++){
					
					var sku = $j.cookie("cart-item-"+f+"-sku");
					var desc = $j.cookie("cart-item-"+f+"-name");
					var img = $j.cookie("cart-item-"+f+"-image");
					var quant = $j.cookie("cart-item-"+f+"-quantity");
					var dollaz = $j.cookie("cart-item-"+f+"-price");
					
					
					$j("<li><input type='text' value='"+quant+"' class='outtaHere' name='quantity("+sku+")'><input type='checkbox' class='outtaHere' value='"+sku+"' name='removedProducts'><a href='/store/products/display.do?id="+sku+"'><img src='"+img+"' /><h4>"+desc+"</h4><h5>"+sku+"</h5><h6>QTY: "+quant+" | "+dollaz+"</h6></a></li>").appendTo(miniCartList);
					
					
				}		
			
				var cookieBasedCount = cartQuantity;

				$j("#cart-summary").empty().html("<a href='/store/cart/display.do'><span class='inline-block'></span>"+cookieBasedCount+" <em>/</em> $"+cartTotal+"</a>");
			} else {
				$j("#cart-summary").empty().html(emptyMessage);
			}
		}		
	}
	//for all other "normal" pages grab the active cart dynamically
	else {
		
		//browse page code
		$j("#product-browse-container li .go-to-cart").removeClass("go-to-cart").addClass("add-to-cart").html("Add to Cart<span></span>");
		
		$j("#cart-summary").empty().html(loadingMessage);
		deleteTheCartCookies();
		
		//remove any existing cart details container and append a new one to the body
		$j("div.cart-details").remove();
		$j("#the-mini-cart").remove();
		$j("<div class='cart-details outtaHere'></div>").appendTo("body");
		$j("div.cart-details").load("/store/cart/display.do?random="+Math.random(1000)+" .item-container, #master-subtotal, #free-shipping-query .bottom", function(){
			var details = $j(this);
			if (details.find(".item-container").length > 0){
				
				
				cartTotal = details.find("#master-subtotal span").text();
				theFreeShipMinimum = parseInt(details.find(".bottom").text().replace(/\$/g,""));
				items = details.find(".item-container");
				uniqueItems = items.length;
				
				//testing :: alert total and items
				//alert("Total: "+cartTotal+"\nUnique Items: "+uniqueItems+"\nFree Shipping Over: "+theFreeShipMinimum);
				
				
				//if there are items in the cart
				if (uniqueItems > 0) {
		
					
					
					//set up the div and the form for holding these items
					var downStatus;
					var clipHeight;
					if (uniqueItems > 2){
						downStatus = "down-active";
						clipHeight = 260;
					} else {
						downStatus = "down-inactive";
						clipHeight = 130*uniqueItems;
					}
					var shipStatus;
					var differenceForFreeShipping = (theFreeShipMinimum-(parseFloat(cartTotal))).toFixed(2);
					if (parseInt(cartTotal) >= theFreeShipMinimum){
						shipStatus = "\n\t\t<span class='yes-shipping'>Your order qualifies for</span>\n\t\t<span class='yes-shipping emphasize'>Free U.S. Ground Shipping</span>";
					} else {
						shipStatus = "\n\t\t<span class='no-shipping'>Add $"+differenceForFreeShipping+" to qualify for</span>\n\t\t<span class='no-shipping emphasize'>Free U.S. Ground Shipping</span>";
					}
					
					var offset = $j("#container").offset();
					var right = offset.left + 670;
					
					$j("<div id='the-mini-cart' style='left: "+right+"px;'>\n\t<h2>Currently In Your Cart</h2>\n\t<span class='arrow up-inactive'></span>\n\t<form action='/store/cart/updateCart.do' method='post' name='cartForm'>\n\t\t<div class='clip' style='height: "+clipHeight+"px;'>\n\t\t\t<ul style='margin-top: 0'></ul>\n\t\t</div>\n\t\t<span class='arrow "+downStatus+"'></span>\n\t\t<h3>Total: $"+cartTotal+"</h3>\n\t\t<a class='mini-cart-button' href='/store/cart/display.do'>view cart</a>\n\t</form>\n\t<div class='shipping'>"+shipStatus+"</div></div>").appendTo("body");
					
					
					var miniCartList = $j("#the-mini-cart ul");
					
					cartCounter = 0;
					//iterate through the items in the cart and set cookies
					for (f=0;f<uniqueItems;f++){
						var thisItem = items.eq(f);
						var thisItemProperties = [];
						setTheCartItemCookies(thisItem,f,thisItemProperties);
						
						
						//on product browse page, note that the item is already in the cart
						$j("#product-browse-container li[data-id='"+thisItemProperties[0]+"'] .add-to-cart").each(function(){
								$j(this).removeClass("add-to-cart").addClass("go-to-cart").html("In Cart <span></span>");
						});						
						
						//on indiv product page, note the same
						var page = window.location.href;
						var queryBegin = page.split("?");
						if (queryBegin[1] == "id="+ thisItemProperties[0]) {
							if (!$j(".add-to-cart").hasClass("going-to-cart")){
								$j(".in-cart-notice").remove();
								$j("h2.bigger").after("<p class='in-cart-notice'>You have "+thisItemProperties[2]+" in your cart. Update?</p>");
								$j(".add-to-cart").html("Change Quantity<span></span>").addClass("adjust-quantity");
								$j("label[for='quantity']").text("Change Quantity To:");
								if ($j(".go-to-cart").length == 0){
									$j(".add-to-cart").after("<a href='/store/cart/display.do' class='go-to-cart'>Go to Cart</a>");
								}
							}
						}						
						$j("<li data-productID='"+thisItemProperties[0]+"'><input type='text' value='"+thisItemProperties[2]+"' class='outtaHere' name='quantity("+thisItemProperties[0]+")'><input type='checkbox' class='outtaHere' value='"+thisItemProperties[0]+"' name='removedProducts'><a href='/store/products/display.do?id="+thisItemProperties[0]+"'><img src='"+thisItemProperties[4].replace(/(-S)/g,"-M")+"' /><h4>"+thisItemProperties[1]+"</h4><h5>"+thisItemProperties[0]+"</h5><h6>QTY: "+thisItemProperties[2]+" | "+thisItemProperties[3]+"</h6></a><span class='remove-this-item'><em>Remove This?</em></span></li>").appendTo(miniCartList);
						
						
					}
		
					//set global cart cookies
					$j.cookie("cart-subtotal",cartTotal,{path:"/",expires: 365});
					$j.cookie("cart-freeship",theFreeShipMinimum,{path:"/",expires:365});
					$j.cookie("cart-unique-items",uniqueItems,{path:"/",expires: 365});
					$j.cookie("cart-quantity",cartCounter,{path:"/",expires: 365});
		
					//testing :: alert global cookies
					//alert($j.cookie("cart-subtotal")+'\n'+$j.cookie("cart-unique-items")+'\n'+$j.cookie("cart-quantity")+'\n'+$j.cookie("cart-freeship"));

					cartQuantity = cartCounter;
					
						//populate the summary
						$j("#cart-summary").empty().html("<a href='/store/cart/display.do'><span class='inline-block'></span>"+cartQuantity+" <em>/</em> $"+cartTotal+"</a>");
						
						
						// provide a callback
						
						if (callback == "showCart"){
							function moduleCloseMod(){
								var module = $j("#the-mini-cart");
								module.slideUp(200,function(){
									$j("#cart-summary").removeClass("showing-mini-cart");
								});
							}
							
							if (promote === undefined){
								promote = "none";
							}
							
							if (promote.length > 0 && promote != "none"){
								$j("#the-mini-cart li[data-productID='"+promote+"']").prependTo("#the-mini-cart ul");
							}
							
							$j("#the-mini-cart").css("display","block");
							$j(window).scrollTo("#the-mini-cart",{offset: -100, duration: 500});
							$j("#the-mini-cart").live("mouseleave",function(){
								moduleCloseMod();
							});
						}
						
						
						
					} else {
						$j("#cart-summary").html(emptyMessage);
					}
				} else {
					$j("#cart-summary").html(emptyMessage);
				}
		});
		
	}
}
$j(document).ready(function(){
	getTheCart();
	$j(".cart-status").live("click",function(){
		if (!$j(this).hasClass("showing-the-cart")) {
			$j(this).parent("div").css("overflow","visible");
			$j(this).addClass("showing-the-cart");
		} else {
			$j(this).parent("div").css("overflow","hidden");
			$j(this).removeClass("showing-the-cart");
		}
	});
	$j(".close-the-cart-box").live("click",function(){
		$j(".cart-status").click();
	});
	$j(".search-text").focus(function(){
		$j(this).val("");
	});
	$j(".search-text").blur(function(){
		if ($j(this).val() == "") {
			$j(this).val("Search Jewelry");
		}
	});
	$j("#cart-summary a.empty").live("click",function(){return false;});
});
