/**
 * Bibliothek erstellt von Lutz Hoffarth.
 * Voraussetzung sind die Bibliotheken: jQuere-1.4.4, jQuere-ui-1.8.10
 * @author Lutz Hoffarth
 * @since 01.08.2011 Erstellt
 * 
 * @since 04.08.2011 Parallellaufende Animationen unterbunden.
 * @since 04.08.2011 Thumbleistenbreite wird aus kompatibilitätsgründen hardcodet berechnet.
 * @since 04.08.2011 Zuverlässiges zurückschalten des Galeriebildes umgesetzt.
 * 
 * @since 05.08.2011 Steuerung und Thumbs neu positioniert und angepasst.
 * @since 05.08.2011 Preload des Playsymbols zwecks unverzögernder Nutzung.
 * @since 05.08.2011 Universelle PreloadMethode: 'preloadImage(image)' in maria.js ausgelagert.
 * @since 05.08.2011 Steuerung ohne Warten auf Animationsende. Wenn der Fade läuft: abbruch und mit neuer ID weitermachen.
 * @since 05.08.2011 Logo eingebunden.
 * @since 05.08.2011 Navigationssymbole werden beim ersten ausblenden immernoch angezeigt. erledigt.
 * @since 10.08.2011 Exit- und Logoclick umgesetzt.
 * @since 10.08.2011 Lutz Hoffarth - Thumbs blenden ein und aus.
 * @since 05.08.2011 TODO Funktion der Einbindung von Titelimages von außen Checken.
 * @since 05.08.2011 TODO Browser Checken.
 * @since 05.08.2011 TODO Controllsymbole faden ungünstig aus.
 * @since 05.11.2011 Lutz Hoffarth | Um beim ersten laden der Seite das Erste Bild zu zeigen ist eine Größe der Gallery notwendig.
 */

/**
 * Seitenverhältnis der Galerie.
 */
var galleryAspectRatioWidth = 320; // 03.08.2011
var galleryAspectRatioHeight = 213; // 03.08.2011

/** @since 05.11.2011 Lutz Hoffarth */
var galleryMinHeight = 187; 

/**
 * @since 04.08.2011 Systempfad der Galerie.
 */
var gallerySystemPath = "resources/images/system/gallery/";
/**
 * @since 11.04.2011 Bildbpfad: "resources/images/gallery/background/"
 */
var galleryImagePath = "resources/images/gallery/background/";
var galleryImagePathThumb = galleryImagePath + "thumb/";
var galleryImagePathThumbInactiv = galleryImagePath + "thumbInactive/";
var galleryImageTitelPath = "resources/images/titel/";

/**
 * Zeitraum zwischen den Bildwechseln in Millisekunden.
 * @since 11.04.2011 - 2000
 * @since 21.10.2011 - 5000 | damit mehr Zeit zum Laden ist & wirkt entspannter
 */
var galleryCenterFadeInterval = 5000;
/**
 * Dauer der Animation des Verschiebens der Thumbs.
 * @since 04.08.2011 - 500
 * @since 21.10.2011 - 700
 */
var galleryThumbSlideTime = 700;
/**
 * Dauer der Animation des Überblendens beim Bildwechsels im zentralen Sichtbereich.
 * @since 04.08.2011 - 1000
 */
var galleryCenterAnimationTime = 1000;

/**
 * Höhe des Navigationsmenübar.
 * @since 02.08.2011 35
 * @since 05.08.2011 37
 */
var galleryNavBarHeight = 37;
/**
 * Breite des einzelnen Thumbnails
 * @since 04.08.2011 53
 * @since 05.08.2011 56
 */
var galleryThumbWidth = 56;
/**
 * Abstand zwischen den einzelnen Thumbnails
 * @since 05.08.2011 1
 */
var galleryThumbPadding = 1;
/**
 * Breite der Leiste mit den sichtbaren Thumbnails.
 * @since 03.08.2011 805
 * @since 05.08.2011 854
 */
var galleryNavThumbBarWidth = 854;
/**
 * Breite der Leiste der Thumbnails
 * @since 04.08.2011 940
 */
var galleryNavThumbBarFrameWidth = 940;

/**
 * Animationsparameter für Content- und Center-Bereich
 */
//var galleryAnimation = new Animation(Animation.EASING_EFFECT_EXPO, Animation.EASING_LOCATION_OUT, 5000);
var galleryAnimation = new Animation(Animation.EASING_EFFECT_LINEAR, Animation.EASING_LOCATION_NONE, galleryCenterAnimationTime);

/**
 * @since 11.04.2011
 */
var galleryAutoFadePaused = false;
/**
 * @since 11.04.2011
 */
var galleryAutoFade = true;

/**
 * @version 08.03.2011
 */
var galleryOldIdCenter = "0";

/**
 * @since 04.08.2011 
 */
var galleryIsFade = false;
/**
 * Vermeidet parallele durchläufe der Animation.
 * @since 04.08.2011
 */
var galleryIsRun = false;

/**
 * @since 04.08.2011 
 */
var galleryImageIds;

/**
 * @since 10.08.2011 Lutz Hoffarth Wird für den Logo- und Exit-Click benötigt.
 */
var isToHomeClick = false;

/**
 * @since 10.08.2011 Lutz Hoffarth
 */
var galleryShowTitle = false;

//var galleryFadeTitelImage = false;
/**
 * im Moment laufende aktivierung eines Thumbnails 
 * @since 12.08.2011 Lutz Hoffarth */
var activateThumb = null;
/**
 * im Moment laufende deaktivierung eines Thumbnails 
 * @since 12.08.2011 Lutz Hoffarth */
var inactivateThumb = null;

/**
 * Ständig verwendete HTML-Objecte werden zwecks performance und Speicherlast einmalig definiert.
 * @since 12.08.2011 Lutz Hoffarth
 */
