// Lightbox für rel-Tag vorbereiten
$(function() {$('a[rel*=lightbox]').lightBox();});

(function($) {
    // Lightbox aufruf für ein jQuery-Element
	$.fn.lightBox = function(settings) {
		// Einstellungen festlegen
		settings = jQuery.extend({
			overlayBgColor: 		      '#000',
			overlayOpacity:			      0.8,
			fixedNavigation:		      false,
			imageLoading:			      '/layout/gallery/loading.gif',
			imageBtnPrev:			      '/layout/gallery/prev.gif',
			imageBtnPrevHover:		      '/layout/gallery/prev_1.gif',
			imageBtnNext:			      '/layout/gallery/next.gif',
			imageBtnNextHover:		      '/layout/gallery/next_1.gif',
			imageBtnClose:			      '/layout/gallery/close.gif',
			imageBtnCloseHover:		      '/layout/gallery/close_1.gif',
			imageBtnSlideshow:		      '/layout/gallery/slide_off.gif',
			imageBtnSlideshowHover:	      '/layout/gallery/slide_off_1.gif',
			imageBtnSlideshowActive:      '/layout/gallery/slide_on.gif',
			imageBtnSlideshowActiveHover: '/layout/gallery/slide_on_1.gif',
			imageBlank:				      '/layout/gallery/blank.gif',
			overlayFadeInSpeed:	          400,
			lightboxBorderSize:	          10,
			lightboxFadeInSpeed:	      300,
			lightboxResizeSpeed:	      400,
			lightboxRepositionSpeed:      800,
			imageDataSlideSpeed:          'fast',
			txtImage:				      'Bild',
			txtOf:					      'von',
			keyToClose:				      'c',
			keyToPrev:				      'p',
			keyToNext:				      'n',
			keyToToggleSlideshow:	      's',
			imageArray:				      [],
			activeImage:			      0,
			slideShowSpeed:               6000,
			ignoreMultiple:               false,
			showInfo:                     true,
			lightboxImageLoop:            true,
			disableSlideshow:             true
		},settings);

        // Funktionsübergreifen Variablen
		var jQueryMatchedObj = this;
		var objImagePreloader;
		var slideshowTimeout;
		var slideshowMode = 0;

		// Laden der Lightbox
		function _start(objClicked) {
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			_set_interface();

			uniqueArray = [];
			settings.imageArray.length = 0;
			settings.activeImage = 0;

			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				$.each(jQueryMatchedObj, function() {
					if (settings.ignoreMultiple) {
					    if ($.inArray(this.getAttribute('href'), uniqueArray) != -1) { return false; }
					    uniqueArray.push(this.getAttribute('href'));
					}
					settings.imageArray.push(new Array(this.getAttribute('href'),this.getAttribute('title')));
				});
			}

			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}

			_set_image_to_view();
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="jquery-overlay"></div>
			<div id="jquery-lightbox">
				<div id="lightbox-container-image-box">
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image">
						<div id="lightbox-nav">
							<a href="#" id="lightbox-nav-btnPrev"></a>
							<a href="#" id="lightbox-nav-btnNext"></a>
						</div>
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../images/lightbox-ico-loading.gif">
							</a>
						</div>
					</div>
				</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-secNav">
							<a href="#" id="lightbox-secNav-btnClose">
								<img src="../images/lightbox-btn-close.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			var arrPageSizes = ___getPageSize();
			var arrPageScroll = ___getPageScroll();

			$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></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-secNav"><a href="#" id="lightbox-secNav-btnSlide"></a><a href="#" id="lightbox-secNav-btnClose"></a><div style="clear: both"></div></div></div></div></div>');
			$('#jquery-lightbox,#jquery-overlay,#lightbox-loading').hide();

			if (settings.disableSlideshow) {
				$('#lightbox-secNav-btnSlide').hide();
			}

			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				'100%',
				height:				arrPageSizes[1]
			}).fadeIn(settings.overlayFadeInSpeed, function() {
    			$('#jquery-lightbox').css({
    				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
    				left:	arrPageScroll[0]
    			}).fadeIn(settings.lightboxFadeInSpeed);
            })

            // Close
            var imageBtnClose = new Image();
            imageBtnClose.src = settings.imageBtnClose;
            imageBtnClose.onload = function() {                $('#lightbox-secNav-btnClose').css({ 'height' : imageBtnClose.height});
            }
			$('#lightbox-secNav-btnClose').unbind().css({ 'background' : 'url(' + settings.imageBtnClose + ') right no-repeat' }).hover(function() {
				$(this).css({ 'background' : 'url(' + settings.imageBtnCloseHover + ') right no-repeat' });
			},function() {
				$(this).css({ 'background' : 'transparent url(' + settings.imageBtnClose + ') right no-repeat' });
			}).show();

			// Slide
            var imageBtnSlide = new Image();
            imageBtnSlide.src = settings.imageBtnSlideshow;
            imageBtnSlide.onload = function() {
                $('#lightbox-secNav-btnSlide').css({ 'height' : imageBtnSlide.height});
            }
			$('#lightbox-secNav-btnSlide').unbind().css({ 'background' : 'url(' + settings.imageBtnSlideshow + ') center no-repeat' }).hover(function() {
				$(this).css({ 'background' : 'url(' + settings.imageBtnSlideshowHover + ') center no-repeat' });
			},function() {
				$(this).css({ 'background' : 'transparent url(' + settings.imageBtnSlideshow + ') center no-repeat' });
			}).show();

			// Prev
			var imageBtnPrev = new Image();
            imageBtnPrev.src = settings.imageBtnPrev;
            imageBtnPrev.onload = function() {
                //$('#lightbox-nav-btnPrev').css({ 'height' : imageBtnPrev.height});
            }
			$('#lightbox-nav-btnPrev').unbind().css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' }).hover(function() {
				$(this).css({ 'background' : 'url(' + settings.imageBtnPrevHover + ') left 15% no-repeat' });
			},function() {
				$(this).css({ 'background' : 'transparent url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
			}).show();

			// Next
			var imageBtnNext = new Image();
            imageBtnNext.src = settings.imageBtnNext;
            imageBtnNext.onload = function() {
                //$('#lightbox-nav-btnNext').css({ 'height' : imageBtnNext.height});
            }
			$('#lightbox-nav-btnNext').unbind().css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' }).hover(function() {
				$(this).css({ 'background' : 'url(' + settings.imageBtnNextHover + ') right 15% no-repeat' });
			},function() {
				$(this).css({ 'background' : 'transparent url(' + settings.imageBtnNext + ') right 15% no-repeat' });
			}).show();

			$('#jquery-overlay,#jquery-lightbox').click(function() {
				_finish();
			});

			$('#lightbox-secNav-btnSlide').click(function() {
			    _toggle_slideshow();
			    return false;
			});

			$('#lightbox-nav-btnPrev').click(function() {
						return _show_image_prev();
			});

			$('#lightbox-nav-btnNext').click(function() {
						return _show_image_next();
			});

			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});

			$(window).resize(function() {
				var arrPageSizes = ___getPageSize();

				$('#jquery-overlay').css({
    				backgroundColor:	settings.overlayBgColor,
    				opacity:			settings.overlayOpacity,
    				width:				'100%',
    				height:				arrPageSizes[1]
    			}).show();

				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
			});
		}

		function _set_image_to_view() {
			$('#lightbox-loading').show();

			if ( settings.fixedNavigation ) {
				$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			} else {
				$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			}

			objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};

		function _resize_container_image_box(intImageWidth,intImageHeight) {

			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();

			var intWidth = (intImageWidth + (settings.lightboxBorderSize * 2));
			var intHeight = (intImageHeight + (settings.lightboxBorderSize * 2));

			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;

			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.lightboxResizeSpeed,function() { _reposition_container_image_box(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);
				}
			}

            // EDITORS NOTE - CSS Problem muss behoben werden
            $('#lightbox-container-image-data-box').css({ width: intImageWidth });
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intHeight });
		};

		function _reposition_container_image_box() {
			var arrPageScroll = ___getPageScroll();

			var nHeight = parseInt($('#jquery-lightbox').height(),10);

			var nTop = arrPageScroll[1] + ($(window).height() - nHeight) / 2.5;
			var nLeft = arrPageScroll[0];

			if (nTop < 0) {nTop = 0;}

			$('#jquery-lightbox').animate({
				left: nLeft,
				top: nTop
			}, settings.lightboxRepositionSpeed, function() { _show_image(); });
		}

		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();

			if (slideshowMode) { _slideshow_start(); }
		};

		function _show_image_prev() {
			_slideshow_stop();

			if ( settings.activeImage != 0 ) {
				settings.activeImage = --settings.activeImage;
				_set_image_to_view();
				_disable_keyboard_navigation();
			} else if ( settings.lightboxImageLoop ) {			    settings.activeImage = settings.imageArray.length - 1;
				_set_image_to_view();
				_disable_keyboard_navigation();
			}

			return false;
		};

		function _show_image_next() {
			_slideshow_stop();

			if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
				settings.activeImage = ++settings.activeImage;
				_set_image_to_view();
				_disable_keyboard_navigation();
			} else if ( settings.lightboxImageLoop ) {				settings.activeImage = 0;
				_set_image_to_view();
				_disable_keyboard_navigation();
			}

			return false;
		};

		function _show_image_data() {
			$('#lightbox-container-image-data-box').slideDown(settings.imageDataSlideSpeed);
			if (settings.showInfo) {
    			$('#lightbox-image-details-caption').hide();
    			if ( settings.imageArray[settings.activeImage][1] ) {
    				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
    			}

    			if ( settings.imageArray.length > 1 ) {
    				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
    			}
            }
		}


		function _set_navigation() {
			$('#lightbox-nav').show();


			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').hide();


            if ( ( settings.lightboxImageLoop && settings.imageArray.length > 1 ) || settings.activeImage != 0 ) {
				$('#lightbox-nav-btnPrev').show();
			}

			if ( ( settings.lightboxImageLoop && settings.imageArray.length > 1 ) || settings.activeImage != ( settings.imageArray.length -1 ) ) {
				$('#lightbox-nav-btnNext').show();
			}

			_enable_keyboard_navigation();
		}

		// Keyboardfunktionen aktivieren
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}

		// Keyboardfunktionen deaktivieren
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}

		// Keyboardfunktionen
		function _keyboard_action(objEvent) {

			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}

			key = String.fromCharCode(keycode).toLowerCase();

			if ( ( key == settings.keyToClose ) || ( keycode == escapeKey ) ) {
				_finish();
			}

			if ( key == settings.keyToPrev ) {
				_show_image_prev();
			}

			if ( key == settings.keyToNext ) {
				_show_image_next();
			}

			if ( key == settings.keyToToggleSlideshow ) {
				_toggle_slideshow();
			}
		}

		// Benachbarte Bilder laden
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			} else if (settings.lightboxImageLoop && (settings.imageArray.length -1) == settings.activeImage) {
				objNext = new Image();
				objNext.src = settings.imageArray[0][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			} else if (settings.lightboxImageLoop && settings.activeImage == 0) {
				objNext = new Image();
				objNext.src = settings.imageArray[(settings.imageArray.length -1)][0];
			}
		}

		// Slodeshow starten
		function _slideshow_start() {
            _slideshow_stop();

			if (settings.imageArray.length > 1) {
                slideshowTimeout = setTimeout(function(){_show_image_next();}, settings.slideShowSpeed);
			}
		}

		// Slideshow anhalten
		function _slideshow_stop( clear ) {
            clearTimeout(slideshowTimeout);
		}

		function _toggle_slideshow() {
			if (!slideshowMode) {
				slideshowMode = 1;
			   	_slideshow_start();
			   	$('#lightbox-secNav-btnSlide').css({ 'background' : 'url(' + settings.imageBtnSlideshowActive + ') center no-repeat' }).hover(function() {
        			$(this).css({ 'background' : 'url(' + settings.imageBtnSlideshowActiveHover + ') center no-repeat' });
        		},function() {
        			$(this).css({ 'background' : 'transparent url(' + settings.imageBtnSlideshowActive + ') center no-repeat' });
        		}).show();
			} else {
				slideshowMode = 0;
				_slideshow_stop();
			   	$('#lightbox-secNav-btnSlide').css({ 'background' : 'url(' + settings.imageBtnSlideshow + ') center no-repeat' }).hover(function() {
        			$(this).css({ 'background' : 'url(' + settings.imageBtnSlideshowHover + ') center no-repeat' });
        		},function() {
        			$(this).css({ 'background' : 'transparent url(' + settings.imageBtnSlideshow + ') center no-repeat' });
        		}).show();
			}
		}

		// Lightbox entfernen
		function _finish() {			_slideshow_stop()
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}


		// Seitengröße
		function ___getPageSize() {
			var xScroll, yScroll;

        	if (window.innerHeight && window.scrollMaxY) {
        		xScroll = document.body.scrollWidth;
        		yScroll = window.innerHeight + window.scrollMaxY;
        	} else if (document.body.scrollHeight > document.body.offsetHeight){
        		xScroll = document.body.scrollWidth;
        		yScroll = document.body.scrollHeight;
        	} else {
        		xScroll = document.body.offsetWidth;
        		yScroll = document.body.offsetHeight;
        	}

        	var windowWidth, windowHeight;
        	if (self.innerHeight) {
        		windowWidth = self.innerWidth;
        		windowHeight = self.innerHeight;
        	} else if (document.documentElement && document.documentElement.clientHeight) {
        		windowWidth = document.documentElement.clientWidth;
        		windowHeight = document.documentElement.clientHeight;
        	} else if (document.body) {
        		windowWidth = document.body.clientWidth;
        		windowHeight = document.body.clientHeight;
        	}

        	if(yScroll < windowHeight){
        		pageHeight = windowHeight;
        	} else {
        		pageHeight = yScroll;
        	}

        	if(xScroll < windowWidth){
        		pageWidth = windowWidth;
        	} else {
        		pageWidth = xScroll;
        	}

        	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
        	return arrayPageSize;
		};

        // Scrollposition der Seite
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};

		function ___pause(ms) {
			var date = new Date();
			curDate = null;
			do { var curDate = new Date(); }
		    while ( curDate - date < ms);
		};

		return this.unbind('click').click(function() {		    _start(this);
		    return false;
		});
	};
})(jQuery);
