/*
	Modifications, 2007 by Tobias Brunner
	Update to MooTools 1.2.2+, 2009 by Tobias Brunner
	Slimbox v1.41 - The ultimate lightweight Lightbox clone
	by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
	Inspired by the original Lightbox v2 by Lokesh Dhakar.
*/

var Lightbox = new Class({
	Implements: [ Options, Events ],

	options: {
		resizeDuration: 400,
		resizeTransition: false,	// default transition
		initialWidth: 250,
		initialHeight: 250,
		animateCaption: true,
		showCounter: true,
		autoScanLinks: true,
		relString: 'lightbox',
		loadDefaultCss: true,
		assetBaseUrl: '/css/',
		locale: 'de',
		strings: {
			image: 'Image',
			of: 'of'
		},
		onImageShow: $empty,
		onDisplay: $empty,
		onHide: $empty
	},

	localization: {
		'de': {
			image: 'Bild',
			of: 'von'
		}
	},

	initialize: function(options, anchors) {
		this.setOptions(options);

		if (this.options.locale) {
			$extend(this.options.strings, this.localization[this.options.locale]);
		}

		if (this.options.loadDefaultCss) {
			this.loadCss();
		}

		this.anchors = anchors || [];

		if (this.options.autoScanLinks) {
			$$('a').each(function(el) {
				if (el.getProperty('rel') && el.getProperty('rel').test('^' + this.options.relString, 'i')) {
					if (!el.getProperty('lightboxed')) {
						this.anchors.push(el);
					}
				}
			}, this);
		}

		if (!$$(this.anchors).length) {
			return;
		}

		$$(this.anchors).each(function(el) {
			if (!el.getProperty('lightboxed')) {
				el.setProperty('lightboxed', true);
				el.addEvent('click', function(e) {
					new Event(e).stop();
					this.click(el);
				}.bind(this));
			}
		}, this);

		this.eventKeyDown = this.keyboardListener.bindWithEvent(this);
		this.eventPosition = this.position.bind(this);

		window.addEvent('domready', this.addHtmlElements.bind(this));
	},

	addHtmlElements: function() {
		this.overlay = new Element('div', { 'class': 'lbOverlay' }).injectInside(document.body);
		this.center = new Element('div', {
			'class': 'lbCenter',
			'styles': {
				'width': this.options.initialWidth + 'px',
				'height': this.options.initialHeight + 'px',
				'marginLeft': -(this.options.initialWidth / 2) + 'px',
				'display': 'none'
			}
		}).injectInside(document.body);
		this.image = new Element('div', { 'class': 'lbImage', 'styles': { 'opacity': 0 } }).injectInside(this.center);
		this.prevLink = new Element('a', {
			'class': 'lbPrevLink',
			'styles': {
				'display': 'none',
				'cursor': 'pointer'
			}
		}).injectInside(this.image);
		this.nextLink = this.prevLink.clone().removeClass('lbPrevLink').addClass('lbNextLink').injectInside(this.image);
		this.prevLink.addEvent('click', function(e) {
			new Event(e).stop();
			this.previous();
		}.bind(this));
		this.nextLink.addEvent('click', function(e) {
			new Event(e).stop();
			this.next();
		}.bind(this));

		this.bottomContainer = new Element('div', {
			'class': 'lbBottomContainer',
			'styles': {
				'display': 'none'
			}
		}).injectInside(document.body);
		this.bottom = new Element('div', { 'class': 'lbBottom' }).injectInside(this.bottomContainer);
		new Element('a', {
			'class': 'lbCloseLink',
			'styles': {
				'cursor': 'pointer'
			}
		}).injectInside(this.bottom).addEvent('click', function(e) {
			new Event(e).stop();
			this.close();
		}.bind(this));
		this.overlay.addEvent('click', this.close.bind(this));
		this.caption = new Element('div', { 'class': 'lbCaption' }).injectInside(this.bottom);
		this.number = new Element('div', { 'class': 'lbNumber' }).injectInside(this.bottom);
		new Element('div', { 'styles': { 'clear': 'both' } }).injectInside(this.bottom);

		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.get('tween', { property: 'opacity', duration: 500 }).set(0),
			resize: this.center.get('morph', $extend({ duration: this.options.resizeDuration, onComplete: nextEffect }, this.options.resizeTransition ? { transition: this.options.resizeTransition } : {})),
			image: this.image.get('tween', { property: 'opacity', duration: 500, onComplete: nextEffect }),
			bottom: this.bottom.get('tween', { property: 'margin-top', duration: 400, onComplete: nextEffect })
		};

		this.preloadPrev = new Image();
		this.preloadNext = new Image();
	},

	loadCss: function() {
		window.addEvent('domready', function() {
			if (!$('SlimboxCss')) {
				var file = 'slimbox' + (this.options.locale ? '_' + this.options.locale : '') + '.css';
				new Asset.css(this.options.assetBaseUrl + file, { 'id': 'SlimboxCss' });
			}
		}.bind(this));
	},

	click: function(link) {
		var rel = link.getProperty('rel') || this.options.relString;
		if (rel == this.options.relString) return this.show(link.href, link.title);

		var j, imageNum, images = [];
		this.anchors.each(function(el) {
			if (el.getProperty('rel') == rel) {
				for (j = 0; j < images.length; j++) {
					if(images[j][0] == el.getProperty('href'))
						break;
				}
				if (j == images.length) {
					images.push([el.href, el.title]);
					if (el.href == link.href) imageNum = j;
				}
			}
		});
		return this.open(images, imageNum);
	},

	show: function(url, title) {
		return this.open([[url, title]], 0);
	},

	open: function(images, imageNum) {
		this.fireEvent('onDisplay');
		this.images = images;
		this.position();
		this.setup(true);
		this.top = (window.getScrollTop() + (window.getHeight() / 25)).toInt();
		this.center.setStyles({ top: this.top + 'px', display: '' });
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
	},

	position: function() {
		this.overlay.setStyles({ 'top': window.getScrollTop() + 'px', 'height': window.getHeight() + 'px' });
	},

	setup: function(open) {
		var elements = $$('object, iframe');
		elements.extend($$(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.getStyle('visibility');
			el.setStyle('visibility', open ? 'hidden' : el.lbBackupStyle);
		});
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
		this.fx.image.set(0);
	},

	keyboardListener: function(event) {
		switch (event.code){
			case 27: case 88: case 67: case 83: this.close(); break;
			case 37: case 80: case 90: this.previous(); break;
			case 39: case 78: case 87: this.next();
		}
	},

	previous: function() {
		this.changeImage(this.activeImage - 1);
	},

	next: function() {
		this.changeImage(this.activeImage + 1);
	},

	changeImage: function(imageNum) {
		this.fireEvent('onImageShow', imageNum);
		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 0;
		this.activeImage = imageNum;

		this.fx.image.set(0);
		this.fx.bottom.start(-this.bottom.offsetHeight)
		this.prevLink.setStyle('display', 'none');
		this.nextLink.setStyle('display', 'none');
		this.center.addClass('lbLoading');
		
		this.preload = new Image();
		this.preload.onload = function() { this.fx.image.start(0) }.bind(this);
		this.preload.src = this.images[imageNum][0];
	},

	nextEffect: function() {
		switch (this.step++) {
		case 1:
			this.center.removeClass('lbLoading');
			this.image.setStyle('backgroundImage', 'url(\'' + this.images[this.activeImage][0] + '\')');
			this.image.setStyle('width', this.preload.width + 'px');
			this.bottom.setStyle('width', this.preload.width + 'px');
			this.image.setStyle('height', this.preload.height + 'px');
			this.prevLink.setStyle('height', this.preload.height + 'px');
			this.nextLink.setStyle('height', this.preload.height + 'px');

			this.caption.set('html', this.images[this.activeImage][1] || '');
			this.number.set('html', (!this.options.showCounter || (this.images.length == 1)) ? '' : this.options.strings.image + ' ' + (this.activeImage + 1) + ' ' + this.options.strings.of + ' ' + this.images.length);

			if (this.activeImage) this.preloadPrev.src = this.images[this.activeImage - 1][0];
			if (this.activeImage != (this.images.length - 1)) this.preloadNext.src = this.images[this.activeImage + 1][0];

			if (this.center.clientHeight != this.image.offsetHeight){
				this.fx.resize.start({height: this.image.offsetHeight});
				break;
			}
			this.step++;
		case 2:
			if (this.center.clientWidth != this.image.offsetWidth){
				this.fx.resize.start({width: this.image.offsetWidth, marginLeft: -this.image.offsetWidth/2});
				break;
			}
			this.step++;
		case 3:
			this.bottomContainer.setStyles({
				'top': (this.top + this.center.getSize().y) + 'px',
				'height': '0px',
				'margin-left': this.center.getStyle('margin-left'),
				'display': ''
			});
			this.fx.image.start(1);
			break;
		case 4:
			if (this.options.animateCaption){
				this.fx.bottom.set(-this.bottom.offsetHeight);
				this.bottomContainer.setStyle('height', '');
				this.fx.bottom.start(0);
				break;
			}
			this.bottomContainer.style.height = '';
		case 5:
			if (this.activeImage) this.prevLink.setStyle('display', '');
			if (this.activeImage != (this.images.length - 1)) this.nextLink.setStyle('display', '');
			this.step = 0;
		}
	},

	close: function(){
		this.fireEvent('onHide');
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = $empty;
			this.preload = null;
		}
		for (var f in this.fx) this.fx[f].cancel();
		this.center.setStyle('display', 'none');
		this.bottomContainer.setStyle('display', 'none');
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
	}
});

window.addEvent('domready', function() { new Lightbox() });