var galleryId_galleryCenterView; // = $("#galleryCenterView");
var galleryId_galleryNaviThumbs; // = $("#galleryNaviThumbs");
var galleryId_galleryThumb; // = $("#galleryThumb");
var galleryId_galleryNaviControlPlaySymbol; // = $("#galleryNaviControlPlaySymbol");
var galleryId_galleryNaviControlLeftSymbol; // = $("#galleryNaviControlLeftSymbol");
var galleryId_galleryNaviControlExitSymbol; // = $("#galleryNaviControlExitSymbol");
var galleryId_galleryNaviControlRightSymbol; // = $("#galleryNaviControlRightSymbol");
var galleryId_galleryLogoImage; // = $("#galleryLogoImage");
var galleryId_galleryImageWrapper; // = $("#galleryImageWrapper");
var galleryId_galleryNaviBar; // = $("#galleryNaviBar");
var galleryId_galleryCenterImage; // = $("#galleryCenterImage");
var galleryId_galleryNaviControlFrame; // = $("#galleryNaviControlFrame");
var galleryID_galleryThumbAktive_;

/**
 * Pausiert die Gallery bei Fokusverlust, lässt sie weiterlaufen bei Fokusaufnahme.
 * @since 12.10.2011 Adam Laszlo | Erstellt
 */
$(function() {
	var galleryWasRunning = true;

	function onBlur() {
		galleryWasRunning = galleryAutoFade && !galleryAutoFadePaused;
		pauseGalleryAutoFade();
	}
	;
	function onFocus() {
		if (galleryWasRunning) {
			galleryPausedPlay();
		}
	}
	;

	if ($.browser.msie) { // für Internet Explorer
		document.onfocusin = onFocus;
		document.onfocusout = onBlur;
	} else {
		window.onfocus = onFocus;
		window.onblur = onBlur;
	}
});

/**
 * @author Lutz Hoffarth
 * @since 03.08.2011
 */
function galleryFadeTo(galleryId) {
	pauseGalleryAutoFade();
	fadeCenterTo(galleryId);
}

/**
 * @author Lutz Hoffarth
 * @since 03.08.2011
 */
function galleryPausedPlay() {
	if (galleryAutoFadePaused) {
		runGalleryAutoFade();
	} else {
		pauseGalleryAutoFade();
	}
}

/**
 * @author Lutz Hoffarth
 * @since 03.08.2011
 */
function galleryShowNextImage() {
	fadeStop();
	pauseGalleryAutoFade();
	fadeCenterTo(getNextId());
}

/**
 * @author Lutz Hoffarth
 * @since 03.08.2011
 */
function galleryShowPreviousImage() {
	fadeStop();
	pauseGalleryAutoFade();
	fadeCenterTo(getPreviouId());
}

/**
 * @author Lutz Hoffarth
 * @since 03.08.2011
 * @since 10.08.2011 Lutz Hoffarth
 * @since 13.08.2011 Lutz Hoffarth - Optimierung durch Variableneinsatz.
 */
function galleryMouseOver(galleryId) {
	//	$("#galleryThumb_" + galleryId).attr("src", galleryImagePathThumb + "Image_" + galleryId + ".jpg");
	galleryID_galleryThumbAktive_[galleryId].css("opacity", 1);
}

/**
 * @author Lutz Hoffarth
 * @since 03.08.2011
 * @since 10.08.2011 Lutz Hoffarth
 */
function galleryMouseOut(galleryId) {
	if (galleryId == galleryOldIdCenter)
		//		$("#galleryThumb_" + galleryId).attr("src", galleryImagePathThumb + "Image_" + galleryId + ".jpg");
		galleryID_galleryThumbAktive_[galleryId].css("opacity", 1);
	else
		//		$("#galleryThumb_" + galleryId).attr("src", galleryImagePathThumbInactiv + "Image_" + galleryId + ".jpg");
		galleryID_galleryThumbAktive_[galleryId].css("opacity", 0);
}

/**
 * Zeichnet das aktive Thumbnail anhand der var: galleryOldIdCenter.<br>
 * Zusätzlich wird die Thumbleiste '#galleryNaviThumbs' bei bedarf um 'left: ?px;' nach links oder rechts verschoben.
 * @author Lutz Hoffarth
 * @since 03.08.2011
 * @since 05.08.2011 Positionierung ausgerichtet.
 * @since 10.08.2011 Lutz Hoffarth Thumb einblenden.
 * @since 25.08.2011 Adam Laszlo | Korrektur, für scrollen mit dynamischen Image IDs
 */
function setThumbActiv() {
	//	debug("function setThumbActiv() galleryID_galleryThumbAktive_["+galleryOldIdCenter+"]:"+galleryID_galleryThumbAktive_[galleryOldIdCenter]);
	if (galleryOldIdCenter == 0) return;

	// Thumbs werden eingeblendet.
	activateThumb = galleryID_galleryThumbAktive_[galleryOldIdCenter];
	if (activateThumb == undefined) return;
	activateThumb.stop().animate({
		opacity : 1
	}, galleryThumbSlideTime * 1.5, galleryAnimation.getEasing(), function() {
		activateThumb = null;
	});

	// Thumbleiste '#galleryNaviThumbs' bei bedarf um 'left: ?px;' verschieben.
	var aktLeft = 0;
	var aktWidth = 0;
	//	var thumbWidth = 0;
	// Berechnung der Positionen und Maße.
	for ( var i = 0; i < galleryImageIds.length; i++) {
		// 05.08.2011 start
		aktWidth = aktLeft + galleryThumbWidth;
		if (parseInt(galleryImageIds[i]) == galleryOldIdCenter) break;
		aktLeft += galleryThumbWidth + galleryThumbPadding;
		// 05.08.2011 ende
	}
	//	aktLeft -= galleryThumbPadding;

	// Neuen Wert für die linke Position ermitteln.
	// 05.08.2011 start
	var newLeft = -(aktWidth + (galleryThumbWidth - galleryNavThumbBarWidth) / 2);
	newLeft = newLeft - (newLeft % (galleryThumbWidth + galleryThumbPadding)); // Genaue Positionierung am anfang eines Thumbs.
	// 05.08.2011 ende

	// Max- und Minbereich festlegen.
	if (newLeft > 0) newLeft = 0; // Maximale Rechte Position
	if (newLeft < -(galleryId_galleryNaviThumbs.width() - galleryNavThumbBarWidth - galleryThumbPadding)) { // Maximale Linke Position
		newLeft = -(galleryId_galleryNaviThumbs.width() - galleryNavThumbBarWidth - galleryThumbPadding);
	}

	// Werte zuweisen.
	galleryId_galleryNaviThumbs.stop().animate({
		left : newLeft
	}, galleryThumbSlideTime, galleryAnimation.getEasing());
}
/**
 * Zeichnet das inaktive Thumbnail anhand der var: galleryOldIdCenter.
 * @author Lutz Hoffarth
 * @since 03.08.2011
 * @since 10.08.2011 Lutz Hoffarth Thumb ausblenden.
 */
