
 var map;
 var nodes;
 var maxNodes = 13;
 var altitudes = [];
 var dirn;
var bounds;
var poly;
var icon1, icon2;
var fromdone =false;
var todone=false;

var geocoder;
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

 



      function getAltitude(i) {
        var point = poly.GetPointAtDistance(i*poly.Distance()/maxNodes);
        GDownloadUrl('getalti.php?lat=' +point.lat()+ '&lng=' +point.lng(), function(data) {
          var doc = GXml.parse(data);
          altitudes[i] = parseInt(GXml.value(doc));
          nodes = nodes+1;
          if (nodes == maxNodes) {
            drawProfile();
          }
        });
      }
      
function calcHeight() {
	var objBody = document.getElementsByTagName("body").item(0);
  	var h= window.innerHeight || self.innerHeight || document.body.clientHeight;
    h = h - Element.getDimensions('navi').height - 3;
    $('map').style.height = h + 'px';
}

//// hier geits los!!     
function startApp() {
	_mPreferMetric = true;
	geocoder = new GClientGeocoder();
    calcHeight();
    map = new GMap2($("map"));
    map.setCenter(new GLatLng(53.57787,10.059741),12);
	var copyright = new GCopyright(1,
	new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0,
	'(<a rel="license" href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>)');
	var copyrightCollection =
	new GCopyrightCollection('Kartendaten &copy; 2009 <a href="http://www.openstreetmap.org/">OpenStreetMap</a> Contributors');
	copyrightCollection.addCopyright(copyright);
	var tilelayers_mapnik = new Array();
	tilelayers_mapnik[0] = new GTileLayer(copyrightCollection, 0, 18);
	tilelayers_mapnik[0].getTileUrl = GetTileUrl_Mapnik;
	tilelayers_mapnik[0].isPng = function () { return true; };
	tilelayers_mapnik[0].getOpacity = function () { return 1.0; };
	var mapnik_map = new GMapType(tilelayers_mapnik,
	new GMercatorProjection(19), "Mapnik",{ 
		urlArg: 'mapnik', 
		linkColor: '#000000'
	});
	map.addMapType(mapnik_map);
	var tilelayers_tah = new Array();
	tilelayers_tah[0] = new GTileLayer(copyrightCollection, 0, 17);
	tilelayers_tah[0].getTileUrl = GetTileUrl_TaH;
	tilelayers_tah[0].isPng = function () { return true; };
	tilelayers_tah[0].getOpacity = function () { return 1.0; };
	var tah_map = new GMapType(tilelayers_tah,
	new GMercatorProjection(19), "T@H",	{ 
		urlArg: 'tah', 
		linkColor: '#000000' });
	map.addMapType(tah_map);
	map.setMapType(mapnik_map);
  //   map.addControl(new GSmallMapControl());

	
	
	//	new Draggable('steps');
      dirn = new GDirections(null,null);
      bounds= new GBounds();
   
   	  var baseIcon = new GIcon();
          baseIcon.iconSize=new GSize(24,24);
          baseIcon.shadowSize=new GSize(38,30);
          baseIcon.iconAnchor=new GPoint(12,12	);
          baseIcon.infoWindowAnchor=new GPoint(16,0);
          
       icon1 = new GIcon(baseIcon, "./res/taxi.png", null, "http://maps.google.com/mapfiles/kml/pal5/icon7s.png");
       icon2   = new GIcon(baseIcon, "./res/taxi.png", null, "http://maps.google.com/mapfiles/kml/pal5/icon7s.png");

      new Ajax.Autocompleter('from','from_sel','./res/hamburgstreets.php',{paramName:'nadel',updateElement:function(val) {
  			$('from').value = val.innerHTML;
  			fromdone=true;
  			if (todone==true) $('starter').disabled = null;
      	}});
      new Ajax.Autocompleter('to','to_sel','./res/hamburgstreets.php',{paramName:'nadel',updateElement:function(val) {
  			$('to').value = val.innerHTML;
  			todone=true;
  			if (fromdone==true) $('starter').disabled = null;

      	}});
    
      function done($a,$b) {
      }

      //$('starter').disabled=null;
	    
      ///// hier kommts rein:
       GEvent.addListener(dirn, "error", function() {
        var code = gdir.getStatus().code;
        var reason="Code "+code;
        if (reasons[code]) {
          reason = reasons[code]
        } 
        alert("So geht das nicht, "+reason);
      });

      
      GEvent.addListener(dirn,"load",function() {
        	nodes = 0;
        	Element.hide('warte');
		  	poly = dirn.getPolyline();
    		getPreis();
    		getProfil();
    
            // 1. Marker:
       	 	var marker1 = new GMarker(poly.getVertex(0),{icon:icon1,draggable:true});
       	 	map.addOverlay(marker1);  	 	
       	 	
    		// 2:
        	var marker2 = new GMarker(dirn.getPolyline().getVertex(poly.getVertexCount()-1),{icon:icon2,draggable:true});
			map.addOverlay(marker2);  	 	
       	 	
       	 	GEvent.addListener(marker1, "dragend", function() {
    				map.clearOverlays();
        			dirn.loadFromWaypoints([marker1.getPoint(),marker2.getPoint()],{getPolyline:true});
   					map.fit(poly.getBounds());
   					getPreis();
   					$('from').value='';
   					$('to').value='';
   					$('starter').disabled=null;
   					$('profile').hide();
   					geocoder.getLocations(poly.getVertex(0), showFrom);
   					geocoder.getLocations(poly.getVertex(poly.getVertexCount()-1),showTo);
					startProfil();
   			});
	   	 	GEvent.addListener(marker2, "dragend", function() {
        			map.clearOverlays();
        			dirn.loadFromWaypoints([marker1.getPoint(),marker2.getPoint()],{getPolyline:true});
   					map.fit(poly.getBounds());
   					getPreis();
   					$('from').value='';
   					$('to').value='';
   					$('profile').hide();
   					geocoder.getLocations(poly.getVertex(0), showFrom);
   					geocoder.getLocations(poly.getVertex(poly.getVertexCount()-1),showTo);
					startProfil();

   			});
			var polypoints = poly.getPointArray();
       	 	var dottedpoly = new KMPolyline(polypoints, 'red', 4, 0.9,'Text', 'dot');
            map.addOverlay(dottedpoly);
        	bounds.extend(dottedpoly);
        	map.fit(poly.getBounds());
      	}
      );
 
}
 
