Cs3000.Novasib = {}

Cs3000.Novasib.EventsLoader = Class.create({
	timerInterval: 20,
	initialize: function(map, options) {
		this.overlays = {};
		
		if (!map) {
			return;
		}
		
		this.map = map;
		this.map.mapType = options.mapType;
		
		options = Object.extend({
			streckeKmlUrl: false, 
			streckeDataUrl: false,
			positionKmlUrl: false,
			positionDataUrl: false,
			profilKmOffset: 0,
			refreshInterval: 10,
			streckeKmLength: 0
		}, options || {});
		
		
		this.profilOffset = options.kmProfilOffset * 1000;
		this.routeLength = (options.streckeKmLength * 1000) + (options.kmProfilOffset * 1000);
		
		this.lastLoaded = 0;
		this.isLoading = false;
		
		this.ZoomedToPosition = 0;
		this.streckeLoaded = false;
		
		this.STATUS = -1;
		this.routeStarttime = options.START_UM;
		
		this.ETAPPENTYP = options.ETAPPENTYP;
		
		this.URL_Liveticker_kurz = options.URL_Liveticker_kurz;
		
		this.route = new Object();
		
		this.streckeOverlayToggleElement = $('togglestrecke');
		
		//Strecken-Layer
		this.streckeKmlUrl = options.streckeKmlUrl;
		this.streckeIconsKmlUrl = options.streckeIconsKmlUrl;
		this.streckeVEXmlUrl = options.streckeVEXmlUrl;
		this.streckeIconsXmlUrl = options.streckeIconsXmlUrl;
		
		if (this.streckeOverlayToggleElement && options.streckeDataUrl) {
			new Ajax.Request(options.streckeDataUrl+'?t='+(new Date().getTime()), {
				method: 'get',
				onSuccess: (function(transport) {
					var o = eval('('+transport.responseText+')');
					//alert(o.coords);
					if (o && o.coords) {
						try {
							this.initRoute(o);
						} catch (e) {
							Novajax.handleError(e);
						}
					}
				}).bind(this)
			});
			
			this.addTrack();
			
			/*
			//Google-Maps --> KML-Dateien
			if(options.mapType == 'GM') {
				if (options.streckeKmlUrl) {
					this.addOverlay('strecke', location.absoluteUrl(options.streckeKmlUrl));
					this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'strecke'));
				}
					
				if (options.streckeIconsKmlUrl) {
					this.addOverlay('streckeicons', location.absoluteUrl(options.streckeIconsKmlUrl));
					this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'streckeicons'));
				}
			}
				
			
			//VirtualEarth --> Tiles und XML-Dateien
			if(options.mapType == 'VE') {
				if(options.streckeIconsXmlUrl) {
					this.addOverlay('streckeicons', location.absoluteUrl(options.streckeIconsXmlUrl));
					this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'streckeicons'));
				}
				
				if(options.streckeVEXmlUrl) {
					this.addOverlay('strecke', location.absoluteUrl(options.streckeVEXmlUrl));
					this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'strecke'));
				}
			}
			*/
			
		}
		
		
		//Maus über der Karte --> Anzeige der Position im Höhenprofil
		//Object.observe(this.map, 'mousemove', this.onMapMousemove.bind(this));
		var strZoom = $('zoomstrecke');
		if (strZoom) {
			strZoom.observe('click', this.gotoOverlayViewport.bind(this, 'strecke'));
		}
		
		var e = $('reloaddata');
		if (e) {
			e.observe('click', this.loadPositionData.bind(this));
			e.observe('click', this.loadLiveticker.bind(this));
		}
		
		e = $('setcenterposition');
		if (e) {
			e.observe('click', this.centerToPositionOverlay.bind(this));
		}
		
		this.positionDataUrl = location.absoluteUrl(options.positionDataUrl);
		this.positionOverlays = [];
		this.newPositionOverlay = false;
		
		//this.startTimer(options.refreshInterval);
		this.startTimer(10);
		
		//Link zum gesamten Liveticker setzen
		var e = $('tickerurl');
		if (e) {
			e.href = options.tickerLinkUrl;
		}
		
		$$('.liveonly').invoke('show');
		
		//Nach dem Laden der Seite
		if(options.mapType == 'VE') {
			var setToPos = this.centerToPositionOverlay.bind(this);
			window.setTimeout(setToPos, 3500);
		}		
	},
	addTrack: function() {
		//Google-Maps --> KML-Dateien
		if(this.map.mapType == 'GM') {
			if (this.streckeKmlUrl) {
				this.addOverlay('strecke', location.absoluteUrl(this.streckeKmlUrl));
				this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'strecke'));
			}
				
			if (this.streckeIconsKmlUrl) {
				this.addOverlay('streckeicons', location.absoluteUrl(this.streckeIconsKmlUrl));
				this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'streckeicons'));
			}
		}
			
		//VirtualEarth --> XML-Dateien
		if(this.map.mapType == 'VE') {
			if(this.streckeIconsXmlUrl) {
				this.addOverlay('streckeicons', location.absoluteUrl(this.streckeIconsXmlUrl));
				this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'streckeicons'));
			}
			
			if(this.streckeVEXmlUrl) {
				this.addOverlay('strecke', location.absoluteUrl(this.streckeVEXmlUrl));
				this.streckeOverlayToggleElement.observe('click', this.toggleOverlay.bind(this, 'strecke'));
			}
		}
	},	
	initRoute: function(o) {
		for (var index = 0, len = o.coords.length; index < len; ++index) {
			var c = o.coords[index];
			o.coords[index] = this.map.createLatLng(c[1], c[0]);
		}
		
		this.route.coords = o.coords;
		
		this.routeMarker = this.map.createMarker('_data/icon10.png', {
			size: [10, 10],
			anchor: [5, 5],
			latlon: o.coords[o.coords.length-1]
		});
		
		this.map.addOverlay(this.routeMarker);
		
		if(this.map.mapType == 'VE') {
			this.routeMarker.SetCustomIcon("<img src='_data/icon10.png'/>");
		}
		
		this.routeSnapper = new Cs3000.SnapToRoute(this.map, o.coords, this.map.getProjection());
		this.routeLength2PolylineLength = this.routeLength / this.routeSnapper.getRouteLength();
		
		var e = $('profil');
		if (e) {
			this.profilGui = new ProfilGui(e, this.profilOffset, this.routeLength, this.profilOffset);
			
			this.profilGui.addProgressBar('ende', 0, this.routeLength-this.profilOffset);
			this.profilGui.addProgressBar('peloton', 0, this.routeLength-this.profilOffset);
			this.profilGui.addProgressBar('spitze', 0, this.routeLength-this.profilOffset, true, 'Spitze: ');
			
			Object.observe(this.profilGui, 'mousemove', this.onProfilMousemoved.bind(this));
			Object.observe(this.profilGui, 'click', this.onProfilClicked.bind(this));
		}
	},
	destroy: function() {
	},
	addOverlay: function(name, url) {
		this.overlays[name] = this.map.createGeoXmlOverlay(url, this.onOverlayLoaded.bind(this, name));
		//alert("this.overlays[name].loadedCorrectly: " + this.overlays[name].loadedCorrectly());
	},
	
	addPositionLayer: function(name) {
		if(this.map.mapType == 'VE') {
			this.overlays[name] = this.map.addShapeLayer(name);
		}
	},	
	toggleOverlay: function(name) {
		if (this.overlays[name] && this.overlays[name].loadedCorrectly()) {
			if (this.guiShowOverlay(name)) {
				this.overlays[name].show();
			} else {
				this.overlays[name].hide();
			}
		}
	},
	guiShowOverlay: function(name) {
		if (name == 'strecke' || name == 'streckeicons') {
			return this.streckeOverlayToggleElement && this.streckeOverlayToggleElement.checked
		}
		
		return true;
	},
	gotoOverlayViewport: function(name) {
		if (this.overlays[name]) {// && this.streckeOverlay.loadedCorrectly()) {
			this.overlays[name].gotoDefaultViewport(this.map);
			this.ZoomedToPosition = 0;
		} 
	},
	centerToPositionOverlay: function() {
		if(this.map.mapType == 'GM') {
			if (this.positionOverlay) {
				this.map.panTo(this.positionOverlay.getDefaultCenter());
			}
			else {
				if (this.markerEnde && this.wurmPolyline && this.markerPeloton && this.markerSpitze) {
					var b = this.wurmPolyline.getBounds();
					b.extend(this.markerEnde.getPoint());
					b.extend(this.markerPeloton.getPoint());
					b.extend(this.markerSpitze.getPoint());
					
					var z = this.map.getBoundsZoomLevel(b)
					
					if (this.map.getZoom() > z) {
						this.map.setZoom(z);
					}
					
					this.map.panTo(b.getCenter());
				}
			}
		}
		if(this.map.mapType == 'VE') {
			if(this.streckeLoaded) {
				//alert("hier");
				//Prüfen, ob alle Punkte innerhalb des aktuellen Anzeigebereiches liegen
				if(this.markerEnde || this.markerPeloton || this.markerSpitze) {
					var boolZoom = false;
					
					if(this.markerEnde && !this.map.isPointInRect(this.markerEnde.GetPoints()[0],this.map.getMapView())) {
						boolZoom = true;
					}
					
					if(this.markerPeloton && !this.map.isPointInRect(this.markerPeloton.GetPoints()[0],this.map.getMapView())) {
						boolZoom = true;
					}
					
					if(this.markerSpitze && !this.map.isPointInRect(this.markerSpitze.GetPoints()[0],this.map.getMapView())) {
						boolZoom = true;
					}
					
					if(this.ZoomedToPosition<2) {
						boolZoom = true;
					}
					
					if(!boolZoom) {
						if(parseInt(this.map.getZoom())>14)  boolZoom = true; 
					}				
					
					if(boolZoom == true) {
						this.map.setMapView(this.overlays['tourpunkte'].GetBoundingRectangle());
						
						var obj = this;
						window.setTimeout(function(){obj.validateMapZoom();},750);
					}
					
					this.ZoomedToPosition++;
					if(this.ZoomedToPosition>=90) {
						top.location.href = top.location.href;
					}
				}
				
				/*
				if(this.markerEnde && this.markerPeloton && this.markerSpitze) {
					if(!this.map.isPointInRect(this.markerEnde.GetPoints()[0],this.map.getMapView()) ||
					   !this.map.isPointInRect(this.markerPeloton.GetPoints()[0],this.map.getMapView()) || 
					   !this.map.isPointInRect(this.markerSpitze.GetPoints()[0],this.map.getMapView()) || 
					   this.ZoomedToPosition <= 2) {
						   this.map.setMapView(this.overlays['tourpunkte'].GetBoundingRectangle());
						   if(parseInt(this.map.getZoom())>14)  this.map.setZoom(14);
						   //else this.map.setZoom(parseInt(this.map.getZoom())-1);
						   //this.ZoomedToPosition++;
					}
					this.ZoomedToPosition++;
				}
				*/
			}
		}
	},

	validateMapZoom: function() {
		//alert("validateMapZoom");
		if(parseInt(this.map.getZoom())>14)  {
			//alert(">14: " + this.map.getZoom());
			this.map.setZoom(14);	
		}
	},
	
	loadLiveticker: function() {
		
		new Ajax.Request(this.URL_Liveticker_kurz+'?t='+(new Date().getTime()), {
				method: 'get',
				onSuccess: (function(transport) {
					try {
						
						//Link zum Liveticker einblenden
						$('tickerurl').show();
						
						if ($('tickerdata')) {
							$('tickerdata').src = this.URL_Liveticker_kurz+'?t='+(new Date().getTime());
						}
						
					} catch(e) {
						//Link zum Liveticker ausblenden
						$('tickerurl').hide();
						
						if ($('tickerdata')) {
							$('tickerdata').src = '_data/liveticker_kurz_kein_eintrag.html?t='+(new Date().getTime());
						}
					}
				}).bind(this),
				onFailure: (function(transport) {
					try {
						//Link zum Liveticker ausblenden
						$('tickerurl').hide();
						
						if ($('tickerdata')) {
							$('tickerdata').src = '_data/liveticker_kurz_kein_eintrag.html?t='+(new Date().getTime());
						}
						//alert("onFailure");
					} catch(e) {
						//Link zum Liveticker ausblenden
						$('tickerurl').hide();
						
						if ($('tickerdata')) {
							$('tickerdata').src = '_data/liveticker_kurz_kein_eintrag.html?t='+(new Date().getTime());
						}
					}
				}).bind(this)
			});
		
	},	
	loadPositionData: function() {
			this.isLoading = true;
			new Ajax.Request(this.positionDataUrl+'?'+(new Date().getTime()/100), {
				method: 'get',
				onSuccess: (function(transport) {
					try {
						var o = eval('('+transport.responseText+')');
						if (o) {
							this.setPosition(o);
							this.onPositionDataLoaded();
							
							if(this.ETAPPENTYP == 'EZF' || this.ETAPPENTYP == 'MZF' || this.ETAPPENTYP == 'PROLOG') {
								//Aktualisierung 60 Sekunden
								this.startTimer(60);
							} else {							
								if(parseInt(o.status) != 1) this.startTimer(30); //Etappe nicht gestartet, dann alle 30 Sekunden Aktualisierung
								else this.startTimer(10); //Wenn Etappe gestartet, dann alle 10 Sekunden Aktualisierung
							}
							
						}
					} catch(e) {						this.loadPositionData();
						// Novajax.handleError('', e);
					}
				}).bind(this),
				onFailure: (function(transport) {
					try {
						this.onPositionDataLoaded();
					} catch(e) {
						// Novajax.handleError('', e);
					}
				}).bind(this)
			});
	},
	setPosition: function(data) {
		if(this.map.mapType == 'GM') {
			for (var index = 0, len = data.wurm.length; index < len; ++index) {
				var c = data.wurm[index];
				data.wurm[index] = new GLatLng(c[1], c[0]);
			}
			
			this.profilGui.setValue('ende',    data.ende[2]);
			this.profilGui.setValue('peloton', data.peloton[2]);
			this.profilGui.setValue('spitze',  data.spitze[2]);
			
			data.spitze = new GLatLng(data.spitze[1], data.spitze[0]);
			data.peloton = new GLatLng(data.peloton[1], data.peloton[0]);
			data.ende = new GLatLng(data.ende[1], data.ende[0]);
			
			if (!this.wurmPolyline) {
				this.wurmPolyline = new GPolyline(data.wurm, '#00ff00', 5, 1);
				this.map.addOverlay(this.wurmPolyline);
			}
			else {
				for (var index = 0, len = data.wurm.length; index < len; ++index) {
					var c = data.wurm[index];
					this.wurmPolyline.insertVertex(index, c);
				}
				
				while (this.wurmPolyline.getVertexCount() > data.wurm.length) {
					this.wurmPolyline.deleteVertex(this.wurmPolyline.getVertexCount()-1);
				}
			}
			
			if (!this.markerEnde) {
				var ticon = new GIcon();
				ticon.image = '_data/Ende.gif';
				ticon.iconSize = new GSize(32,15);
				ticon.iconAnchor = new GPoint(16, 15);
				this.markerEnde = new GMarker(data.ende, {
					icon: ticon,
					clickable: false
				});
				this.map.addOverlay(this.markerEnde);
			}
			else {
				this.markerEnde.setPoint(data.ende);
			}
			
			if (!this.markerPeloton) {
				var ticon = new GIcon();
				ticon.image = '_data/Peloton.gif';
				ticon.iconSize = new GSize(54,15);
				ticon.iconAnchor = new GPoint(27, 15);
				this.markerPeloton = new GMarker(data.peloton, {
					icon: ticon,
					clickable: false
				});
				this.map.addOverlay(this.markerPeloton);
			}
			else {
				this.markerPeloton.setPoint(data.peloton)
			}
			
			if (!this.markerSpitze) {
				var ticon = new GIcon();
				ticon.image = '_data/Spitze.gif';
				ticon.iconSize = new GSize(43,15);
				ticon.iconAnchor = new GPoint(21, 15);
				this.markerSpitze = new GMarker(data.spitze, {
					icon: ticon,
					clickable: false
				});
				this.map.addOverlay(this.markerSpitze);
			}
			else {
				this.markerSpitze.setPoint(data.spitze)
			}
			
			if ($('centerposition') && $('centerposition').checked) {
				this.centerToPositionOverlay();
			}
		}
		
		if(this.map.mapType == 'VE') {
			
			if(data.status) this.STATUS = parseInt(data.status);
			
			if(!this.overlays['tourwurm']) this.addPositionLayer('tourwurm');
			if(!this.overlays['tourpunkte']) this.addPositionLayer('tourpunkte');
			
			//Zeitfahren / Prolog
			if(this.ETAPPENTYP == 'EZF' || this.ETAPPENTYP == 'MZF' || this.ETAPPENTYP == 'PROLOG') {
				//Status der Etappe
				var elem_kmdata = false;
				if ($('kmdata')) {
					elem_kmdata = $('kmdata');
				}

				var strEtappentyp = ''; 
				if(this.ETAPPENTYP == 'EZF') {							
					strEtappentyp = "Einzelzeitfahren";
				}
				if(this.ETAPPENTYP == 'MZF') {
					strEtappentyp = "Mannschaftszeitfahren";
				}
				if(this.ETAPPENTYP == 'PROLOG') {
					strEtappentyp = "Prolog";
				}
				
				switch (this.STATUS) {
					case -1:
					case 0:
						if(this.route && this.route.coords) {
							var layer = this.overlays['tourpunkte'];
							for(var i=0;i<layer.GetShapeCount();i++) {
								var s=layer.GetShapeByIndex(i);
								if(typeof(s.STATUS) && parseInt(s.STATUS) == this.STATUS) return; 
							}
							
							var labelText="<nobr>Start " + strEtappentyp + ":</nobr>";
							
							labelText+="<br/>";						
							labelText+="<nobr> " + this.routeStarttime + " </nobr>";
									
							this.map.deletePositionLayer();
							this.markerEnde=false;
							this.markerPeloton=false;
							this.markerSpitze=false;
							
							var shape = this.map.addLabel(layer, this.route.coords[0], labelText, 'position:relative; white-space:nowrap; background-color:red; left: 18px; color:#FFFFFF; text-align:left; font: bold 14px Arial; cursor: pointer;', true);
							shape.STATUS=this.STATUS;
							
							if(this.profilGui && this.profilGui != undefined) {
								this.profilGui.setValue('ende',    0);
								this.profilGui.setValue('peloton', 0);
								this.profilGui.setValue('spitze',  0);
							}
							
						} else {
							alert("Start der Etappe: " + this.routeStarttime);
						}
						
						elem_kmdata.update("<li><nobr>Start " + strEtappentyp + " " + this.routeStarttime + "</nobr></li>"); 
						
						break;
				 
					case 1:
						//Etappe läuft ... Positionen zeigen
						var layer = this.overlays['tourpunkte'];
						for(var i=0;i<layer.GetShapeCount();i++) {
							var s=layer.GetShapeByIndex(i);
							if(typeof(s.STATUS) && parseInt(s.STATUS) == this.STATUS) return; 
						}
							
						var labelText="<nobr>" + strEtappentyp + " läuft ...</nobr>";

						this.map.deletePositionLayer();
						this.markerEnde=false;
						this.markerPeloton=false;
						this.markerSpitze=false;
						
						var shape = this.map.addLabel(layer, this.route.coords[0], labelText, 'position:relative; white-space:nowrap; background-color:red; left: 18px; color:#FFFFFF; text-align:left; font: bold 14px Arial; cursor: pointer;', true);
						shape.STATUS=this.STATUS;
							
						if(this.profilGui && this.profilGui != undefined) {
							this.profilGui.setValue('ende',    0);
							this.profilGui.setValue('peloton', 0);
							this.profilGui.setValue('spitze',  0);
						}
						//alert(elem_kmdata.innerText);
						elem_kmdata.update("<li>" + labelText + "</li>");
						
						break;
				 
					case 2: 
						//Etappe beendet
						if(this.route && this.route.coords) {
							//Start in wenigen Minuten
							var layer = this.overlays['tourpunkte'];
							for(var i=0;i<layer.GetShapeCount();i++) {
								var s=layer.GetShapeByIndex(i);
								if(typeof(s.STATUS) && parseInt(s.STATUS) == this.STATUS) return; 
							}
							var labelText="<nobr>" + strEtappentyp + " beendet</nobr>";
							
							this.map.deletePositionLayer();
							this.markerEnde=false;
							this.markerPeloton=false;
							this.markerSpitze=false;
							
							var shape = this.map.addLabel(layer, this.route.coords[this.route.coords.length-1], labelText, 'position:relative; white-space:nowrap; background-color:red; left: 18px; color:#FFFFFF; text-align:left; font: bold 14px Arial; cursor: pointer;', true);
							shape.STATUS=this.STATUS;
							
							if(this.profilGui && this.profilGui != undefined) {
								this.profilGui.setValue('ende',    this.routeLength-this.profilOffset);
								this.profilGui.setValue('peloton', this.routeLength-this.profilOffset);
								this.profilGui.setValue('spitze',  this.routeLength-this.profilOffset);
							}
						} else {
							alert("Etappe beendet");
						}
						
						elem_kmdata.update("<li><nobr>" + strEtappentyp + " beendet</nobr></li>");
						
						break;
				}
				
			} else {
				//"Normale Etappe"
				//KM, noch zu fahren ...
				
				var s_km,p_km,e_km =  -1;
				var s_km_z,p_km_z,e_km_z = -1;
				
				//Koordinaten
				var s_x,s_y,p_x,p_y,e_x,e_y = 0;
				
				if ($('kmdata')) {
					if(this.STATUS == 1) {
						//Etappe läuft gerade
						s_km =  (data.spitze[2]/1000).toFixed(1).replace('\.',',');
						p_km = (data.peloton[2]/1000).toFixed(1).replace('\.',',');
						e_km = (data.ende[2]/1000).toFixed(1).replace('\.',',');
						
						s_x = (data.spitze[0]).toFixed(6).replace('\.',',');
						s_y = (data.spitze[1]).toFixed(6).replace('\.',',');
						
						p_x = (data.peloton[0]).toFixed(6).replace('\.',',');
						p_y = (data.peloton[1]).toFixed(6).replace('\.',',');
						
						e_x = (data.ende[0]).toFixed(6);
						e_y = (data.ende[1]).toFixed(6);
						
						//e_x = (data.ende[0]).toFixed(6).replace('\.',',');
						//e_y = (data.ende[1]).toFixed(6).replace('\.',',');
						
						s_km_z = ((this.routeLength - this.profilOffset - data.spitze[2])/1000);
						p_km_z = ((this.routeLength - this.profilOffset- data.peloton[2])/1000);
						e_km_z = ((this.routeLength - this.profilOffset - data.ende[2])/1000);
						
						//alert(p_km);
						
						if(s_km_z>=0.3)	s_km_z = ((this.routeLength - this.profilOffset - data.spitze[2])/1000).toFixed(1).replace('\.',',');
						else {
							s_km_z = "0";
							s_km = ((this.routeLength - this.profilOffset)/1000).toFixed(1).replace('\.',',');
						}
							
						if(p_km_z>=0.3) p_km_z = ((this.routeLength - this.profilOffset- data.peloton[2])/1000).toFixed(1).replace('\.',',');
						else { 
							p_km_z = "0";
							p_km = ((this.routeLength - this.profilOffset)/1000).toFixed(1).replace('\.',',');
						}
						
						if(e_km_z>=0.3) e_km_z = ((this.routeLength - this.profilOffset - data.ende[2])/1000).toFixed(1).replace('\.',',');
						else {
							e_km_z = "0";
							e_km = ((this.routeLength - this.profilOffset)/1000).toFixed(1).replace('\.',',');
						}
									
						
						var status = '';
						//alert(e_x + ": " + parseFloat(e_x));
						
						//Spitze
						if(parseFloat(s_x) != 0 || parseFloat(s_y) != 0) status+= '<li>Spitze bei KM: ' + s_km + ' / KM bis Ziel: ' + s_km_z + '</li>';
						if(parseFloat(p_x) != 0 || parseFloat(p_y) != 0) status+= '<li>Peloton bei KM: ' + p_km + ' / KM bis Ziel: ' + p_km_z + '</li>';
						if(parseFloat(e_x) != 0 || parseFloat(e_y) != 0) status+= '<li>Ende bei KM: ' + e_km + ' / KM bis Ziel: ' + e_km_z + '</li>';
						
						/*
						var status = '<li>Spitze bei KM: ' + s_km + ' / KM bis Ziel: ' + s_km_z + '</li>';
						status+= '<li>Peloton bei KM: ' + p_km + ' / KM bis Ziel: ' + p_km_z + '</li>';
						status+= '<li>Ende bei KM: ' + e_km + ' / KM bis Ziel: ' + e_km_z + '</li>';
						*/						
						
						$('kmdata').update(status);
					}
					
					if(this.STATUS == -1) {
						//Start am / um
						$('kmdata').update('<li>Start der Etappe: ' + this.routeStarttime + '</li>');
					}
					
					if(this.STATUS == 0) {
						//Start in wenigen Minuten
						$('kmdata').update('<li>Start in wenigen Minuten</li>');
					}
					
					if(this.STATUS > 1) {
						//Etappe beendet
						$('kmdata').update('<li>Etappe beendet</li>');
					}								
				}
				
				
				switch (this.STATUS) {
					case -1:
						if(this.route && this.route.coords) {
							var layer = this.overlays['tourpunkte'];
							for(var i=0;i<layer.GetShapeCount();i++) {
								var s=layer.GetShapeByIndex(i);
								if(typeof(s.STATUS) && parseInt(s.STATUS) == this.STATUS) return; 
							}
							var labelText="<nobr>Start der Etappe:</nobr>";
							labelText+="<br/>";						
							labelText+="<nobr> " + this.routeStarttime + " </nobr>";
									
							this.map.deletePositionLayer();
							this.markerEnde=false;
							this.markerPeloton=false;
							this.markerSpitze=false;
							
							var shape = this.map.addLabel(layer, this.route.coords[0], labelText, 'position:relative; white-space:nowrap; background-color:red; left: 18px; color:#FFFFFF; text-align:left; font: bold 14px Arial; cursor: pointer;', true);
							shape.STATUS=this.STATUS;
							
							if(this.profilGui && this.profilGui != undefined) {
								this.profilGui.setValue('ende',    0);
								this.profilGui.setValue('peloton', 0);
								this.profilGui.setValue('spitze',  0);
							}
							
						} else {
							alert("Start der Etappe: " + this.routeStarttime);
						}
						
						break;
				 
					case 0: 
						if(this.route && this.route.coords) {
							//Start in wenigen Minuten
							var layer = this.overlays['tourpunkte'];
							for(var i=0;i<layer.GetShapeCount();i++) {
								var s=layer.GetShapeByIndex(i);
								if(typeof(s.STATUS) && parseInt(s.STATUS) == this.STATUS) return; 
							}
							var labelText="<nobr>Start in wenigen Minuten</nobr>";
							
							this.map.deletePositionLayer();
							this.markerEnde=false;
							this.markerPeloton=false;
							this.markerSpitze=false;
							
							var shape = this.map.addLabel(layer, this.route.coords[0], labelText, 'position:relative; white-space:nowrap; background-color:red; left: 18px; color:#FFFFFF; text-align:left; font: bold 14px Arial; cursor: pointer;', true);
							shape.STATUS=this.STATUS;
							
							if(this.profilGui && this.profilGui != undefined) {
								this.profilGui.setValue('ende',    0);
								this.profilGui.setValue('peloton', 0);
								this.profilGui.setValue('spitze',  0);
							}
						} else {
							alert("Start in wenigen Minuten");
						}
						break;
				 
					case 1: 
						//Etappe läuft ... Positionen zeigen
						
						if(this.overlays['tourpunkte'].GetShapeCount() < 2) this.map.deletePositionLayer();
						
						if(data.wurm.length >=2) { 					
							for (var index = 0, len = data.wurm.length; index < len; ++index) { 
								var c = data.wurm[index];
								data.wurm[index] = new VELatLong(c[1], c[0]);
							}
						} else data.wurm=false;
						
						if(this.profilGui && this.profilGui != undefined) {
							this.profilGui.setValue('ende',    data.ende[2]);
							this.profilGui.setValue('peloton', data.peloton[2]);
							this.profilGui.setValue('spitze',  data.spitze[2]);
						}
						
						
						//Wenn maximal noch 300 meter zu fahren sind, 
						//dann den jeweiligen Punkt auf die letzte Koordinate ziehen
						try {
							s_km_z = parseFloat(s_km_z.replace('\,','.'));
							p_km_z = parseFloat(p_km_z.replace('\,','.'));
							e_km_z = parseFloat(e_km_z.replace('\,','.'));
						} catch(e) {
						}
						
						if(this.route.coords) {
							if(s_km_z >= 0 && s_km_z <= 0.3) {
								var a = this.route.coords[this.route.coords.length-1];
								data.spitze[1] = a.Latitude;
								data.spitze[0] = a.Longitude;
							}
							
							if(p_km_z >= 0 && p_km_z <= 0.3) {
								var a = this.route.coords[this.route.coords.length-1];
								data.peloton[1] = a.Latitude;
								data.peloton[0] = a.Longitude;
							}
							
							if(e_km_z >= 0 && e_km_z <= 0.3) {
								var a = this.route.coords[this.route.coords.length-1];
								data.ende[1] = a.Latitude;
								data.ende[0] = a.Longitude;
							}
						}

						if(data.spitze[1] == 0 && data.spitze[0] == 0) data.spitze=null;
						else data.spitze = new VELatLong(data.spitze[1], data.spitze[0]);
						
						if(data.peloton[1] == 0 && data.peloton[0] == 0) data.peloton=null;
						else data.peloton = new VELatLong(data.peloton[1], data.peloton[0]);
						
						if(data.ende[1] == 0 && data.ende[0] == 0) data.ende=null;
						else data.ende = new VELatLong(data.ende[1], data.ende[0]);

						/*
						data.spitze = new VELatLong(data.spitze[1], data.spitze[0]);
						data.peloton = new VELatLong(data.peloton[1], data.peloton[0]);
						data.ende = new VELatLong(data.ende[1], data.ende[0]);
						*/
						
						//alert(data.ende);
						
						//data.ende = new VELatLong(data.ende[1], data.ende[0]);
						
						//Tourwurm
						if(data.wurm && data.peloton && data.ende) {
							this.wurmPolyline = new VEShape(VEShapeType.Polyline, data.wurm);
							this.overlays['tourwurm'].DeleteAllShapes();
							this.overlays['tourwurm'].AddShape(this.wurmPolyline);
							for(var i=0;i<this.overlays['tourwurm'].GetShapeCount();i++) {
								this.overlays['tourwurm'].GetShapeByIndex(i).HideIcon();
								this.overlays['tourwurm'].GetShapeByIndex(i).SetLineWidth(5);
								this.overlays['tourwurm'].GetShapeByIndex(i).SetLineColor(new VEColor(0,0,0,1));
							}
						}
						
						//Ende
						if(data.ende) {
							if(!this.markerEnde) {
								this.markerEnde = new VEShape(VEShapeType.Pushpin, data.ende);
								this.markerEnde.SetCustomIcon('_data/Ende.gif');
								this.overlays['tourpunkte'].AddShape(this.markerEnde);
							} else {
								this.markerEnde.SetPoints(new Array(data.ende));
							}
						} else {
							if(this.markerEnde) {
								//alert("loeschen");
								//this.markerEnde.Hide();
								this.overlays['tourpunkte'].DeleteShape(this.markerEnde);
								this.overlays['tourwurm'].DeleteAllShapes();
								this.markerEnde = false;
								//alert(this.markerEnde.GetPoints().Longitude);
								//alert("Ende Null");
							}
						}
						
						//Peloton
						if(data.peloton) {
							if(!this.markerPeloton) {
								this.markerPeloton = new VEShape(VEShapeType.Pushpin, data.peloton);
								this.markerPeloton.SetCustomIcon('_data/Peloton.gif');
								this.overlays['tourpunkte'].AddShape(this.markerPeloton);
							} else {
								this.markerPeloton.SetPoints(new Array(data.peloton));
							}
						} else {
							if(this.markerPeloton) {
								//alert("loeschen");
								//this.markerEnde.Hide();
								this.overlays['tourpunkte'].DeleteShape(this.markerPeloton);
								this.overlays['tourwurm'].DeleteAllShapes();
								this.markerPeloton = false;
								//alert(this.markerEnde.GetPoints().Longitude);
								//alert("Ende Null");
							}
						}
						
						//Spitze
						if(data.peloton) {
							if(!this.markerSpitze) {
								this.markerSpitze = new VEShape(VEShapeType.Pushpin, data.spitze);
								this.markerSpitze.SetCustomIcon('_data/Spitze.gif');
								this.overlays['tourpunkte'].AddShape(this.markerSpitze);
							} else {
								this.markerSpitze.SetPoints(new Array(data.spitze));
							}
						} else {
							if(this.markerSpitze) {
								//alert("loeschen");
								//this.markerEnde.Hide();
								this.overlays['tourpunkte'].DeleteShape(this.markerSpitze);
								this.markerSpitze = false;
								//alert(this.markerEnde.GetPoints().Longitude);
								//alert("Ende Null");
							}
						} 
						
						this.overlays['tourwurm'].Show();
						this.overlays['tourpunkte'].Show();
						
						if ($('centerposition') && $('centerposition').checked) {
							this.centerToPositionOverlay();
						}
						
						break;
				 
					case 2: 
						//Etappe beendet
						if(this.route && this.route.coords) {
							//Start in wenigen Minuten
							var layer = this.overlays['tourpunkte'];
							for(var i=0;i<layer.GetShapeCount();i++) {
								var s=layer.GetShapeByIndex(i);
								if(typeof(s.STATUS) && parseInt(s.STATUS) == this.STATUS) return; 
							}
							var labelText="<nobr>Etappe beendet</nobr>";
							
							this.map.deletePositionLayer();
							this.markerEnde=false;
							this.markerPeloton=false;
							this.markerSpitze=false;
							
							var shape = this.map.addLabel(layer, this.route.coords[this.route.coords.length-1], labelText, 'position:relative; white-space:nowrap; background-color:red; left: 18px; color:#FFFFFF; text-align:left; font: bold 14px Arial; cursor: pointer;', true);
							shape.STATUS=this.STATUS;
							
							if(this.profilGui && this.profilGui != undefined) {
								this.profilGui.setValue('ende',    this.routeLength-this.profilOffset);
								this.profilGui.setValue('peloton', this.routeLength-this.profilOffset);
								this.profilGui.setValue('spitze',  this.routeLength-this.profilOffset);
							}
						} else {
							alert("Etappe beendet");
						}					
						break;
				}
			} //this.ETAPPENTYP
		}
	},
	setLastLoaded: function(d) {
		this.lastLoaded = d;
		this.progressBar.setValue(new Date().getTime() - this.lastLoaded);
	},
	
	setStreckenStyle: function(name) {
		if(this.overlays[name].setTrackStyle) this.overlays[name].setTrackStyle();
	},	
	setTrackIconStyle: function(name) {
		if(this.overlays[name].setTrackIconStyle) this.overlays[name].setTrackIconStyle();
	},	
	onIntervalEvent: function() {
		if (this.isLoading || !this.streckeLoaded) {
			return;
		}
		var now = new Date().getTime();
		if ($('autorefreshdata').checked) {
			if (this.lastLoaded + this.refreshInterval < now) {
				this.progressBar.setValue(this.refreshInterval);
				this.loadPositionData();
				this.loadLiveticker();
			} else {
				this.progressBar.setValue(now - this.lastLoaded);
			}
		} else {
			this.setLastLoaded(now);
		}
	},
	onPositionOverlayLoaded: function() {
		if (this.newPositionOverlay) {
			if (this.newPositionOverlay.loadedCorrectly()) {
				this.map.addOverlay(this.newPositionOverlay);
				
				if (this.positionOverlay) {
					this.map.removeOverlay(this.positionOverlay);
				}
				
				this.positionOverlay = this.newPositionOverlay;
				
				if ($('centerposition') && $('centerposition').checked) {
					this.centerToPositionOverlay();
				}
				
				this.newPositionOverlay = false;
			}
		}
		
		this.onPositionDataLoaded();
	},
	onOverlayLoaded: function(name) {
		this.toggleOverlay(name);
		//Wenn Strecke geladen wurde
		if(name == 'strecke') {
			//Auf Layer zoomen
			this.gotoOverlayViewport(name);
			//Style der Strecke anpassen
			this.setStreckenStyle(name);
			this.streckeLoaded = true;
			
			if(!this.overlays[name].loadedCorrectly()) {
			};
			
		}
		if(name == 'streckeicons') {
			this.setTrackIconStyle(name);
		}
	},
	onPositionDataLoaded: function() {
		this.setLastLoaded(new Date().getTime());
		this.isLoading = false;
	},
	onMapMousemove: function(point) {
		if (!this.routeSnapper) {
			return;
		}
		
		var csr = this.routeSnapper.getSnapped(point);
		
		this.profilGui.setValue('mouse', csr.distance / this.routeLength2PolylineLength);
		this.routeMarker.setPoint(csr.point);
	},
	onProfilMousemoved: function (prz, v) {
		this.profilGui.setPercent('mouse', prz);
		
		if (this.routeSnapper) {
			var point = this.routeSnapper.getPointAtLength(v * this.routeLength2PolylineLength);
			this.routeMarker.setPoint(point);
			//window.status =  (d * prz / 1000).toFixed(3);
		}
	},
	onProfilClicked: function (prz) {
		if (this.routeSnapper) {
			var d = this.routeLength - this.profilOffset;
			var point = this.routeSnapper.getPointAtLength(d * prz + this.profilOffset);
			//this.map.panTo(point);
		}
	},
	startTimer: function(refreshInterval) {
		this.timerLnr = null;
		this.refreshInterval = refreshInterval * 1000;
		if(!this.progressBar) this.progressBar = new ProgressBar('progressbar', 0, this.refreshInterval);
		else this.progressBar.setMax(this.refreshInterval);
		this.timerLnr = this.onIntervalEvent.bind(this);
		window.setInterval(this.timerLnr, this.timerInterval);
	}
});