function setThumbInactiv() {
	//	debug("function setThumbInactiv() galleryOldIdCenter:"+galleryOldIdCenter);
	if (galleryOldIdCenter == 0) return;
	//	$("#galleryThumb_" + galleryOldIdCenter).attr("src", galleryImagePathThumbInactiv + "Image_" + galleryOldIdCenter + ".jpg");
	inactivateThumb = galleryID_galleryThumbAktive_[galleryOldIdCenter];
	if (inactivateThumb == undefined) return;
	inactivateThumb.stop().animate({
		opacity : 0
	}, galleryThumbSlideTime, galleryAnimation.getEasing(), function() {
		inactivateThumb = null;
	});
}

///**
// * setzt den fade Flag und den Mousecursor auf den notwendigen Elementen.
// * @author Lutz Hoffarth
// * @since 03.08.2011
// * @param fade
// */
//function setFade(fade) {
//	if (galleryIsFade == fade) return // Nicht notwendig
//	galleryIsFade = fade;
////	var cursor = "pointer";
////	if (fade) {
////		cursor = "progress";
////	}
////
////	galleryId_galleryNaviControlLeftSymbol.css("cursor", cursor);
////	galleryId_galleryNaviControlRightSymbol.css("cursor", cursor);
////
////	for ( var i = 1; i <= galleryImageIds.length; i++) {
////		$("#galleryThumb_" + i).css("cursor", cursor);
////	}
//}

/**
 * Der animierte Austausch der Center-Bilder erfolgt per Überblendung.
 * @param contentId ID des Bildes.
 * @since 06.03.2011
 * @since 03.08.2011
 * @since 04.08.2011 Paralleldurchläufe durch die Variable 'galleryIsRun' verhindert.
 * @since 05.08.2011 Wenn der Fade läuft: abbruch und mit neuer ID weitermachen.
 * @since 10.08.2011 Lutz Hoffarth - Wenn die contentId 0 ist, wird die nächste gültige geladen.
 */
function fadeCenterTo(contentId) {
	if (galleryIsRun) return; // 04.08.2011 Abbruch, wenn der Fade aktuell läuft.
	galleryIsRun = true; // Ein Animationslauf wird gestartet.
	if (contentId == null) return;
	if (galleryShowTitle) return;

	fadeStop();
	if (contentId == 0) contentId = getNextId(); // @since 10.08.2011
	if (contentId == null) return;

	galleryIsFade = true; // Ein neuer Fade wird begonnen.
	if (galleryAutoFade && !galleryAutoFadePaused) galleryId_galleryNaviControlPlaySymbol.attr("src", gallerySystemPath + "nav_pause.png");

	setThumbInactiv();
	galleryOldIdCenter = contentId;
	setThumbActiv();

	// Neues Bild erzeugen.
	var imagePath = galleryImagePath + "Image_" + contentId + ".jpg";
	var image = "<img class=\"galleryImageView\" src=\"" + imagePath + "\">";

	// Bisherigen Bildträger ermitteln
	var old_inner = $(".galleryImageInner");
	if (old_inner == null) return;

	// Bisherigem Bildträger bewegungsstyle zuweisen
	old_inner.removeClass("galleryImageInner").addClass("galleryImageInnerOld");

	// Neuen Bildträger erstellen und Bild einbinden.
	var new_inner = "<div class=\"galleryImageInnerNew\">" + image + "</div>";
	// Neue Box erstellen und Bildträger mit Bild einbinden.
	var new_box = "<div class=\"galleryImageBoxNew\" >" + new_inner + "</div>";

	// Bisherige Box ermitteln
	var old_box = $(".galleryImageBox");
	if (old_box == null) return;
	// Bisheriger Box bewegungsstyle zuweisen
	old_box.removeClass("galleryImageBox").addClass("galleryImageBoxOld");

	// new_box am (ende Bzw.: right==true->anfang) des galleryImageWrappers einfügen.
	galleryId_galleryImageWrapper.append(new_box);

	// Neue Box holen
	new_box = $(".galleryImageBoxNew");
	new_inner = $(".galleryImageInnerNew");

	// Animation
	//	debug("1 function fadeCenterTo("+contentId+") galleryShowTitle:"+galleryShowTitle+" || contentShowing:"+contentShowing);
	old_box.stop().animate({
		opacity : 0
	}, galleryAnimation.getSpeed(), galleryAnimation.getEasing(), function() {
		new_inner.removeClass("galleryImageInnerNew").addClass("galleryImageInner");
		new_box.removeClass("galleryImageBoxNew").addClass("galleryImageBox");
		old_box.remove();

		// Vor start der Pause zum Weitersliden des Centers
		if (!galleryAutoFadePaused && galleryAutoFade && !galleryShowTitle && !contentShowing) {
			setTimeout(function() {
				// Nach ablauf der Pause.
				//				debug("2 function fadeCenterTo("+contentId+") galleryShowTitle:"+galleryShowTitle+" || contentShowing:"+contentShowing);
				if (galleryShowTitle || contentShowing) {
					galleryIsFade = false;
					return;
				}
				galleryIsRun = false; // Kurzfristig für den nächsten durchlauf deaktivieren.
				if (galleryAutoFade && !galleryAutoFadePaused && !galleryShowTitle && !contentShowing) { // Zeitversetzte Nachprüfung
					fadeCenterTo(getNextId());
				}
			}, galleryCenterFadeInterval);
		} else {
			galleryIsRun = false; // Der Animationslauf ist beendet.
		}
		//		galleryIsFade = false; // Der Fade ist abgeschlossen
	});
};

/**
 * Alle laufenden Animationen werden gestoppt.<br>
 * - Der aktuelle Bildwechsel wird gestoppt und zurückgesetzt.<br>
 * - Thumbanimationen werden gestoppt.
 * @since 10.08.2011 Lutz Hoffarth
 */
