
///
/// Document onload
///
$(document).ready(function() {
	setTimeout("mc.load()", 750);
});

///
/// Mini cart product class
///
function MiniCartProduct(product) {
	// load all of the properties
	for (var property in product) {
		this[property] = product[property];
	}

	// Adds the product to the cart
	this.addToCart = function(button, quantity, updateActiveCart, customAnalyticsEvent) {
		if (quantity > 0) {
			var currentQuantity = this.getQuantity();
			// Enable and show the mini cart
			mc.enable();
			
			// Set the current text, so we can change it back later
			if ($(button).html() != "Item Added")
				mc.currentButtonText[button.id] = $(button).html();
				
			if (mc.elems) {
				mc.showAndHide(this.sku, button.id);
			} else {
				//delay because IE6 is still loading
				setTimeout("mc.showAndHide('" + this.sku + "','" + button.id + "');",2000);
			}
			
			if (button.tagName.toLowerCase() == "a")
				$(button).html("Item Added");
			
			// Execute the AJAX method to add the product to the active cart
			if (updateActiveCart)
				mc.addItemToActiveCart(this, quantity, this.addToCartUrl);
			
			// Record add to cart for analytics
			analyticsProvider.trackAddToCart(this, quantity, customAnalyticsEvent);
			
			// Warranties are special :)
			if (this.isWarranty) {
				// Add the parent product
				if(this.getMasterQuantity() < currentQuantity + quantity)
					mc.addProduct(mc.pageProducts[this.masterSku], quantity);
					
				// Make sure the parent product's dividing line is removed
				$("#" + this.masterSku).addClass("hasSp");
				
				// Set the warranty text
				$("#" + this.sku).find(".productName").html((currentQuantity + quantity == 1) ? "Service Plan" : "Service Plans");
				
				// Add the warranty
				mc.addWarranty(this, quantity);
			} else {
				mc.addProduct(this, quantity);
			}
			
			// Add the current price to the total
			mc.calculateTotals();
		}
	}
	
	this.setQuantity = function(quantity) {
		// Increment the quantity
		$("#lineItems #" + this.sku + " div.quantity").html(this.getQuantity() + quantity);
	}
	
	this.getQuantity = function() {
		var html = $("#lineItems #" + this.sku + " div.quantity").html();
		return html ? parseInt(html) : 0;
	}
	
	this.getMasterQuantity = function() {
		var html = $("#lineItems #" + this.masterSku + " div.quantity").html();
		return html ? parseInt(html) : 0;
	}
}

