/*!
	Slimbox expansion which is able to display videos aswell. The code is based
	on Slimbox http://www.digitalia.be/demo/slimbox/ and Videobox 
	http://videobox-lb.sourceforge.net/
	
	(c) 2009 Robbert Krebbers
	MIT-style license.
*/

(function() {

	// Global variables, accessible to Slimbox only
	var win = window, ie6 = Browser.Engine.trident4, options, images, activeImage = -1, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,

	// Preload images
	preload = {}, preloadPrev = new Image(), preloadNext = new Image(),

	// DOM elements
	overlay, center, image, sizer, prevLink, nextLink, bottomContainer, bottom, caption, number,

	// Effects
	fxOverlay, fxResize, fxImage, fxBottom;

	/*
		Initialization
	*/
	win.addEvent("domready", function() {
		// Append the Slimbox HTML code at the bottom of the document
		$(document.body).adopt(
			$$(
				overlay = new Element("div", {id: "lbOverlay"}).addEvent("click", close),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			).setStyle("display", "none")
		);

		image = new Element("div", {id: "lbImage"}).injectInside(center).adopt(
			sizer = new Element("div")
		);

		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			new Element("div", {id: "lbCaptionNav"}).adopt(
				new Element("div", {id: "lbNav"}).adopt(
					prevLink = new Element("a", {id: "lbPrevLink", href: "#"}).adopt(
						new Element('strong').appendText('< ')).appendText('vorige').adopt(
						new Element('strong').appendText(' | ')).addEvent("click", previous),
					new Element("a", {id: "lbCloseLink", href: "#"}).appendText('sluiten').addEvent("click", close),
					nextLink = new Element("a", {id: "lbNextLink", href: "#"}).adopt(
						new Element('strong').appendText(' | ')).appendText('volgende').adopt(
						new Element('strong').appendText(' >')).addEvent("click", next)
				),
				caption = new Element("div", {id: "lbCaption"})
			),
			number = new Element("div", {id: "lbNumber"}),
			new Element("div", {styles: {clear: "both"}})
		);
	});


	/*
		API
	*/

	Slimbox = {
		open: function(_images, startImage, _options) {
			options = $extend({
				video: false, // Whether they are videos or images
				defaultVideoWidth: 600, // The default width of videos
				defaultVideoHeight: 400, // The default height of videos
				loop: false,				// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				overlayFadeDuration: 400,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
				resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// false uses the mootools default transition
				initialWidth: 250,			// Initial width of the box (in pixels)
				initialHeight: 250,			// Initial height of the box (in pixels)
				imageFadeDuration: 400,			// Duration of the image fade-in animation (in milliseconds)
				captionAnimationDuration: 400,		// Duration of the caption animation (in milliseconds)
				counterText: _options.video ? "Video {x} van {y}" : "Foto {x} van {y}",	// Translate or change as you wish, or set it to false to disable counter text for image groups
				closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
				previousKeys: [37, 80],			// Array of keycodes to navigate to the previous image, default: Left arrow (37), 'p' (80)
				nextKeys: [39, 78]			// Array of keycodes to navigate to the next image, default: Right arrow (39), 'n' (78)
			}, _options || {});

			// Setup effects
			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});
			fxResize = new Fx.Morph(center, $extend({duration: options.resizeDuration, link: "chain"}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			fxImage = new Fx.Tween(image, {property: "opacity", duration: options.imageFadeDuration, onComplete: animateCaption});
			fxBottom = new Fx.Tween(bottom, {property: "margin-top", duration: options.captionAnimationDuration});

			// The function is called for a single image, with URL and Title as first two arguments
			if (typeof _images == "string") {
				_images = [{url: images, caption: startImage, width: null, height: null}];
				startImage = 0;
			}

			middle = win.getScrollTop() + (win.getHeight() / 2);
			centerWidth = options.initialWidth;
			centerHeight = options.initialHeight;
			center.setStyles({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2, display: ""});
			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			fxOverlay.set(0).start(options.overlayOpacity);
			position();
			setup(1);

			images = _images;
			options.loop = options.loop && (images.length > 1);
			return changeImage(startImage);
		}
	};

	Element.implement({
		slimbox: function(_options, linkMapper) {
			// The processing of a single element is similar to the processing of a collection with a single element
			$$(this).slimbox(_options, linkMapper);

			return this;
		}
	});

	Elements.implement({
		/*
			options:	Optional options object, see Slimbox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an object containing 4 fields:
					the image or video URL, the caption (may contain HTML), the width and the height. The latter two are only applicable for
					videos.
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		slimbox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				var parts = el.rel.split(" ");
				var width = null, height = null;
				var dim = parts[parts.length - 1];
				if(parts.length >= 2 && dim.match(/(\d*)x(\d*)/)) {
					width = dim.split("x")[0]; height = dim.split("x")[1];
				}
				return {url: el.href, caption: el.title, width: width, height: height};
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredLinks = links.filter(linksFilter, this);
				return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
			});

			return links;
		}
	});


	/*
		Internal functions
	*/

	function position() {
		var scroll = win.getScroll(), size = win.getSize();
		$$(center, bottomContainer).setStyle("left", scroll.x + (size.x / 2));
		if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
	}

	function setup(open) {
		["object", ie6 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});

		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		win[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		var code = event.code;
		// Prevent default keyboard action (like navigating inside the page)
		return options.closeKeys.contains(code) ? close()
			: options.nextKeys.contains(code) ? next()
			: options.previousKeys.contains(code) ? previous()
			: false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if (imageIndex >= 0) {
			activeImage = imageIndex;
			prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
			nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);

			stop();
						
			if(options.video) {
				animateBox();
			} else {
				center.className = "lbLoading";
				preload = new Image();
				preload.onload = animateBox;
				preload.src = images[imageIndex].url;
			}
		}

		return false;
	}

	function animateBox() {
		fxImage.set(0);

		if(options.video) {
			var vWidth = images[activeImage].width > 0 ? images[activeImage].width : options.defaultVideoWidth;
			var vHeight = images[activeImage].height > 0 ? images[activeImage].height : options.defaultVideoHeight;
			so = videoToSo(images[activeImage].url, vWidth, vHeight);
			so.write(sizer);
			image.setStyles({display: ""});
			sizer.setStyle("width", vWidth+"px");
			sizer.setStyle("height", vHeight+"px");
		} else {
			center.className = "";
			var url = preload.src.replace(/\(/g,"%28").replace(/\)/g,"%29");
			image.setStyles({backgroundImage: "url(" + url + ")", display: ""});
			sizer.setStyle("width", preload.width);
			sizer.setStyle("height", preload.height);
		}

		caption.set("html", images[activeImage].caption || "");
		number.set("html", (((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));

		if (prevImage >= 0) preloadPrev.src = images[prevImage].url;
		if (nextImage >= 0) preloadNext.src = images[nextImage].url;

		centerWidth = image.offsetWidth;
		centerHeight = image.offsetHeight;
		var top = Math.max(0, middle - (centerHeight / 2)), fn;
		if (center.clientHeight != centerHeight) {
			fxResize.start({height: centerHeight, top: top});
		}
		if (center.clientWidth != centerWidth) {
			fxResize.start({width: centerWidth, marginLeft: -centerWidth/2});
		}
		fn = function() {
			bottomContainer.setStyles({width: centerWidth, top: top + centerHeight, marginLeft: -centerWidth/2, visibility: "hidden", display: ""});
			fxImage.start(1);
		};
		if (fxResize.check(fn)) fn();
	}

	function animateCaption() {
		if (prevImage >= 0) prevLink.style.display = "";
		if (nextImage >= 0) nextLink.style.display = "";
		fxBottom.set(-bottom.offsetHeight).start(0);
		bottomContainer.style.visibility = "";
	}

	function stop() {
		if(options.video) {
			sizer.empty();
		} else {
			preload.onload = $empty;
			preload.src = preloadPrev.src = preloadNext.src = "";
		}
		fxResize.cancel();
		fxImage.cancel();
		fxBottom.cancel();
		$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
	}

	function close() {
		if (activeImage >= 0) {
			stop();
			activeImage = prevImage = nextImage = -1;
			center.style.display = "none";
			fxOverlay.cancel().chain(setup).start(0);
		}

		return false;
	}

	function videoToSo(link, width, height) {
		if(link.match(/youtube\.com\/watch/i))
			link = "http://www.youtube.com/v/"+link.split("=")[1];
		var so = new SWFObject(link, "vidbox", width, height, "0");
		so.addParam("wmode", "transparent");
		return so;
	}
})();

window.addEvent("domready", function() {
	function linksFilter(el) {
		// ignore the part after the last " ", this contains the dimensions
		if(this == el) return true;
		var rel = [this.rel, el.rel].map(function(r) {
			return r.lastIndexOf(" ") > 0 ? r.substr(0, el.rel.lastIndexOf(" ")) : r;
		});
		return rel[0] != "lightbox" && rel[0] != "vidbox" && rel[0] == rel[1];
	}
	$$(document.links).filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	}).slimbox({}, null, linksFilter);
	$$(document.links).filter(function(el) {
		return el.rel && el.rel.test(/^vidbox/i);
	}).slimbox({video: true}, null, linksFilter);
});