function fadeStop() {
	//	debug("function fadeStop()");
	var boxOld = $("#galleryImageBoxOld");
	var innerNew = $(".galleryImageInnerNew");
	var boxNew = $(".galleryImageBoxNew");

	if (boxOld.length > 0) boxOld.stop();
	//	if (innerNew.length > 0) {
	if (innerNew.length > 0) innerNew.removeClass("galleryImageInnerNew").addClass("galleryImageInner");
	if (boxNew.length > 0) boxNew.removeClass("galleryImageBoxNew").addClass("galleryImageBox");

	if (boxOld.length > 0) boxOld.remove();
	galleryIsFade = false;
	galleryIsRun = false;
	//	}

	//	if(inactivateThumb != null) inactivateThumb.stop();
	if (activateThumb != null) activateThumb.stop();
	galleryId_galleryNaviThumbs.stop();
}

/**
 * Der animierte Austausch der Center-Bilder erfolgt per überblendung.<br>
 * Sämtliche fadeAnimationen werden zu anfang gestoppt.
 * @param imagePath
 *          Bild im Pfad 'images/content/' mit der Endung '.png' das eingeblendet werden soll.
 * @since 04.08.2011 Geänderte Kopie von fadeCenterTo(contentId).
 */
function fadeCenterToImage(imagePath) {
	fadeStop();
	if (imagePath == null || imagePath == undefined) {
		fadeCenterTo(galleryOldIdCenter);
		return;
	}
	//	debug("1 fadeCenterToImage("+imagePath+") galleryShowTitle:"+galleryShowTitle+" || contentShowing:"+contentShowing);
	imagePath = galleryImageTitelPath + imagePath;
	//	galleryFadeTitelImage = true;

	// Neues Bild erzeugen.
	var image = "<img class=\"galleryImageView\" src=\"" + imagePath + "\">";

	// Bisherigen Bildträger ermitteln
	var old_inner = $(".galleryImageInner");
	if (old_inner == null) return;

	// Bisherigem Bildträger bewegungsstyle zuweisen
	old_inner.removeClass("galleryImageInner").addClass("galleryImageInnerOld");

	// Neuen Bildträger erstellen und Bild einbinden.
	var new_inner = "<div class=\"galleryImageInnerNew\">" + image + "</div>";
	// Neue Box erstellen und Bildträger mit Bild einbinden.
	var new_box = "<div class=\"galleryImageBoxNew\" >" + new_inner + "</div>";

	// Bisherige Box ermitteln
	var old_box = $(".galleryImageBox");
	//	if (old_box == null) return;
	if (old_box.length <= 0) return;
	// Bisheriger Box bewegungsstyle zuweisen
	old_box.removeClass("galleryImageBox").addClass("galleryImageBoxOld");

	// new_box am (ende Bzw.: right==true->anfang) des galleryImageWrappers einfügen.
	galleryId_galleryImageWrapper.append(new_box);

	// Neue Box holen
	new_box = $(".galleryImageBoxNew");
	new_inner = $(".galleryImageInnerNew");

	// Animation
	old_box.stop().animate({
		opacity : 0
	}, galleryAnimation.getSpeed(), galleryAnimation.getEasing(), function() {
		new_inner.removeClass("galleryImageInnerNew").addClass("galleryImageInner");
		new_box.removeClass("galleryImageBoxNew").addClass("galleryImageBox");

		old_box.remove();
		//		setFade(false);
		galleryIsFade = false;
		//		galleryFadeTitelImage = false;
	});
};

/**
 * @since 08.04.2011
 * @since 11.04.2011
 * @since 03.08.2011
 */
function pauseGalleryAutoFade() {
	//	debug("function pauseGalleryAutoFade()");
	galleryAutoFadePaused = true;
	galleryId_galleryNaviControlPlaySymbol.attr("src", gallerySystemPath + "nav_play.png");
};

/**
 * Startet bedingungslos den automatischen Bildwechsel der Galerie.
 * @since 08.04.2011
 * @since 11.04.2011
 * @since 03.08.2011
 */
function runGalleryAutoFade() {
	//	debug("runGalleryAutoFade");
	galleryAutoFadePaused = false;
	galleryAutoFade = true;
	fadeCenterTo(getNextId());
};

/**
 * Startet den automatischen Bildwechsel der Galerie wenn er nicht pausiert ist.
 */
function startGalleryAutoFade() {
	//	debug("function startGalleryAutoFade() galleryAutoFadePaused:" + galleryAutoFadePaused);
	fadeStop();
	var isPause = galleryAutoFadePaused;
	galleryAutoFadePaused = true;
	//	debug("function startGalleryAutoFade() isPause:" + isPause)
	setTimeout(function() {
		galleryAutoFade = true;
		// Nach ablauf der Pause.
		galleryAutoFadePaused = isPause;
		if (!galleryAutoFadePaused) {
			fadeCenterTo(getNextId());
		}
	}, galleryCenterFadeInterval);
}

/**
 * @param galleryImageIds
 * @since 04.04.2011
 */
function getNextId() {
	if (galleryImageIds.length == 0) return null;
	if (galleryOldIdCenter == 0) return galleryImageIds[0];
	if (jQuery.type(galleryImageIds) === "string")
		return galleryImageIds;
	else if (jQuery.type(galleryImageIds) === "array") {
		for ( var i = 0; i < galleryImageIds.length; i++) {
			if (galleryImageIds[i] == galleryOldIdCenter) {
				var naechsteId = 0;
				if (i < galleryImageIds.length - 1)
					naechsteId = galleryImageIds[i + 1]; // Nächster Eintrag
				else
					naechsteId = galleryImageIds[0]; // Erster Eintrag
				return naechsteId;
			}
		}
		// nicht im Bereich -> an den Anfang.
		return galleryImageIds[0];
	}
};

/**
 * @param galleryImageIds
 * @since 03.08.2011
 */
