﻿// JavaScript Document

$(document).ready(function(){

	var locationMap				= new GMap2(document.getElementById('locationmap'));
	var locationMapPointCount	= $('div#locationmapinformation').children('div.location').size();;

		
	if (GBrowserIsCompatible()) {
			
		var locationMapBounds	= new GLatLngBounds();
		var maxZoom				= 16;
		var newZoom				= 0;
		var initCenter			= 0;
		var hideTimer			= null;
		var hideSpeed			= 500;
		var actPointer			= null;
		var actPointerHTML		= null;
		
		locationMap.setCenter(new GLatLng(0, 0), 0);
		locationMap.setUIToDefault();
		locationMap.setMapType(G_HYBRID_MAP);
		
		var baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(36, 47);
		baseIcon.iconAnchor = new GPoint(12, 37);
		baseIcon.shadow = '';
		
		
		var makeHim = function(point, p) {		
			var pointerIcon = new GIcon(baseIcon);
				pointerIcon.image = $('div#locationmapinformation div:nth-child(' + p +')').children('img.point').attr('src');
			
			var pointerOptions = { icon:pointerIcon };
			var pointer = new GMarker(point, pointerOptions);
			
			locationMap.addOverlay(pointer);
			locationMapBounds.extend(pointer.getPoint());
			
			if((p) == locationMapPointCount) {
				resetMap();
			}
		}				
		
		var createPointer = function(p){
			var pointerAddress = $('div#locationmapinformation div.location:nth-child(' + p + ')').children('span.address').text();
			
			var geocoder = new GClientGeocoder();
			
			geocoder.getLatLng(
				pointerAddress,
				function(point) {
					if(!point) {
						alert("Adresse nicht gefunden: " + pointerAddress);
					} else {
						makeHim(point, p);
					}
				}
			);
		}
		
		var resetMap = function(){
			newZoom = locationMap.getBoundsZoomLevel(locationMapBounds);
		
			if(newZoom > maxZoom) {
				newZoom = maxZoom;
			}
			
			initCenter = locationMapBounds.getCenter();
			
			locationMap.setZoom(newZoom);
			locationMap.panTo(initCenter);
			locationMap.closeExtInfoWindow();
		}
		
		$('div#locationmapinformation').children('div.location').each(function(elmIndex){
			elmIndex++;
			createPointer(elmIndex);
		});		
		
		GEvent.addListener(locationMap, 'zoomend', function() {
			
			if(locationMap.getExtInfoWindow() != null) {					
				clearTimeout(hideTimer);
				locationMap.closeExtInfoWindow();
				
				actPointer.openExtInfoWindow(
				  locationMap,
				  'customoverlay',
				  actPointerHTML,
				  {beakOffset: 0}
				);
			}
			
		});
		
	} else {
		
		$('div#locationmap').html('Sorry, Ihr Browser wird nicht unterst&uuml;tzt!');
		
	}
	
});
