$(function() {
	$(".fancybox").fancybox();
	makeNaviJustify();
	makeReferenzJustify();
	window.setTimeout("makeReferenzJustify()",300);	// IE gets some extra love
	
	// make navi-hover left if there isn't enough space right
	$("#nav > li").hover(
		function() {
			var oWidth = $(this).children("ul").outerWidth();
			var relPos = $(this).offset().left - $("#nav > li:first").offset().left;
			var rightBorder = relPos + oWidth;
			var parentWidth = $(this).outerWidth();
			var maxWidth = $("#nav").width();
			if (rightBorder > maxWidth) {
				var moveLeft = oWidth - parentWidth;
				$(this).children("ul").css({"left" : "auto"});
				$(this).children("ul").css({"left" : "-=" + (moveLeft + 1) + "px" });
				$(this).find(".produktNaviFirst").addClass("left");
			}
			/*
			console.log("relPos: " + relPos);
			console.log("rightBorder: " + rightBorder);
			console.log("parentWidth: " + parentWidth);
			console.log("maxWidth: " + maxWidth);
			*/
		}, 
		function(){}
	);
});



// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};



// catch all document.write() calls
/*
(function(doc){
  var write = doc.write;
  doc.write = function(q){ 
    log('document.write(): ',arguments); 
    if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
  };
})(document);
*/


/*
 * make the navigation as small as needed to fit into the <div>
 */
function makeNaviJustify() {
	var gesamtbreite = 0;
	$("#nav li.firstLevel").each(function(index) {
		gesamtbreite += parseFloat($(this).outerWidth(true));
	});
	var erlaubtebreite = $("#pageTop-mainnavi").width();

	// stop if everything fits
	if (gesamtbreite <= erlaubtebreite) return;
	
	// turn font stepwise smaller
	/* Note:
	 * due to jQuery and Browser shortcomings it's needed to use animate() 
	 * instead of simpler functions like css(). This way a "did-it-really-really"
	 * callback function is provided. Also inserted was some sort of delay just
	 * to be sure the browser doesn't re-call the function recursively *before* 
	 * he has done it's job of resizing the font!
	 * Ha-GRR!
	 * --- Ludwig Rafelsberger, accxmedia.com
	 */
	if (gesamtbreite > erlaubtebreite) {
		$("#nav a.firstLevelLink")
			.animate(
				{"font-size": "-=1px"},
				"50",
				function() {
					if($(this).is($("#nav a.firstLevelLink:last"))) {
						makeNaviJustify();
					}
				});
	}
}

function changeDisplaySeite(seite, el) {
	// stop previously running animation
	$('.displayAreaWidth').stop();

	// calculate destination (now in absolute pixels, regardless of the previous position)
	destination = (-1)*(seite-1)*960;

	// animate flow
	$('.displayAreaWidth').animate( {left: destination + "px"}, 1500, 'easeInOutQuart');

	// mark new active button
	$(".displayAreaButton .displayButtonActive").removeClass("displayButtonActive");
	$(el).addClass("displayButtonActive");
}

/**
 * justify height of referenz gallery to the heighest of each row
 * short: make 'em same!
 */
function makeReferenzJustify(){
	refArray = $("div.referenz-galerie");

	rowStart = 0
	while (refArray.length > rowStart) {
		// split out current row
		tmpArray = refArray.slice(rowStart, rowStart+4);
		
		// get row's heighest elements height
		rowMaxHeight = 0;
		tmpArray.each(function(index, domEle){
			eleHeight = $(domEle).height();
			if(rowMaxHeight < eleHeight) rowMaxHeight = eleHeight;
		});

		// make all elements in this row the same height
		tmpArray.each(function(index, domEle){
			$(domEle).css("height", rowMaxHeight);
		});

		// skip over to next row
		rowStart += 4;
	}
}

function ajaxLoadReferenz(contentID, nodeID, lang) {
	$.ajax({
		type: "POST",
		url: "ajaxServer.php",
		data: "action=getReferenz&contentID="+contentID+"&nodeID="+nodeID+"&lang="+lang,
		success: function(response){
			$("#referenz-galerie-Area").append(response);
			$(".referenz-galerie-weitere").hide("slow");
			$(".fancybox").fancybox();
			// justify height of all elements new
			makeReferenzJustify();
		}	
   });
}

