/*!
	Slimbox v1.7 - The ultimate lightweight Lightbox clone
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
	
	Modified for working with Flickr.com, Hyves.net & Oypo.nl
	(c) added functions 2009 Vincent Vijn <http://vincent.vijn.me>
	The added functions are licenced under the Creative Commons Attribution-Non-Commercial-Share Alike 3.0
	Unported License. To view a copy of this licence, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
	or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/

var Slimbox = (function() {

	// Global variables, accessible to Slimbox only
	var win = window, ie6 = Browser.Engine.trident4, options, images, activeImage = -1, activeURL, 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,
	
	// Added for this edition
	slimboxRequest, albumId, saveLink;
	

	/*
		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", events: {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", {styles: {position: "relative"}}).adopt(
				prevLink = new Element("a", {id: "lbPrevLink", href: "#", events: {click: previous}}),
				nextLink = new Element("a", {id: "lbNextLink", href: "#", events: {click: next}})
			)
		);

		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			new Element("a", {id: "lbCloseLink", href: "#", events: {click: close}}),
			new Element("a", {id: "lbOrderLink", href: "#", title: 'Bestel een afdruk van deze foto', events: {click: order}}),
			saveLink = new Element("a", {id: "lbSaveLink", href: "#", title: 'Bewaar deze foto op je computer', events: {click: pageTracker._trackPageview("/album/download_photo")}}),
			new Element("a", {id: "lbHyvesLink", href: "#", title: 'Voeg dit album toe aan je Hyves blog', events: {click: hyves}}),
			caption = new Element("div", {id: "lbCaption"}),
			number = new Element("div", {id: "lbNumber"}),
			new Element("div", {styles: {clear: "both"}})
		);
		
		// Open album directly for users clicking through from RSS feed
		if (location.hash!='') {
			$(location.hash.substr(1)).onclick();
		}
	});


	

	/*
		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 imageUrl(imageIndex,mode) {
		// Contstructs link to image on Flickr server based on index in the images array
		// All references to the image URL in the original Slimbox script are now replaced with this function
		if (mode == 'disp') {
			return 'http://farm'+images[imageIndex].farm+'.static.flickr.com/'+images[imageIndex].server+'/'+images[imageIndex].id+'_'+images[imageIndex].secret+'.jpg';
		} else if (mode == 'dl') {
			return 'http://farm'+images[imageIndex].farm+'.static.flickr.com/'+images[imageIndex].server+'/'+images[imageIndex].id+'_'+images[imageIndex].originalsecret+'_o_d.'+images[imageIndex].originalformat;
		} else if (mode == 'page') {
			return ' http://flickr.com/photo.gne?id='+images[imageIndex].id;
		}
	}

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

			stop();
			center.className = "lbLoading";

			preload = new Image();
			preload.onload = animateBox;
			preload.src = activeURL;
		}

		return false;
	}

	function animateBox() {
		center.className = "";
		fxImage.set(0);
		image.setStyles({backgroundImage: "url(" + activeURL + ")", display: ""});
		sizer.setStyle("width", preload.width);
		$$(sizer, prevLink, nextLink).setStyle("height", preload.height);
		
		// Flickr API therms require a link to the photo's page on Flickr
		flickrLink = '&nbsp;<a href="'+imageUrl(activeImage,'page')+'" onclick="pageTracker._trackPageview(\'/album/clickout_flickr\')" target="flickr"><img src="../media/fotoviewer/external.gif" width="8" height="8" border="0" /></a>';
		number.set("html", (((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length)+flickrLink);
		// Update download button to point to this phot's download link
		saveLink.setProperty('href',imageUrl(activeImage,'dl'));

		if (prevImage >= 0) preloadPrev.src = imageUrl(prevImage,'disp');
		if (nextImage >= 0) preloadNext.src = imageUrl(nextImage,'disp');

		centerWidth = image.offsetWidth;
		centerHeight = image.offsetHeight;
		var top = Math.max(0, middle - (centerHeight / 2)), check = 0, fn;
		if (center.offsetHeight != centerHeight) {
			check = fxResize.start({height: centerHeight, top: top});
		}
		if (center.offsetWidth != centerWidth) {
			check = 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 (check) {
			fxResize.chain(fn);
		}
		else {
			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() {
		preload.onload = $empty;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		fxResize.cancel();
		fxImage.cancel();
		fxBottom.cancel();
		$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
	}
	
	function hyves() {
		// Uses Hyves Smartbutton API <http://trac.hyves-api.nl/wiki/Smartbuttons> to post
		// a gadget on user's Hyves blog, containing a Flickr slideshow of the current album.
		pageTracker._trackPageview("/album/hyves_blog");
		strBody = 'Hier zijn de foto\'s van mijn zeilkamp:\n\n';
		strBody+= '[gadget]<object width="500" height="375"> <param name="flashvars" value="offsite=true&lang=en-us&page_show_url=%2Fphotos%2Fzeilkamp_waterland%2Fsets%2F'+albumId+'%2Fshow%2F&page_show_back_url=%2Fphotos%2Fzeilkamp_waterland%2Fsets%2F'+albumId+'%2F&set_id='+albumId+'&jump_to="></param> <param name="movie" value="http://www.flickr.com/apps/slideshow/show.swf?v=71649"></param> <param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/slideshow/show.swf?v=71649" allowFullScreen="true" flashvars="offsite=true&lang=en-us&page_show_url=%2Fphotos%2Fzeilkamp_waterland%2Fsets%2F'+albumId+'%2Fshow%2F&page_show_back_url=%2Fphotos%2Fzeilkamp_waterland%2Fsets%2F'+albumId+'%2F&set_id='+albumId+'&jump_to=" width="500" height="375"></embed></object>[/gadget]\n';
		strBody+= 'Foto\'s gemaakt door [url=http://www.zeilkamp.net/zeilen_vakantie_kamp/home.asp?utm_source=social&utm_campaign=Hyves_blog]Zeilkamp Waterland[/url].';
		strQuery = Hash.toQueryString({
			title: 'Foto\'s zeilkamp',
			body: strBody,
			type: 9
		});
		pop('http://www.hyves.nl/hyvesconnect/smartbutton?'+strQuery);
		return false;
	}
	
	function order() {
		// Order a print of the picture via Oypo. The server script will check if the size is
		// good enough for printing, and then request an ID for that image at Oypo
		strUrl = '/zeilen_vakantie_kamp/foto_bestel.asp?mod=get_id2&id=' + images[activeImage].id;
		new Request.JSON({url: strUrl, method: 'get', onSuccess: Slimbox.add2basket}).send();
		return false;
	}

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

	return {
		open: function(_images, startImage, _options) {
			options = $extend({
				title: '',
				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: 300,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
				resizeDuration: 300,			// 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: 200,		// Duration of the caption animation (in milliseconds)
				counterText: "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});

			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);
		},
		
		loadAlbum: function(id,year,title) {
			// Position the 'loading...' image in the middle of the screen
			var topPos = window.getScrollTop() + (window.getHeight() / 2) - $($('lbOpenen').parentNode).getPosition().x;
			$('lbOpenen').setStyles({top: topPos + 'px', display: 'block'});

			// The caption is set here, since it's used to display the album title instead of each picture's title.
			caption.set("html", title);
			
			// Store album ID for the Hyves function
			albumId = id;
			
			// Request list of pictures in the album at Flickr
			new Request.JSONP({
				url: 'http://api.flickr.com/services/rest/',
				data: {
					api_key: '14bc3b2c77d47837afb61ee88f3c624c',
					method: 'flickr.photosets.getPhotos',
					photoset_id: id,
					extras: 'original_format',
					format: 'json'
				},
				onComplete: Slimbox.openAlbum,
				callbackKey: 'jsoncallback'
			}).send();
			pageTracker._trackPageview('/album/'+year+'/'+title);
		},
		
		openAlbum: function(data) {
			// If the Flickr response arrives, hide 'loading..' image and open Slimbox
			$('lbOpenen').style.display = 'none';
			if (data.stat=='ok') {
				Slimbox.open(data.photoset.photo,0);
			} else {
				alert('Fout tijdens laden album:\n'+data.message);
			}
		},
		
		add2basket: function(data){
			// Called after foto_bestel.asp checked for image dimensions and got the Oypo ID for this picture
			if (data.stat == "error") {
				alert("Sorry, er is iets misgegaan bij het toevoegen van de foto aan de bestellijst. Probeer het later nog eens alsjeblieft.");
			} else if (data.stat == "tiny") {
				alert("Sorry, de afmetingen van het fotobestand zijn te klein om een mooie afdruk te maken. Je kunt deze foto wel downloaden.");
			} else if (data.stat == "ok") {
				// Check if the picture is already in the shopping basked. If so, offer to remove it, otherwise add it to the basket
				// The script checks if a thumbnail with the Oypo ID is present in the shoppingcart div
				if (objRef('sel'+data.guid)) {
					if (!confirm('Deze foto zit al in je winkelmandje. Druk op Annuleren om deze foto te verwijderen of op OK om hem in je winkelmandje te laten.')) {
						ajaxcall('http://www.oypo.nl/pixxer/ajax/api2.0.asp', 'orderbutton', 'cb_orderbutton', data.guid, 'del', winkelwagen);
					}
				} else {
					alert('De foto is toegevoegd aan je winkelmandje.\n\nAls je klaar bent, kun je dit album sluiten om af te rekenen');
					ajaxcall('http://www.oypo.nl/pixxer/ajax/api2.0.asp', 'orderbutton', 'cb_orderbutton', data.guid, 'add', winkelwagen);
				}
			}
		}

	};

})();

//Mootools.More.JSONP
//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.

MooTools.More={version:"1.2.5.1",build:"254884f2b83651bf95260eed5c6cceb838e22d8e"};(function(){var c=this;var b=function(){if(c.console&&console.log){try{console.log.apply(console,arguments);
}catch(d){console.log(Array.slice(arguments));}}else{Log.logged.push(arguments);}return this;};var a=function(){this.logged.push(arguments);return this;
};this.Log=new Class({logged:[],log:a,resetLog:function(){this.logged.empty();return this;},enableLog:function(){this.log=b;this.logged.each(function(d){this.log.apply(this,d);
},this);return this.resetLog();},disableLog:function(){this.log=a;return this;}});Log.extend(new Log).enableLog();Log.logger=function(){return this.log.apply(this,arguments);
};})();Request.JSONP=new Class({Implements:[Chain,Events,Options,Log],options:{url:"",data:{},retries:0,timeout:0,link:"ignore",callbackKey:"callback",injectScript:document.head},initialize:function(a){this.setOptions(a);
if(this.options.log){this.enableLog();}this.running=false;this.requests=0;this.triesRemaining=[];},check:function(){if(!this.running){return true;}switch(this.options.link){case"cancel":this.cancel();
return true;case"chain":this.chain(this.caller.bind(this,arguments));return false;}return false;},send:function(c){if(!$chk(arguments[1])&&!this.check(c)){return this;
}var e=$type(c),a=this.options,b=$chk(arguments[1])?arguments[1]:this.requests++;if(e=="string"||e=="element"){c={data:c};}c=$extend({data:a.data,url:a.url},c);
if(!$chk(this.triesRemaining[b])){this.triesRemaining[b]=this.options.retries;}var d=this.triesRemaining[b];(function(){var f=this.getScript(c);this.log("JSONP retrieving script with url: "+f.get("src"));
this.fireEvent("request",f);this.running=true;(function(){if(d){this.triesRemaining[b]=d-1;if(f){f.destroy();this.send(c,b).fireEvent("retry",this.triesRemaining[b]);
}}else{if(this.running&&f&&this.options.timeout){f.destroy();this.cancel().fireEvent("failure");}}}).delay(this.options.timeout,this);}).delay(Browser.Engine.trident?50:0,this);
return this;},cancel:function(){if(!this.running){return this;}this.running=false;this.fireEvent("cancel");return this;},getScript:function(c){var b=Request.JSONP.counter,d;
Request.JSONP.counter++;switch($type(c.data)){case"element":d=document.id(c.data).toQueryString();break;case"object":case"hash":d=Hash.toQueryString(c.data);
}var e=c.url+(c.url.test("\\?")?"&":"?")+(c.callbackKey||this.options.callbackKey)+"=Request.JSONP.request_map.request_"+b+(d?"&"+d:"");if(e.length>2083){this.log("JSONP "+e+" will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs");
}var a=new Element("script",{type:"text/javascript",src:e});Request.JSONP.request_map["request_"+b]=function(){this.success(arguments,a);}.bind(this);return a.inject(this.options.injectScript);
},success:function(b,a){if(!this.running){return false;}if(a){a.destroy();}this.running=false;this.log("JSONP successfully retrieved: ",b);this.fireEvent("complete",b).fireEvent("success",b).callChain();
}});Request.JSONP.counter=0;Request.JSONP.request_map={};
