(function($) {
	$(function() {
		// auto-highlight the current nav item
		$('#top-nav a.active').each(function() {
			var $a = $(this);
			var $img = $a.find('img');
			var current_src = $img.attr('src');
			
			var bits = current_src.split('/');
			var filename = bits.pop();
			bits.push(filename.replace(/\./, '_over.'));
			
			$img.attr('src', bits.join('/'));
		});
	});
	
	$(function() { 
		$('.rotate').each(function() {
			var $table = $(this);
	
			// collect all the available images
			var imgs = [];
			$('img', $table).each(function() {
				imgs.push($(this).attr('src'));
			});
			
			// set up rotation on each TD
			offset = 0;
			$('td', $table).each(function() {
				var $cell = $(this);
				var $img1 = $cell.find('img');
				var $img2 = $img1.clone();
				
				// fix the cell size, otherwise they'll collapse when the fades happen
				$cell.css('position', 'relative');
				$cell.css('width', $img1.width());
				$cell.css('height', $cell.height());
				
				// set them on top of each other
				$img1.addClass('img1');
				$img2.addClass('img2');
				
				$img2.css('position', 'absolute');
				$img2.css('left', '0px');
				$img2.css('top', '0px');
				
				$cell.append($img2);
				
				// hide the top img
				$img2.hide();
				
				// assign a randomized rotation to this cell
				$cell.data('offset', offset++);
				imgs = shuffle(imgs);
				
				// set up a rotation
				setInterval(function() {
					
					// find the next image to display						
					var offset = $cell.data('offset');
					if(offset >= imgs.length) {
						offset = 0;
					}
					var new_img_top = imgs[offset];
					
					$cell.data('offset', offset + 1);
					
					// set the top img to the new one
					$img2.attr('src', new_img_top);
					$img2.fadeIn(900, function() {
						// set the one underneath to the same as the top
						$img1.attr('src', new_img_top);
						
						// fade the the top one out to get ready for the next rotation
						$img2.fadeOut(100);
					});
	
				}, 5000); //Math.floor(100 * Math.random()) + 5000);
			});
		});
	});
	
	
	shuffle = function(o){
		for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
		return o;
	};
	

})(jQuery);
