var interval = 100; // Zur Drosselung => fluessiger
var letzterContentMoveUpdate = 0;

function initArrowEvents() {
	$(window).resize(function() {
		var jetzt = new Date().getTime();
		if (jetzt - letzterContentMoveUpdate > interval) {
			activateArrowsIfNeeded();
		}
	});
}

function activateArrowsIfNeeded() {
	var anzDargestellterElemente = calcMaxMove();
	var anzElementeInsgesamt = $(".contentPartFloat").size();

	if (anzDargestellterElemente < anzElementeInsgesamt) {
		$("#rewind,#fastRewind,#forward,#fastForward").show(500);

		$("#rewind").unbind("mouseenter mouseleave").hover(function() {
			$(this).css('background-position', '-27px -31px');
			$("#rewindText").text("rewind");
		}, function() {
			$(this).css('background-position', '0px -31px');
			$("#rewindText").text("");
		});

		$("#fastRewind").unbind("mouseenter mouseleave").hover(function() {
			$(this).css('background-position', '-34px 0');
			$("#rewindText").text("fast rewind");
		}, function() {
			$(this).css('background-position', '0px 0px');
			$("#rewindText").text("");
		});

		$("#forward").unbind("mouseenter mouseleave").hover(function() {
			$(this).css('background-position', '-80px -31px');
			$("#forwardText").text("forward");
		}, function() {
			$(this).css('background-position', '-53px -31px');
			$("#forwardText").text("");
		});

		$("#fastForward").unbind("mouseenter mouseleave").hover(function() {
			$(this).css('background-position', '-102px 0px');
			$("#forwardText").text("fast forward");
		}, function() {
			$(this).css('background-position', '-68px 0px');
			$("#forwardText").text("");
		});

	} else {
		$("#rewind,#fastRewind,#forward,#fastForward").unbind("mouseenter mouseleave").hide(500);
	}
}

function initContentFloatMenueClicks() {
	$(".submenue_link,.subsubmenue_link").unbind("click").click(function() {
		var rel = $(this).attr("rel") || "";
		refreshContent(rel);

		$(this).parent().find(".aktivLink").removeClass("aktivLink");
		$(this).addClass("aktivLink");

		return false;
	});
}

function moveViewportLeft(steps) {
	moveViewport("left", steps);
}

function moveViewportRight(steps) {
	moveViewport("right", steps);
}

function calcMaxMove() {
	// Berechne Maximale noetige Bewegung um einmal alles zu bewegen;
	var cpl = $(".contentPartFloat").first();

	if ($(cpl).length > 0) {
		var cplLength = $(cpl).outerWidth(true);
		var vpWidth = getViewportWidth();
		var cWidth = getContentWidth();

		var rest = (vpWidth - contentOffsetLeft) % cplLength;

		return (vpWidth - contentOffsetLeft - rest) / cplLength;
	} else {
		return 0;
	}
}

function moveViewport(direction, steps) {

	switch (direction) {
		case "right" :
			moveToIndex(angezeigterIndex + steps);
			break;
		case "left" :
			moveToIndex(angezeigterIndex - steps);
			break;
		default :
			alert("Diese Richtung gibt es nicht");
	}

}

