var type;
var inTransaction = false;

$(document).ready(function()
{
	startup();
	
	$("ul.sort a").bind("click", function()
	{
		if(inTransaction == false)
		{
			
			if($(this).parent().hasClass("fresh"))
			{
				type = "fresh";
			}
			else if($(this).parent().hasClass("popular"))
			{
				type = "popular";
			}
		
			if($(this).parent().hasClass("selected") == false)
			{
				
				inTransaction = true;
				
				$("ul.games").stop().animate({"opacity" : 0.0}, 100, function()
				{
					$("ul.games").load("/games/sort/" + type, function()
					{
						startup();
						
						$("ul.games li.game").css({opacity:0});
						
						$("ul.games").stop().animate({"opacity" : 1}, 0, function()
						{
							$("ul.games li.game").each(function(i, elem)
							{
								var item = $(this);
								
								window.setTimeout(function(i)
								{
									item.animate({opacity:1}, 200).queue();
								}, 200*i);
							});
							inTransaction = false;
						});
					});
				});
			}

			$("ul.sort li").removeClass("selected");
			$(this).parent().addClass("selected");
		}
		
		return false;
	});
});

function startup()
{
	// Startup
	$("ul.games li").css("cursor", "pointer").each(fnMouseOut).bind("click", fnClick);
	
	// Mouse over
	$("ul.games li").bind("mouseover", fnMouseOver);

	// Mouse out
	$("ul.games li").bind("mouseout", fnMouseOut);
	
	$("ul.games li li").unbind();
}

function fnMouseOver()
{
	$(this).children("a").stop().animate({"opacity":0.8, "fontSize":"1.6em"}, 100);
	$(this).children("ul").stop().animate({"opacity":0.8, "bottom":"0px"}, 100);
}

function fnMouseOut()
{
	var barHeight = $(this).children("ul").outerHeight();

	$(this).children("a").stop().animate({"opacity":0.6, "fontSize":"1.2em"}, 100);
	$(this).children("ul").stop().animate({"opacity":0.0, "bottom": "-" + barHeight + "px"}, 100);
}

function fnClick()
{
	window.location = $(this).children("a").attr("href");
}