$(document).ready(function () {
	$("#cartBtn #cartBtnImg").mouseover(function () {
		showCartPopup();
		/*var cartBtnImgPosition = $(this).position();
		var cartBtnPaddingRight = $(this).closest("#cartBtn").css("paddingRight");
		$("#cartPopup").css({right: cartBtnPaddingRight, top: cartBtnImgPosition.top + 55 + "px"});
		$("#cartPopup").fadeIn();*/
	});
	
	$("#cartPopupClose").click(function (e) {
		e.preventDefault();
		$("#cartPopup").fadeOut();
	});
	
	$("body").click(function (e) {
		if($(e.target).closest("#cartPopup").length != 0 || $(e.target).closest(".addToCart").length != 0) {
			// clicked within the popup or on the addToCart link; don't close the popup
			return;
		}
		else $("#cartPopup").fadeOut();
	});
	
	$(".removeFromCart").click(function(e) {
		e.preventDefault();
		var tblRow = $(this).closest("tr");
		removeItemFromCart($(this).attr("href"), tblRow);
	});
});

function showCartPopup()
{
	var cartBtnImgPosition = $("#cartBtn #cartBtnImg").position();
	var cartBtnPaddingRight = $("#cartBtn #cartBtnImg").closest("#cartBtn").css("paddingRight");
	$("#cartPopup").css({right: cartBtnPaddingRight, top: cartBtnImgPosition.top + 55 + "px"});
	$("#cartPopup").fadeIn();
}

function addItemToCart(url)
{
	// send request to the server
	var genericErrorMsg = "Error: something went wrong. Maybe this page wasn't done loading before you tried to perform this action  or maybe our server is malfunctioning at the moment. Please try again later.";
	$.ajax({
		url: url,
		cache: false,
		success: function(result) {
			if(result.resCode != "success") {
				$("#cartPopupText_Success").hide();
				$("#cartPopupText_Error").html(genericErrorMsg).show();
			}
			else {
				$("#cartPopupText_Success").show();
				$("#cartPopupItemNum").html(result.itemCount);
			}
		},
		error: function() {
			$("#cartPopupText").html(genericErrorMsg);
		}
	});
	
	// show the cart button
	$("#cartBtn").removeClass("hidden");
	showCartPopup();
}

// this function is intended to be used on on the view cart page
function removeItemFromCart(url, tblRow)
{
	// send request to the server
	var genericErrorMsg = "Error: something went wrong. Maybe this page wasn't done loading before you tried to perform this action or maybe our server is malfunctioning at the moment. Please try again later.";
	$.ajax({
		url: url,
		cache: false,
		success: function(result) {
			if(result.resCode != "success") {
				// error happened
				$("#cart #errorMsg").show();
			}
			else {
				// success
				
				// updating the page dynamically ended up too involved (need to update total too), so just reload the page
				window.location.reload();
				
				/*$("#cart #errorMsg").hide();
				$(tblRow).remove();
				$("#cartPopupItemNum").html(result.itemCount); // update item count in cart popup*/
			}
		},
		error: function() {
			$("#cart #errorMsg").show();
		}
	});
}