ProgressBar = Class.create({
	initialize: function(element, min, max, cls) {
		this.element = $(element);
		this.min = min;
		this.max = max;
		
		this.progressElement = new Element('div');
		
		if (cls) {
			this.progressElement.addClassName(cls);
		}
		
		this.element.insert(this.progressElement);
	},
	setValue: function(value) {
		if (value < this.min) {
			value = this.min;
		}
		else if (value > this.max) {
			value = this.max;
		}
		
		this.value = value;
		
		var width = this.element.getWidth();
		
		this.progressElement.setStyle({
			width: (width * (this.value - this.min) / (this.max - this.min)).toFixed()+'px'
		});
	},
	getValue: function() {
		return this.value;
	},
	getPercent2Value: function(p) {
		if (p < 0) {
			p = 1;
		}
		else if (p > 1) {
			p = 1;
		}
		
		return this.min + (this.max - this.min) * p;
	},
	setPercent: function(value) {
		this.setValue(this.getPercent2Value(value));
	},
	getProgressElement: function() {
		return this.progressElement;
	},
	setMin: function(min) {
		this.min=min;
	},
	setMax: function(max) {
		this.max=max;
	}
});

ProfilGui = Class.create({
	initialize: function(element, min, max, offset) {
		this.element = element;
		
		this.offset=offset;
		
		var img = element.select('img');
		this.img = img[0];
		var imgHeight = this.img.getHeight() - 2;
		
		this.progressBarsHeight = imgHeight +'px';
		this.progressbars = {};
		
		this.addProgressBar('mouse', min, max, true, 'Maus: ');
		
		this.element.observe('mousemove', this.onMousemoved.bindAsEventListener(this));
		this.element.observe('click', this.onClicked.bindAsEventListener(this));
		
		var le = new Element('p');
		le.addClassName('km');
		le.addClassName('ende');
		le.update('Gesamt: '+((max-offset) / 1000).toFixed(2) + 'km');
		element.insert(le);
	},
	addProgressBar: function(name, min, max, doOutput, outputPrefix) {
		var pb = new ProgressBar(this.element, min, max, name);
		pb.getProgressElement().setStyle({
			height: this.progressBarsHeight
		});
		
		this.element.insert(pb.getProgressElement(), {position: top});
		
		var p = false;
		
		if (doOutput) {
			p = new Element('p');
			p.addClassName('km');
			p.addClassName(name);
			
			p.insert(new Element('span').update(outputPrefix));
			
			this.element.insert(p);
			var a = p;
			p = new Element('span');
			a.insert(p);
		}
		
		this.progressbars[name] = {
			progressBar: pb,
			output: p
		}
	},
	getProgressBarEntry: function(name) {
		return this.progressbars[name];
	},
	setPercent: function(name, value) {
		var p = this.getProgressBarEntry(name);
		if (p) {
			p.progressBar.setPercent(value);
			
			if (p.output) {
				p.output.update(((p.progressBar.getValue()-this.offset) / 1000).toFixed(2) + 'km');
			}
		}
	},
	setValue: function(name, value) {
		var p = this.getProgressBarEntry(name);
		if (p) {
			p.progressBar.setValue(value);
			
			if (p.output) {
				p.output.update((p.progressBar.getValue() / 1000).toFixed(2) + 'km');
			}
		}
	},
	onMousemoved: function(event) {
		var p = this.getProgressBarEntry('mouse');
		if (p) {
			var prz = this._posFromEvent(event);
			var v = p.progressBar.getPercent2Value(prz);
			Object.fireEvent(this, 'mousemove', prz, v);
		}
	},
	onClicked: function(event) {
		var p = this.getProgressBarEntry('mouse');
		if (p) {
			var prz = this._posFromEvent(event);
			var v = p.progressBar.getPercent2Value(prz);
			Object.fireEvent(this, 'click', prz, v);
		}
	},
	_posFromEvent: function(event) {
		var offset = this.img.cumulativeOffset()[0];// -  this.img.positionedOffset()[0];
		
		var width = this.img.getWidth() - 1;
		var height = this.img.getHeight();
		var x = event.pointerX();
		var y = event.pointerY();
		
		// window.status = this.img.cumulativeOffset()[0] + ' ' + this.img.positionedOffset()[0] + ' ' + width;
		
		var prz = (x - offset) / width;
		
		return prz < 0 ? 0 : (prz > 1 ? 1 : prz);
	}
});

