$(window).load(function() {
  var viewer = $("#viewer");
  
  $.getJSON('/util/load_featured.php', function(data) {
  	/* Set up the viewer's frame and background */
		viewer
			.width('595px')
			.height('526px')
			.css('position', 'relative')
			.css('background-image', 'url(/images/viewer-main.jpg)');
		
		/* Load the thumbnails */
		var offset = 4;
    $.each(data, function(i, item){
      viewer.append('<img src="'+item.thumbnail+'" rel="'+item.fullsize+'" class="thumbnail 0" style="position:absolute; top: 440px; left:'+offset+'px">');
      offset += 118;
    });
  		
		
		/* Add an opacity effect to indicate mouseovers */
		viewer.children('.thumbnail')
			.css('opacity', 0.8)
			.hover(function() {
				$(this).css('opacity', 1);
			}, function() {
				$(this).css('opacity', 0.8);				
			});

		/* Attach an event to each child to load the image */
		viewer.children('.thumbnail').bind('select_image', function() {
		//viewer.children('.thumbnail').click(function() {
			var url = $(this).attr('rel');
			var fullsize_img = $("#viewer .fullsize");

			/* Perform the image swap if it will give us a new image */
			if (url != fullsize_img.attr('src')) {
				fullsize_img.fadeOut('slow', function() {
					fullsize_img.load(function() {
						$(this).fadeIn();
					})
					fullsize_img.attr('src', url);
				});
			}
		}).click(function() {
			stop_rotating();
			$(this).trigger('select_image');
		});

		/* Attach our blank image to use as a target */
		viewer.append('<img src="/images/blank.gif" class="fullsize" style="position: absolute; top:14px; left: 17px">')
		viewer.data('counter', '0');

		/* Start the image rotation */
		rotate_next_image();
  });

});
	
function rotate_next_image()
{
	var viewer = $("#viewer");
	var counter = viewer.data('counter');
	
	//viewer.children(".thumbnail:eq(" + counter % 5 + ")").click();
	viewer.children(".thumbnail:eq(" + counter % 5 + ")").trigger('select_image');
	
	var timeout = setTimeout("rotate_next_image()", 5 * 1000);
	
	viewer.data('counter', ++counter);
	viewer.data('timeout', timeout);
}

function stop_rotating()
{
	var viewer = $("#viewer");
	var timeout = viewer.data('timeout');
	clearTimeout(timeout);
}
