/*
 * tinyLightbox 2.0 - Plugin for jQuery
 * 
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Depends:
 *   jquery.js
 * 
 *
 *  Copyright (c) 2008 Oleg Slobodskoi (ajaxsoft.de)
 */
;(function($) {

 	
	$.fn.extend({
		tinyLightbox: function ( options ) {
			var tl = new $.tinyLightbox(this, options);
			tl.init();
	
		}
	});

 	$.tinyLightbox = function ( elements, opt )
	{
		//defaults
		var d = {
			slideshow: 5000,
			pathAttr: 'href',
			descrAttr: 'title',				
			resizeSpeed: 300,
			fadeInSpeed: 300,
			fadeOutSpeed: 300,
			slideSpeed: 300,
			border: 10,
			top: 20,
			statLabelImage: 'Bild', //Label for word "Image" in the bar
			statLabelFrom: 'von'//Label for word "from" in the bar
		};

		$.extend( d, opt);
		
		var images = [],
			descr = [],
			activeImageId,
			imageWidth,
			imageHeight,
			left,
			scrollTop,
			wHeight,
			wWidth,
			inProgress,
			slideshowInterval,
			pauseCallback,
			//filter elements without path attr
			$elems = $(elements).filter('['+d.pathAttr+'!=""]'),
			$tinyLightbox,
			$overlay,
			$image,
			self = this
		;
		
		this.init = function ()
		{
			//serialize the gallery
			$elems.each(function(i, elem){
				images[i] = $(elem).attr(d.pathAttr);				
				descr[i] = $(elem).attr(d.descrAttr) || '';				
			}).		
			
			click(function() {
	
				create();
				
				var path = $(this).attr(d.pathAttr);
				activeImageId = $.inArray(path, images);

				preloadImage(path, function(image){
					animate(image, function(){
						showImage(image);
					});	
				});

				bindKeyNavigation();

				return false;
			});
		};


	
		
		/********************************************************************************************************/
		//Interface part

		function create ()
		{
			$overlay = $('<div class="tinyLightbox-overlay" />').click(close).appendTo('body');
			resizeOverlay();

			$tinyLightbox = $('<div class="tinyLightbox loading" />').
			css({'top': scrollTop+d.top,'left': wWidth/2-100}).
			appendTo('body');
			
		};
		
		function animate ( image, callback )
		{

			imageWidth= image.width + d.border*2;
			imageHeight= image.height + d.border*2;
			left= wWidth/2- imageWidth/2;
			
			$tinyLightbox.animate({width: imageWidth, left: left}, d.resizeSpeed,function(){
				$tinyLightbox.animate({'height': imageHeight - d.border+ 25}, d.resizeSpeed, function(){
					callback();
				});
			});
		};		

		function showImage(image)
		{	
			$image = $('<img class="image" src="'+image.src+'"/>').
			appendTo($tinyLightbox).
			fadeIn(d.fadeInSpeed*2/3, function(){
				$('<div class="label-close"/>').
				click(close).
				prependTo($tinyLightbox);
				showBar();
			});

						

			
		};
		function removeImage(callback)
		{
			//$('#tinyLightboxLeftLabel, #tinyLightboxRightLabel').hide(d.slideSpeed);			

			$image.fadeOut(d.fadeOutSpeed*2/3, function(){
				$image.remove();
				callback();
			});

		};		
		
		function showBar()
		{
			var barWidth = document.compatMode == 'BackCompat' ? imageWidth : imageWidth - d.border*2;
			$bar = $('<div class="bar">').css({'padding': d.border, 'width': barWidth }).
			append(
					$('<a class="button label-left"/>').click(function(){
						changeImage(-1) ? shake($tinyLightbox, 20, 150) : changeImage(-1);
					}),
					$('<a class="button label-right"/>').click(function(){
						changeImage(1) ? shake($tinyLightbox, 20, 150) : changeImage(1);
					}),
					slideshow('getBtn'),

				
					$('<div class="descr"/>').append('<p>'+descr[activeImageId]+'</p>').width(imageWidth-260),
					
					$('<div class="counter"/>').append( getGalStats() )
			);
		
			$bar.appendTo($tinyLightbox).
			slideDown(d.slideSpeed, function(){
				resizeOverlay();
			});			
		};
		
		function removeBar(callback){
			$bar.slideUp(d.slideSpeed, function(){
				$bar.remove();
				callback();
			});
		};
			
		function shake ($elem, size, speed)
		{
			var left = $elem.position().left;
			$elem.animate({'left': left+size}, speed, function(){
				$elem.animate({'left': left-2*size},speed, function(){
					$elem.animate({'left': left+2*size}, speed, function(){
						$elem.animate({'left': left}, speed);
					});
				});
			});
		};			

		function close()
		{
			$tinyLightbox.fadeOut(d.fadeOutSpeed/2,function(){
				$overlay.fadeOut(d.fadeOutSpeed/2,function(){
					$tinyLightbox.remove();
					$overlay.remove();
					$(document).unbind('keydown');
					inProgress = false;
				});	
			});
		};


		/********************************************************************************************************/
		//Main function for changing of image

		function changeImage (sw){
			//to prevent the double click or keydown
			if ( !inProgress )
			{
				if ( images[activeImageId+sw])
				{
					activeImageId = activeImageId + sw;
					inProgress = true;
							
					removeBar(function(){
						removeImage(function(){
							preloadImage(images[activeImageId], function(image){
								animate(image, function(){
									showImage(image);
									inProgress = false;
								});
							});
						});
					});

				} else 
					//its error - out of stack
					return true;
			};
		};

			
		/********************************************************************************************************/
		//helper functions

		function resizeOverlay ()
		{
			initDocSize();
			$overlay.css({'height': wHeight + d.top+100});
		};
		
		function initDocSize ()
		{
			scrollTop = $(document).scrollTop(); 
			wHeight= $(document).height() + scrollTop;
			wWidth= $(document).width();
		};
		
		function preloadImage (url, callback)
		{
			$tinyLightbox.addClass('loading');
			pause(100,function(){
				var prelImage = new Image();
				prelImage.onload=function()
				{	
					$tinyLightbox.removeClass('loading');
					callback(prelImage);
				}
				prelImage.src= url;
			
			});
		};
		function getGalStats ()
		{
			return images.length > 1 ? '<span>'+d.statLabelImage+' '+ (activeImageId+1) +' '+ d.statLabelFrom+' '+ images.length+'</span>' : '';
		};
		
		function pause ( time, callback )
		{
			if ( time && callback )
			{
				pauseCallback = callback;
				setTimeout(pause, time );
			}
			else	
				pauseCallback();
		}
		/********************************************************************************************************/
		//Additional functions
		
		function bindKeyNavigation ()
		{
			$(document).keydown(function(e){
				//39 -> 37 <- 27 esc
				var re;
				if ( e.keyCode == 39)
					re = changeImage(1);
				else if (e.keyCode == 37)
					re = changeImage(-1);
				else if (e.keyCode == 27)
					close();
				if ( re )
					shake($tinyLightbox, 20, 150);	
			 });
		};
		
		function slideshow ( sw )
		{
			if ( d.slideshow && sw == 'getBtn' && images.length>1 )
			{
				if ( slideshowInterval )
					return $('<a id="slideShowLabelStop" class="button label-stop"></a>').click(function(){
						slideshow('stop');
						$(this).attr('id','slideShowLabelStart');
					});
				else
					return $('<a id="slideShowLabelStart" class="button label-start"></a>').click(function(){
						slideshow();
						$(this).attr('id','slideShowLabelStop');
						if ( !slideshowInterval )
							slideshowInterval = setInterval(slideshow, d.slideshow);
					});
			}
			else if ( !sw )
			{
				if ( changeImage(1) )
				{
					activeImageId = -1;
					changeImage(1);
				};
			}
			else if ( sw == 'stop' )
			{
				clearInterval(slideshowInterval);
				slideshowInterval = null;
			};
		};
		



	};//end of $.tinyLightbox
	
	

})( jQuery );