Cs3000.MapWrapper = {}

Cs3000.MapWrapper.GoogleMap = Class.create({
	initialize: function(element, pos, zoom) {
		this.map = new GMap2(element);
		this.map.enableScrollWheelZoom();
		this.map.enableContinuousZoom();
		this.map.addControl(new GLargeMapControl());
		this.map.addMapType(G_PHYSICAL_MAP);
		this.map.addControl(new GMapTypeControl());
		
		GEvent.addListener(this.map, 'mousemove', this.onMapMousemove.bind(this));
		GEvent.addListener(this.map, 'zoomend', this.onMapZoomend.bind(this));
	},
	destroy: function() {
		GUnload();
	},
	createMarker: function(imageUrl, options) {
		var ticon = new GIcon();
		ticon.image = imageUrl;
		ticon.iconSize = new GSize(options.size[0], options.size[1]);
		ticon.iconAnchor = new GPoint(options.anchor[0], options.anchor[1]);
		
		return new GMarker(options.latlon, {
			icon: ticon,
			clickable: false
		});
	},
	createGeoXmlOverlay: function(url, callback) {
		var overlay = new GGeoXml(url, callback);
		this.map.addOverlay(overlay);
		return overlay;
	},
	createLatLng: function(lat, lon) {
		return new GLatLng(lat, lon);
	},
	createPixelPoint: function(x, y) {
		return new GPoint(x, y);
	},
	getMap: function() {
		return this.map;
	},
	getZoom: function() {
		return this.map.getZoom();
	},
	getProjection: function() {
		return G_NORMAL_MAP.getProjection();
	},
	setCenter: function(lat, lon, zoom) {
		this.map.setCenter(new GLatLng(lat, lon), zoom);
	},
	addOverlay: function(overlay) {
		this.map.addOverlay(overlay);
	},
	onMapMousemove: function(point) {
		Object.fireEvent(this, 'mousemove', point);
	},
	onMapZoomend: function() {
		Object.fireEvent(this, 'zoomend');
	}	
});

