$(document).ready(function() {
$("#facebook .connect_widget_comment_area").css("padding", "0");
function GalleryLoad(GaleriOrdner, Startposition) {
	//Gallery Übersicht ausblenden und ToolBar einblenden
	$("#Frame").show();
	$("#Play").fadeIn();
	$("#Information").hide();
	$("#GalleryList").fadeOut();
	$("#Titel").addClass("ToolElementActive");
	$("#Uebersicht").removeClass("ToolElementActive");
	$("#LadeAnzeige").fadeIn();
	$("#horizon").fadeIn();
	$("#BildLadeAnzeige").show();
	CookieNavigation();
	FrameFadeIn();
	
	//Pfeile laden
	pfeilforward = new Image();
	pfeilforward.src = "./forward.png";
	pfeilback = new Image();
	pfeilback.src = "./back.png";
	
	//DIV Bereiche leeren
	$("#PreviewFrame").html("");
	$("#Image .bilder").html("");
	
	//Variablen angeben rsp. leeren
	Bilder = "";
	LetzteBildID = "";
	BilderPreview = new Array();	//Vorschau der Bilder im Hintergrund wird vorgeladen
	BilderDaten = new Array();		//Daten zu den Bildern, Breite, Hoehe, Zeit
	
	//KeyEvents entfernen
	KeyEvents('unbind');
	
	//JSON Abfrage starten
	Zeit = new Date();
	Zeitpunkt1 = Zeit.getTime();

	$.getJSON('galeri.php',
		{
			gallery: GaleriOrdner
		},
		function(response) {
			if(response.error == "") {
				$("#Titel").html(response.titel);
				$("#Titel").fadeIn();
				$("#Counter").fadeIn();
				
				Bilder = response.bilderliste;
				$.each(Bilder, function(index, werte) {
					$("#PreviewFrame").append("<span id=\"im" + index + "\" class=\"BildElement\"><img src=\"./thumbnails/" + GaleriOrdner + "/" + werte[0] + "\" class=\"preview\" /></span>");
					$("#im" + index).click(function() {
						GeheZuBild(index);
						BilderPreview[index] = "";
					});
					if(index+1 == Bilder.length) { 	
						$("#PreviewFrame").fadeTo(0, 1);;
						$("#LadeAnzeige").hide();
						Zeit = new Date();
						Zeitpunkt2 = Zeit.getTime();
					}
				});
				$(".BildElement").fadeTo(0, 0.6);
				if(Startposition != "0"){
					//Bildanzeige durch Anker
					if(location.href.split('#')[1]) {
						var anker = location.href.split('#')[1];
						var bildnr = anker.split('/')[1];
						var BildNummer = parseInt( bildnr );
						if(isNaN(BildNummer)) {
							BildNummer = 0;
						}
					}
					GeheZuBild(BildNummer);
				} else {
					GeheZuBild(Startposition);
				}
				
				$("#loading").fadeOut();
				$("#gallery").fadeIn("slow");
				
				//KeyEvents hinzufügen
				KeyEvents('start');

				
				$.getJSON('galeri_data.php',
					{
						'galeri_galerien_id': response.id,
						ladezeit: Zeitpunkt2-Zeitpunkt1,
						browserversion: $.browser.version,
						breite: $(window).width(),
						hoehe: $(window).height()
					}
				);
				
			} else {
				alert( response.error );
			}
	});
	AktuelleGaleri = GaleriOrdner;
}

//Funktion Bildwechsel
function GeheZuBild(BildID){
	if(BildID == 'up') { BildID = LetzteBildID+1; } else if(BildID == 'down') { BildID = LetzteBildID-1; } 
	
	//Überprüfen ob BildID im Bereich ist
	if(BildID >= 0 && BildID < Bilder.length) {
		if ( typeof LetzteBildID != "undefined") { $(".BildElement").eq(LetzteBildID).fadeTo(200, 0.6); }
		gallery = AktuelleGaleri;
		
		var BildPfad = "images/" + gallery + "/" + Bilder[BildID][0];
		if(BilderPreview[BildID] == "") {
			BilderPreview[BildID] = new Image();
			BilderPreview[BildID].src = BildPfad;
		}
		//Bild laden versteckt
		$("#Image").append('<div class="bilder"><img src="'+BildPfad+'" /></div>');
		
		//Vorschau Bilder
		$(".BildElement").eq(BildID).fadeTo(200, 1);
		$("#PreviewFrame").stop();
		FensterBreite2 = parseInt($(window).width()/2);
		AktuellePosition = parseInt(168*BildID);
		if(FensterBreite2 > AktuellePosition) {
			offset = 0;
		} else {
			offset = parseInt(AktuellePosition-FensterBreite2+74);
		}
		$("#PreviewFrame").scrollTo({ top: '0', left: offset }, 300);
			
		//Höhe anpassen
		max_hoehe = $(window).height();
		frame_height = $("#Frame").height();
		frame_height2 = parseInt(frame_height/2);
		max_hoehe = parseInt(max_hoehe-frame_height);
		bild_hoehe = Bilder[BildID][2];
		bild_breite = Bilder[BildID][1];
		max_breite = parseInt($(window).width());
		
		//Bild passt
		if(bild_hoehe < max_hoehe && bild_breite < max_breite) {
			$("#Image div[class=bilder]:last img").height(bild_hoehe + 'px');
			$("#Image div[class=bilder]:last img").width(bild_breite + 'px');
			$("#Image div[class=bilder]:last").css('margin-top', parseInt(-frame_height2-bild_hoehe/2));
		//Bild ist zu hoch
		} else if(bild_hoehe > max_hoehe && bild_breite < max_breite) {
			$("#Image div[class=bilder]:last img").height(max_hoehe + 'px');
			$("#Image div[class=bilder]:last").css('margin-top', parseInt(-frame_height2-max_hoehe/2));
		//Bild ist zu breit
		} else if(bild_hoehe < max_hoehe && bild_breite > max_breite) {
			$("#Image div[class=bilder]:last img").width(max_breite + 'px');
			bild_hoehe_neu = bild_hoehe/(bild_breite/max_breite);
			$("#Image div[class=bilder]:last").css('margin-top', parseInt(-frame_height2-bild_hoehe_neu/2));
		//Bild ist zu breit und zu hoch
		} else if(bild_hoehe > max_hoehe && bild_breite > max_breite) {
			breiten_nr = max_breite/bild_breite;
			hoehen_nr = max_hoehe/bild_hoehe;
			//Wenn hoehe besser passt
			if(breiten_nr > hoehen_nr) {
				$("#Image div[class=bilder]:last img").height(max_hoehe + 'px');
				$("#Image div[class=bilder]:last").css('margin-top', parseInt(-frame_height2-max_hoehe/2));
			//Wenn breite besser passt
			} else {
				$("#Image div[class=bilder]:last img").width(max_breite + 'px');
				bild_hoehe_neu = bild_hoehe/(bild_breite/max_breite);
				$("#Image div[class=bilder]:last").css('margin-top', parseInt(-frame_height2-bild_hoehe_neu/2));
			}
		}
		
		
		$("#Image div[class=bilder]:last").fadeIn('normal', function() {
			if($("#Image div[class=bilder]").size() > 1) {
				$("#Image div[class=bilder]:first").fadeOut('fast', function() { $("#Image div[class=bilder]:first").remove() } );
			}
		});
		
		//Counter erhöhen
		$("#Counter").html(parseInt(BildID+1) + " / " + parseInt(Bilder.length));
		window.location = "#"+gallery+"/"+BildID+"";
		
		//Facebook Link anpassen
		$("#facebookframe").attr("src", "http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.prima-f.ch%2Fgalerii%2F%3Fgaleri%3D"+gallery+"%26bildnr%3D"+BildID+"%23"+gallery+"%2F"+BildID+"&amp;send=false&amp;layout=standard&amp;width=430&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font=lucida+grande&amp;height=25");
		
		// Navigation rechts/links ein-/ausblenden
		if($.cookie("navigation") != "hide") {
			if(BildID == 0) { $("#left").fadeOut(); } else { $("#left").fadeIn(); }
			if(BildID == parseInt(Bilder.length-1)) { $("#right").fadeOut(); } else { $("#right").fadeIn();  }
		}
		// Bild vorher und nacher laden, wenn noch nicht
		if(BildID < Bilder.length-1) {
			if(BilderPreview[BildID+1] == undefined) {
				BilderPreview[BildID+1] = new Image();
				BilderPreview[BildID+1].src = "images/" + gallery + "/" + Bilder[BildID+1][0];
			}
		}
		if(BildID < Bilder.length-2) {
			if(BilderPreview[BildID+2] == undefined) {
				BilderPreview[BildID+2] = new Image();
				BilderPreview[BildID+2].src = "images/" + gallery + "/" + Bilder[BildID+2][0];
			}
		}
		LetzteBildID = BildID;
	} else {
		TimerStop();
	}
}

//BEIM LADEN DER SEITE
//==================================================================
	//Bildanzeige durch Anker
	if(location.href.split('#')[1]) { 
		var anker = location.href.split('#')[1];
		var galerie = anker.split('/')[0];
		GalleryLoad( galerie );
	} else {
		$("#PreviewFrame").hide();
	}
	
	//KeyEvent Funktion starten
	function KeyEvents(event) {
		if(event == 'start') {
			$(document).keydown(function(event){
				switch (event.keyCode) {
					case 37: // Pfeil links
						GeheZuBild('down');
					break;
					case 39: // Pfeil rechts
						GeheZuBild('up');
					break;
					case 32: // Leerschlag
						ToggleTimer();
					break;
					case 122: // f11
						ToggleFrame();
					break;
					case 27: // ESC
						SettingsHide();
					break;
				}
			});
			//Mausrad
			$(document).mousewheel(function(event, delta) {
				if (delta > 0)
					GeheZuBild('down');
				else if (delta < 0)
					GeheZuBild('up');
				return false; // prevent default
			});
			
			$("#left").click( function() { GeheZuBild('down'); });
			$("#right").click( function() { GeheZuBild('up'); });
		} else {
			$("#left").unbind("click");		//Event Button Links entfernen
			$("#right").unbind("click");	//Event Button Rechts entfernen
			$(document).unbind("keydown");	//Event Keydown entfernen
			$(document).unmousewheel();		//Event Mousewheel entfernen
		}
				
	}
	
	//AnimationsCookie Animationen abschalten
	if($.cookie("animationoff") == "true") {
		AnimationOff();
	}
	
	//TimerDaten aus Cookie lesen
	if($.cookie("timer") == null) {
		$.cookie("timer", "3", { expires: 999 });
	}

	//Bei Internet Explorer beschleunigungen aktivieren
	if($.browser.msie && parseInt($.browser.version) < 9) {
		
		AnimationOff();
		$(".AnimationSwitch").html("<span>Animationen deaktiviert</span>Animationen sind im Internet Explorer bis Version 9 aufgrund von Performance-Problemen standardgemäss deaktiviert.");
		$(".AnimationSwitch").css("color","#404040");
		$(".AnimationSwitch span").css("color","#404040");
	}
	
	//Iinformationsbar ausblenden
	$("#shortcut-close").click( function() {
		$("#Information").fadeOut();
	});

//FUNKTIONEN
//==================================================================
	
	//Navigation ein/ausblenden
	//=========================================================
	function CookieNavigation() {
		if($.cookie("navigation") == "hide") {
			NavigationHide();
		} else if($.cookie("navigation") == "show") {
			NavigationShow();
		}
	}
	
	function NavigationShow() {
		if($.cookie("navigation") != "hide");
		$(".Navigation").fadeIn();
		$("#NavigationSwitch span").html("Buttons aktiviert");
		$.cookie("navigation", "show", { expires: 999 });
	}
	function NavigationHide() {
		$(".Navigation").fadeOut();
		$("#NavigationSwitch span").html("Buttons deaktiviert");
		$.cookie("navigation", "hide", { expires: 999 });
	}
	
	$("#NavigationSwitch").click( function() {
		if($(".Navigation").css("display") == "none") {
			NavigationShow();
		} else {
			NavigationHide();
		}
	});
	//Ende Navigation
	//=========================================================
	
	//Frame ein- ausblenden
	function FrameFadeIn() {
		$("#Titel").addClass("ToolElementActive");
		$("#Uebersicht").removeClass("ToolElementActive");
		$("#GalleryList").fadeOut();
		$("#horizon").fadeIn();
		$("#ToggleShow img").attr("src", "./images/hide.png");
		$("#PreviewFrame").show();
		$("#Frame").animate({
			height: "170px"
		});
	}
	function FrameFadeOut() {
		$("#ToggleShow img").attr("src", "./images/show.png");
		$("#Frame").animate({
			height: "28px"
		});
	}
	function ToggleFrame() {
		SettingsHide();
		if($("#Frame").height() == 170) {
			FrameFadeOut();
		}else if($("#Frame").height() == 28) {
			FrameFadeIn();
		}
	}
	
	
	$("#Uebersicht").click( function() {
		$("#BildLadeAnzeige").hide();
		//Aktuelle Seite weiss hervorheben in der Auswahl unten
		$("#Uebersicht").addClass("ToolElementActive");
		$("#Titel").removeClass("ToolElementActive");
		//Galerie übersicht einblenden, Bilder ausblenden
		$("#GalleryList").fadeIn();
		$("#horizon").fadeOut();
		FrameFadeOut(); //Frame ausblenden
		NavigationHide(); //navigation verstecken
		SettingsHide(); //Einstellugnen ausblenden
		window.location = "#";
		KeyEvents('unbind');
	});
	
	$("#Titel").click( function() {
		KeyEvents('start');
		$("#BildLadeAnzeige").show();
		FrameFadeIn();
		$("#Play").fadeIn();
		$("#KategorienFrame").hide();
		$("#PreviewFrame").fadeIn();
		NavigationShow();
		SettingsHide();
	});

	$("#ToggleShow").click( function() { ToggleFrame() });

	$(".galeri").fadeTo(0, 0.7);
	$(".galeri div.description").fadeTo(0, 0.7);
	$(".galeri").live('mouseover mouseleave', function(event) {
	  if (event.type == 'mouseover') {
			$(this).fadeTo(200, 1);
	  } else {
			$(this).fadeTo(200, 0.6);
	  }
	});
	
	$(".BildElement").live('mouseover mouseleave', function(event) {
	  if (event.type == 'mouseover') {
			$(this).fadeTo(200, 1);
	  } else {
			$(this).fadeTo(200, 0.6);
	  }
	});

	$(".galeri").live('click', function(event) {
		GalleryLoad($(this).attr("rel"), 0);
	});
	
	function AnimationOff() {
		$.fx.off=true;
		$(".AnimationSwitch span").html("Animationen deaktiviert");
		$.cookie("animationoff", "true", { expires: 999 });
	}
	$(".AnimationSwitch").click( function() {
		if($.fx.off == false || $.fx.off == undefined) {
			AnimationOff();
		} else {
			if($.browser.msie) {
				alert("Warnung für den Internet Explorer\n\nSie surfen mit dem Internet Explorer. Sie haben die Animationen aktiviert. Dies führt bei Ihrem Browser meistens zu Problemen.\nIdealerweise benutzen Sie einen Browser wie Mozilla Firefox oder Google Chrome, welche Leistungsfähriger und sicherer sind.");
			}
			$.fx.off=false;
			$(".AnimationSwitch span").html("Animationen aktiviert");
			$.cookie("animationoff", "false", { expires: 999 });
		}
	});	
	

	
	
	// Diashow beenden
	function TimerStop() {
		$("#Play img").attr("src","./images/play.png");
		$("#Play").attr("rel", "Stop");
		if ( typeof Intervall != "undefined") {
			clearInterval (Intervall);
		}
	}
	//Diashow starten
	function TimerPlay() {
		SettingsHide();
		$("#Play img").attr("src","./images/stop.png");
		$("#Play").attr("rel", "Play");
		DefaultIntervall = $.cookie("timer")*1000;
		Intervall = setInterval (function() { GeheZuBild('up'); }, DefaultIntervall );
	}
	//Diashow starten/beenden
	function ToggleTimer() {
		if($("#Play").attr("rel") == "Stop") {
			TimerPlay();
		} else {
			TimerStop();
		}
	}
	//Event für Button hinzufügen
	$("#Play").click( function() {
		ToggleTimer();
	});
	function SettingsHide() {
		$("#Settings").hide();
		$("#SettingsButton").css({
			'border': '0',
			'border-left': '1px solid #000',
			'border-right': '1px solid #000',
			'margin-top': '0'
		});
	}
	$("#SettingsClose").click( function() {
		SettingsHide();
	});
	
	function SettingsShow() {
		$("#Settings").css("bottom", $("#Frame").height());
		$("#Settings").show();
		$("#SettingsButton").css({
			'border': '1px solid #fff',
			'border-top': '0',
			'margin-top': '-1px'
		});
	}
	//Event für Button hinzufügen
	$("#SettingsButton").click( function() {
		if($("#SettingsButton").css("margin-top") == "-1px") {
			SettingsHide();
		} else {
			SettingsShow();
		}
	});
	
	//Slider für Diasho Zeit Einstellugnen
	$( "#slider" ).slider({
		value: $.cookie("timer"),
		min: 1,
		range: "min",
		max: 5,
		step: 0.2,
		slide: function( event, ui ) {
			$( "#timer" ).html(ui.value );
			$.cookie("timer", ui.value, { expires: 999 });
		}
	});
	$( "#timer" ).html($( "#slider" ).slider( "value" ) );
	
	//Feedback
	//=================================================================
	$("#FeedbackButton").click( function() {
		KeyEvents('unbind');
		$("#SendButton").click( function() {
			SendButton();
		});
		$("#SendButton").html("Feedback speichern");
		$("#SendButton").css({
			"border-color": "#fff",
			"color": "#fff",
			"cursor": "pointer"
		});
		$.getJSON('feedback.php',
			{
				load: true
			},
			function(response) {
				if(response.error == "") {
					if(response.name != "") {
						$("#name").val(response.name);
						$("#email").val(response.email);
					} else {
						if($("#name").val() == "Name") {
							$("#name").click( function() {
								$("#name").val("");
								$("#name").unbind("click");
							});
						}
						if($("#email").val() == "Mail") {
							$("#email").click( function() {
								$("#email").val("");
								$("#email").unbind("click");
							});
						}
					}
					if($("#feedback").val() == "Ihr Feedback") {
						$("#feedback").click( function() {
							$("#feedback").html("");
							$("#feedback").unbind("click");
						});
					}
				} else {
					alert(response.error);
				}
			}
		);
		$("#Feedback-Form").fadeIn();
	});	
	
	function SendButton() {
		if($("#feedback").val() != "" && $("#feedback").val() != "Ihr Feedback") {
			$.getJSON('feedback.php',
				{
					save: true,
					name: $("#name").val(),
					email: $("#email").val(),
					feedback: $("#feedback").val()
				},
				function(response) {
					if(response.error == "") {
						$("#SendButton").unbind("click");
						$("#SendButton").html("Feedback gespeichert");
						$("#feedback").val("");
						$("#SendButton").css({
							"border-color": "#404040",
							"color": "#404040",
							"cursor": "default"
						});
					} else {
						alert(response.error);
					}
				}
			);
			$("#Feedback-Form").fadeIn();
		} else {
			alert("Das Feld Feedback muss ausgefüllt werden.");
		}
	}
	$("#Feedback-Close").click( function() {
		$("#Feedback-Form").fadeOut();
		KeyEvents('start');
	});

});



/*Als ZIP downloaden()
$("#download_zip").click( function() {
  url = SeitenURL + "./create_zip.php?folder=" + gallery;
  fenster=window.open(url, "facebook", "width=400,height=250,resizable=yes");
  fenster.focus();
});

//facebook share mit encodeURICompnent()
$("#facebook").click( function() {
  aktuelleURL = encodeURIComponent(self.location.href);
  aktuellerTitel = encodeURIComponent(document.title);
  url = "http://www.facebook.com/sharer.php?u=" + aktuelleURL + "&t=" + aktuellerTitel;
  fenster=window.open(url, "facebook", "width=700,height=350,resizable=yes");
  fenster.focus();
});

//buzz share
$("#buzz").click( function() {
  aktuelleURL = encodeURIComponent(self.location.href);
  PrimaURL = encodeURIComponent(SeitenURL + "");
  aktuellerTitel = encodeURIComponent(document.title);
  url = "http://www.google.com/buzz/post?url=" + aktuelleURL + "&imageurl=" + SeitenURL + gallery + "/" + Bilder[AktuelleBildID];
  fenster=window.open(url, "buzz", "width=700,height=400,resizable=yes,scrollbars=yes");
  fenster.focus();
});
*/
