﻿$(document).ready(function()
{
	try
	{
		// Seiten-Context
		var container = $("#wrapper"),
			list_items = $("#navigation ul li"),
			link_items = $("#navigation ul li a"),
			starterPanel = $("#starter"),
			txtContactHints = $(".contact"),
			slider = $(".sidebar"),
			floatingText = $(".floating_content"),
			terminScrollPane = $("#termine"),
			err = $(".error"),
			errComment = $("#errComment");

		// Timer-Konstanten	
		var time = 500,
    		timer = 0,
			multiplier = .8;

		// Startseite langsam einblenden...
		starterPanel.stop().animate({ opacity: "show" }, { duration: 2000, queue: false });

		// (Animation) Einfliegen der Navigation beim Starten
		list_items.each(function(fn)
		{
			//$(this).css("margin-top", "-80px");
			// updates timer  
			timer = (timer * multiplier + time);
			$(this).animate({ marginTop: "40px" }, { duration: (timer * 2), easing: "easeOutBounce", queue: true });
		});

		// Animation der Navigation (beim Hover-Event)
		list_items.hover(function()
		{
			$(this).stop().animate({ marginTop: "35px" }, { duration: "normal", queue: false });

		}, function()
		{
			$(this).stop().animate({ marginTop: "40px" }, { duration: "normal", queue: false });
		});

		// Click-Events() der einzelnen Link-Buttons
		link_items.click(function()
		{
			$("#navigation ul li a").removeClass('selected');
			$(this).addClass("selected");
			container.scrollTo($(this).attr("href"), { axis: "y", duration: 1500, easing: "easeOutElastic", queue: false });
			starterPanel.stop().animate({ opacity: "hide" }, { duration: 1000, queue: false });

			// '#item2' ist der Link Termine in der Navigation
			if ($(this).attr("href") === "#item2")
			{
				ShowEventsFromXml();
			}
			$(this).blur();
			return false;
		});

		// Plugin:TextBoxHints
		txtContactHints.hint();

		// Plugin:FancyBox
		$("a#lnkAnfahrt").fancybox(
    			{
    				'zoomOpacity': true,
    				'overlayShow': false,
    				'zoomSpeedIn': 500,
    				'zoomSpeedOut': 500
    			});

		// Scrollen des Contents bei einem Mouse-Move-Event()
		slider.mousemove(function(e)
		{
			// Das Offset des Text-Containers ermitteln - hier TOP (Sidebar Offset, Top value)
			var s_top = parseInt(slider.offset().top);

			// Das Offset des Text-Containers ermitteln - hier BOTTOM (Sidebar Offset, Bottom value)
			var s_bottom = parseInt(slider.height() + s_top);

			// Roughly calculate the height of the menu by multiply height of a single LI with the total of LIs
			// Berechne die Hoehe des Anzeigebereiches UND die totale Hoehe des Objektes (also den kompletten Text)
			var mheight = parseInt(floatingText.height());
			// var mheight = parseInt(floatingText.height() * floatingText.length);

			// Berechne neue TOP-Value (Calculate the top value)
			// This equation is not the perfect, but it 's very close	
			var top_value = Math.round(((s_top - e.pageY) / 100) * mheight / 2);

			// Animiere den Text-Container bei Aktualisierung des neuen TOP-VALUE-Wertes (Animate the #menu by chaging the top value)
			floatingText.animate({ top: top_value }, { queue: false, duration: 500 });
		});

		// Window-Resize-Event() ueberwachen
		$(window).bind("resize", function(fn)
		{
			resizePanel();
		});

		// PlugIn: jScrollPane
		//terminScrollPane.jScrollPane();

		// ===========================================================================
		// AJAX - Context

		// Re-initialisiere das jScrollPane nach einem AJAX-Request
		reinitialiseScrollPane = function()
		{
			terminScrollPane.jScrollPane({
				scrollbarWidth: 10,
				maintainPosition: false,
				reinitialiseOnImageLoad: true
			});
		}

		// Hole die Termine aus der XML-Dateie mit Hilfe von AJAX
		function ShowEventsFromXml()
		{
			var xmlContainer = $("#xml_wrap"),
    			ajaxIndicator = $("#ajax_loader");

			$.ajax({
				type: "GET",
				url: "termine.xml",
				dataType: "xml",
				beforeSend: function()
				{
					xmlContainer.empty().hide();
					ajaxIndicator.stop().fadeIn("slow");
					//terminScrollPane.empty().append($('<p>Nothing to see here</p>')).jScrollPane({ scrollbarWidth: 20, scrollbarMargin: 10 });
					terminScrollPane.jScrollPane({ scrollbarWidth: 20, scrollbarMargin: 10 });

				},
				success: function(xml)
				{
					//alert(xml);
					$(xml).find("termin").each(function(i)
					{
						var titel = $(this).find("titel").text(),
    						inhalt = $(this).find("inhalt").text(),
    						datum = $(this).find("datum").text();

						$('<div class="items" id="link_' + i + '"></div>').html('<div class="xml_header">' + titel + '&nbsp;' + datum + '</div><div class="xml_content">' + inhalt + '</div><br />').appendTo(xmlContainer);
						ajaxIndicator.fadeOut("slow", function()
						{
							// im CallBack der FadeIn-Funktion das jScrollPane-Objekt erneut binden
							reinitialiseScrollPane();
							xmlContainer.fadeIn("normal");
							//xmlContainer.fadeIn("normal", reinitialiseScrollPane);
						});
					});
				},
				error: function(XMLHttpRequest, textStatus, errorThrown)
				{
					// typically only one of textStatus or errorThrown will have info
					var errMsg = "XMLHttpRequest:\t" + this.XMLHttpRequest + "\ntextStatus:\t" + this.textStatus + "\nerrorThrown:\t" + this.errorThrown;
					alert(errMsg);
				}
			});
		}

		err.hide();
		errComment.hide();

		function ValidateForm()
		{
			// Context verwenden
			var name = $("#txtName"),
				email = $("#txtEmail"),
				kontaktGrund = $("#txtGrund"),
				nachricht = $("#txtMsg"),
				content = "",
				erg = true;

			// ueberpruefe das Eingabefeld des 'Namens'
			if (name.val().length > 0 && name.val() !== name.attr("title"))
			{
				$("label#errName").hide();
			}
			else
			{
				$("label#errName").show();
				name.focus();
				erg = false;
				return false;
			}

			// ueberpruefe das Eingabefeld der 'Emailadresse'
			if (email.val().length > 0 && email.val() !== email.attr("title"))
			{
				var regex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
				var matches = regex.exec(email.val());

				// ueberpruefe die Eingabe der Emailadresse auf Richtigkeit
				if (matches === null)
				{
					$("label#errEmail").show();
					email.focus();
					erg = false;
					return false;
				}
				else
				{
					$("label#errEmail").hide();
				}
			}
			else
			{
				$("label#errEmail").show();
				email.focus();
				erg = false;
				return false;
			}

			// ueberpruefe das Eingabefeld der 'GrundDerKontaktaufnahme'
			if (kontaktGrund.val().length > 0 && kontaktGrund.val() !== kontaktGrund.attr("title"))
			{
				$("label#errGrund").hide();
			}
			else
			{
				$("label#errGrund").show();
				kontaktGrund.focus();
				erg = false;
				return false;
			}

			// ueberpruefe das Textfeld der 'Nachricht'
			if (nachricht.val().length > 0 && nachricht.val() != nachricht.attr("title"))
			{
				$("label#errMsg").hide();
			}
			else
			{
				$("label#errMsg").show();
				nachricht.focus();
				erg = false;
				return false;
			}

			// Auswertung, ob alle Eingabefelder richtig ausgefuellt wurden
			if (erg !== false)
			{
				err.hide();
				var dataString = 'name=' + name.val() + '&email=' + email.val() + '&kontaktGrund=' + kontaktGrund.val() + '&nachricht=' + nachricht.val();
				alert(dataString);

				/*$.ajax({
				type: "POST",
				url: "bin/process.php",
				data: dataString,
				success: function()
				{
				$('#contact_form').html("<div id='message'></div>");
				$('#message').html("<h2>Das Kontaktformular wurde erfolgreich verschickt!</h2>").append("<p>wir werden sie bald kontaktieren.</p>").hide().fadeIn(1500, function()
				{
				$('#message').append("<img id='checkmark' src='images/check.png' />");
				});
				}
				});
				*/
				return false;

			}
			/*else
			{
			alert("Leider ist ein Fehler aufgetreten");
			}*/
		}

		$("#senden").bind("click", function()
		{
			// validate and process form here
			ValidateForm();
			return false;
		});

		$(".fade").css({ opacity: .5 });

	}
	catch (e)
	{
		alert(e);
	}
});

// Fkt. welche beim Window-Resize-Event gefeuert wird, um den Content erneut zu poitionieren
function resizePanel()
{
	var width = $(window).width(),
		height = $(window).height();

	mask_height = height * $('.content_item').length;

	//$('#debug').html(width  + ' ' + height + ' ' + mask_height);

	$("#wrapper, .content_item").css({ width: width, height: height });
	$("#mask").css({ width: width, height: mask_height });
	var x = $("#navigation ul li a.selected").attr("href");
	if (x !== undefined)
		$("#wrapper").scrollTo($("#navigation ul li a.selected").attr("href"), 0);
}

//QueryLoader.selectorPreload = "body";
//QueryLoader.init();
