$(document).ready(function(){
	$(".showLogin").bind("click",function(){
		$("#topUserLogin").toggle()
	});
	
	
	if($("#alert").length>0) {
		var alertID = $("#alert").attr("class").match(/-([0-9]*)$/)[1];
		var ALERTHIDE = "npys.alertHide";
		
		if(window.localStorage[ALERTHIDE]!==alertID) {
			$("#alert").slideDown(200);
		}
	
		$(".hideAlert").bind("click",function() {
			window.localStorage[ALERTHIDE] = alertID;
			$("#alert").slideUp(200);
		});		
	}
	
	$("#ajaxLogin")
		.bind("click",submitLogin);
	$("#ajaxLoginForm")
		.bind("keydown",function(ev){
			if(ev.keyCode===13) submitLogin(ev)
		});

	function submitLogin(ev) {
		ev.preventDefault();
		var ajaxForm = $("#ajaxLoginForm");
		$.ajax({
			url  : $(ajaxForm).attr("action"),
			data : $(ajaxForm).serialize(),
			type : "post",
			success : function(response) {
				if(response.success) {
					$(".topUserLogin").html("<a class='showLogin' href='/logout'>Logout</a>")
					$("#topUserLogin").hide()
				} else {
						alert("Login failed.");
				}
			}, error : function(response) {	
					alert("Login failed.");
			}
		})
	}

	$("input#checkout").bind("click",function(){
		window.location = $("#checkoutURL").val()	
	})
	
	$("*[class^='removeItem-']").bind("click",function(ev){
		var row  = $(this).closest("tr");
		var id   = this.id.match(/cartItemRemove-(.*)/)[1];
		var form = $(this).closest("form").attr("action").replace("/update","/remove");
		$.ajax({
			url : form,
			data : {
				id : id
			},
			type : "post",
			success : function(res) {
				$(".showCartCount").html(res.count);
				if(res.count>0){
					$(row).remove();
					$("#cartTax").html(res.tax);
					$("#cartTotal").html(res.total);
				} else {
					$(row).closest(".shoppingCart").find("form").remove();
					$(".shoppingCart")[0].innerHTML = "<p>There are currently no items in your cart.</p>";
				}
			}
		})
	});
})

function cancelLogin() {
	$("#ajaxLoginForm input").val("")
	$("#topUserLogin").hide();
}

