$(document).ready(function() {
	// image preload arrays
	var rollImgArray = new Array();
	var thumbImgArray = new Array();

	// image sizes
	var thumbImgWidth = 55;
	var thumbImgWidthHover = 114;

	// thumb quality and list length
	var thumbJpegQuality = 95;
	var navSubLength = $(".nav_level3 li a, .nav_level2 li a").length - 1;

	$(".nav_level3 li a, .nav_level2 li a").each(function(i) {
		// get rollover relative img src
		var rollImgSrc = $(this).children("img").attr("src");
		var start = rollImgSrc.indexOf("cmsimages");
		var end = rollImgSrc.length;
		var rollRelSrc = rollImgSrc.substring(start, end);

		// preload rollover img
		rollImgArray[i] = new Image();
		rollImgArray[i].src = rollRelSrc;

		// preload thumbnail img
		thumbImgArray[i] = new Image();
		thumbImgArray[i].src = "phpThumb.php?src=" + encodeURIComponent(rollRelSrc) + "&zc=C" + "&w=" + thumbImgWidth + "&h=" + thumbImgWidth + "&q=" + thumbJpegQuality;
		$(this).children("img").attr("src", thumbImgArray[i].src);

		// keep track of animation state
		var okToAnimate = true;

		// animate hover image
		$(this).hover(function() {
			// if other animations are not running, animate current anchor
			if ( okToAnimate )
			{
				okToAnimate = false;

				// remove width
				$(this).children("img").removeAttr("width");
				$(this).children("img").removeAttr("height");

				// fade out thumb, fade in rollover
				$(this).fadeTo("fast", 0.01, function() {
					$(this).next(".description").hide();
					$(this).children("img").attr("src", rollImgArray[i].src);
					$(this).addClass("hover");
					$(this).fadeTo("normal", 1.0, function() {
						okToAnimate = true;
					});
				});
			}
		},function() {
			// if mouseout happened before animation was done, reset anchor
			if ( !okToAnimate )
			{
				$(this).dequeue();
				$(this).stop();

				// original state
				$(this).children("img").attr("src", thumbImgArray[i].src);
				$(this).removeClass("hover");
				$(this).next(".description").show();
				$(this).fadeTo(1, 1.0);

				okToAnimate = true;
			}

			// if other animation is not running, reset anchor on mouseout
			if ( okToAnimate )
			{
				okToAnimate = false;

				// original state
				$(this).children("img").attr("src", thumbImgArray[i].src);
				$(this).removeClass("hover");
				$(this).next(".description").show();

				okToAnimate = true;
			}
		});
	});
});

