/**
 * Google Map Frontend
 * @author Michael Feinbier
 **/

$(function() {
	//Direktauswahl der Selectbox
	$('#direct-select').change(function() {
		window.location.href = '/' + $(this).val();
	});
	
	
	$('#google-map').each(function() {
		//LatLngBounds
		var bounds = new google.maps.LatLngBounds();
		var markerToAdd = [];
		var infoWindows = [];
		
		//Jetzt alle Marker durchgehen
		$.each(googleMapsMarker, function() {
			//console.log(this);
			
			//einen Marker erstellen
			var spot = new google.maps.LatLng(this.lat, this.lon);
			var marker = new google.maps.Marker({
				position: spot,
				//title: 'Click Me',
				icon: 'typo3conf/ext/lumogooglemaps/templates/marker_icon.png',
				shadow: 'typo3conf/ext/lumogooglemaps/templates/marker_shadow.png'
			});
			
			var infoWindow = new google.maps.InfoWindow({
				content: $(this.content).html()
			});
			
			bounds.extend(spot);
			markerToAdd.push(marker);
			infoWindows.push(infoWindow);
		});
		
		var centerPoint = (bounds.isEmpty() ? new google.maps.LatLng(51.165691, 10.451526) : bounds.getCenter());
		var map = new google.maps.Map(this,{
			zoom: 6,
			center: centerPoint, 
			mapTypeId: google.maps.MapTypeId.ROADMAP
		});
		
		//Wenn es Bounds gibt, dann Karte darauf anpassen
		if( !bounds.isEmpty()) {
			map.fitBounds(bounds);
			
			google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
				//Zoomlevel korrigieren
				if(this.getZoom() > 16 ) this.setZoom(16);
			});
		}
		
		//Jetzt die Marker wieder auf die Karte pushen
		$.each(markerToAdd, function(i) {
			//console.log(i);
			this.setMap(map);
			
			//Event
			google.maps.event.addListener(this, 'click', function() {
				infoWindows[i].open(map,this);
			});
		});
	});
});
