var Easybox = Class.create({
	// konfigurace
	loadingImage: 'img/easybox/loading.gif',	// obrázek pro upload
	imageCountName: 'Obrázek',					// text který se vypisuje v případě, že je více obrázků
	imageCountOf: 'z',							// to samé co výše -> např. Obrázek 14 z 16
	imageTopInfoHeight: 33,						// výška horního infa o obrázku, nutné změnit i ve stylech pro #easyboxtopinfo
	imageBottomInfoHeight: 30,					// výška dolního infa o obrázku, nutné změnit i ve stylech pro #easyboxbottominfo
	imagePadding: 20,							// padding kolem obrázku, nutné změnit i ve stylech pro #easyboximagecontainer
	shadowAppearDuration: 0.2,					// trvání animace pro ztmavnutí pozadí v sec.
	shadowOpacity: 0.8,							// výsledná průhlednost pozadí
	
	images: [],
	currentImage: undefined,
	
	initialize: function() {
		// toto metoda by měla být volána po změně obsahu stránky, např.  ajaxem
		this.updateImages();
		
		// pokud dosud nebyl vytvořen easybox tak ho vytvoříme, jinak nic dělat nemusíme...např. po ajaxu
		if(!$('easyboxshadow')) {
			var bodyE = $$('body')[0];
			
			// struktura easyboxu
			bodyE.appendChild(Builder.node('div',{id:'easyboxshadow'}));
			bodyE.appendChild(Builder.node('div', {id: 'easybox'}, [
				Builder.node('div', {id: 'easyboxouterimagecontainer'}, [
					Builder.node('div', {id: 'easyboxtopinfo'}, [
						Builder.node('span', {id: 'easyboximagecount'}),
						Builder.node('a', {id: 'easyboxclosebtn', href: '#'})
					]),
					Builder.node('div', {id: 'easyboximagecontainer'}, [
						Builder.node('img', {id: 'easyboximage'}),
						Builder.node('div', {id: 'easyboxnavigation'}, [
							Builder.node('a', {id: 'easyboxprev', href: '#'}),
							Builder.node('a', {id: 'easyboxnext', href: '#'})
						]),
						Builder.node('div',{id: 'easyboxloading'},
							Builder.node('img', {src: this.loadingImage}))
					]),
					Builder.node('div', {id: 'easyboxbottominfo'},
						Builder.node('div', {id: 'easyboxbottominfocontent'})
					)
				]),
			]));
			
			$('easyboxshadow').hide().observe('click', (function() { this.end(); }).bind(this));
			$('easybox').hide().observe('click', (function(e) { 
				if(e.element().id == 'easybox') this.end();
			}).bind(this));
			$('easyboxprev').observe('click', (function(e) { e.stop(); this.changeImage(this.currentImage - 1); }).bindAsEventListener(this));
			$('easyboxnext').observe('click', (function(e) { e.stop(); this.changeImage(this.currentImage + 1); }).bindAsEventListener(this));
			$('easyboxclosebtn').observe('click', (function(e) { e.stop(); this.end(); }).bindAsEventListener(this));
		}
	},
	
	/* 
	 * projde všechny odkazy s rel=easybox a přidá hodnotu odkazu do seznamu obrázků
	 * zaregistruje posluchače pro všechny odkazy
	 * volat po změně obsahu stránky jinak nebude fungovat
	 */
	updateImages: function() {
		this.updateImages = Prototype.emptyFunction;
		
		document.observe('click', (function(e) {
			var target = e.findElement('a[rel^=easybox]');
			if(target) {
				e.stop();
				this.start(target);
			}
		}).bind(this));
	},
	
	start: function(imageLink) {
		var imageNum = 0;
		this.images = [];
		
		// zobrazíme stín přes obrazovku
		var pageSize = this.getPageSize();
		//$('easyboxshadow').setStyle({width: pageSize.width+'px', height: pageSize.height+'px'});
		$('easyboxshadow').setStyle({width: f_clientWidth()+'px', height: '900px'});
		new Effect.Appear($('easyboxshadow'), {duration: this.shadowAppearDuration, from: 0.0, to: this.shadowOpacity});
		
		// obrázek je samotný
		if(imageLink.rel == 'easybox') {
			this.images.push([imageLink.href, imageLink.readAttribute('caption')]);
		}
		// obrázek je v galerii
		else {
			this.images = $$(imageLink.tagName + '[href][rel="'+imageLink.rel+'"]').
			collect(function(a) {
				return [a.href, a.readAttribute('caption')];
			}).uniq();
			// najdeme index aktuálního obrázku
			while(this.images[imageNum][0] != imageLink.href) {
				imageNum++;
			}
		}
		
		var pageScroll = document.viewport.getScrollOffsets();
		var viewPortSize = document.viewport.getDimensions();
		var easyboxLeft = pageScroll.left;
		var easyboxHeight = ($('easybox').getHeight());
		var easyboxTop = (viewPortSize.height / 2) + pageScroll.top - (easyboxHeight / 2);
		// nastavíme umístění do prostřed obrazovky
		$('easybox').setStyle({ left: easyboxLeft+'px', top: easyboxTop+'px'}).show();
		
		this.changeImage(imageNum);
	},
	
	/* 
	 * změna aktuálního obrázku
	 */
	changeImage: function(imageNum) {
		this.currentImage = imageNum;
		
		$('easyboxloading').show();
		$('easyboximage').hide();
		$('easyboxnavigation').hide();
		$('easyboxprev').hide();
		$('easyboxnext').hide();
		$('easyboxtopinfo').hide();
		$('easyboximagecount').hide();
		$('easyboxclosebtn').hide();
		$('easyboxbottominfo').hide();
		
		// preloadneme obrázek, abysme mohli změnit rozměry containeru
		var imgPreload = new Image();
		
		imgPreload.onload = (function() {
			$('easyboximage').src = this.images[this.currentImage][0];
			this.resizeImageContainer(imgPreload.width, imgPreload.height);
		}).bind(this);
		
		imgPreload.src = this.images[this.currentImage][0];
	},
	
	/*
	 * změna velikosti containeru na základě velikosti viditelné oblasti prohlížeče
	 * a velikosti obrázku
	 */
	resizeImageContainer: function(imgWidth, imgHeight) {
		var currentDim = $('easyboxouterimagecontainer').getDimensions();
		
		var wDiff = currentDim.width - imgWidth;
		var hDiff = currentDim.height - imgHeight;
		
		if(wDiff != 0) {
			$('easyboxouterimagecontainer').setStyle({width: (imgWidth + (this.imagePadding*2))+'px'});
		}
		if(hDiff != 0) {
			var pageScroll = document.viewport.getScrollOffsets();
			var viewPortSize = document.viewport.getDimensions();
			$('easyboxouterimagecontainer').setStyle({height: (imgHeight + (this.imagePadding*2 + this.imageTopInfoHeight + this.imageBottomInfoHeight))+'px'});
			$('easyboxnavigation').setStyle({height: imgHeight+'px'});
			var containerHeight = ($('easyboxouterimagecontainer').getHeight());
			
			/*
			 * pokud se obrázek nevejde do viditelné oblasti tak ho posuneme dolů tak aby 
			 * byl viditelný horní okraj easyboxu, zbytek je dole
			 */
			if(containerHeight > viewPortSize.height) {
				var diff = containerHeight - viewPortSize.height;
				var shadowHeight = $('easyboxshadow').getHeight() + diff;
				containerHeight -= diff;
				$('easyboxshadow').setStyle({height: shadowHeight+'px'});
			}
			
			$('easybox').setStyle({top: ((viewPortSize.height/2 + pageScroll.top) - containerHeight/2)+'px'});
		}
		
		var timeout = 0;
		if(wDiff == 0 && hDiff == 0) {
			timeout = 100;
			if(Prototype.Browser.IE) {
				timeout = 250;
			}
		}
		
		(function() {
			$('easyboxprev').setStyle({height: imgHeight+'px'});
			$('easyboxnext').setStyle({height: imgHeight+'px'});
			this.showImage();
		}).bind(this).delay(timeout / 1000);
	},
	
	/*
	 * zobrazíme obrázek
	 */
	showImage: function() {
		$('easyboxloading').hide();
		new Effect.Appear($('easyboximage'), {
			duration: 0,
			afterFinish: (function() { this.updateDetails(); }).bind(this)
		});
		this.preloadNeighbourImage();
	},
	
	/*
	 * upravíme zobrazované detaily a zobrazíme je
	 */
	updateDetails: function() {
		$('easyboxtopinfo').show();
		$('easyboximagecount').update(this.imageCountName+' '+(this.currentImage+1)+' '+this.imageCountOf+' '+this.images.length).show();
		$('easyboxclosebtn').show();
		
		$('easyboxbottominfocontent').update(this.images[this.currentImage][1]);
		$('easyboxbottominfo').show();
		
		this.updateNav();
	},
	
	/*
	 * upravíme navigaci
	 */
	updateNav: function() {
		$('easyboxnavigation').show();
		
		if(this.currentImage > 0) {
			$('easyboxprev').show();
		}
		
		if(this.currentImage < (this.images.length - 1)) {
			$('easyboxnext').show();
		}
		
		this.enableKeybordNav();
	},
	
	enableKeybordNav: function() {
		document.observe('keydown', this.keybordAction.bindAsEventListener(this));
	},
	
	disableKeybordNav: function() {
		document.stopObserving('keydown');
	},
	
	keybordAction: function(event) {
		event.stopPropagation();
		var keyCode = event.keyCode;
		
		if(keyCode == Event.KEY_ESC) {
			this.end();
		}
		else if(keyCode == Event.KEY_LEFT) {
			if(this.currentImage != 0) {
				this.disableKeybordNav();
				this.changeImage(this.currentImage - 1);
			}
		}
		else if(keyCode == Event.KEY_RIGHT) {
			if(this.currentImage != (this.images.length - 1)) {
				this.disableKeybordNav();
				this.changeImage(this.currentImage + 1);
			}
		}
	},
	
	preloadNeighbourImage: function() {
		var prevImage, nextImage;
		if(this.images.length > this.currentImage + 1) {
			nextImage = new Image();
			nextImage.src = this.images[this.currentImage][0];
		}
		if(this.currentImage > 0) {
			prevImage = new Image();
			prevImage.src = this.images[this.currentImage][0];
		}
	},
	
	end: function(e) {
		this.disableKeybordNav();
		$('easybox').hide();
		new Effect.Fade($('easyboxshadow'), {duration: 0.2});
	},
	
	getPageSize: function() {
		return $$('body')[0].getDimensions();
	}
});

var eb;

/*Event.observe(window, 'load', function() {
	eb = new Easybox();
});*/
document.observe("dom:loaded", function() {
	eb = new Easybox();
});

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

