// JavaScript Document
//http://econym.org.uk/gmap/index.htm
var map;
var point;
var marker;
var geocoder = null;
var directionsPanel;
var directions;
var addressMarker; // ???
var	auswahl;
var fromAddressField;
var reasons=new Array(); // reasons for failure

//=======================================================================================================
function initialize() {
//=======================================================================================================
if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("googleMapCanvas"));
	point = new GLatLng(latitude,longitude);
	marker = new GMarker(point);

	//for(i in map) { GLog.write(i); } //debug

	map.setCenter(point, 17); //max zoomstufe 17 für strassenkarte

	map.setMapType(G_SATELLITE_MAP);
	//map.setMapType(G_NORMAL_MAP);

	//map.openInfoWindow(map.getCenter(), document.createTextNode("Plain-Text"));
	//map.openInfoWindowHtml(map.getCenter(),html,{buttons:{close:{show:4}}, noCloseOnClick:true});
	//map.openInfoWindowHtml(map.getCenter(),html);

	map.addOverlay(marker);
	marker.openInfoWindowHtml(html);
	GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
	
	GEvent.addListener(map, 'click',
		function(overlay, point){
			if (point){
				if (debug){debug.innerHTML+="<br>latitude: "+point.y+" longitude: "+point.x;}
			}
		}
	);	

	//map.addControl(new GSmallMapControl());
	map.addControl(new GLargeMapControl());
	
	map.addControl(new GOverviewMapControl());

	map.removeMapType(G_HYBRID_MAP);
	map.addMapType(G_PHYSICAL_MAP);
	map.addControl(new GMapTypeControl());
	
	//map.addOverlay(trafficInfo);

	geo = new GClientGeocoder(); 


	directionsPanel = document.getElementById("googleMapDirections"); //alert(directionsPanel);
	directions = new GDirections(map, directionsPanel);
	GEvent.addListener(directions, "load", onGDirectionsLoad);
	GEvent.addListener(directions, "error", handleErrors);
	GEvent.addListener(directions, "addoverlay", addOverlay);
	//directions.load("from: A-6200 Gallzein to: A-6215 Achenkirch 130A");
	
	reasons[G_GEO_SUCCESS]            = "Success [200]";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed [500]";

	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given [610]";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded [620]";

	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value [601]";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Es konnte keine geographische Position gefunden werden.\nGeben sie Land und Postleitzahl an.\n\nNo corresponding geographic location could be found.\nProvide country and ZIP-code\n\nGB-Birmingham, A-4020 Linz, Gallzein Österreich\n\n[602]";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address: The geocode for the given address cannot be returned due to legal or contractual reasons [603]";
	
	//604 unknown directions

  }
}

//======= Geocoding =====================================================================================
function showAddress(search, toAddress, locale) {
	if (search==""){
		return false;
	}
	auswahl=document.getElementById("googleMapDirections");
	fromAddressField=document.getElementById("fromAddress");
	geo.getLocations(search, function (result){
			//GLog.write("geo.getLocations(search, function (result)");
			//GLog.write("showAddress("+search+","+toAddress+","+locale+") #Placemarks:"+result.Placemark.length+" Statuscode: "+result.Status.code+" Coord: "+result.Placemark[0].Point.coordinates);
			if (result.Status.code == G_GEO_SUCCESS) {
				
				if (result.Placemark.length > 1) { //liste anzeigen wenn mehr als ein ergebnis
					auswahl.innerHTML = "<strong>Google hat folgende Ziele erkannnt, bitte w&auml;hlen Sie eines aus</strong><br>";

					for (var i=0; i<result.Placemark.length; i++) {
						var p = result.Placemark[i].Point.coordinates;
						adresse=result.Placemark[i].address;
						if (i==0) {
							place(p[1],p[0],adresse);//gleich mal markert setzen
						}

						zaehler="0"+(i+1);
						zaehler=zaehler.substr(zaehler.length-2,2);
						funktion="place(" + p[1] + "," +p[0] + ",'"+adresse+"')";
						//GLog.write(funktion);
						auswahl.innerHTML += ""+zaehler+": <a href=\"javascript:"+funktion+"\">"+ adresse+"<\/a><br>";
					}
					return false;
				}
				
				else { // eindeutiges ergebnis
					auswahl.innerHTML = "";
					directions.load("from: " + fromAddressField.value + " to: " + toAddress,	{ "locale": locale });
					map.setMapType(G_NORMAL_MAP);
					return true;
				}
			}
			// ====== Decode the error status ======
			else {
				var reason="Code "+result.Status.code;
				if (reasons[result.Status.code]) {
					reason = reasons[result.Status.code]
				} 
				alert('"'+search+'"\n\n' + reason);
				return false;
			}
		}
	);
}

//=======================================================================================================
function place(lat,lng, address) {
//=======================================================================================================
	map.clearOverlays(); 
	var point = new GLatLng(lat,lng);
	map.setCenter(point,14); 
	map.addOverlay(new GMarker(point));
	fromAddressField.value=address; //setz die adresse in das eingabefeld des formulars
}

//=======================================================================================================
function handleErrors(){ //obsolete????
//=======================================================================================================
reason = reasons[directions.getStatus().code];


if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	alert(reason);

else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
	alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);

else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
	alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

else if (directions.getStatus().code == G_GEO_BAD_KEY)
	alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);

else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
	alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);

else if (directions.getStatus().code == 604)
	alert("Es konnte keine Wegbeschreibung gefunden werden.\nGeben sie Land und Postleitzahl an.\n\nUnknown directions.\nProvide country and ZIP-code\n\nGB-Birmingham, A-4020 Linz, Gallzein Österreich\n\n[604]");

else 
	alert("Unknown Error code: " + directions.getStatus().code);
}

//=======================================================================================================
function onGDirectionsLoad(){ 
//=======================================================================================================
  // Use this function to access information about the latest load()
  // results. e.g. document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}

//=======================================================================================================
function addOverlay() {    
//=======================================================================================================
	//GLog.write($("td[jscontent='address']").append("<strong>&lt;p&gt;</strong>"));
	element1=$("td[jscontent='address']")[0]; //jQuery!!!!
	element2=$("td[jscontent='address']")[1];
	setDivHeight(_posFromBody(element2,'y')+parseInt(element2.offsetHeight)+45); // prima !!!!
}	