function getPreviouId() {
	if (galleryImageIds.length == 0) return null;
	if (galleryOldIdCenter == 0) return galleryImageIds[galleryImageIds.length - 1]; // Letztes Element
	if (jQuery.type(galleryImageIds) === "string")
		return galleryImageIds;
	else if (jQuery.type(galleryImageIds) === "array") {
		for ( var i = 0; i < galleryImageIds.length; i++) {
			if (galleryImageIds[i] == galleryOldIdCenter) {
				var naechsteId = 0;
				if (i > 0)
					naechsteId = galleryImageIds[i - 1]; // Vorheriger Eintrag
				else
					naechsteId = galleryImageIds[galleryImageIds.length - 1]; // Letzter Eintrag
				return naechsteId;
			}
		}
		// nicht im Bereich -> an das Ende.
		return galleryImageIds[galleryImageIds.length - 1];
	}
};

/**
 * Vergrößert und/oder Zentriert je nach min-Größe des Bildes innerhalb des
 * HTML-Elements mit der id='galleryCenterImage'.
 * <p>
 * Das HTML-Element mit der id='container' nimmt die Gesamtgröße des Browsers
 * ein.<br>
 * Der Center-Bereich mit der id='galleryCenterView' nimmt die Größe des 'container'
 * abzüglich des South-Bereichs ein.<br>
 * Der Bereich mit der id='galleryCenterImage' nimmt mindestens die Größe des
 * Bildes ein. Ist dieser größer wird das Bild vergrößert.
 * 
 * <pre>
 * &lt;!-- MinnimalCode: --&gt;
 * &lt;div id=&quot;container&quot; style=&quot;position: relative; &quot;&gt;
 *   &lt;div id=&quot;galleryCenterView&quot; style=&quot;overflow: hidden; position: absolute; top: 0px; z-index: 10;&quot;&gt;
 *     &lt;div id=&quot;galleryCenterImage&quot; style=&quot;overflow: hidden; position: absolute; &quot;&gt;
 *       &lt;img class=&quot;galleryImageView&quot; src=&quot;...&quot; style=&quot;display: inline; width: 100%; height: 100%&quot; /&gt;
 *     &lt;/div&gt;
 *   &lt;/div&gt;
 * &lt;/div&gt;
 * </pre>
 * 
 * <!-- MinnimalCode: --> <div id="container" style="position: relative;
 * background-color: #EEEEEE; "> <div id="galleryCenterView" style="overflow:
 * hidden; position: absolute; top: 0px; z-index: 10; "> <div
 * id="galleryCenterImage" style="overflow: hidden; position: absolute; "> <img
 * class="galleryImageView" src="..." style="display: inline; width: 100%; height:
 * 100%" /> </div> </div> </div>
 * @since 12.03.2011 nicht kleiner als Contentbereich. Absprache vom
 *          11.03.2011
 * @since 08.03.2011
 * @since 26.02.2011
 * @since 02.08.2011 Feste Höhe, wenn der Content angezeigt wird.
 * @since 05.09.2011 Minimalhöhe für den Galeriebereich festgelegt.
 */
function setGalleryCenterSize() {
	debug("gallery.js->setGalleryCenterSize()");
	//	var wiw = getBrowserWidth();
	var wiw = getBrowserOuterWidth();
	if (wiw < minWidth) wiw = minWidth;

	//	var wih = getBrowserHeight();
	var scrollTop = $(window).scrollTop();

	// Größe des Menüs.
	//	var menuTop = $("#menu").position().top;
	// @since 05.11.2011 Lutz Hoffarth | Start
	var menuTop = 0;
	if (id_menu != undefined) {
		menuTop = id_menu.position().top;
	}
	// @since 05.11.2011 Lutz Hoffarth | alt
	//	var menuTop = id_menu.position().top;
	// @since 05.11.2011 Lutz Hoffarth | Ende

	var centerInnerWidth = wiw;
	var centerInnerHeight = menuTop - scrollTop;
	if (centerInnerHeight < galleryMinHeight) centerInnerHeight = galleryMinHeight;

	if (contentShowing) {
		centerInnerHeight = titleImageHeight; // @since 02.08.2011 
	} else {
		galleryId_galleryNaviBar.css("height", galleryNavBarHeight);
	}

	// nicht schmaler als vorgesehen.
	var imgWidth = wiw;
	if (imgWidth < galleryAspectRatioWidth) imgWidth = galleryAspectRatioWidth;

	// nicht niedriger als vorgesehen.
	var imgHeight = centerInnerHeight;
	if (imgHeight < galleryAspectRatioHeight) imgHeight = galleryAspectRatioHeight;

	// Seitenverhältnis bewahren
	var imgOrigVerh = galleryAspectRatioWidth / galleryAspectRatioHeight;
	var imgVerh = imgWidth / imgHeight;
	if (imgVerh > imgOrigVerh) { // Wenn breiter als Original
		imgHeight = Math.floor(imgWidth / imgOrigVerh); // Höhe an die Breite anpassen
	} else if (imgVerh < imgOrigVerh) { // Wenn schmaler als Original
		imgWidth = Math.floor(imgHeight * imgOrigVerh); // Breite an die Höhe anpassen
	}

	// Überstand links und oben berechnen
	var imgLeft = Math.floor((centerInnerWidth - imgWidth) / 2);
	var imgTop = Math.floor((centerInnerHeight - imgHeight) / 2);

	//	debug("function setGalleryCenterSize() galleryStartResize:"+galleryStartResize + " centerInnerHeight:"+centerInnerHeight);
	if (galleryStartResize) {
		resizeGallery(null, anim);
	} else {
		// Berechnete Werte anwenden.
		galleryId_galleryCenterView.css("width", wiw).css("height", centerInnerHeight);
		galleryId_galleryCenterImage.css("width", imgWidth).css("height", imgHeight).css("left", imgLeft).css("top", imgTop);
	}
};

var galleryStartResize = false;
/**
 * Wird beim öffnen des Contents verwendet, um die Gallerie animiert in ihre fixe Größe zu bringen.<br>
 * Wird ein image-Pfad mitgegeben, wird dieses Bild im Titel eingeblendet.<br>
 * Ohne Parameter wird das aktuelle Galeriebild eingeblendet.
 * @param image 
 * 				- Pfad vom TitelBild.
 * 				- Ohne Parameter wird Die Galerie wiederhergestellt.
 * @param resizeAnim Ist der Parameter gefüllt wird der Resize animiert.
 * @author Lutz Hoffarth
 * @since 02.08.2011
 * @since 04.08.2011 Erweiterung um die Mittgabe eines Bildpfades
 * @since 10.08.2011 Lutz Hoffarth Logo Klick eingebaut.
 * @since 10.08.2011 Lutz Hoffarth Ergänzung um den @param resizeAnim und deren Verwendung.
 */
