$(window).load(function() {
	$('body').addClass('fx');
	
	$('#route h2').each(function() {
		var from = $(this).next('table').find('tr:first .location').text();
		var to   = $(this).next('table').find('tr:last  .location').text();
		$(this).append('<div class="leg">von <span class="location-from">' + from + '</span> nach <span class="location-to">' + to + '</span></div>');
		$(this).click(function() {
			var table = $(this).next('table');
			if (table.is('.open')) table.removeClass('open');
			else {
				$(this).parent().find('table').removeClass('open');
				table.addClass('open');
			}
		});
		$('#route table tr').mouseover(function() {
			$('div.city-label[title="' + $(this).find('.location').text() + '"]').show();
		});
		$('#route table tr').mouseout(function() {
			$('div.city-label[title="' + $(this).find('.location').text() + '"]').not('.large').hide();
		});
	});
	$('#route table:has(tr.time-past):last').addClass('open').length || $('#route table:first').addClass('open');
	
	
	if (GBrowserIsCompatible()) {


		/* CityLabel-Definition */
		function CityLabel(latlng, city, type) {
			this.latlng_ = latlng;
			this.city_ = city;
			this.type_ = type;
		}
		CityLabel.prototype = new GOverlay();

		CityLabel.prototype.initialize = function(map) {
			var div = document.createElement('div');
			div.className = 'city-label';
			if (this.type_ == 'large') div.className += ' large';
			else if (this.type_ == 'off-route') div.className += ' off-route';
			div.setAttribute('title', this.city_);
			div.innerHTML = this.city_;

			map.getPane(G_MAP_MAP_PANE).appendChild(div);
			this.div_ = div;
			this.map_ = map;
		}

		CityLabel.prototype.remove = function() {
			this.div_.parentNode.removeChild(this.div_);
		}

		CityLabel.prototype.copy = function() {
			return new CityLabel(this.latlng_, this.city_, this.type_);
		}

		CityLabel.prototype.redraw = function(force) {
			if (!force) return;
			var anchor = this.map_.fromLatLngToDivPixel(this.latlng_);
			this.div_.style.width = "100px";
			this.div_.style.height = "25px";
			if (this.type_ == 'large') {
				this.div_.style.left = (anchor.x+12) + 'px';
				this.div_.style.top = (anchor.y+3) + 'px';
				this.div_.style.textAlign = 'left';
			} else if (this.type_ == 'off-route' && ((m = ((this.latlng_.lat() - sw.lat()) / (this.latlng_.lng() - sw.lng())))>0) /* Der Punkt liegt östlich des Startpunkts */ && (((ne.lat() - sw.lat()) / (ne.lng() - sw.lng())) > m) /* Der Punkt liegt östlich der Strecke */) { 
				this.div_.style.left = (anchor.x+6) + 'px';
				this.div_.style.top = (anchor.y) + 'px';
				this.div_.style.textAlign = 'left';
			} else {
				this.div_.style.left = (anchor.x-105) + 'px';
				this.div_.style.top = (anchor.y-15) + 'px';
				this.div_.style.textAlign = 'right';
			}
		}
		
		
		/* Karte initialisieren */
		var map = new GMap2(document.getElementById("map"));
		map.disableDragging();
		
		/* Begrenzungspunkte der Karte ermitteln */
		var s = $('#route tr:first .latitude').text();
		var w = $('#route tr:first .longitude').text();
		var n = $('#route tr:last .latitude').text();
		var e = $('#route tr:last .longitude').text();

		/* Begrenzungsrahmen bauen */
		var sw = new GLatLng(s,w);
		var ne = new GLatLng(n,e);
		var bounds = new GLatLngBounds(sw, ne);

		/* Karte auf fixen Mittelpunkt zentrieren */
		var center = new GLatLng(50.8, 11.52);
		map.setCenter(center, map.getBoundsZoomLevel(bounds));

		/* Eigenen Kartentyp mit weißen Tiles definieren, hinzufügen und aktivieren */
		var copyright = new GCopyright(1, bounds, 0, 'webfactory GmbH');
		var copyrightCollection = new GCopyrightCollection('Berner');
		var tilelayers = [new GTileLayer(copyrightCollection , 0, 17)];
		tilelayers[0].getTileUrl = function(tile, zoom) {
			return 'static/common/img/ground-overlay.png';
		}
		var bernermap = new GMapType(tilelayers, new GMercatorProjection(18), "Berner", { errorMessage:"No data available" });
		map.addMapType(bernermap);
		map.setMapType(bernermap);

		/* Marker definieren */
		var smallIcon = new GIcon(G_DEFAULT_ICON);
		smallIcon.image = 'static/common/img/marker-small.png';
		smallIcon.iconSize = new GSize(7,7);
		smallIcon.shadow = null;
		smallIcon.iconAnchor = new GPoint(3,3);
		smallIcon.infoWindowAnchor = smallIcon.iconAnchor;
		smallIcon.imageMap = [0,0,7,0,7,7,0,7];
		
		var largeIcon = new GIcon(smallIcon);
		largeIcon.image = 'static/common/img/marker-large.png';
		largeIcon.iconSize = new GSize(15,15);
		largeIcon.iconAnchor = new GPoint(6,6);
		largeIcon.infoWindowAnchor = largeIcon.iconAnchor;
		largeIcon.imageMap = [0,0,15,0,15,15,0,15];
		
		var offRouteIcon = new GIcon(smallIcon);
		offRouteIcon.image = 'static/common/img/marker-off-route.png';
		
		var currentPositionIcon = new GIcon(G_DEFAULT_ICON);
		currentPositionIcon.image = 'static/common/img/current-position.png';
		currentPositionIcon.shadow = null;
		currentPositionIcon.iconSize = new GSize(81,85);
		currentPositionIcon.iconAnchor = new GPoint(81,85);
		currentPositionIcon.infoWindowAnchor = new GPoint(90,20);
		currentPositionIcon.imageMap = [0,0,81,0,81,85,0,85];
		
		/* Positionspunkte auf der Karte platzieren */
		var latlngsPast = [];
		var latlngsFuture = [];
		$('#route tr').each(function() {
			var tr = this;
			var location = $(this).find('.location').text();
			var latlng = new GLatLng($(this).find('.latitude').text(),$(this).find('.longitude').text());
			if ($(this).is('.time-past')) latlngsPast.push(latlng);
			else latlngsFuture.push(latlng);

			var marker = new GMarker(latlng, $(this).is('.large') ? largeIcon : smallIcon);
			GEvent.addListener(marker, "mouseover", function() {
				$('div.city-label[title="' + location + '"]').show();
			});
			GEvent.addListener(marker, "mouseout", function() {
				$('div.city-label[title="' + location + '"]').not('.large').hide();
			});
			map.addOverlay(marker);
			
			var cityLabel = new CityLabel(latlng, location, $(this).is('.large') ? 'large' : 'small');
			map.addOverlay(cityLabel);
		});
		
		/* Orte abseits der Strecke platzieren */
		$('#off-route tr').each(function() {
			var tr = this;
			var location = $(this).find('.location').text();
			var latlng = new GLatLng($(this).find('.latitude').text(),$(this).find('.longitude').text());
			var marker = new GMarker(latlng, offRouteIcon);
			map.addOverlay(marker);

			var cityLabel = new CityLabel(latlng, location, 'off-route');
			map.addOverlay(cityLabel);
		});

		/* Grafiken platzieren */
		var logoIcon = new GIcon(G_DEFAULT_ICON);
		logoIcon.image = '/static/common/img/logo-small.png';
		logoIcon.shadow = null;
		logoIcon.iconSize = new GSize(140,140);
		logoIcon.iconAnchor = new GPoint(140,140);
		logoIcon.imageMap = [0,0,140,0,140,140,0,140];
		
		var imageLogo = new GMarker(map.fromContainerPixelToLatLng(new GPoint(460,600)), logoIcon);
		GEvent.addListener(imageLogo, "click", function() {
			window.location.href = 'http://www.berner-group.com/cps/rde/xchg/group-de-de/hs.xsl/873.html';
		});
		map.addOverlay(imageLogo);

		/* Aktuelle Position berechnen */
		var currentPosition = $('#route .current-position');
		var currentPositionLatLng = new GLatLng($(currentPosition).find('.latitude').text(), $(currentPosition).find('.longitude').text());
		latlngsPast.push(currentPositionLatLng);

		/* Zurückgelegte und bevorstehende Strecke einzeichnen */
		latlngsFuture.unshift(latlngsPast[latlngsPast.length-1]);
		var polylineFuture = new GPolyline(latlngsFuture, '#CCCCCC', 5, 1);
		var polylinePast = new GPolyline(latlngsPast, '#0061B0', 5, 1);
		map.addOverlay(polylineFuture);
		map.addOverlay(polylinePast);
		
		/* Aktuelle Position markieren */
		var currentPositionMarker = new GMarker(currentPositionLatLng, currentPositionIcon);
		GEvent.addListener(currentPositionMarker, "click", function() {
			currentPositionMarker.openInfoWindowHtml('<strong>Jürgen Mennel,</strong><br />ehemaliger 100km-Vizeweltcupsieger, hat bereits im Alter von acht Jahren seine Leidenschaft fürs Laufen entdeckt. <a href="http://www.berner-group.com/cps/rde/xchg/group-de-de/hs.xsl/883.html">Erfahren Sie mehr über Jürgen Mennel</a>', {maxWidth: 200});
		});
		
		/* Kilometer-Zähler aktualisieren */
		var km = $('#route table:last tr:last .distance .km').text() - $('#route .current-position .distance').text();
		if (km>0) $('#route').prepend('<div id="distance"><label for="distance-km">Bis Berlin<br />verbleiben</label><div id="distance-km"><img src="http://wf.imgtxt.com/berner_distance/' + km + '.png" alt="' + km + ' km" /> km</div></div>');
		
		map.addOverlay(currentPositionMarker);
	}

});

