if ($(window).width() < 640) {
	$('meta[name=viewport]').attr('content', 'width=640');
} else if ($(window).width() < 980) {
	$('meta[name=viewport]').attr('content', 'width=980');
}

$(function() {
	var stretchWrapper = function() {
		var centerMargin = (($(window).height() - $("#wrapper").height()) / 2) - 80;
		var marginTop = (centerMargin > -320 ? centerMargin : -320) + "px";
		$("#wrapper").css("margin-top", marginTop);
	};
	
	$(window).resize(function() { stretchWrapper(); });
	stretchWrapper();

	// hide modals when outside area is clicked
	$("#modalContainer").click(function(e) {
		e.preventDefault();
		$(".modal").hide();
	});
	
	// show associated modal when icon is clicked
	$(".shelf li a").click(function(e) {
		e.preventDefault();
		var $modal = $("#" + $(this).parent().attr("id") + "Modal");
		
		// center modal
		var marginTop = (($(window).height() - $modal.height()) / 2) + $(window).scrollTop();
		$modal.css("margin-top", (marginTop > -35 ? marginTop : -35) + "px");
		
		$modal.show();
	});
	
	// racing click
	$("#message a").unbind("click");
	$("#racing a").unbind("click");
	
	// setup modal images
	$(".modal").each(function() {
		$(this).find("li").hide().first().show();
	});
	
	// setup modal arrows
	$("a.left").click(function(e) {
		e.preventDefault();
		e.stopPropagation();
		advancePreview($(this).parent(), -1);
	}).hide();
	
	$("a.right").click(function(e) {
		e.preventDefault();
		e.stopPropagation();
		advancePreview($(this).parent(), 1);
	});
	
	$("a.howto").click(function(e) {
		e.preventDefault();
		e.stopPropagation();
		$(".modal").hide();
		$("#howtoModal").show();
	});
	
	$("a.download").click(function(e) {
		e.stopPropagation();
	});
	
	$("a.close").click(function(e) {
		e.preventDefault();
	});
	
	function advancePreview($parent, modifier) {
		$parent.find("li").each(function(index) {
			if ($(this).is(":visible")) {
				var newIndex = index + modifier;
				
				if (newIndex === 0) {
					$parent.find("a.left").hide();
				} else {
					$parent.find("a.left").show();
				}
				
				if (newIndex === $parent.find("li").length - 1) {
					$parent.find("a.right").hide();
				} else {
					$parent.find("a.right").show();
				}
				
				$(this).fadeOut(500);
				$($parent.find("li")[newIndex]).fadeIn(500);
				
				return false;
			}
		});
	}
});