var angezeigterIndex = 0;
function moveToIndex(index, partElementClass) {

	if (partElementClass == undefined) {
		partElementClass = "contentPartFloat"
	}

	var maxIndex = $("#content ." + partElementClass).size() - 1;
	var vp = $("#contentViewPort");
	var c = $("#content");
	var vpWidth = getViewportWidth();
	var cWidth = getContentWidth();

	// Nur hinbewegen, wenn moeglich
	if (index < 0) {
		index = 0;
	} else if (index > maxIndex) {
		index = maxIndex;
	}

	// Nur hinbewegen, wenn noetig
	var indexElement = $("." + partElementClass).eq(index);
	var allElements = $("." + partElementClass);
	var rest = vpWidth - contentOffsetLeft - $(indexElement).outerWidth(true);
	$(indexElement).nextAll().each(function(aktIndex, value) {
		rest = rest - $(this).outerWidth(true);

		if (rest <= 0) {
			return false;
		}
	});

	// Es ist noch viel Platz da => wir muessen nicht bis zu diesem Index
	// schieben ...
	// Also nochmal ein paar Indexe wieder zurück
	var schiebeElement = indexElement;
	var stop = false;
	while (schiebeElement.length != 0 && rest > 0) {

		schiebeElement = $(schiebeElement).prev("." + partElementClass);
		rest = rest - $(schiebeElement).outerWidth(true);

		if (rest > 0) {
			index--;
		}
	}

	if (angezeigterIndex != index) {
		// Bewegung berechnen
		var xOffset = 0;
		$(allElements).each(function(aktIndex, value) {
			if (aktIndex >= index)
				return false;
			else
				xOffset += $(this).outerWidth(true);
		});

		// Bewegungsgeschwindigkeit berechnen
		var anzSek = 0;
		var indexDif = angezeigterIndex - index;
		indexDif = (indexDif < 0) ? indexDif * -1 : indexDif;
		switch (indexDif) {
			case 1 :
				anzSek = 0.5;
				break;
			case 2 :
			case 3 :
			case 4 :
				anzSek = indexDif * 0.3;
				break;
			default :
				anzSek = 1.5;
				break;
		}

		// Horizontal
		$(c).stop().animate({
			left : contentOffsetLeft - xOffset + "px"
		}, anzSek * 1000, 'swing');

		angezeigterIndex = index;
	}
}

function resetPositionOfViewport() {
	// $("#content").
}

function refreshContent(elementID) {
	$.getJSON('/' + elementID + ',home_content', function(data) {
		// $.getJSON('projekt_content.json', function(data) {
		var items = [];

		$.each(data.projekte, function(key, val) {
			var item = '<div class="contentPartFloat">';
			item += '<div class="contentPartFloat_title title">' + val.title + '</div>';
			item += '<div class="contentPartFloat_subtitle content">' + val.subtitle + '</div>';

			// Bildergalerie hinzufügen
			var countItems = countProperties(val.grafiken);
			if (countItems > 0) {
				item += '<div class="contentPartFloat_miniSlideshow">';
				item += '<div class="contentPartFloat_media-thumb-medium-progressbar"></div>';

				for (i = 0; i < countItems; i++) {
					var display = (i == 0) ? 'block' : 'none';
					item += '<a href="' + val.grafiken[i]["media-big"] + '" rel="lightboxSteven[' + val.galerie + ']" title="' + val.grafiken[i]["description"] + '">';
					item += '<img class="contentPartFloat_media-thumb-medium" src="' + val.grafiken[i]["media-thumb-medium"] + '" style="display:' + display + '"/>';
					item += '<img class="contentPartFloat_media-thumb-mini" src="' + val.grafiken[i]["media-thumb-mini"] + '" style="display:none"/>';
					item += '<img class="contentPartFloat_media-thumb-big" width="754" height="563" src="' + val.grafiken[i]["media-big"] + '" style="display:none"/>';

					if (val.grafiken[i].videos) {
						var countVideoLinks = countProperties(val.grafiken[i].videos);

						// Eindeutige ID besteht aus Galerie + Reihenfolge
						item += '<div id="' + val.galerie + '_' + i + '" class="video-js-box" style="display:none;">';
						item += '<video class="video-js" width="754" height="563" controls preload poster="' + val.grafiken[i]["media-big"] + '">';

						for (j = 0; j < countVideoLinks; j++) {
							item +=
									'<source src="' + val.grafiken[i].videos[j]["path"] + '" type=\'' + val.grafiken[i].videos[j]["type"] + '; codecs="'
											+ val.grafiken[i].videos[j]["codecs"] + '"\' />\n';
						}

						item +=
								'<object class="vjs-flash-fallback" width="754" height="562" type="application/x-shockwave-flash" '
										+ ' data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">';
						item += '<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />';
						item += '<param name="allowfullscreen" value="true" />';
						item +=
								'<param name="flashvars" value=\'config={"playlist":["' + val.grafiken[i]["media-big"] + '", {"url": "' + val.grafiken[i].videos[0]["path"]
										+ '","autoPlay":false,"autoBuffering":true}]}\' />';
						item += '<img src="' + val.grafiken[i]["media-big"] + '" width="754" height="562" alt="Poster Image" title="No video playback capabilities." />';
						item += '</object>';
						item += '</video>';
						item += '</div>';
					}
					item += '</a>';
				}

				item += '</div>';
			}
			var regex = new RegExp("^(www\..*)", "g");
			var url = val.url;
			if (regex.test(val.url)) {
				url = 'http://' + RegExp.$1;
			}

			item += '<a href="' + url + '" class="contentPartFloat_url" target="_blank">' + val.url + '</a>';

			if (val.description != "") {
				item += '<a class="contentPartFloat_infoButton" href="" alt="Info Button" title="' + val.description + '"></a>';
				item += '<div class="contentPartFloat_infoText content">' + val.description + '</div>';
			}

			item += '</div>';
			items.push(item);
		});

		var fadeOutTime = ($("#content_wrapper").text().trim() == "") ? 50 : 500;

		$("#content_wrapper").stop(true, true).fadeOut(fadeOutTime, function() {
			$("#content_wrapper").html(items.join(''));
			generateInfoButtonClick();
			initPositionOfFloatContents();
			initURLHover();
			initMouseOverGalerieWithProgressbar();
			generateLightbox();
		});

		$("#content_wrapper").fadeIn(1000, function() {
			activateArrowsIfNeeded();
		});

		var itemsub = new Array();
		if (typeof (data.kunden) != "undefined" && data.kunden != null) {
			$.each(data.kunden, function(key, val) {
				var item = '';
				item += '<a href="/' + +val.id + '" rel="' + val.id + '" class="dinSchrift subsubmenue_link">' + val.name + '</a>';
				itemsub.push(item);
			});

			if ($("#content_wrapper").text().trim() != "") {
				$("#subsubmenue").stop(true, true).fadeOut(500, function() {
					$("#subsubmenue").html(itemsub.join(''));
					initContentFloatMenueClicks();
				});
			} else {
				$("#subsubmenue").html(itemsub.join(''));
				initContentFloatMenueClicks();
			}

			$("#subsubmenue").fadeIn(1000);
		}
	});
	moveToIndex(0);
}