function resizeGallery(image, resizeAnim) {
	//	debug("function resizeGallery(" + image + ", " + resizeAnim + ") START");
	fadeCenterToImage(image); // Der ganz normale Bildwechsel mit dem Titelimage.

	//	if(galleryStartResize) return;
	//	galleryStartResize = true;

	if (image != null || image != undefined) {
		// Die Gallerie ist schon für das Anzeigen des Titelbildes verkleinert. 
		if (galleryShowTitle || galleryStartResize) {
			if (contentShowing) {
				galleryAutoFade = false;
			}
			//			debug("function resizeGallery(" + image + ", " + resizeAnim + ") VERLASSE");
			return;
		}
	}
	galleryStartResize = true;

	// Ab hier erfolgt der Resize der Galerie.
	var wiw = getBrowserWidth();
	if (wiw < minWidth) wiw = minWidth;

	var wih = getBrowserHeight();
	var scrollTop = $(window).scrollTop();

	// Größe des Menüs.
	southMinHeight = id_menu.height();
	var menuTop = wih - naviHeightExtended;
	if (contentShowing) {
		menuTop = id_menu.position().top;
	}

	// Größe des ContentCenter.
	var centerInnerWidth = wiw;
	var centerInnerHeight = menuTop - scrollTop;

	var cursor = "default";
	if (contentShowing) { // Der Content wird angezeigt
		galleryAutoFade = false;
		centerInnerHeight = titleImageHeight; // @since 02.08.2011 
		cursor = "pointer";
		//	} else {
		//		galleryAutoFade = true;
	}
	galleryId_galleryCenterView.css("cursor", cursor);

	// nicht schmaler als vorgesehen.
	var imgWidth = wiw;
	if (imgWidth < galleryAspectRatioWidth) imgWidth = galleryAspectRatioWidth;

	// nicht niedriger als vorgesehen.
	var imgHeight = centerInnerHeight;
	if (imgHeight < galleryAspectRatioHeight) imgHeight = galleryAspectRatioHeight;

	// Seitenverhältnis bewahren
	var imgOrigVerh = galleryAspectRatioWidth / galleryAspectRatioHeight;
	var imgVerh = imgWidth / imgHeight;
	if (imgVerh > imgOrigVerh) { // Wenn breiter als Original
		imgHeight = Math.floor(imgWidth / imgOrigVerh); // Höhe an die Breite anpassen
	} else if (imgVerh < imgOrigVerh) { // Wenn schmaler als Original
		imgWidth = Math.floor(imgHeight * imgOrigVerh); // Breite an die Höhe anpassen
	}

	// Überstand links und oben berechnen
	var imgLeft = Math.floor((centerInnerWidth - imgWidth) / 2);
	var imgTop = Math.floor((centerInnerHeight - imgHeight) / 2);

	// Berechnete Werte anwenden.
	//	debug("function resizeGallery(" + image + ", " + resizeAnim + ") centerInnerHeight:"+centerInnerHeight);
	if (resizeAnim == null || resizeAnim == undefined) { // @since 10.08.2011 ---- Ohne Animation 
		//		debug("function resizeGallery(image, resizeAnim) Ohne Animation");
		galleryId_galleryCenterView.css("width", wiw).css("height", centerInnerHeight);
		galleryId_galleryCenterImage.css("width", imgWidth).css("height", imgHeight).css("left", imgLeft).css("top", imgTop);
		if (contentShowing) {
			// Gallery-Navigation ausblenden.
			galleryId_galleryNaviBar.css("height", 0);
			galleryShowTitle = true;
		} else {
			// Gallery-Navigation einblenden.
			galleryId_galleryNaviBar.css("height", galleryNavBarHeight);
			galleryShowTitle = false;
			startGalleryAutoFade();
		}
		galleryStartResize = false;
	} else { // @since 10.08.2011 ---- Mit Animation
		//		debug("function resizeGallery(image, resizeAnim) Mit Animation");
		galleryId_galleryCenterView.stop().animate({
		width : wiw + "px",
		height : centerInnerHeight + "px"
		}, resizeAnim.getSpeed(), resizeAnim.getEasing());

		galleryId_galleryCenterImage.stop().animate({
		width : imgWidth + "px",
		height : imgHeight + "px",
		left : imgLeft + "px",
		top : imgTop + "px"
		}, resizeAnim.getSpeed(), resizeAnim.getEasing());

		if (contentShowing) {
			// Gallery-Navigation ausblenden.
			galleryId_galleryNaviBar.stop().animate({
				height : "0px"
			}, resizeAnim.getSpeed(), resizeAnim.getEasing(), function() {
				galleryStartResize = false;
			});
			galleryShowTitle = true;
		} else {
			// Gallery-Navigation einblenden.
			galleryId_galleryNaviBar.stop().animate({
				height : galleryNavBarHeight + "px"
			}, resizeAnim.getSpeed(), resizeAnim.getEasing(), function() {
				galleryStartResize = false;
				startGalleryAutoFade();
			});
			galleryShowTitle = false;
			fadeCenterTo(galleryOldIdCenter);
		}
	}
	//	debug("function resizeGallery(" + image + ", " + resizeAnim + ") ENDE");
}

// ------ Laden der Galerie -----------------------------------------------------------------------
/**
 * @since 02.08.2011 Lutz
 * @since 04.08.2011 Lutz
 * @since 10.08.2011 Lutz Hoffarth - Titelimages werden geladen.
 * @since 13.08.2011 Lutz Hoffarth - Optimierung durch den Einsatz von globalen Variablen
 */