function changeNewsSeite (neueSeite) {
	$(".newsDetailNaviSeite").hide();
	$("#newsDetailSeite"+neueSeite).show(250);
	$("#newsDetailNaviAreaButtons .button").removeClass("aktuelleSeite");
	$(".buttonSeite"+neueSeite).addClass("aktuelleSeite");
}

var hA = {	
	//---------------------------------------
	// GALLERY
	//---------------------------------------
	
	homeAnimationConfig : {
		"interval": 5000
	},
	homeAnimationTimer: '',
	
	
	homeAnimation: function(userConfig) {		
		hA.homeAnimationConfig = $.extend(hA.galleryConfig, userConfig);
		
		$('#homeGalleryPreview').each(function(i, el) {
			hA.homeAnimationInit(el);
			
			if (!hA.homeAnimationConfig.noAutoSwap) {
				//Auto-Bildwechsel starten
				hA.homeAnimationSetTimer();
			}
	    });
		
	},
	
	homeAnimationInit: function(el) {
		//Klick-Event hinzufügen
		$("a.mediaThumb", $(el))
                    .click(function(e) {
			e.preventDefault();
			clearInterval(hA.homeAnimationTimer);
			hA.homeAnimationChangeItem(this);
                    })
                ;
	},
	
        homeAnimationHover: function(image) {
		/* prevent hover if image is already active */
		if ($("#" + image).parent().hasClass("homeSelected")) {
			return ;
		}
		$("#" + image)
			.fadeIn(200)
			.mouseout(
				function(){
					$("#" + image)
						.clearQueue()
						.fadeOut(200, function() {$("#" + image).css('opacity', '');})
						.mouseout(function(){});
				}
			);
        }, 
	homeAnimationSetTimer: function() {
		hA.homeAnimationTimer = setInterval(function(){
			hA.homeAnimationAutoChange();
		}, hA.homeAnimationConfig.interval);
	},
	
	homeAnimationAutoChange: function() {
		//nächstes Objekt w�hlen - wenn am Ende auf 1. Element springen
		var nextObj = $('a.mediaThumb.homeSelected').parent().next().find('a.mediaThumb');
		
		if(!nextObj.attr('id')) {		// wir sind beim letzten element, d.h. wir müssen zum ersten springen
			nextObj = $('a.mediaThumb.homeSelected').parent().parent().find("li:first a.mediaThumb");
		}
		//console.log("autochange " + nextObj.attr("id"));
		hA.homeAnimationChangeItem(nextObj);
	},
	
	
	homeAnimationChangeItem: function(obj, dontStartTimer, routeContainer) {
		//clearInterval(hA.homeAnimationTimer);
		
		oldObj = $(obj).parent().parent().find("a.mediaThumb.homeSelected");
		
		if ($(oldObj).attr("id") && $(obj).attr("id")) {
			$.ajax({
				type: "POST",
				url: "ajaxServer.php",
				data: "action=getHomeAnimation&oldID="+$(oldObj).attr("id")+"&newID="+$(obj).attr("id"),
				success: function(response){
					$("#homeGalleryHeadline").html(response.headline);
					$("#homeGalleryText").html(response.text);
					$("#homeGalleryButton a").attr("href", response.link);
					$(obj).find("img.haImage").attr("src", response.newImgSmall+'?'+Math.random());
					$(oldObj).find("img.haImage").attr("src", response.oldImgSmall+'?'+Math.random());
					$("#homeGallery").css("backgroundImage", "url('"+response.newImg+"')");
					
					$(oldObj).removeClass('homeSelected');
					$(obj).addClass("homeSelected");
					//clearInterval(hA.homeAnimationTimer);
				}
			});
		}
	}
};

var kF = {	
	//---------------------------------------
	// Kundendienst Flappe  
	//---------------------------------------
	
	kundenFlappeConfig : {
		"speed": "250"
	},
	kundenFlappeTimer: '',
	

	kundenFlappeShow: function() {
		$('#pageTop-kundendienstArea')
			.slideDown(kF.kundenFlappeConfig["speed"]);
	},
	kundenFlappeHide: function() {
		$('#pageTop-kundendienstArea') 
			.slideUp(kF.kundenFlappeConfig["speed"]);
	}
};





