$(function() {
	$('.gallery').each(function() {
		var
			FADE_SPEED = 300,
			gallery = $(this),
			menu = gallery.find('ul'),
			caption, display;
		
		// Handle menu clicks
		var items = gallery.find('li a').click(function() {
			var cur = display.find('img');
			if (cur.attr('src') != this.href) {
				cur.fadeOut(FADE_SPEED, function() {
					$(this).remove();
				});
				
				var _new = $('<img />').attr('src', this.href).attr('alt', this.title).hide().appendTo(display).mousedown(function() {
					var to = menu.find('.selected').next();
					if (to.size() === 0) {
						to = menu.find('li:first-child');
					}
					to.find('a').click();
				});
				cur.size() ? _new.hide().fadeIn(FADE_SPEED) : _new.show();
			}
			
			menu.find('.selected').removeClass('selected');
			$(this).parent().addClass('selected');
			caption.html(this.title);
			return false;
		});
		
		// Append gallery structure
		caption = $('<div class="gallery-caption"></div>');
		display = $('<div class="gallery-displayed"></div>').append(caption).prependTo(gallery);
		
		// Handle preload and image thumbs
		items.each(function() {
			$(this).parent().css('background-image', 'url(' + this.href + ')');
		});
		
		// Set first image
		gallery.find('li:first-child a').click();
		
		// Prevent dragging
		$(this).bind('dragstart', function() {
			return false;
		});
	});
});
