$(function() {
	
	$.extend(Array.prototype, {
		/**
		 * 
		 */
		shuffle : function() {
			var s = [];
			while (this.length) {
				s.push(this.splice(Math.random() * this.length, 1));
			}

			while (s.length) {
				this.push(s.pop());
			}

			return this;
		}
	});

	$.extend($.fn, {
		/**
		 * Slideshow plugin
		 * 
		 * Takes a list (ul or ol) of images and
		 * show each of them one after another at the
		 * same position
		 */
		slideshow : function(options) {
			var defaults = {
						data : [],
						listElement : null,
						timeout : 5000,
						effectLength : 2000,
						randomize : true
				},
				settings = $.extend(defaults, options),
				el = $(this),
				position = el.position(),
				x = el.left,
				y = el.top,
				items = null,
				switchImage = null;

			if (settings.randomize) {
				settings.data = settings.data.shuffle();
			}

			if (el.is("ul, ol")) {
				$.each(settings.data, function(i, value) {
					$("<li><img src='" + value + "' alt='' /></li>").appendTo(el);
				});
			}

			items = $("li", el);

			items.each(function(index) {
				var li = $(this);

				li.css({
					top : y,
					left : x
				});

				if (index !== 0) {
					li.hide().removeClass("visible");
				} else {
					li.addClass("visible");
				}
			});

			switchImage = function() {
				var	current = $(".visible", el),
					next = current.next(),
					fxLength = settings.effectLength,
					clazz = "visible",
					body = $("body");

				if (!next.length) {
					next = items.eq(0);
				}
				
				if (!body.data("ui-switchingImage")) {
					
					body.data("ui-switchingImage", true);
					
					current.fadeOut(fxLength);
					next.fadeIn(fxLength);

					current.removeClass(clazz);
					next.addClass(clazz);
					
					body.data("ui-switchingImage", false);
				}				
			};

			window.setInterval(switchImage, settings.timeout);

			el.addClass("ui-slideshow");
		}
	});
	
	// Fancy box stuff
	$(".gallery a").fancybox({
		cyclic: true,
		overlayColor: "#000",
		titlePosition: "over",
		transitionIn: "elastic",
		transitionOut: "elastic",
		easingIn: "easeInBack",
		easingOut: "easeOutBack"
	});
});