///
/// Mini cart utility class
///
mc = {
	itemCountElement: null,
	savedCarts: null,
	elems: null,
	saveBtnDiv: null,
	miniCartAnimating: false,
	savedCartsAnimating: false,
	stickOpen: false,
	hideMiniCartTimeout: 0,
	hideMiniCartUserTimeout: 0,
	showMiniCartTimeout: 0,
	hideSavedCartsTimeout: 0,
	showSavedCartsTimeout: 0,
	pageProducts: new Array(),
	quickListProducts: new Array(),
	addToCartTimeouts: new Array(),
	currentButtonText: new Array(),
	mcAnimation: null,
	scAnimation: null,
	blockOut: false,
	
	load: function() {
		var savedCartCount = mc.savedCartsCount();
		var itemCount = mc.countItems();
		
		mc.elems = $("#elements");
		mc.savedCarts = $("#savedCarts");
		mc.itemCountElement = $("#itemCount");
		mc.savedCarts.hide();
		
		// Bind to the mini cart trap control to handle scrolling
		$("#miniCartTrap").bind("mouseover", function() {
			mc.stickOpen = true;
		});
		
		// Bind to the document mouse over to reset the stick open property
		$(document).bind("mouseover", mc.documentMouseOver);
		
		// Check to see if there are any saved carts
		if(savedCartCount < 4)
			$("#viewAllCartsLink").css("display", "none");
		
		// Check to see if there are items
		if(itemCount == 0) {
			mc.itemCountElement.removeClass();
			mc.hideSaveCartButton();
		} else {
			mc.attachMiniCartEvents();
		}
		
		// Attach mini cart events if necessary
		if(itemCount > 0 || savedCartCount > 0) {
			mc.attachSavedCartEvents();
		} else {
			$("#savedCartsCount").removeClass();
		}
	},
	
	enable: function() {
		mc.attachMiniCartEvents();
		mc.attachSavedCartEvents();
		mc.showSaveCartButton();
		$("#savedCartsCount").addClass("seeItems");
	},
	
	showAndHide : function(sku,buttonId) {
	    //handle show and hide
	    mc.show();
		// Clear the mini cart timeouts
		mc.clearAddToCartTimeout(this.sku);
		clearTimeout(mc.hideMiniCartUserTimeout);
	    // Hide the mini cart after 2 seconds
		mc.hideMiniCartUserTimeout = setTimeout(function() { mc.hide() }, 2000);
		
		// Change the button text back after 1.5 seconds
		if (document.getElementById(buttonId).tagName.toLowerCase() == "a")
			mc.addToCartTimeouts[this.sku] = setTimeout("$(\"#" + buttonId + "\").html(\"" + mc.currentButtonText[buttonId] + "\");", 1500);
	},
	
	show: function() {
		mc.mcAnimation.show();
	},
	
	hide: function(timeout) {
		mc.mcAnimation.hide(timeout);
	},
	
	onMcPreHover: function(e) {
		mc.blockOut = false;
		mc.itemCountElement.addClass("seeItems open");
	    $("#miniCartTrap").show();
	    $("#miniCartTrap").css("width", ((document.width ? document.width : document.body.offsetWidth) - $("#MiniCartContainer").offset().left - $("#miniCartLeft").width()) + "px");
	    $("#MiniCartContainer").css("width", $("#miniCartTrap").width() + $("#miniCartLeft").width());
	},
	
	onMcPreHoverOut: function(e) {
		if (!mc.stickOpen && (mc.blockOut || !e.userAction)) {
			$("#miniCartTrap").hide();
			// Change the arrow
			mc.itemCountElement.removeClass("open");
		} else {		
			e.continueAnimation = false;
		}
	},
	
	onScPreHover: function(e) {
		$("#savedCartsCount").addClass("open");
	},
	
	onScPreHoverOut: function(e) {
		$("#savedCartsCount").removeClass("open");
	},
	
	onMcPostHover: function (e) {
		$("#miniCartTrap").css("height", $("#MiniCartContainer").height() + "px");
	},
	
	savedCartsCount: function() {
		return parseInt($("#savedCartsCount span").html())
	},
	
	attachMiniCartEvents: function() {
		// set up the animations
		mc.mcAnimation = new rolloverAnimation(document.getElementById("MiniCartBlock"), mc.elems, document.getElementById("MiniCartContainer"));
		mc.mcAnimation.hoverDelay = 500;
		mc.mcAnimation.hoverOutDelay = 1000;
		mc.mcAnimation.showAnimation = { height: "show", opacity: "show" };
		mc.mcAnimation.hideAnimation = { height: "hide", opacity: "hide" };
		mc.mcAnimation.onPreHover = mc.onMcPreHover;
		mc.mcAnimation.onPostHover = mc.onMcPostHover;
		mc.mcAnimation.onPreHoverOut = mc.onMcPreHoverOut;
	
		$("#MiniCartContainer").hover(function() { clearTimeout(mc.hideMiniCartUserTimeout); }, function() { mc.blockOut = true; });
		//$("#MiniCartBlock").hover(function() { clearTimeout(mc.hideMiniCartTimeout); clearTimeout(mc.hideMiniCartUserTimeout); mc.showMiniCartTimeout = setTimeout("mc.show()", 250); }, function() { });
	},
	
	attachSavedCartEvents: function() {
		mc.scAnimation = new rolloverAnimation(document.getElementById("miniCartSavedCartsContainer"), mc.savedCarts);
		mc.scAnimation.hoverDelay = 500;
		mc.scAnimation.hoverOutDelay = 500;
		mc.scAnimation.showAnimation = { height: "show", opacity: "show" };
		mc.scAnimation.hideAnimation = { height: "hide", opacity: "hide" };
		mc.scAnimation.onPreHover = mc.onScPreHover;
		mc.scAnimation.onPreHoverOut = mc.onScPreHoverOut;
	},
	
	showSaveCartButton: function() {
		$("#saveCartLink").show();
	},
	
	hideSaveCartButton: function() {
		$("#saveCartLink").hide();
	},
	
	documentMouseOver: function(e) {
		var target = e.target ? e.target : e.srcElement;
		
		if(target.id != "MiniCartContainer" && target.id != "miniCartTrap" && target.tagName != "HTML" && mc.stickOpen) {
			mc.stickOpen = false;
			mc.hide(1500);
		}
	},
	
	getLineItemMarkup: function(product, quantity) {
		return "<div class=\"" + (product.isWarranty ? "warranty" : "product") + "\" id=\"" + product.sku + "\">"
			+ "<div class=\"clear clearBoth\"><div class=\"floatLeft strong quantity\">" + quantity + "</div><div class=\"floatLeft productName\">" + (product.isWarranty || product.isLineListed ? product.name : "<a href=\"/IPA/Shop/Product/Detail.htm?sku=" + product.sku + "\">" + product.name + "</a>") + "</div></div>"
			+ "<div class=\"sku\">#" + product.sku + "</div>"
			+ "<div class=\"mcPrice\">$<span class=\"mcPrice\">" + (parseFloat(product.price)).toFixed(2) + "</span></div></div>";
	},
	
	addItemToActiveCart: function(product, quantity, href) {
		try {
			// If the product is a warranty, it needs special attention
			if(product.isWarranty) {
				// Get the master product for the product name and price
				var masterProduct = mc.pageProducts[product.masterSku];
				// Add to cart
				UI.Services.AjaxWebService.AddItemToActiveCart(product.masterSku, product.sku,
					((product.getQuantity() + quantity <= product.getMasterQuantity()) ? 0 : quantity), product.getQuantity() + quantity, masterProduct.name, masterProduct.price, product.price, product.warrantyType, product.isLineListed);
			} else {
				// Add the product to cart
				UI.Services.AjaxWebService.AddItemToActiveCart(product.sku, "", quantity, 0, product.name,product.price, 0, "", product.isLineListed);
			}
		} catch(e) {
			if (typeof(console) != "undefined")
				console.error(e);
			mc.addItemWithFrame(href);
		}
	},
	
	calculateTotals: function() {
		var subtotal = 0;
		$("#lineItems > div").each(function() {
			var quantity = $(this).find("div.quantity").html();
			var price = $(this).find("span.mcPrice").html();
			subtotal += parseInt(quantity) * parseFloat(price);
		});
		if (subtotal.toFixed) {
			$("#elements span.subtotal").html(subtotal.toFixed(2));
		}
	},
	
	incrementItemCount: function() {
		var itemCount = $("#itemCount").html();
		itemCount = parseInt(itemCount.substring(0, itemCount.indexOf(" "))) + 1;
		$("#itemCount").html(itemCount + " " + mc.getItemText(itemCount));
	},
	
	updateItemCount: function() {
		var itemCount = mc.countItems();
		$("#itemCount").html(itemCount + " " + mc.getItemText(itemCount));
	},

	countItems: function() {
		return $("#elements #lineItems > div.product").length;
	},
	
	getItemText: function(itemCount) {
		return itemCount == 1 ? "Item" : "Items";
	},
	
	clearAddToCartTimeout: function(sku) {
		if(typeof(mc.addToCartTimeouts[sku]) != "undefined") {
			clearTimeout(mc.addToCartTimeouts[sku]);
		}
	},
	
	addProduct: function(product, quantity) {
		// Check to see if the product is already in the mini cart
		if($("#lineItems #" + product.sku).length > 0) {
			product.setQuantity(quantity);
		} else {
			$("#lineItems").append(mc.getLineItemMarkup(product, quantity));
			mc.incrementItemCount();
		}
	},
	
	addWarranty: function(product, quantity) {
		// Check to see if the warranty exists for this product
		if ($("#" + product.masterSku).next("div.warranty").attr("id") == product.sku) {
			// Update the quantity
			product.setQuantity(quantity);
		} else {
			// Remove the old warranty
			$("#" + product.masterSku).next("div.warranty").remove();
			// Add the warranty
			$("#" + product.masterSku).after(mc.getLineItemMarkup(product, quantity));
			// Re-calculate the total
			mc.calculateTotals();
		}
	},
	
	///
	/// Fail-safe - we will create an iframe.
	///
	addItemWithFrame: function(href) {
		if (document.createElement && document.getElementById) {
			container = document.getElementsByTagName("body");
			frame = document.createElement("iframe");
			frame.setAttribute("style", "width: 1px; height: 1px;");
			frame.setAttribute("src", href);
			if (container[0]) {
				container[0].appendChild(frame);
			}
		}
	},
	
	///
	/// Attempts to add quicklist items to the active cart - returns true on error.
	///
	addQuicklistToActiveCart: function(quickListId, selected) {
		try {
			UI.Services.AjaxWebService.AddQuickListToActiveCart(quickListId, selected, cbnull);		
			return false;
		} catch(e) {
			return true;
		}	
	},
	
	addQuickListToCart: function(button, quickListId) {
		// Loop through each quick list product
		for(var sku in mc.quickListProducts) {
			mc.quickListProducts[sku].addToCart(button, mc.quickListProducts[sku].quantity, false, "event12");
		}

		return mc.addQuicklistToActiveCart(quickListId, false);
	},
	
	parseQuantity: function(quantity, element) {
		if (isNaN(quantity) && typeof(element) != "undefined") {
			balloonManager.show("quantity", "Please enter a valid quantity", element);
			return 0;
		} else {
			balloonManager.hide("quantity");
			return parseInt(quantity);
		}
	},
	
	addToCartButtonClick: function(button, sku, quantity, callback, customAnalyticsEvent) {
		// if the quantity is a string, it's an element id
		if (isNaN(quantity)) {
			var element = document.getElementById(quantity);
			
			if (element)
				quantity = mc.parseQuantity(element.value, element.parentNode);
		}
		
		// add the product to the cart
		if (mc.pageProducts[sku] != null) {
			mc.pageProducts[sku].addToCart(button, quantity, true, customAnalyticsEvent);
		}
		
		// call availability
		if (typeof(callback) == "function") {
			callback(sku, mc.pageProducts[sku].getQuantity());
		}
	}
}

///
/// Handles client script for the AddOptionToCart control
///
function addOptionToCart(control, radioGroup, containerID) {
	if (control != null) {
		$(control).click(function() {
			$("#" + containerID).find("input[@type='radio']").each(function() {
				if (this.name == radioGroup && this.checked) {
					var cartProduct = mc.pageProducts[this.value];
					
					if (cartProduct != null) {
						cartProduct.addToCart(control, 1, true);
					}
					
					return false;
				}
			});
			
			return false;
		});
	}
}