/**
***********************************
* Eine Art Popup für Bildanzeigen 
***********************************
*
* Version 2 (2010/10/04)
*
* Diese Bibliothek erzeugt ein Javascript-Objekt (js_popup), das sich im HTML-Code ein DIV-
* Element erzeugt, dessen ID "js-popup" heißt und welches für die Anzeige einer Vollansicht zu
* einem Thubnail-Bild verwendet wird.
*
* Die Benutzung des js_popup-Objektes ist sehr einfach. Da sich das Script basierend auf einer
* hier einzustellenden CSS-Klasse die Link-Elemente dynamisch aus einem beliebigen Eltern-
* Element holt und ihnen ein onClick-Event zuweist, braucht es im HTML- Quelltext lediglich
* folgende Struktur (<element> steht stellvertretend für Elemente wie <p>, <div>, <span> usw.):
*
* <element class="bildergalerie">
* <a href="pfad/img.jpg"><img src="pfad/tn_img.jpg" alt="Beschreibung" /></a>
* </element>
*
* Die Vollansicht wird als Bildunterschrift den Wert aus dem ohnehin zwingend erforderlichen
* alt-Attribut verwenden.
*
* Neu in Version 2 ist der Blättermechanismus, mit dem man vor- und zurückblättern kann, wenn es
* in einer Galerie mehr als einen Bilderlink gibt.
*
* Diese Bibliothek unterliegt der LGPL!
*
* SOFTWARE LICENSE: LGPL
* (C) 2006-2010 Felix Riesterer
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* 
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*
*
*erstellt von Felix Riesterer (Felix.Riesterer@gmx.net)
*/