function loadGallary(galleryIds) {
	debug("gallery.js->loadGallary(" + galleryIds + ")");
	galleryImageIds = galleryIds;

	// Elemente, die immer wieder verwendet werden.
	// Steigert die Performance und vermindert die Speicherlast.
	galleryId_galleryCenterView = $("#galleryCenterView");
	galleryId_galleryLogoImage = $("#galleryLogoImage");
	galleryId_galleryImageWrapper = $("#galleryImageWrapper");
	galleryId_galleryCenterImage = $("#galleryCenterImage");

	$("#galleryLogoContainer").css("width", 256);
	galleryId_galleryLogoImage.attr("src", gallerySystemPath + "logo.png");
	
	galleryInitNavBar(); // @since 05.11.2011 Lutz Hoffarth | Ausgelagert

	preloadGallery(); // @since 04.08.2011
	setGalleryCenterSize(); // @since 05.11.2011 Lutz Hoffarth | Um beim ersten laden der Seite das Erste Bild zu zeigen ist eine Größe der Gallery notwendig.
	preloadGalleryTitleImages(); // @since 10.08.2011 

	/**
	 * Nur wenn der Galeriebereich zusammengefahren ist, kann er per Klick wieder erweitert werden.
	 * @since 02.08.2011 Lutz
	 * @since 10.08.2011 Lutz Hoffarth Die Clickfunktionalität wird erst eingebaut, wenn sie auch notwendig ist.
	 * @since 10.08.2011 Lutz Hoffarth Logo Klick eingebaut.
	 * @since 13.08.2011 Lutz Hoffarth - Der Click wird nur im Titelmodus ausgeführt.
	 */
	galleryId_galleryCenterView.click(function() { // Click-Event erzeugen.
		if (!galleryShowTitle) return;
		if (isToHomeClick) { // Der Click auf das Loge, löst auch den click aufs Image aus. Das wird vermieden. 
			//					debug("galleryCenterView click abbruch");
			isToHomeClick = false;
			return;
		}
		naviSlideDown();
	});
	debug("gallery.js->loadGallary(" + galleryIds + ") ENDE");
}

/** @since 05.11.2011 Lutz Hoffarth */
var galleryIsNavBarInitialisized = false;
/**
 * @since 05.11.2011 Lutz Hoffarth
 */
function galleryInitNavBar(){
//	debug("gallery.js->galleryInitNavBar() galleryNavBarHeight: "+galleryNavBarHeight);
	if(galleryIsNavBarInitialisized) return;
	galleryIsNavBarInitialisized = true;
	galleryId_galleryNaviThumbs = $("#galleryNaviThumbs");
	galleryId_galleryThumb = $("#galleryThumb");
	galleryId_galleryNaviControlPlaySymbol = $("#galleryNaviControlPlaySymbol");
	galleryId_galleryNaviControlLeftSymbol = $("#galleryNaviControlLeftSymbol");
	galleryId_galleryNaviControlExitSymbol = $("#galleryNaviControlExitSymbol");
	galleryId_galleryNaviControlRightSymbol = $("#galleryNaviControlRightSymbol");
	galleryId_galleryNaviBar = $("#galleryNaviBar"); 
	galleryId_galleryNaviControlFrame = $("#galleryNaviControlFrame");
	galleryID_galleryThumbAktive_ = [];
	
	galleryId_galleryNaviBar.css("height", galleryNavBarHeight);
	$("#galleryNaviThumbsFrame").css("width", galleryNavThumbBarFrameWidth);
	$("#galleryNaviThumbsView").css("width", galleryNavThumbBarWidth);

	galleryId_galleryNaviControlFrame.css("padding-left", 1034);
	galleryId_galleryNaviControlFrame.css("width", 166);
	galleryId_galleryNaviControlLeftSymbol.attr("src", gallerySystemPath + "nav_left.png");
	galleryId_galleryNaviControlPlaySymbol.attr("src", gallerySystemPath + "nav_pause.png");
	galleryId_galleryNaviControlExitSymbol.attr("src", gallerySystemPath + "nav_exit.png");
	galleryId_galleryNaviControlRightSymbol.attr("src", gallerySystemPath + "nav_right.png");

	galleryId_galleryNaviBar.css("background-image", "url('" + gallerySystemPath + "backgroundNaviBar.png')");

	/**
	 * @since 03.08.2011 Lutz
	 */
	galleryId_galleryNaviControlLeftSymbol.click(function() {
		//		debug("galleryNaviControlLeftSymbol Click");
		galleryShowPreviousImage();
	});
	/**
	 * @since 03.08.2011 Lutz
	 */
	galleryId_galleryNaviControlPlaySymbol.click(function() {
		//				debug("galleryNaviControlPlaySymbol Click");
		galleryPausedPlay();
	});
	/**
	 * @since 03.08.2011 Lutz
	 * @since 14.09.2011 Lutz Hoffarth | Bedingungsloser HomeLink
	 */
	galleryId_galleryNaviControlExitSymbol.click(function() {
		isToHomeClick = true;
		//		debug("galleryNaviControlExitSymbol Click");
		naviToHome(true);
	});
	/**
	 * @since 03.08.2011 Lutz
	 */
	galleryId_galleryNaviControlRightSymbol.click(function() {
		//		debug("galleryNaviControlRightSymbol Click");
		galleryShowNextImage();
	}); 

	/**
	 * Pfeiltastenabfrage
	 * @since 12.08.11
	 * @author Adam Laszlo
	 */
	$(document).keydown(function(event) {
		if (event.which == 37) { // links
			galleryShowPreviousImage();
		} else if (event.which == 39) { // rechts
			galleryShowNextImage();
		}
	});
}

/**
 * @since 04.08.2011 aus der Main hergeschoben.
 */
$(window).resize(function() {
	setGalleryCenterSize();
});

/**
 * Nachdem der Preload abgeschlossen ist.<br>
 * - Gesamte breite der ThumbLeiste Ermitteln.
 * - Größe der Gallerie festlegen.
 * - Animation starten.
 * @since 04.08.2011 
 * @since 13.08.2011 Lutz Hoffarth
 */