GMap2.prototype.fit = function(bounds){
    this.setZoom(map.getBoundsZoomLevel(bounds));
    this.panTo(bounds.getCenter()); 
 }

function startProfil() {
$('profile').innerHTML = '<div style="width:100%;;padding:10px;color:orange;font-weight:bold;background-color:white;font-size:13pt;">&nbsp;<img src="./res/raedle.gif" />Besorge gewünschte Höhendaten und berechne Profil …</div>';
		  		for (var i=0; i<maxNodes; i++) {
             		getAltitude(i)
        		} 
        		


}
 
function startRoute() {
	$('warte').show();
	map.clearOverlays();
 	dirn.load( "from: Hamburg " + $F('from') + " to: Hamburg  " + $F('to'),{getPolyline:true});

}


GPolyline.prototype.getPointArray = function () {
  var points = new Array;
  var len = this.getVertexCount()||0;
  var lastpoint;
  for (var i=0; i<len; i++){
  		var point = this.getVertex(i);
 	    points.push(point);
  }
  return points;
}

function getPreis() {
	var preis = 0;
	var km = poly.getLength()/1000;
	switch ($F('tarif')) {
		case 'HH':
 			preis = 260;
			if (km <4) {
				preis += km*180;
			} else if (km<10) {
				preis += km*169;
			} else {
				preis += km*128;
			}
		break;
		case 'FR':
 			preis = 310;
			if (km <=2) {
				preis += km*180;
			} else {
				preis += km*140;
			}
		break;
		case 'L':
 			preis = 210;
			if (km <=2) {
				preis += km*190;
			} else {
				preis += km*125;
			}
		break;
		case 'H':
 			preis = 250;
			if (km <=3) {
				preis += km*160;
			} else {
				preis += km*140;
			}
		break;
		case 'J':
 			preis = 270;
			if (km <=1) {
				preis += km*230;
			} else {
				preis += km*150;
			}
		break;
		case 'S':
 			preis = 290;
			if (km <=4) {
				preis += km*190;
			} else {
				preis += km*160;
			}
		break;

		case 'DD':
 			preis = 250;
			if (km <=3) {
				preis += km*150;
			} else {
				preis += km*130;
			}
		break;

		case 'K':
 			preis = 250;
			if (km <=5) {
				preis += km*165;
			} else {
				preis += km*135;
			}
		break;
		
		case 'M':
 			preis = 290;
			if (km <5) {
				preis += km*160;
			} else if (km<10) {
				preis += km*140;
			} else {
				preis += km*125;
			}
		break;
		
		case 'B':
			if (km<=2) {
				preis = 400;
			}
			else {
				preis=320;
				if (km <7) {
					preis += km*165;
				} else {
					preis += km*128;
				}
			}	
		break;
	}	
	$('preis').innerHTML= (preis/100).toFixed(2) + ' €';
	//Ajax.Updater('preis','./ajax.getpreis.php',{parameters:'km='+km+ '&tarif='+$F('tarif')});

}



function showFrom(response) {
        if (response.Status.code == G_GEO_SUCCESS) {
        	place = response.Placemark[0].address.split(',')[0];
        	$('from').value=place;
		} else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Kann ' . $F['from'] + ' nicht finden. ' + reason);
            }

}
function showTo(response) {
		if (response.Status.code == G_GEO_SUCCESS) {
        
        	place = response.Placemark[0].address.split(',')[0];
        	$('to').value=place;
		} else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Kann ' . $F['to'] + ' nicht finden. ' + reason);
            }

}

function getProfil() {
      
      	$('profile').show();
        var min=Infinity, max=0;
        // ==== some Google Chart parameters ====
        var width = $('map').getDimensions()['width']-80;
        if (width>900) width=900;
        var url = "http://chart.apis.google.com/chart?cht=ls&amp;chs="+width+"x50&amp;chco=000000&amp;&chf=a,s,EFEFEFF0&amp;chm=B,33cc33,0,0,0&amp;chd=t:"
        for (var i=0; i<maxNodes; i++) {
          // == filter out bogus values ==
          if (altitudes[i] < -10000000000) altitude[i] = 0;
          // == find min and max values ==
          if (altitudes[i]<min) min=altitudes[i];
          if (altitudes[i]>max) max=altitudes[i];
          // == add to the Chart URL ==
          url += altitudes[i];
          if (i<maxNodes-1) url += ","; 
        }
        // == add min/max values to Chart URL ==
        url += "&amp;chds="+min+","+max;
        // == create the Google Chart image ==
        $("profile").innerHTML = '<img src="' +url+ '" width="'+width+'" height="50" >';
        Element.setOpacity('profile',0.6);
      }


function GetTileUrl_Mapnik(a, z) {
    return "http://tile.openstreetmap.org/" +
                z + "/" + a.x + "/" + a.y + ".png";
}

function GetTileUrl_TaH(a, z) {
    return "http://tah.openstreetmap.org/Tiles/tile/" +
                z + "/" + a.x + "/" + a.y + ".png";
}

window.onload = startApp;
window.onresize = calcHeight;