var pH = {	
	//---------------------------------------
	// produktHeader: Animationen u.#. von 
	// zusätzlichen Bildern im Header
	//---------------------------------------
	
	pHConfig : {
		"intervalIn": 1000,
		"intervalOut": 200
	},
	pHNOfMedia: 0,
	pHMedia: [],
	pHCurrentMedia: 0,
	
	pHAddJSON: function(arrMedia) {
		pH.pHMedia.push(jQuery.parseJSON(arrMedia));
	},

	pHAdd: function(title, image, video, isVideo) {
		var m = new Array(title, image, video, isVideo);
		pH.pHMedia.push(m);
		pH.pHNOfMedia++;
	},
	pHThumbHover: function(image) {
		/* prevent hover if image is already active */
		/*if ($("#" + image).parent().hasClass("homeSelected")) {
			return ;
		}*/
		$("#" + image)
			.fadeIn(200)
			.mouseout(
				function(){
					$("#" + image)
						.clearQueue()
						.fadeOut(200, function() {$("#" + image).css('opacity', '');})
						.mouseout(function(){});
				}
			);
	},
	/**
	 * Generische Funktion, die das angegebene Medium
	 * anzeigt, unabhängig von dessen Typ
	 */
	pHShow: function(i) {
		if(i == pH.pHCurrentMedia)
			return;
		var wasVideo = pH.pHMedia[pH.pHCurrentMedia][3];
		pH.pHCurrentMedia = i;
		var isVideo = pH.pHMedia[i][3];
		
		if(isVideo) {
			pH.pHFadeOut(wasVideo, pH.pHShowVideoWrapper);
		}
		else { // is an image
			pH.pHFadeOut(wasVideo, pH.pHShowImageWrapper);
		}
	},
	pHFadeOut: function(wasVideo, callback) {
		if (wasVideo) {
			$("#phYtPPlayer").animate(
				{opacity: 0.0}, 
				pH.pHConfig["intervalOut"], 
				function() { 
					document.getElementById("myytplayer").stopVideo();
					callback(); 
				}
			);
		} else {
			$("#phimagePlayer").fadeOut(pH.pHConfig["intervalOut"], callback);
		}

		// remove original background image
		$("div.produktHeaderArea").css({'background-image': 'url("")'});
	},
	
	pHShowNext: function() {
		pH.pHShow( (pH.pHCurrentMedia+1)%pH.pHNOfMedia);
	},
	pHShowVideoWrapper: function() {
		pH.pHShowVideo(pH.pHMedia[pH.pHCurrentMedia][0], pH.pHMedia[pH.pHCurrentMedia][2]);
	},
	pHShowImageWrapper: function() {
		pH.pHShowImage(pH.pHMedia[pH.pHCurrentMedia][0], pH.pHMedia[pH.pHCurrentMedia][1])
	},
	pHShowVideo: function(title, youtubeVideoID) {
		/* alert("Video : " + title + " - " + youtubeVideoID); */
		ytplayer = document.getElementById("myytplayer");
		
		// "show" player
		$("#phYtPPlayer")
			.css("opacity", "0.0")
			.css("visibility", "visible");

		// switch, fade in and play
		ytplayer.cueVideoById(youtubeVideoID);
		$('#phYtPPlayer').animate({
			opacity: 1.0
		}, pH.pHConfig["intervalIn"], function() {
			// Animation complete.
			ytplayer.playVideo();
		});
	},
	pHShowImage: function(title, imgSource) {
		//alert("Bild : " + title + " - " + imgSource);		
		// switch image
		$("#phimagePlayer img").attr("src", imgSource);
		$("#phimagePlayer").fadeIn(pH.pHConfig["intervalIn"]);
	}
}


/* Youtube API needs this */
function onYouTubePlayerReady(playerId) {
}

/* Preload images for fast animations */
function preloadImages(sources) {
	var images = [];
	for (i = 0, length = sources.length; i < length; ++i) {
		images[i] = new Image();
		images[i].src = sources[i];
	}
}