$(window).load(function() {
			debug("gallery.js->$(window).load()");
	// Gesamte breite der ThumbLeiste Ermitteln.
	//	var gesThumbsWidth = 0;
	//	if(galleryImageIds == undefined || galleryImageIds.length == 0) return;
	for ( var i = 0; i < galleryImageIds.length; i++) {
		//		debug("galleryImageIds[i]:" + galleryImageIds[i]);
		// Dynamischer Einbau von HTML-Images in das Dokument
		var html = "<div class='galleryThumb'>";

		html += "<div id='galleryNaviThumbImageWrapper_" + galleryImageIds[i] + "' style='position: relative; '>";
		html += "<div id='galleryNaviThumbImageBox_" + galleryImageIds[i] + "' style='position: relative;'>";
		html += "<div id='galleryNaviThumbImageInner_" + galleryImageIds[i] + "' style='position: absolute;'>";

		html += "<img id='galleryThumb_" + galleryImageIds[i] + "' style='cursor: pointer; position: absolute;'";
		html += " src='" + galleryImagePathThumbInactiv + "Image_" + galleryImageIds[i] + ".jpg'";
		html += " onmouseover='galleryMouseOver(" + galleryImageIds[i] + ")'";
		html += " onmouseout='galleryMouseOut(" + galleryImageIds[i] + ")'";
		//		html += " onclick='galleryFadeTo(" + galleryImageIds[i] + ")' />";
		html += " onclick='galleryMouseThumbClick(" + galleryImageIds[i] + ")' />";

		//		html += "<img id='galleryThumbAktive_" + galleryImageIds[i] + "' class='galleryThumbAktive' style='cursor: pointer; position: absolute; opacity: 0;'";
		html += "<img id='galleryThumbAktive_" + galleryImageIds[i] + "' class='galleryThumbAktive'";
		html += " src='" + galleryImagePathThumb + "Image_" + galleryImageIds[i] + ".jpg'";
		html += " onmouseover='galleryMouseOver(" + galleryImageIds[i] + ")'";
		html += " onmouseout='galleryMouseOut(" + galleryImageIds[i] + ")'";
		//		html += " onclick='galleryFadeTo(" + galleryImageIds[i] + ")' />";
		html += " onclick='galleryMouseThumbClick(" + galleryImageIds[i] + ")' />";

		html += "</div></div></div></div>";
		galleryId_galleryNaviThumbs.append(html);
		galleryID_galleryThumbAktive_[galleryImageIds[i]] = $("#galleryThumbAktive_" + galleryImageIds[i]); // @since 13.08.2011 Lutz Hoffarth

		//		debug($("#galleryThumb_" + galleryImageIds[i]).width());
		//		$("#galleryNaviThumbImageWrapper_" + galleryImageIds[i]).css("width", $("#galleryThumb_" + galleryImageIds[i]).width());
		$("#galleryNaviThumbImageWrapper_" + galleryImageIds[i]).css("width", galleryThumbWidth);
		// Gesamtbreite ermitteln.
		//		gesThumbsWidth += $("#galleryThumb_" + galleryImageIds[i]).width() + galleryThumbPadding;
	}
	//	gesThumbsWidth -= galleryThumbPadding;

	// Gesamtbreite ermitteln.
	// Chrome Version 13.0.782.107 Funktioniert die Galeriemenüleiste nicht.
	//	debug("galleryImageIds.length:" + galleryImageIds.length);
	//	debug("galleryThumbWidth:" + galleryThumbWidth);
	//	debug("galleryThumbPadding:" + galleryThumbPadding);
	var gesThumbsWidth = galleryImageIds.length * (galleryThumbWidth + galleryThumbPadding);

	galleryId_galleryNaviThumbs.css("width", gesThumbsWidth);
	galleryId_galleryThumb.css("width", galleryThumbWidth);

	// Größe der Gallerie festlegen.
	setGalleryCenterSize(); // @since 04.08.2011
	// Start der Animation.
	if (!contentShowing) runGalleryAutoFade(); // @since 04.08.2011
});

/**
 * @since 05.08.2011 
 * @param galleryId
 */
function galleryMouseThumbClick(galleryId) {
	//	debug("function galleryMouseThumbClick(" + galleryId + ")");
	fadeStop();
	galleryIsRun = false;
	galleryAutoFade = false;
	galleryAutoFadePaused = false;
	galleryFadeTo(galleryId);
}

/**
 * @since 12.04.2011 
 * @since 03.08.2011 Thumbs werden automatisch eingebunden.
 * @since 05.08.2011 Preload des Playsymbols zwecks unverzögernder Nutzung.
 * @since 05.08.2011 PreloadMethode 'preloadImage(image)' in maria.js ausgelagert.
 * @since 28.08.2011 Lutz | Umstellung auf Preloader.
 */
function preloadGallery() {
	debug("gallery.js->preloadGallery()");
	if (jQuery.type(galleryImageIds) === "array") {
		for ( var i = 0; i < galleryImageIds.length; i++) {
			Preloader.preloadImage(galleryImagePath + "Image_" + galleryImageIds[i] + ".jpg");
			Preloader.preloadImage(galleryImagePathThumb + "Image_" + galleryImageIds[i] + ".jpg");
			Preloader.preloadImage(galleryImagePathThumbInactiv + "Image_" + galleryImageIds[i] + ".jpg");
		}
	}
	// 05.08.2011
	Preloader.preloadImage(gallerySystemPath + "nav_play.png");
	debug("gallery.js->preloadGallery() ENDE");
};

/**
 * Voraussetzung ist eine 1- oder 2-dimensionale Array-Variable: 'galleryTitle'.
 * @since 10.08.2011
 * @since 12.08.2011 Lutz Hoffarth - Erweitert für 1- und 2-dimensionale Arrays.
 * @since 28.08.2011 Lutz | Umstellung auf Preloader.
 */
function preloadGalleryTitleImages() {
	//	debug("galleryTitle:" + galleryTitle);
	for ( var i = 0; i < galleryTitle.length; i++) {
		// 12.08.2011 start
		if ($.isArray(galleryTitle[i])) {
			for ( var j = 0; j < galleryTitle[i].length; j++) {
				if (galleryTitle[i][j] == undefined) continue;
				Preloader.preloadImage(galleryImageTitelPath + galleryTitle[i][j]);
			}
		} else {
			if (galleryTitle[i] == undefined) continue;
			Preloader.preloadImage(galleryImageTitelPath + galleryTitle[i]);
		}
		// 12.08.2011 ende
	}
}

