var timeout    = 200;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open() {
	jsddm_canceltimer();
	jsddm_close();

	ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}

function jsddm_close() {
	if(ddmenuitem)
		ddmenuitem.css('visibility', 'hidden');
}

function jsddm_timer() {
	closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
	if(closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

document.onclick = jsddm_close;

function showError(error) {
	$("#shopping_error").html(error).show();

	setTimeout(function() {
		$("#shopping_error").hide("fade", {}, 2000);
	}, 4000);
}

function removedCart(data, status) {
	if (data.error == 1) {
		if (data.message != '') {
			showError(data.message);
		}
	} else {
		if (data.id != '') {
			var current_entry = $("#shopping_cart_" + data.id);

			if (current_entry.length > 0) {
				current_entry.hide(500, function() {$(this).remove(); checkCart();});
			}
		}
	}

	$("#shopping_removing").stop().hide();
}

function removeCart(event) {
	event.preventDefault();

	// If a removing message is already visible, return
	if ($("#shopping_removing:visible").length > 0) {
		return;
	}

	// If an error message is visible, return
	if ($("#shopping_error:visible").length > 0) {
		return;
	}

	// Remove the item
	$("#shopping_removing").stop().effect("highlight", {}, 2000);

	$.getJSON(this.href, {ajax:'1'}, removedCart);
}

function checkCart() {
	if ($("#shopping_items").children().length > 0) {
		$("#shopping_none").hide();
		$("#shopping_cart").show();

		// Setup the total
		var total = 0;

		$("div.jsPrice").each(function () {
			var val = $(this).html();

			if (val.indexOf('$', 0) == 0) {
				val = val.substr(1);
			}

			var valNum = parseFloat(val);

			if (isNaN(valNum) == false) {
				total = total + valNum;
			}

		});

		$("#cart_total").html("* $" + total);
	} else {
		$("#shopping_none").show();
		$("#shopping_cart").hide();
	}
}

$(document).ready(
function() {
	if ($("#dropmenu").css('visibility') == "hidden") {
		$('#mainmenu > li').bind('mouseover', jsddm_open);
		$('#mainmenu > li').bind('mouseout',  jsddm_timer);
	}

	$("a.jsRemoveFromCart").click(removeCart);
});