/*
 * ZoomBox jQuery plugin
 * @category jQuery plugin
 * @copyright (c) mpunkt
 * @author reinhard naegler
 */

(function($){
	$.fn.zoombox = function(options){

		var defaults = {
			identifyBy:			'a',	// Bilder werden anhand diesem Selektor identifiziert (z.B. auch a.klasse möglich)
			switchDuration:		250,	// Wechseldauer in ms
			showPictureNumber:	true,	// Numerierung anzeigen
			showOverlay:		true,	// Overlay anzeigen?
			showNavigation:		true,	// Steuerung (vor/zurück) aktivieren? Nur bei mehreren Bildern
			keyNavigation:		true	// Tastaturnavigation (vor/zurück)
		};
		var options = $.extend(defaults, options);
		var isIE6 = $.browser.msie == true && $.browser.version == '6.0';

		return this.each(function(){

			// Folgende Variablen je Instanz
			var self = this;
			var images = [];
			var active_image = 0;
			var key_navigation = options.keyNavigation;
			var show_navigation = options.showNavigation;

			this.collect = function(){
				$(self).find(options.identifyBy).each(function(i){
					images[images.length] = {
					    src: $(this).attr('href'),
					    title: ($(this).attr('title') ? $(this).attr('title') : ($(this).find('img').attr('title') ? $(this).find('img').attr('title') : '')),
					    width: 0,
					    height: 0
					}
					$(this).click(function(){
						self.show(i);
						return false;
					});
				});
				if(images.length <= 1) show_navigation = key_navigation = false;
			}

			this.create = function(){
				if($('#zoombox-div')[0] == undefined){
				    self.enableAutoResize();
				    $('embed, object, select').css('visibility','hidden');
					$('body').append((options.showOverlay===true?'<div id="zoombox-bg"></div>':'')+'<div id="zoombox-div"></div>');
					if(isIE6 == true){
					    document.body.style.overflow = 'auto';
						$('#zoombox-bg').css('position','absolute'); // wegen position:fixed
						$('#zoombox-div').css('position','absolute'); // wegen position:fixed
					}
					$('#zoombox-div').css({
						width: '150px',
						height: '150px',
	                    marginLeft: '-75px',
	                    marginTop: '-75px'
					});
					$('#zoombox-bg').click(self.close);
				}
			}

			this.show = function(i){
			    self.disableKeyNav();

				active_image = i;
				if(active_image >= images.length) active_image = 0;
				if(active_image < 0) active_image = images.length-1;

                if($('#zoombox-div')[0] == undefined) self.create();

                $('#zoombox-div').html('');
				var preload_image = new Image();
				preload_image.onload = function(){
					// Originalgröße beibehalten
					images[active_image].width = this.width;
					images[active_image].height = this.height;
				    self.showImage();
				}
				preload_image.onerror = function(){
					// Bei Bildfehler
					self.enableKeyNav();
					$('#zoombox-div').prepend('<div id="zoombox-img" style="width:100%; height:100%; text-align:center;"><br /><br /><br />Bild kann nicht geladen werden!</div>');
				    if(show_navigation == true) $('#zoombox-div > #zoombox-img').click(self.next).css('cursor','pointer');
					$('#zoombox-div').prepend('<a href="#" id="zoombox-btn-close"></a>');
					$('#zoombox-btn-close').click(self.close);
					if(show_navigation == true){
						$('#zoombox-div').prepend('<a href="#" id="zoombox-btn-next"></a><a href="#" id="zoombox-btn-prev"></a>');
						$('#zoombox-btn-prev').click(self.prev);
						$('#zoombox-btn-next').click(self.next);
					}
					preload_image.onerror = function(){}
				}
				preload_image.src = images[active_image].src;
			}

			this.showImage = function(){

			    // Bild davor und danach schon mal vorladen
			    self.preloadNeighborImages();

				// Maximale Anzeigebreite und -höhe vom Body ermitteln
				maxWidth = document.body.clientWidth-100; // Max. Anzeigebreite
				maxHeight = document.body.clientHeight-100; // Max. Anzeigehöhe

				w = images[active_image].width;
				h = images[active_image].height;

				// Bildmaße ggf. verkleinern
				if(w > maxWidth)
				{
					h = Math.round(maxWidth/w*h);
					w = maxWidth;
				}
				if(h > maxHeight)
				{
				    w = Math.round(maxHeight/h*w);
					h = maxHeight;
				}

				w_div = w;
				h_div = h;

				// Caption
				if(show_navigation == true || images[active_image].title != ""){
					$('#zoombox-div').append('<div id="zoombox-caption" style="display:none; width:'+w_div+'px;"><div>'+images[active_image].title+
						(options.showPictureNumber == true ? ' <span>('+(active_image+1)+'/'+images.length+')</span>' : '')+
						'</div></div>');
					h_div = h_div+$('#zoombox-caption').height();
				}

				// Wenn sich die Zoomboxgröße für das nächste Bild nicht ändert, dann soll die animierte Wechseldauer 0 ms sein
				if($('#zoombox-div').width() == w_div && $('#zoombox-div').height() == h_div)
				    var switchTime = 0;
				else
				    var switchTime = options.switchDuration;

				$('#zoombox-div').animate({
                    width: w_div+'px',
                    height: h_div+'px',
                    marginLeft: '-'+Math.round(w_div/2)+'px',
                    marginTop: '-'+Math.round(h_div/2)+'px'
				}, switchTime, function(){
				    self.enableKeyNav();
                    $('#zoombox-div').prepend('<div id="zoombox-img"><img src="'+images[active_image].src+'" width="'+w+'" height="'+h+'" alt="" title="" style="display:none;" /></div>');
                    if(show_navigation == true) $('#zoombox-div > #zoombox-img > img').click(self.next).css('cursor','pointer');
                    $('#zoombox-div > #zoombox-img > img').fadeIn(function(){
                        $('#zoombox-div').prepend('<a href="#" id="zoombox-btn-close"></a>');
						$('#zoombox-btn-close').click(self.close);
						if(show_navigation == true){
							$('#zoombox-div').prepend('<a href="#" id="zoombox-btn-next"></a><a href="#" id="zoombox-btn-prev"></a>');
							$('#zoombox-btn-prev').click(self.prev);
							$('#zoombox-btn-next').click(self.next);
						}
					});
					$('#zoombox-caption').show();
				});
			
			}

			this.preloadNeighborImages = function(){
				if(active_image < (images.length -1)){
					imgNext = new Image();
					imgNext.src = images[active_image + 1].src;
				}
				if(active_image > 0){
					imgPrev = new Image();
					imgPrev.src = images[active_image -1].src;
				}
			}

			this.close = function(){
				if($('#zoombox-div')[0] != undefined){
				    $('embed, object, select').css('visibility','visible');
					$('#zoombox-bg').fadeOut(200,function(){
						$(this).remove();
					});
					$('#zoombox-div').remove();
				}
				self.disableKeyNav();
				self.disableAutoResize();
				if(isIE6 == true){
				    document.body.style.overflow = 'visible';
				}
				return false;
			}

			this.next = function(){
			    self.show(active_image+1);
			    return false;
			}

			this.prev = function(){
			    self.show(active_image-1);
			    return false;
			}

			this.enableKeyNav = function(){
				$(document).unbind('keydown').bind('keydown',function(e){
					if(e.keyCode == 27){
						e.preventDefault();
						self.close();
					}
			    	if(key_navigation == true && show_navigation == true){
						if(e.keyCode == 37){
							e.preventDefault();
							self.prev();
						}
						if(e.keyCode == 39){
							e.preventDefault();
							self.next();
						}
					}
				});
			}

			this.disableKeyNav = function(){
				$(document).unbind('keydown');
			}
			
			this.enableAutoResize = function(){
			    $(window).unbind('resize').bind('resize',function(){
                    self.autoResize();
			    });
			}

			this.disableAutoResize = function(){
			    $(window).unbind('resize');
			}
			
			this.autoResize = function(){
				// Maximale Anzeigebreite und -höhe vom Body ermitteln
				maxWidth = document.body.clientWidth-100; // Max. Anzeigebreite
				maxHeight = document.body.clientHeight-100; // Max. Anzeigehöhe

				w = images[active_image].width;
				h = images[active_image].height;

				// Bildmaße ggf. verkleinern
				if(w > maxWidth)
				{
					h = Math.round(maxWidth/w*h);
					w = maxWidth;
				}
				if(h > maxHeight)
				{
				    w = Math.round(maxHeight/h*w);
					h = maxHeight;
				}

				w_div = w;
				h_div = h;

				// Caption
				$('#zoombox-caption').width(w_div);
				h_div = h_div+$('#zoombox-caption').height();

				$('#zoombox-img > img').css({
					width: w+'px',
					height: h+'px'
				});

				$('#zoombox-div').css({
                    width: w_div+'px',
                    height: h_div+'px',
                    marginLeft: '-'+Math.round(w_div/2)+'px',
                    marginTop: '-'+Math.round(h_div/2)+'px'
				});
			}

			this.collect();

		});

	};
})(jQuery);




