$.extend(jQuery.fn, {
	fancyHide: function (opts) {
		opts = $.extend({
			fade: !($.browser.msie || $.browser.safari),
			speed: 'fast',
			opacity: .05
		}, opts);
		
		return $(this).each(function () {
			if (opts.fade) {
				$(this).stop(true).fadeTo(opts.speed, opts.opacity);
			} else {
				$(this).hide();
			}
		});
	},
	fancyShow: function (opts) {
		opts = $.extend({
			fade: !($.browser.msie || $.browser.safari),
			speed: 'fast',
			opacity: 1
		}, opts);
		
		return $(this).each(function () {
			if (opts.fade) {
				$(this).stop(true).fadeTo(opts.speed, opts.opacity);
			} else {
				$(this).show();
			}
		});
	}
});

$(function () {
	$('ul#gallery').galleria({
		history: false,
		clickNext: false,
		onImage: function (image, caption, thumb) { // let's add some image effects for demonstration purposes
			// fade in the image & caption
			$(image[0], caption[0]).css('display', 'none').fadeIn('fast');
			
			// fade out inactive thumbnail
			thumb.parents('li').siblings().children('img.selected').fadeTo(500, 0.5);
			
			// fade in active thumbnail
			thumb.fadeTo('fast', 1).addClass('selected');
			
			// add next/previous buttons to image
			var left = $('<a id="galleryLeft" />'),
				right = $('<a id="galleryRight" />'),
				w = thumb.attr('longdesc').split('|')[0],
				full = thumb.attr('longdesc').split('|')[1],
				zoom = full ? $('<a id="galleryZoom" href="' + full + '" target="_blank"></a>') : false;
				
			$([left[0], right[0]])
				.append($('<span />'))
				.attr('href', '#')
				.width(w / 3)
				.insertBefore(image)
				.find('span').fancyHide({ speed: 0 });
			
			right.css('left', w - w / 3);
			
			$('.galleria_wrapper').width(w);
			$('.galleria_container .caption').width(w);
			
			if (zoom) {
				console.log(zoom);
				image.wrap(zoom).after($('<span />').css('left', w / 2 - 15).fancyHide());
			}
		},
		onThumb: function (thumb) { // thumbnail effects goes here
			
			// fetch the thumbnail container
			var _li = thumb.parents('li'),
			
			// if thumbnail is active, fade all the way.
				_fadeTo = _li.is('.active') ? 1 : .4;
			
			// fade in the thumbnail when finnished loading
			thumb.css({ display: 'none', opacity: _fadeTo }).fadeIn('fast');
			
			// hover effects
			thumb.hover(
				function() { thumb.stop(true).fadeTo('fast', 1); },
				function() { _li.not('.active').children('img').stop(true).fadeTo('fast', .4); } // don't fade out if the parent is active
			)
		}
	});
});

$('#galleryLeft').live('click', function () {
	$.galleria.prev();
	return false;
});
$('#galleryRight').live('click', function () {
	$.galleria.next();
	return false;
});

$('#galleryLeft, #galleryRight, #galleryZoom')
	.live('mouseover', function () {
		$(this).find('span').fancyShow();
	})
	.live('mouseout', function () {
		$(this).find('span').fancyHide();
	});