function initURLHover() {
	$(".contentPartFloat_url,#content_wrapper div.contentPartTextImage a").hover(function() {
		$("<div class='contentPartFloar_urlArrow'></div>").appendTo(this);
	}, function() {
		$(this).find(".contentPartFloar_urlArrow").remove();
	});

}

function generateInfoButtonClick() {
	$(".contentPartFloat_infoButton").unbind("click").each(function(object) {
		$(this).click(function() {
			// alert($(this).attr("title"));
			toggleFloatInfo(this);
			return false;
		});
		$(this).data("infoOpen", false);
		$(this).addClass("contentPartFloat_infoButtonPassiv");
	});
}

var mouseOverGalerieSwitchTime = 2000;
function initMouseOverGalerieWithProgressbar() {
	$(".contentPartFloat_miniSlideshow").mouseenter(function() {
		startMouseOverGalerieProgress(this);
	}).mouseleave(function() {
		stopMouseOverGalerieProgress(this);
	}).hover(function() {
		$.data(this, 'hover', true);
	}, function() {
		$.data(this, 'hover', false);
	}).data('hover', false);
}

function startMouseOverGalerieProgress(galerieObject) {
	$(galerieObject).find(".contentPartFloat_media-thumb-medium-progressbar").stop().css({
		width : "0px",
		opacity : 1
	}).animate({
		width : $(galerieObject).width()
	}, mouseOverGalerieSwitchTime, "linear", function() {
		nextMouseOverGalerieImage(galerieObject);
	});

}

function stopMouseOverGalerieProgress(galerieObject) {
	mouseOverGalerieEnter = new Date().getTime();
	$(galerieObject).find(".contentPartFloat_media-thumb-medium-progressbar").stop().animate({
		opacity : 0
	}, 1000);
}