Cs3000.MapWrapper.VirtualEarthMap = Class.create({
	initialize: function(element) {
		this.map = new VEMap('map');
		this.map.LoadMap();
		this.map.AttachEvent('onmousemove', this.onMapMousemove.bind(this));
		//this.map.AttachEvent('onerror', this.onError.bind(this));
		//this.map.AttachEvent("onresize", this.onResize.bind(this));
		this.map.onLoadMap = this.setStartOptions();
		//this.map.AttachEvent('onendzoom', this.onMapZoomend.bind(this));
	},
	setStartOptions: function() {
		this.map.SetMapStyle(VEMapStyle.Shaded);
		//this.map.AttachEvent("onendzoom", this.setMinZoom.bind(this));
  	},	
	destroy: function() {
	},
	onError: function() {
		//alert("error");
	},
	onResize: function() {
		//alert("onResize");
	},
	createMarker: function(imageUrl, options) {
		return Object.extend(new VEShape(VEShapeType.Pushpin, options.latlon), {
			setPoint: function(veLatLong) {
				this.SetPoints([veLatLong]);
			}
		});
	},
	createGeoXmlOverlay: function(url, callback) {
		var layer = Object.extend(new VEShapeLayer(), {
			_map: this.map,
			loadedCorrectly: function() {
				return this.GetShapeCount() > 0;
			},
			show: function() {this.Show()},
			hide: function() {this.Hide()},
			
			setTrackStyle: function() {
				//Style der Strecke setzen
				for(var i=0; i < this.GetShapeCount(); ++i) {
					var s = this.GetShapeByIndex(i);
					s.HideIcon();
					s.SetLineWidth(6);
					s.SetLineColor(new VEColor(0,255,0,1));
				}
			},			
			setTrackIconStyle: function() {
				for(var i=0; i < this.GetShapeCount(); ++i) {
					var s = this.GetShapeByIndex(i);
					
					if(s.GetDescription().toUpperCase().match(/NEUTRAL/)) {
						s.SetCustomIcon("<img src='_data/neutraler_start.gif'/>");
						s.SetDescription('Neutraler Start');
					}
					if(s.GetDescription().toUpperCase().match(/SCHARF/)) {
						s.SetCustomIcon("<img src='_data/scharfer_start.gif'/>");
						s.SetDescription('Scharfer Start');
					}
					if(s.GetDescription().toUpperCase().match(/START UND ZIEL/)) {
						s.SetCustomIcon("<img src='_data/ziel.gif'/>");
						s.SetDescription('Start und Ziel');
					}
					else {
						if(s.GetDescription().toUpperCase().match(/ZIEL/)) {
							s.SetCustomIcon("<img src='_data/ziel.gif'/>");
							s.SetDescription('Ziel');
						}
					}
					if(s.GetDescription().toUpperCase().match(/SPRINT/)) s.SetCustomIcon("<img src='_data/sprintwertung.gif'/>");
					if(s.GetDescription().toUpperCase().match(/BERG/)) s.SetCustomIcon("<img src='_data/bergwertung.gif'/>");
					if(s.GetDescription().toUpperCase().match(/START/) && s.GetDescription().toUpperCase().match(/VERPFLEGUNG/)) s.SetCustomIcon("<img src='_data/verpflegung_beginn.gif'/>");
					if(s.GetDescription().toUpperCase().match(/ENDE/) && s.GetDescription().toUpperCase().match(/VERPFLEGUNG/)) s.SetCustomIcon("<img src='_data/verpflegung_ende.gif'/>");
				}
			},			
			gotoDefaultViewport: function() {
				this._map.SetMapView(this.GetBoundingRectangle());
			}
		});
		var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, url, layer);
		this.map.ImportShapeLayerData(veLayerSpec, callback, 0);
				
		return layer;
	},
	
	createLatLng: function(lat, lon) {
		return Object.extend(new VELatLong(lat, lon), {
			distanceFrom: function(veLatLong) {
				var lat1 = this.Latitude, lat2 = veLatLong.Latitude, lon1 = this.Longitude, lon2 = veLatLong.Longitude;
				var R = 6378137;
				var dLat = (lat2-lat1).toRad();
				var dLon = (lon2-lon1).toRad(); 
				var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2);
				var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
				return R * c;				
			}
		});
	},
	createPixelPoint: function(x, y) {
		return new VEPixel(x, y);
	},
	getMap: function() {
		return this.map;
	},
	getZoom: function() {
		return this.map.GetZoomLevel();
	},
	setZoom: function(zoom) {
		return this.map.SetZoomLevel(zoom);
	},
	setMinZoom: function() {
		if(this.getZoom) if(parseInt(this.getZoom()) > 14) this.setZoom(14);
	},
	getProjection: function() {
		return {
			fromLatLngToPixel: this.map.LatLongToPixel.bind(this.map),
			fromPixelToLatLng: this.map.PixelToLatLong.bind(this.map)
		}
	},
	setCenter: function(lat, lon, zoom) {
		this.map.SetCenter(new VELatLong(lat, lon));
		this.map.SetZoomLevel(zoom);
	},
	setScaleBarDistanceUnit: function(unit) {
		this.map.SetScaleBarDistanceUnit(unit);
	},	
	setMapStyle: function(style) {
		this.map.SetMapStyle(style);
	},	
	getCenter: function() {
		return this.map.GetCenter();
	},
	addOverlay: function(overlay) {
		this.map.AddShape(overlay);
	},	
	setMapView: function(boundingRect) {
		this.map.SetMapView(boundingRect);
	},
	addShapeLayer: function(name) {
		var l = new VEShapeLayer();
		l.SetTitle(name);
		this.map.AddShapeLayer(l);
		return l;
	},	
	onMapMousemove: function(event) {
		var px = new VEPixel(event.mapX, event.mapY);
		Object.fireEvent(this, 'mousemove', this.map.PixelToLatLong(px));
	},
	onMapZoomend: function(event) {
		Object.fireEvent(this, 'zoomend');
	},
	getMapView: function() {
		return this.map.GetMapView();
	}, 
	isPointInRect: function (point, rect) {  
	     return ( (rect.TopLeftLatLong.Longitude <= rect.BottomRightLatLong.Longitude && // longitude  
               rect.TopLeftLatLong.Longitude <= point.Longitude &&  
               rect.BottomRightLatLong.Longitude >= point.Longitude)  
            || (rect.TopLeftLatLong.Longitude > rect.BottomRightLatLong.Longitude &&  // longitude crosses 180 degrees  
               rect.TopLeftLatLong.Longitude >= point.Longitude &&  
               rect.BottomRightLatLong.Longitude <= point.Longitude) )  
            && (rect.TopLeftLatLong.Latitude >= point.Latitude &&     // latitude  
               rect.BottomRightLatLong.Latitude <= point.Latitude);  
 	},
	addLabel: function(overlay,point,text,style,boolZoomTo) {
		var shape = new VEShape(VEShapeType.Pushpin, point);
		var myIcon = "<div nowrap style='"+ style+ "'>";
		myIcon+=text + "</div>";
		shape.SetCustomIcon(myIcon);
		shape.SetIconAnchor(point);
		overlay.AddShape(shape);
		if(boolZoomTo) {
			this.setMapView(overlay.GetBoundingRectangle());
			this.setZoom(13);
		}
		return shape;
	},
	deletePositionLayer: function() {
		for(var i=0;i<this.map.GetShapeLayerCount();i++) {
			var s=this.map.GetShapeLayerByIndex(i);
			if(s.GetTitle() == 'tourwurm' || s.GetTitle() == 'tourpunkte') s.DeleteAllShapes(); 
		}
	},
	resize: function(width,height) {
		this.map.Resize(width,height);
	}
});

