/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com, heavily modified by Franz Koch - http://elements-net.de
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:		0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			showDownload:			false,			// (boolean)
			enableDiashow:			true,			// (boolean)
			diashowDelay:			5000,			// (integer)
			loop:						false,
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			txtNext:					'&gt;', // (string) Specify text "Next >"
			titleNext:				'next image',
			txtPrev:					'&lt;',	// (string) Specify text "< Previous"
			titlePrev:				'previous image',
			txtClose:				'x',	// (string) Specify text "close"
			titleClose:				'close window',
			txtSave:					'save',	// (string) Specify text "save"
			titleSave:				'download image',
			txtPlay:					'start Diashow', // (string)
			txtPause:				'pause Diashow', // (string)
			groupByAttribute:		'rel',	// (string) create image-sets based on defined attribute values
			// Change with care
			attrTarget:				'$this',//'$this.children(\'img\')',
			useAsTitle:				'$this.attr(\'title\')',//'$(\'#\'+$this.attr(\'name\')).html()', //available objects: $this (jQueryObject from matching lightbox enabled item), $tgt (jQueryObject from settings.attrTarget)
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			keyToPlay:				' ',	// (string)
			// Configuration of
			// Don�t alter these variables in any way
			imageArray:				[],
			activeImage:			0,
			buttons:					['Close','Next','Prev','Save','Play','Pause']
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this, // This, in this context, refer to jQuery object
			isPlaying = false;
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			settings.imageArray = new Array();
			// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
			jQueryMatchedObj.each(function(i) {
				var $this = $(this);
				if((settings.groupByAttribute == '' || settings.groupByAttribute == false) || (settings.groupByAttribute && $this.attr(settings.groupByAttribute) == $(objClicked).attr(settings.groupByAttribute))) {
					var $tgt = eval(settings.attrTarget),
						title;
					if(settings.useAsTitle) {
						title = eval(settings.useAsTitle);
					}
					settings.imageArray.push(new Array($this.attr('href'),(title ? title : $tgt.attr('title')) ));
					
					//check if it's the clicked item to set correct value for activeImage
					if(this == objClicked) {
						settings.activeImage = settings.imageArray.length -1;
					}
				}
			});

			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 */
		function _set_interface() {
			var template = '<div id="jquery-overlay" /><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><div id="lightbox-topNav">{BTN_CLOSE}</div><img id="lightbox-image" /><div id="lightbox-nav">{BTN_PREV}{BTN_NEXT}</div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-bottomNav">{BTN_SAVE}{BTN_PLAY}{BTN_PAUSE}</div></div><span class="lightbox-clear"><!-- --></span></div></div></div>';
			// Create buttons
			$.each(settings.buttons,function(index, value) {
				var txt = eval('settings.txt' + value),
					title = eval('settings.title' + value);
				template = template.replace('{BTN_' + value.toUpperCase() + '}', '<a href="#" class="navButton" id="lightbox-btn' + value + '" title="' + (title ? title : txt) + '" style="display:none;"><span>' + txt + '</span></a>');
			});
			// Apply the HTML markup into body tag
			$('body').append(template);	

			_update_positioning();
			
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity
			}).fadeIn();

			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading,#lightbox-btnClose,#jquery-overlay').bind('click',_finish).show();
			
			// handle diashow
			if (settings.enableDiashow && settings.imageArray.length > 1) {
				$('#lightbox-btnPlay').bind('click',_play).show();
				$('#lightbox-btnPause').bind('click',_pause).hide();
			}
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				_update_positioning();
			});
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		
		function _update_positioning() {
			// Get page sizes
			var dims = ___getPageSize(),
				scroll = ___getPageScroll();
			// Style overlay and show it
			$('#jquery-overlay').css({
				width:	dims.pageWidth,
				height:	dims.pageHeight
			});

			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	scroll.y + (dims.pageHeight/10),
				left:	scroll.x
			}).show();	
		}
		/**
		 * Prepares image exibition; doing a image�s preloader to calculate it�s size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#lightbox-container-image-box').toggleClass('loading');
			$('#lightbox-image,#lightbox-nav,#lightbox-btnPrev,#lightbox-btnNext,#lightbox-container-image-data-box').hide();
			$('#lightbox-btnPrev,#lightbox-btnNext').css('visibility','hidden'); //for stupid IE6

			// Image preload process
			var objImagePreloader = new Image(), 
				img =settings.imageArray[settings.activeImage][0];
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',img);
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = img;
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The image�s width that will be showed
		 * @param integer intImageHeight The image�s height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get the width and height of the selected image plus the padding
			$('#lightbox-container-image-box').animate({ width: (intImageWidth + (settings.containerBorderSize * 2)), height:(intImageHeight + (settings.containerBorderSize * 2))  },settings.containerResizeSpeed,function() { _show_image(); });
			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
			$('#lightbox-btnPrev,#lightbox-btnNext').css({ height: intImageHeight });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-container-image-box').toggleClass('loading');
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-container-image-data-box').fadeIn();
			$('#lightbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').fadeIn();
			// If a download link should be shown
			if ( settings.showDownload ) {
				$('#lightbox-btnSave').attr('href',settings.imageArray[settings.activeImage][0]).attr('target','_blank').show();
			}
			if(settings.imageArray.length > 1) {
				if(!isPlaying) {
					// Show the prev button, if not the first image in set
					if (settings.activeImage -1 >= 0 || settings.loop ) {
						$('#lightbox-btnPrev').show().css('visibility','visible').unbind().bind('click',_prev_image);
					}
					// Show the next button, if not the last image in set
					if (settings.activeImage +1 <= settings.imageArray.length -1 || settings.loop ) {
						$('#lightbox-btnNext').show().css('visibility','visible').unbind().bind('click',_next_image);
					}
				} else {
					_initTimer();	
				}
			}
		}

		function _prev_image() {
			if(settings.activeImage -1 >= 0) {
				settings.activeImage--;
				_set_image_to_view();
			} else if(settings.loop) {
				settings.activeImage = settings.imageArray.length -1;
				_set_image_to_view();
			} else {
				_pause();	
			}
			return false;
		}
		
		function _next_image() {
			if(settings.activeImage +1 <= settings.imageArray.length -1) {
				settings.activeImage++;
				_set_image_to_view();
			} else if(settings.loop) {
				settings.activeImage = 0;
				_set_image_to_view();
			} else {
				_pause();	
			}
			return false;
		}

		function _play() {
			if(!isPlaying) {
				isPlaying = true;
				_initTimer();
				$('#lightbox-nav').fadeOut();
				$('#lightbox-btnPlay').hide();
				$('#lightbox-btnPause').show();
			}
			return false;
		}
		
		function _pause() {
			if (isPlaying)	{
				$('#lightbox-diashow').remove();
				isPlaying = false;
				_initTimer();
				_set_navigation();
				$('#lightbox-btnPlay').show();
				$('#lightbox-nav').fadeIn();
				$('#lightbox-btnPause').hide();
			}
			return false;
		}

		function _initTimer() {
			if(!$('#lightbox-diashow').html()) {
				$('#lightbox-container-image-data').prepend('<div id="lightbox-diashow"><span id="lightbox-diashow-timer" /></div>');
			}
			var $t = $('#lightbox-diashow-timer');
			if(isPlaying) {
				$t.css('width',0).hide().animate({width:"100%"},settings.diashowDelay,'linear',function() {
					// unfortunately the callback function seems not to get removed when the animation is stopped.
					// So for now, check if the diashow element still exists - if not, don't trigger the callback
					if($('#lightbox-diashow').html()) {
						_next_image();
					}
				});
			} else {
				$t.stop();
				$('#lightbox-diashow').remove();
			}
		}

		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// For IE
			if ( objEvent == null ) {
				keyCode = event.keyCode;
				escapeKey = 27;
			// For Mozilla
			} else {
				keyCode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			if(isPlaying) {
				_pause();	
			}
			switch (keyCode){
				case escapeKey: case 88: case 67: case settings.keyToClose.charCodeAt(0): _finish(); break;
				case 37: case 80: case settings.keyToPrev.charCodeAt(0): _prev_image(); break;	
				case 39: case 78: case settings.keyToNext.charCodeAt(0): _next_image(); break;
				case 83: case settings.keyToPlay.charCodeAt(0): if(isPlaying){_pause();}else{_play();}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			_pause();
			_disable_keyboard_navigation();
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
			return false;
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var dims = {},
				dbw,
				dbh;
			
			if (window.innerHeight && window.scrollMaxY) {	
				dbw = window.innerWidth + window.scrollMaxX;
				dbh = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				dbw = document.body.scrollWidth;
				dbh = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				dbw = document.body.offsetWidth;
				dbh = document.body.offsetHeight;
			}
			
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					dims.windowWidth = document.documentElement.clientWidth; 
				} else {
					dims.windowWidth = self.innerWidth;
				}
				dims.windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				dims.windowWidth = document.documentElement.clientWidth;
				dims.windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				dims.windowWidth = document.body.clientWidth;
				dims.windowHeight = document.body.clientHeight;
			}

			dims.pageHeight = Math.max(dbh, dims.windowHeight);
			dims.pageWidth = Math.max(dbw, dims.windowWidth);
			//console.log(arrayPageSize);

			return dims;
		};
		
		function ___getPageScroll() {
			var scroll = {};
			
			if (self.pageYOffset) {
				scroll.y = self.pageYOffset;
				scroll.x = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				scroll.y = document.documentElement.scrollTop;
				scroll.x = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				scroll.y = document.body.scrollTop;
				scroll.x = document.body.scrollLeft;	
			}
			
			return scroll;
		}

		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object


/* custom additions for website */
// jQuery
$(function() {
	// lightbox
	$('a[rel*=lightbox]').lightBox({attrTarget:'$this.children(\'img\')',useAsTitle:'$(\'#\'+$this.attr(\'name\')).html()',txtImage:'Bild',txtOf:'von',txtNext:'&gt;', titleNext:'nächstes Bild', txtPrev:'&lt;', titlePrev:'vorheriges Bild', txtClose:'x', titleClose:'Fenster schließen', txtPlay:'Diashow starten', txtPause:'Diashow anhalten'});

	// Direct Access	
	$('select#direct_access').bind('change',function(e) {
		if(this.value != '') window.location.href = this.value;	
	});

	// handle preset text in searchboxes
	$('form[name=teaser_search]').each( function() {
		var sf = $(this).find('input.searchinput'),
			dt = sf.val(); //default text
		if(dt != '' && dt != undefined) {
			$(this).submit(function() {
				if(sf.val() == dt) {
					return false;	
				}
			});
			sf.focus(function() {
				if($(this).val() == dt) {
					$(this).val('');					
				}
			})
			.blur(function() {
				if($(this).val() == '') {
					$(this).val(dt);	
				}
			});
		}
	});
});