function nextMouseOverGalerieImage(galerieObject) {
	var lastImage = $(galerieObject).find(".contentPartFloat_media-thumb-medium:visible");
	var nextImage = $(lastImage).parent().next("a").find(".contentPartFloat_media-thumb-medium");

	if (nextImage.length == 0) {
		nextImage = $(lastImage).parent().parent().find("a:first").find(".contentPartFloat_media-thumb-medium");
	}

	$(lastImage).animate({
		opacity : 0
	}, 500, function() {
		$(lastImage).css("display", "none");
		$(nextImage).css("display", "block");
		$(nextImage).animate({
			opacity : 1
		}, 500, function() {
			if ($(galerieObject).data('hover')) {
				startMouseOverGalerieProgress(galerieObject);
			}
		});
	});
}

/**
 * 
 * @param {Link
 *            of type InfoButton} object
 */
function toggleFloatInfo(object) {
	var cW = getContentWidth();
	var cvpW = getViewportWidth();

	if ($(object).data("infoOpen") == false) {
		// open

		$(object).parent().stop().animate({
			width : "654px"
		}, 500, function() {

			var clWidth = $(this).outerWidth();
			var clLeft = $(this).offset().left;

			// Wenn letztes Element, dann neu nach hinten scrollen
			if (clLeft + clWidth > cvpW) {
				var thisIndex = $(this).parent().parent().find(".contentPartFloat").index(this);
				moveToIndex(thisIndex);
			}

			// Wenn letztes Element, dann neu nach hinten scrollen
			// if (cW + 360 > cvpW && $(object).parent().nextAll().length == 0)
			// {
			// moveToIndex(1000);
			// }

			// Beim anklicken eines andere FloatPartContents die Info wieder
			// schließen
			$(this).parent().parent().find(".contentPartFloat").not(this).unbind("click").click(function() {
				$(".contentPartFloat").unbind("click");
				toggleFloatInfo(object);
			});
		});

		// Info einblenden
		$(object).parent().nextAll().animate({
			left : '+=360'
		}, 500, function() {
			/* 654-358 */
			// Sicherheitshalber anschließend nochmal ausrichten
			initPositionOfFloatContents();
		});

		// Voranpassung der Breite, Nachjustierung via
		// initPositionOfFloatContents() NACH der Animation
		$("#content").width($("#content").outerWidth() + 360);

		// alle anderen aufhellen
		$(".contentPartFloat").not($(object).parent()).animate({
			opacity : 0.4
		}, 300).find(".contentPartFloat_infoButton").css("visibility", "hidden");

		// Info-Button umdrehen
		$(object).addClass("contentPartFloat_infoButtonAktiv").removeClass("contentPartFloat_infoButtonPassiv");

		$(object).data("infoOpen", true);

	} else {
		// close
		$(object).parent().stop().animate({
			width : "294px"
		}, 500, function() {
			// Sicherheitshalber anschließend nochmal ausrichten
			initPositionOfFloatContents();

			if (cW + 360 > cvpW && $(object).parent().nextAll().length == 0) {
				moveToIndex(1000);
			}
		});

		// Info ausblenden
		$(object).parent().nextAll().animate({
			left : '-=360'
		}, 500);

		// alle volle Sichtbarkeit
		$(".contentPartFloat").animate({
			opacity : 1
		}, 300).find(".contentPartFloat_infoButton").css("visibility", "visible");

		// Info-Button umdrehen
		$(object).addClass("contentPartFloat_infoButtonPassiv").removeClass("contentPartFloat_infoButtonAktiv");

		$(object).data("infoOpen", false);
	}
}

function initPositionOfFloatContents() {
	var firstElement = $(".contentPartFloat:first").first();
	var aktElement = firstElement;
	var xOffset = 0;
	var xLengthOffsetRight = 1000;

	$(".contentPartFloat").each(function(value) {
		$(this).css("left", xOffset + 'px');
		xOffset += $(this).outerWidth(true);
	});

	$("#content").width(xOffset + xLengthOffsetRight + "px");
}

function getViewportWidth() {
	return $("#contentViewport").outerWidth(true);
}

function getContentLeft() {
	var offset = $("#content").offset();
	return offset.left;
}

function getContentWidth() {
	return $("#content").outerWidth(true);
}