// js_popup-Objekt definieren
var jsPopup = {

	// Hier steht später die URL dieses Scripts
	baseURL : false,

	// Hier die CSS-Klasse eintragen, die Links in Kindelementen mit der Popup-Funktion versieht!
	triggerCssClass : "kontakt",

	// CSS-ID für das Popup-Eltern-Element (DIV)
	parentDiv : {
		cssID : "js-popup"
	},

	// CSS-ID für die Popup-Box (DIV)
	popupBox : {
		cssID : "js-popup-box"
	},

	// Bilddatei für den Overlay-Hintergrund (teiltransparente PNG-Grafik)
	overlayBackground : {
		src_png : "{$baseURL}/popimages/overlay.png",
		src_blank_gif : "{$baseURL}/popimages/blank.gif"
	},

	// CSS-ID für das Vollansichts-Bild
	fullViewImage : {
		id : "js-popup-image",
		elm : null
	},

	// Bilddatei für die Lade-Animation
	waitAnimation : {
		src : "{$baseURL}/popimages/throbber.gif",
		alt : "Throbber",
		cssID : "js-popup-wait",
		elm : null
	},

	// Bilddatei für das Schließen-Icon
	closeIcon : {
		src : "{$baseURL}/popimages/x-beenden.png",
		alt : "schlie\u00dfen",
		cssID : "js-popup-close"
	},

	// Bilddateien für das Icon zum Vergrößern/Verkleinern
	resizeIcon : {
		src_resize : "{$baseURL}/popimages/resize.gif",
		alt_resize : "verkleinern",
		src_fullSize : "{$baseURL}/popimages/resize_full.gif",
		alt_fullSize : "volle Gr\u00f6\u00dfe",
		cssID : "js-popup-resize",
		elm : null
	},

	// Hover-Icon für "nächstes" Bild
	nextIcon : {
		src : "{$baseURL}/popimages/next.png",
		alt : "next",
		id : "js-popup-next",
		title : "n\u00e4chstes Bild",
		elm : null
	},

	// Hover-Icons für "vorheriges" Bild
	prevIcon : {
		src : "{$baseURL}/popimages/prev.png",
		alt : "next",
		id : "js-popup-prev",
		title : "vorheriges Bild",
		elm : null
	},

	// Meldung während des Ladens
	waitText : "Bild wird geladen...",

	// Alternative Bildunterschrift, falls das Thumbnail kein (oder ein leeres) alt-Attribut besitzt
	altCaption : "...",

	oversize : "resize",
	boxWidth : 90,
	boxHeight : 90,
	boxMaxWidth : 100,
	boxMaxHeight : 100,
	winInnerWidth : 100,
	winInnerHeight : 100,

	// Platzhalter für alte onload-Funktion vor dem Einbinden von jsPopup
	oldWinOnLoad : null,

	// Gruppe von Bildern, durch die hindurchgeblättert werden kann?
	galleries : [],




	// Fensterinhalt überblenden und Lademeldung anzeigen
	preload : function (linkObj) {
		var t = this,
			caption, g, gallery, html_code, i;

		// wurde jsPopup nicht korrekt initialisiert? -> Nachholen!
		if (!t.box) {
			t.oldWinOnResize = window.onresize;

			window.onresize = function () {
				if (typeof(t.oldWinOnResize) == "function")
					t.oldWinOnResize();
				t.initPopupBox();
			}

			t.initPopupBox();
		}

		// Resized-Darstellung und Popup-Abmessungen für die Ladeanzeige setzen
		t.preloadImage = new Image();
		t.preloadImage.src = linkObj.href;

		html_code = t.waitText
			+ ' <img src="' + t.waitAnimation.src
			+ '" alt="' + t.waitAnimation.alt
			+ '" id="' + t.waitAnimation.cssID
			+ '" />';

		t.box.innerHTML = html_code;
		t.boxWidth = 200;
		t.boxHeight = 50;

		t.center();

		// passendes Galerie-Objekt finden und dem box-Objekt zuordnen
		t.box.gallery = null;
		t.box.galleryIndex = null;

		for (g = 0; g < t.galleries.length; g++) {
			for (i = 0; i < t.galleries[g].imageLinks.length; i++) {
				if (t.galleries[g].imageLinks[i] === linkObj) {
					t.box.gallery = t.galleries[g];
					t.box.galleryIndex = i;
				}
			}
		}

		// Bildunterschrift für die Vollansicht vorbereiten
		t.preloadImage.caption = '';

		caption = linkObj.getElementsByTagName("img")[0].getAttribute("alt");
		t.preloadImage.caption = (caption && caption != "") ? caption : t.altCaption;

		t.div.style.display = "block";

		if (t.preloadImage.width > 0) {
			// Bild schon im Cache geladen? -> Sofort anzeigen
			t.display();
		} else {
			// Eventhandler setzen, damit nach dem Laden eine Anzeige kommt
			t.addEvent("load", t.preloadImage, t.display);
			t.addEvent("error", t.preloadImage, t.display);
		}

		return false;
	},




	// Popup mit Vollansichtsbild anzeigen
	display : function () {
		var t = jsPopup,
			html_code, ratio, scale;

		// DIV unsichtbar schalten, um die Ladeanzeige zu deaktivieren
		t.box.style.display = "none";

		// Minimal-Größe für die Popup-Box
		t.boxWidth = 90;
		t.boxHeight = 90;

		// DIV-Box neu mit HTML-Code befüllen
		html_code = '<img id="'
			+ t.closeIcon.cssID
			+ '" src="'
			+ t.closeIcon.src
			+ '" alt="'
			+ t.closeIcon.alt
			+ '" />';

		// Bild größer als Minimal-Größe? -> Box vergrößern
		if (t.preloadImage.width > t.boxWidth || t.preloadImage.height > t.boxHeight) {
			t.boxWidth = t.preloadImage.width;
			t.boxHeight = t.preloadImage.height;
		}

		// Bild größer als Maximal-Größe?
		if (t.boxWidth > t.boxMaxWidth || t.boxHeight > t.boxMaxHeight) {
			html_code += '<img src="';
			html_code += (t.oversize == "resize") ? t.resizeIcon.src_fullSize : t.resizeIcon.src_resize;
			html_code += '" alt="';
			html_code += (t.oversize == "resize") ? t.resizeIcon.alt_fullSize : t.resizeIcon.alt_resize;
			html_code += '" id="' + t.resizeIcon.cssID + '" />';

			// Bild soll verkleinert angezeigt werden?
			if (t.oversize == "resize") {
				// Bild  proportional verkleinern
				ratio = t.preloadImage.width / t.preloadImage.height;
				scale = t.preloadImage.width / t.boxMaxWidth;

				if (t.preloadImage.height / scale > t.boxMaxHeight) {
					scale = t.preloadImage.height / t.boxMaxHeight;
				}

				t.boxWidth = Math.ceil(t.preloadImage.width / scale);
				t.boxHeight = Math.ceil(t.preloadImage.height / scale);
			}
		}

		t.center();

		html_code += '<img id="'
			+ t.fullViewImage.id
			+ '" alt="'
			+ t.preloadImage.caption
			+ '" />';

		if (t.preloadImage.caption != "") {
			html_code += '<br />' + t.preloadImage.caption;
		}

		t.box.innerHTML = html_code;

		t.fullViewImage.elm = document.getElementById(t.fullViewImage.id);
		t.fullViewImage.elm.src = t.preloadImage.src;
		//t.fullViewImage.elm.width = t.boxWidth;
		//t.fullViewImage.elm.height = t.boxHeight;

		t.box.style.display = "block";

		// Eventhandler für das Resize-Icon setzen
		t.resizeIcon.elm = document.getElementById(t.resizeIcon.cssID);
		if (t.resizeIcon.elm) {
			t.addEvent("click", t.resizeIcon.elm, t.toggleResize);
			t.addEvent("mouseover", t.resizeIcon.elm,
				function () { this.style.display = "inline"; }
			);
			t.resizeIcon.elm.style.display = "none";

			t.addEvent("mouseover", t.fullViewImage.elm,
				function () {
					document.getElementById(t.resizeIcon.cssID).style.display = "inline";
				}
			);

			t.addEvent("mouseout", t.fullViewImage.elm,
				function () {
					document.getElementById(t.resizeIcon.cssID).style.display = "none";
				}
			);
		}

		return false;
	},




	// Popup auf dem Bildschirm zentrieren (es wird das DIV mit der id "js-popup-box" ausgerichtet, welches als Objekt "jsPopup.box" verfügbar ist)
	center : function () {
		var t = this,
			// Popup-Box in linke obere Ecke positionieren
			x_pos = 0,
			y_pos = 0;

		// zentrierte Position der Box errechnen
		if (window.innerWidth) {
			x_pos = Math.ceil((t.winInnerWidth - t.boxWidth)/2 + window.pageXOffset);
			y_pos = Math.ceil((t.winInnerHeight - t.boxHeight)/2 + window.pageYOffset);
		} else {
			x_pos = Math.ceil((t.winInnerWidth - t.boxWidth)/2 + t.IE.scrollLeft);
			y_pos = Math.ceil((t.winInnerHeight - t.boxHeight)/2 + t.IE.scrollTop);
		}

		// Padding berücksichtigen
		x_pos -= 15;
		y_pos -= 15;

		// übergroßes Bild? -> in Linke obere Ecke positionieren
		if (x_pos < 0)
			x_pos = 0;

		if (y_pos < 0)
			y_pos = 0;

		// Popup-Box positionieren
		t.box.style.left = x_pos + "px";
		t.box.style.top = y_pos + "px";

		return false;
	},




	// Verkleinerung des Popup-Bildes ein-/ausschalten
	toggleResize : function (e) {
		var t = jsPopup;

		if (!e) {
			e = window.event;
		}

		if (e.stopPropagation) {
			e.stopPropagation();
		}

		e.cancelBubble = true;

		t.oversize = (t.oversize == "resize") ? "fullView" : "resize";
		t.display();

		return false;
	},




	// Popup wieder ausschalten (verbergen) bzw. weiterblättern
	hide : function (e) {
		var t = jsPopup,
			clickElm, dir, next, x, y;

		e = e || window.event;
		clickElm = e.srcElement || e.target;

		// weiteres Bild anzeigen?
		if (!t.box.gallery
			|| t.box.gallery.length < 2
			|| (clickElm === t.div)
			|| (clickElm.id && clickElm.id == t.closeIcon.cssID)
		) {
			// Nein.
			t.div.style.display = "none";

		} else {
			// Ja. Nächstes oder vorheriges?
			dir = e.clientX;

			if (typeof(t.IE.scrollLeft) == "number") {
				dir += t.IE.scrollLeft;
			}

			dir -= t.box.offsetLeft;
			next = t.box.galleryIndex + (dir > t.box.offsetWidth / 2 ? 1 : -1);

			if (next >= 0 && next < t.box.gallery.imageLinks.length) {
				t.preload(t.box.gallery.imageLinks[next]);
			}
		}

		return false;
	},




	// Hover-Bilder für nächstes bzw. vorheriges Bild einblenden
	hover : function (e) {
		var t = jsPopup,
			dir, hoverElm, icon, next;

		e = e || window.event;

		hoverElm = e.srcElement || e.target;

		// Hover-Bild anzeigen?
		if ((hoverElm == t.box || hoverElm.parentNode == t.box)
			&& t.box.gallery
			&& t.box.gallery.imageLinks.length > 1
		) {
			// Ja. Nächstes oder vorheriges?
			dir = e.clientX;

			if (typeof(t.IE.scrollLeft) == "number") {
				dir += t.IE.scrollLeft;
			}

			dir -= t.box.offsetLeft;
			next = t.box.galleryIndex + (dir > t.box.offsetWidth / 2 ? 1 : -1);

			if (next >= 0 && next < t.box.galleryIndex) {
				icon = t.prevIcon;
				icon.elm.style.left = "3px";
				t.fullViewImage.elm.style.cursor = "pointer";
			}

			if (next && next < t.box.gallery.imageLinks.length && next > t.box.galleryIndex) {
				icon = t.nextIcon;
				icon.elm.style.right = "3px";
				t.fullViewImage.elm.style.cursor = "pointer";
			}
		}

		if (icon && !icon.elm.parentNode) {
			icon.elm.style.top = Math.floor((t.box.offsetHeight - icon.elm.height) / 2) + "px";
			t.box.appendChild(icon.elm);
		}

		if (t.nextIcon.elm.parentNode && icon != t.nextIcon) {
			t.box.removeChild(t.nextIcon.elm);
			t.fullViewImage.elm.style.cursor = "";
		}

		if (t.prevIcon.elm.parentNode && icon != t.prevIcon) {
			t.box.removeChild(t.prevIcon.elm);
			t.fullViewImage.elm.style.cursor = "";
		}

		if (!icon) {
			t.fullViewImage.elm.style.cursor = "";
		}

		return false;
	},




	// Funktion zum Ermitteln der maximalen Fensterfläche
	getBrowserDimensions : function () {
		var t = this;

		if (window.innerWidth) {
			t.winInnerWidth = window.innerWidth;
			t.winInnerHeight = window.innerHeight;
		} else {
			t.winInnerWidth = t.IE.offsetWidth;
			t.winInnerHeight = t.IE.offsetHeight;
		}

		// Maximal-Größe für die Popup-Box abzüglich eines Rahmens
		t.boxMaxWidth = t.winInnerWidth - 50;
		t.boxMaxHeight = t.winInnerHeight - 50;

		return false;
	},




	// Funktion zum Setzen eines Eventhandlers
	addEvent : function (ev, obj, handle) {
		if (navigator.userAgent.toLowerCase().lastIndexOf("msie") < 0) {
			obj.addEventListener(ev, handle, false);
			obj.addEventListener(ev, handle, false);
		} else {
			obj.attachEvent("on" + ev, handle);
			obj.attachEvent("on" + ev, handle);
		}
	},




	// Funktion zum Löschen eines Eventhandlers
	removeEvent : function (ev, obj, handle) {
		if (navigator.userAgent.toLowerCase().lastIndexOf("msie") < 0) {
			obj.removeEventListener(ev, handle, false);
			obj.removeEventListener(ev, handle, false);
		} else {
			obj.detachEvent("on" + ev, handle);
			obj.detachEvent("on" + ev, handle);
		}
	},




	// Funktion zum Bereiten der PopupBox
	initPopupBox : function () {
		var allElements = document.getElementsByTagName("*"),
			t = this,
			i, a, links, test;

		// Quirksmode des IE berücksichtigen
		t.IE = (document.compatMode && document.compatMode == "CSS1Compat") ? document.documentElement : document.body || null;

		// Fenstermaße ermitteln
		t.getBrowserDimensions();

		// Falls noch kein DIV-Element mit der ID "js-popup" existiert, ein solches erzeugen und am Ende des body-Dokuments hinzufügen
		t.div = document.getElementById(t.parentDiv.cssID);
		if (!t.div) {
			t.div = document.createElement("div");
			t.div.id = t.parentDiv.cssID;
			document.body.appendChild(t.div);

			// Style-Angaben zum vorläufigen Verstecken des DIVs
			t.div.style.display = "none";
			t.div.style.position = "absolute";
			t.div.style.backgroundImage = "url(" + t.overlayBackground.src_png + ")";

			// Dieses DIV-Element ist die eigentliche Box mit der Vollansicht
			t.box = document.createElement("div");
			t.box.id = t.popupBox.cssID;
			t.box.style.position = "absolute";

			// Die eigentliche Box mit der Vollansicht in das Popup-Eltern-DIV einhängen und click-Ereignis zuweisen
			t.div.appendChild(t.box);
			t.addEvent("click", t.div, t.hide);
			t.addEvent("mousemove", t.div, t.hover);

			// IE-spezifische Stylesheets einbinden
			/*@cc_on
				@if (@_jscript_version == 5.6)
					// zusätzliches Stylesheet für IE6 einbinden
					css = document.createElement("link");
					css.rel = "stylesheet";
					css.type = "text/css";
					css.media = "screen, projection";
					css.href = t.baseURL + "css/ie6.css";
					document.getElementsByTagName("head")[0].appendChild(css);
				@end
			@*/

			// Hover-Icons vorbereiten
			t.nextIcon.elm = new Image();
			t.nextIcon.elm.src = t.nextIcon.src;
			t.nextIcon.elm.alt = t.nextIcon.alt;
			t.nextIcon.elm.id = t.nextIcon.id;
			t.nextIcon.elm.title = t.nextIcon.title;
			t.prevIcon.elm = new Image();
			t.prevIcon.elm.src = t.prevIcon.src;
			t.prevIcon.elm.alt = t.prevIcon.alt;
			t.prevIcon.elm.id = t.prevIcon.id;
			t.prevIcon.elm.title = t.prevIcon.title;

			// Throbber-Bild vorladen
			t.waitAnimation.elm = new Image();
			t.waitAnimation.elm.src = t.waitAnimation.src;
		}

		// Style-Angaben für das "js-popup"-DIV, damit es das komplette Browserfenster ausfüllt
		if (window.innerWidth && typeof(window.scrollMaxY)) {
			t.div.style.width = document.body.scrollWidth + "px";
			t.div.style.height = window.innerHeight + window.scrollMaxY + "px";
		}

		if (t.IE.scrollWidth) {
			t.div.style.width = t.IE.scrollWidth + "px";
			t.div.style.height = t.IE.scrollHeight + "px";
		}

		// alle HTML-Elternelemente mit der oben eingestellten CSS-Klasse ermitteln, um ihnen die Vollansichts-Funktionalität zu geben
		for (i = 0; i < allElements.length; i++) {
			if (allElements[i].className.indexOf(t.triggerCssClass) != -1) {
				// Das Class-Attribut eines HTML-Elementes kann mehrere Klassennamen enthalten, die alle durch Leerzeichen getrennt sind.
				// Diese Leerzeichen werden nun durch Kommata ersetzt, ebenso am Anfang und Ende je ein Komma hinzugefügt, sodass
				// der gesuchte Klassenname zwischen zwei Kommas stehen muss, wenn er denn für dieses Element existiert.
				test = "," + allElements[i].className.split(" ").join(",") + ",";

				if (test.indexOf("," + t.triggerCssClass + ",") != -1)
					t.galleries.push({elm : allElements[i]});
			}
		}

		for (i = 0; i < t.galleries.length; i++) {
			// alle Bilder-Links eines gefundenen Elternelements mit der Popup-Funktion erweitern
			links = t.galleries[i].elm.getElementsByTagName("a");

			for (a = 0; a < links.length; a++) {
				// jedes Link-Element auf enthaltendes Bild überprüfen
				if (links[a].getElementsByTagName("img")[0]) {
					// falls Bild im Link, Popup-Funktion anbringen
					links[a].onclick = function () {
						return t.preload(this);
					};

					if (!t.galleries[i].imageLinks) {
						t.galleries[i].imageLinks = new Array();
					}

					t.galleries[i].imageLinks.push(links[a]);
				}
			}
		}
	},




	// Initialisierung des kompletten jsPopup-Objektes
	init : function () {
		// baseURL bestimmen
		var scripts = document.getElementsByTagName("script"),
			t = this,
			css, i, setting, _setting, v, _v;

		for (i = 0; i < scripts.length; i++) {
			if (scripts[i].src && scripts[i].src.match(/\/js_popup.js\b/i)) {
				t.baseURL = scripts[i].src.replace(/^(.*\/)[^\/]+$/, "$1");
			}
		}

		// CSS einbinden
		css = document.createElement("link");
		css.rel = "stylesheet";
		css.type = "text/css";
		css.media = "screen, projection";
		css.href = t.baseURL + "css/js_popup.css";
		document.getElementsByTagName("head")[0].appendChild(css);

		// URLs in den Settings anpassen
		for (setting in t) {
			v = t[setting];
			if (typeof (v) == "string") {
				if (v.match(/^\{\$baseURL\}/g))
					t.settings[setting] = v.replace(/^\{\$baseURL\}\/?/g, t.baseURL);
			} else {
				for (_setting in v) {
					_v = v[_setting];
					if (typeof (_v) == "string")
						if (_v.match(/^\{\$baseURL\}/g))
							t[setting][_setting] = _v.replace(/^\{\$baseURL\}\/?/g, t.baseURL);
				}
			}
		}

		// PopupBox einrichten lassen, wenn die Seite fertig geladen hat
		t.oldWinOnLoad = window.onload;
		window.onload = function () {
			if (typeof (t.oldWinOnLoad) == "function")
				t.oldWinOnLoad();

			t.initPopupBox();
		};
	}
};


// Die Popup-Funktionalität initialisieren
jsPopup.init();
