// init
$(function() {
	
	//fancybox
	$('.fancybox').fancybox();
	
	setFontSize($.cookie('weltlaeden_font_size'));
	
	/*
	 * Tooltips
	 */
	wl.initiatTooltips();
})

function setFontSize(size) {
	if(size == null) {
		size = 11;
	}
	$('body').css('font-size', size + 'px');
	var date = new Date();
	date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
	$.cookie('weltlaeden_font_size', size, { path: '/', expires: date });
}



var wl = {
	/**
	 * löscht bzw. füllt Beschriftung in Input Felder
	 * @param {Object} 	obj		HTML Objekt
	 * @param str		str		Beschriftung
	 * @param str		action	Event: focus|blur
	 */
	controlInput: function(obj, str, action) {
		switch(action) {
			case "focus":
				if($(obj).val() == str) {
					$(obj).val("");
					$(obj).toggleClass("hasLabel");
				} else {
					$(obj).select();
				}
				break;
			case "blur":
				if($(obj).val() == "") {
					$(obj).val(str);
					$(obj).toggleClass("hasLabel");
				}
				break;	
		}
	},
	
	initiatTooltips: function() {
		$(".tooltip").mouseover(function () {
			var pos = $(this).offset();
			var text = $(this).attr('title');
			$(this).attr('title', '');
			var decoded = $("<div/>").html(text).html();
			$("#tooltipOverlayContent").html(decoded);
			$("#tooltipOverlay").css({'left': pos.left - 155 + 'px', 'top': pos.top - $("#tooltipOverlay").height() - 2 + 'px'});
			$("#tooltipOverlay").css({'display': 'block'});
	
		});
		$(".tooltip").mouseout(function () {
			$(this).attr('title', $("#tooltipOverlayContent").html());
			$("#tooltipOverlay").css({'display': 'none'});
		});
	},
	
	googleMap: '',
	googleDir: '',
	
	getDirections: function(routeContainer, from, to) {
		if (!$('#gallery .media .googleMaps').attr('id')) {
			var map = $('#mapThumb');
			wl.galleryChangeItem(map, true, routeContainer);
		} else {
			wl.googleDir = new GDirections(wl.googleMap, document.getElementById(routeContainer));
			clearInterval(wl.galleryTimer);
		}
		wl.googleMap.clearOverlays();
		$('#' + routeContainer).html('');
		wl.googleDir.load("from: " + from + " to: " + to);
	},
	
	
	toggleList: function(e, obj) {
		e.preventDefault();
		
		var li = $(obj).parents('li');
		
		if ($(li).find('.extend').is(':hidden')) {
			document.location.hash = $(li).attr('id');
		} else {
			document.location.hash = ' ';
		}
		$(li).find('.extend').slideToggle();
		$(li).find('.txt a.icon').toggleClass('opened');
		$(li).find('.txt a.more:visible').fadeOut();
		$(li).find('.txt a.more:hidden').fadeIn();
	},
	
	getCalendar: function(m, y, showLoading) {
		if(showLoading) {
			$('#calendar table').remove();
			$('#calendar').append('<br /><br /><center><img src="img/loading.gif" alt="" /></center><br /><br />');
		}
		$.get("ajax.php", {
			"action": "getCalendar",
			"m": m,
			"y": y
		}, function(res) {
			$('#calendar').html(res);
		}, "html");
	},
	
	//---------------------------------------
	// GALLERY
	//---------------------------------------
	
	galleryConfig : {
		"interval": 5000
	},
	galleryTimer: '',
	
	
	gallery: function(userConfig) {
		
		wl.galleryConfig = $.extend(wl.galleryConfig, userConfig);
		
		$('#gallery').each(function(i, el) {
			wl.galleryInit(el);
			
			if (!wl.galleryConfig.noAutoSwap) {
				//Auto-Bildwechsel starten
				wl.gallerySetTimer();
			}
	    });
		
	},
	
	galleryInit: function(el) {
		//Klick-Event hinzufügen
		$("a.mediaThumb", $(el)).click(function(e) {
			e.preventDefault();
			wl.galleryChangeItem(this);
		});
	},
	
	gallerySetTimer: function() {
		wl.galleryTimer = setInterval(function(){
			wl.galleryAutoChange();
		}, wl.galleryConfig.interval);
	},
	
	galleryAutoChange: function() {
		//nächstes Objekt wählen - wenn am Ende auf 1. Element springen
		
		if ($('li.selected a.mediaThumb').hasClass('googleMaps')) {
			var nextObj = $('li.selected a.mediaThumb').parent().next().next().find('a.mediaThumb');	//2x weiterspringen, weil ein "script"-Tag dazwischen ist
		}
		else {
			var nextObj = $('li.selected a.mediaThumb').parent().next().find('a.mediaThumb');
		}
		
		if(!nextObj.attr('href')) {
			var nextObj = $('li.selected a.mediaThumb').parent().parent().find("li:first a.mediaThumb");
		}
		
		//Bild auf nächster Seite?
		var ulLeft = parseInt($('li.selected a.mediaThumb').parent().parent().css('left'));
		var vpWidth = parseInt($('li.selected a.mediaThumb').parent().parent().parent().css('width'));
		var pos = nextObj.position();

		var currentPage = Math.ceil(ulLeft / ((vpWidth + 24) * -1));
		var page = Math.ceil(pos.left / vpWidth) - 1;
		var pageJumps = Math.max((page - currentPage), (page - currentPage) * -1);
		
		//Seite wechseln
		for (var i = 0; i < pageJumps; i++) {
			if ((page - currentPage) > 0) {
				$('li.selected a.mediaThumb').parent().parent().parent().parent().find('a.next').click();
			} else if ((page - currentPage) < 0) {
				$('li.selected a.mediaThumb').parent().parent().parent().parent().find('a.prev').click();
			}
		}
		
		wl.galleryChangeItem(nextObj);
	},
	
	
	galleryChangeItem: function(obj, dontStartTimer, routeContainer) {
		
		clearInterval(wl.galleryTimer);
		
		// Thumb markieren
		$(obj).parent().parent().find("li.selected").removeClass('selected');
		$(obj).parent("li").addClass('selected');
		
		var mediaObj = $(obj).parent().parent().parent().parent().prev('.media');
		var mediaObj2 = $(obj).parent().parent().parent().parent().prev().find('.media');
		var mediaObj3 = $(obj).parent().parent().parent().parent().parent().find('.media');
				
		if (!mediaObj.hasClass("media"))
			mediaObj = mediaObj2;
		
		if (!mediaObj.hasClass("media"))
			mediaObj = mediaObj3;
		
		// Google Maps statt Bild
		if ($(obj).hasClass('googleMaps')) {
			mediaObj.append('<div id="googleMaps" class="new googleMaps" />');
			if (GBrowserIsCompatible()) {
				$('#googleMaps').hover(
					function() { clearInterval(wl.galleryTimer); },
					function() { /*wl.gallerySetTimer();*/ }
				);
				//var coords = $(obj).attr('href').match(/center=([0-9.]*), ([0-9.]*)/i);
				var coordsAnzeige = new GLatLng(coords[0], coords[1]);
				wl.googleMap = new GMap2(document.getElementById("googleMaps"));
				wl.googleMap.setCenter(coordsAnzeige, 14);
				wl.googleMap.setUIToDefault();
				wl.googleMap.enableRotation();
				wl.googleMap.addOverlay(new GMarker(coordsAnzeige));
				if(routeContainer) {
					wl.googleDir = new GDirections(wl.googleMap, document.getElementById(routeContainer));
				}
				$('#googleMaps').css('height', '373px');
			}
			
			mediaObj.children(':not(.new)').fadeOut('slow', function(){
				//altes Bild löschen
				wl.galleryRemoveOldMedia(mediaObj, dontStartTimer);
			});
		
		// Video
		} else if ($(obj).hasClass('video')) {
			var rand = parseInt(Math.random() * 9000);
			mediaObj.append('<div id="videoSpace' + rand + '" class="new video" />');
			var flashvars = {
				"file": $(obj).attr('href')
			};
			var params = {
				"allowfullscreen": "true",
				"allowscriptaccess": "always",
				"wmode": "opaque"
			};
			var attributes = {
				"id": "videoTag" + parseInt(Math.random() * 9000),
				"name": "videoTag"
			};
			
			jwplayer("videoSpace" + rand).setup({
				file: approot + $(obj).attr('href'),
				width: mediaObj.width(), 
				height: 307,
				skin: "jwplayer/glow.zip",
				stretching: "fill",
				flashplayer: "jwplayer/player.swf",
				image: $(obj).attr('rel'),
		        events: {
		            onReady: function(e) {
						if (!$(this.container).parent().hasClass('video')) {
							$(this.container).wrap('<div class="new video" />');
						}
						$(this.container).parent().hover(
							function() { clearInterval(wl.galleryTimer); },
							function() { /*wl.gallerySetTimer();*/ }
						);
						wl.galleryRemoveOldMedia(mediaObj, dontStartTimer);
					}
		        }
			});
			
		// Normales Bild
		} else {
			// Bild hinzufügen
			mediaObj.append('<img src="' + $(obj).attr('href') + '" class="new" />');
			// ... weiter wenn neues Bild fertig geladen wurde ...
			$('img.new').load(function(){
				//altes Bild ausblenden
				wl.galleryRemoveOldMedia(mediaObj, dontStartTimer);
			});
		}
		
		// Text tauschen, falls aktiviert
		if(wl.galleryConfig.showText) {
			var txtObj = $(obj).parent().parent().parent().parent().parent().parent().find('div.txt');
			txtObj.html('<br /><br /><br /><center><img src="img/loading.gif" alt="" /></center>');
			
			$.post("ajax.php", {"action": "getGalleryText", "id": $(obj).attr('id')}, function(res) {
				txtObj.html(res.content);
				if (!dontStartTimer) {
					wl.gallerySetTimer();
				}
			});
			
		}
	},
	
	galleryRemoveOldMedia: function(mediaObj, dontStartTimer) {
		mediaObj.children(':not(.new)').fadeOut("slow", function(){
			//altes Bild löschen
			$(this).remove();
			//Klasse "new" beim neuen Bild entfernen
			mediaObj.find('.new').removeClass('new');
			
			//Aktiviert den automatischen Bildwechsel - falls showText false ist
			if (!wl.galleryConfig.showText && !dontStartTimer) {
				wl.gallerySetTimer();
			}
		});
	}
};

function produktAnsichtChange(url, wert) {
	window.location.href = url+wert;	
}
function addToMerklist(produktID) {
	$.ajax({
		type: "POST",
		url: "ajax.php",
		data: "action=addToMerklist&produktID="+produktID,
		success: function(anzahl){
			if (anzahl == "0") {
				$("#topbarMerklisteCnt").text("&nbsp;").removeClass("zahl");
			}
			else {
				$("#topbarMerklisteCnt").addClass("zahl").text(anzahl);
			}
		}
	});		
}
function removeFromMerklist(produktID) {
	$("#produktItem_"+produktID).hide(1000);
	
	$.ajax({
		type: "POST",
		url: "ajax.php",
		data: "action=removeFromMerklist&produktID="+produktID,
		success: function(anzahl){
			if (anzahl == "0") {
				$("#topbarMerklisteCnt").text("&nbsp;").removeClass("zahl");
			}
			else {
				$("#topbarMerklisteCnt").addClass("zahl").text(anzahl);
			}
		}
	});		
}
