var map = null;
var gdir = null;
var geo = null;

var poiIcon = new GIcon();
var ownlocIcon = new GIcon();
var locations = [];
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 load(latitude, longitude) {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));

	map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());

	poiIcon.image = "http://www.bonoferta.com/images/icon_poi.png";
	poiIcon.shadow = "http://www.bonoferta.com/images/icon_pois.png";
	poiIcon.iconSize=new GSize(32,32);	
	poiIcon.shadowSize=new GSize(56,32);
	poiIcon.iconAnchor=new GPoint(16,32);
	poiIcon.infoWindowAnchor=new GPoint(16,0);

	ownlocIcon.image = "http://www.bonoferta.com/images/icon_ownloc.png";
	ownlocIcon.shadow = "http://www.bonoferta.com/images/icon_ownlocs.png";
	ownlocIcon.iconSize=new GSize(32,32);	
	ownlocIcon.shadowSize=new GSize(56,32);
	ownlocIcon.iconAnchor=new GPoint(16,32);
	ownlocIcon.infoWindowAnchor=new GPoint(16,0);

	gdir = new GDirections(map, document.getElementById("directions"));
	GEvent.addListener(gdir, "error", function() {
	  var code = gdir.getStatus().code;
	  var reason="Code "+code;
	  if (reasons[code]) {
	    reason = reasons[code]
	  } 

	  alert("Failed to obtain directions, "+reason);
	});
	
	geo = new GClientGeocoder(); 

	showLocation(latitude, longitude);
	
	showMarkers();
  }
}

function showLocation(latitude, longitude) {
	map.setCenter(new GLatLng(latitude,longitude), 13);
	//Latitude: " + latitude + "<br/>Longitude: " + longitude
    var marker = createMarker(new GPoint(longitude,latitude),"<b>Ihre Position</b><br/>" + document.getElementById("address").value, ownlocIcon);
    map.addOverlay(marker);
	GEvent.trigger(marker,'click');
}

function createMarker(point, htmlcontent, icon) {
  var marker = new GMarker(point, icon);
  GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(htmlcontent);});
  return marker;
}

function openDetails(id){
	openWin('http://www.bonoferta.com/search/show_detail/' + id, 'Detailansicht', '640', '580');
}

function tohere(id, name, lat, lng, html, address){
	locations[id].openInfoWindowHtml('<b>Ziel der Route:</b> ' + escapeQuot(name) + "<br/>Startadresse (<a class=\"umkreissuche\" href=\"javascript:setStartAddress('" + document.getElementById("address").value + "')\">Adresse übernehmen</a>)" +
		   ':<form name="directionsform" action="javascript:getDirections()">' +
           '<input type="text" size="40" name="startaddress" id="startaddress" value="' + (address === undefined ? "" : address) + '" /><br>' +
		   '<input type="hidden" id="lat" value="' + lat + '">' + 
		   '<input type="hidden" id="lng" value="' + lng + '">' + 		
		   '<input type="hidden" id="name" value="' + escapeQuot(name) + '">' + 		
		   '<input type="hidden" id="id" value="' + id + '">' + 				
		   '<input type="hidden" id="direction" value="tohere">' + 				
           '<input value="Route berechnen" type="submit">' +
		   '<br/>' + 
           '<input type="hidden" id="destaddress" value="'+ removeQuot(name) + "@"+ lng + ',' + lat + '"/></form>' +
		   (html === undefined ? "" : html));
}

function fromhere(id, name, lat, lng, html, address){
	locations[id].openInfoWindowHtml('<b>Start der Route:</b> ' + escapeQuot(name) + "<br/>Zieladresse (<a class=\"umkreissuche\" href=\"javascript:setDestAddress('" + document.getElementById("address").value + "')\">Adresse übernehmen</a>)" + 			
		   ':<form name="directionsform" action="javascript:getDirections()">' +
           '<input type="text" size="40" name="destaddress" id="destaddress" value="' + (address === undefined ? "" : address) + '" /><br>' +
		   '<input type="hidden" id="lat" value="' + lat + '">' + 
		   '<input type="hidden" id="lng" value="' + lng + '">' + 		
		   '<input type="hidden" id="name" value="' + escapeQuot(name) + '">' + 		
		   '<input type="hidden" id="id" value="' + id + '">' + 				
		   '<input type="hidden" id="direction" value="fromhere">' + 				
           '<input value="Route berechnen" type="submit">' +
		   '<br/>' + 
           '<input type="hidden" id="startaddress" value="'+ removeQuot(name) + "@"+ lng + ',' + lat + '"/></form>' +
		   (html === undefined ? "" : html));
}

function setStartAddress(address){
	document.getElementById("startaddress").value = address;
	document.directionsform.submit();
}

function setDestAddress(address){
	document.getElementById("destaddress").value = address;
	document.directionsform.submit();
}

function setAddress(address){
	document.getElementById("address").value = address;
	document.locateform.submit();
}

function getDirections() {
	var id = document.getElementById("id").value;
	var sourceaddress = removeHTML(document.getElementById("startaddress").value);
	var destaddress = removeHTML(document.getElementById("destaddress").value);

	if (document.getElementById("direction").value == "tohere")
		var search = sourceaddress;
	else
		var search = destaddress;
	
	geo.getLocations(search, function (result)
          {
            if (result.Status.code == G_GEO_SUCCESS) {
	
			  var options = "";
              // ===== If there was more than one result, "ask did you mean" on them all =====
              if (result.Placemark.length > 1) { 

                // Loop through the results
                for (var i=0; i<result.Placemark.length; i++) {
                  var p = result.Placemark[i].Point.coordinates;
				  
				  if (document.getElementById("direction").value == "tohere")
					options += '<br/> ' + (i+1) + ' : <a class="umkreissuche" href="javascript:setStartAddress(\''+ result.Placemark[i].address + '\')">' + result.Placemark[i].address + '</a>';
			 	else		
					options += '<br/> ' + (i+1) + ' : <a class="umkreissuche" href="javascript:setDestAddress(\''+ result.Placemark[i].address + '\')">' + result.Placemark[i].address + '</a>';
                }

				var lat = document.getElementById("lat").value;
				var lng = document.getElementById("lng").value;	
				var name = document.getElementById("name").value;				

				if (document.getElementById("direction").value == "tohere")
					tohere(id, name, lat, lng, options, search);
				else
					fromhere(id, name, lat, lng, options, search);
				return;
					
            }

	              // ===== If there was a single marker =====
	              else {
						gdir.load("from: "+sourceaddress+" to: "+destaddress,  { "locale": "de"});
						locations[id].closeInfoWindow();
	              }
	            }
	            // ====== Decode the error status ======
	            else {
	              var reason="Code "+result.Status.code;
	              if (reasons[result.Status.code]) {
	                reason = reasons[result.Status.code]
	              } 
	              alert('Could not find "'+search+ '" ' + reason);
	            }
	          }
	        );

}

function removeHTML(string){
	string = string.replace(/<br\/>/g,",");
	string = string.replace(/<b>/g,"");
	string = string.replace(/<\/b>/g,"");
	string = string.replace(/"/g,"&quot;");	
	return string;
}

function escapeQuot(string){
	string = string.replace(/"/g,"&quot;");	
	return string;
}


function removeQuot(string){
	string = string.replace(/"/g,"");	
	string = string.replace(/&quot;/g,"");		
	return string;
}


function locateAddress(){
      
	var search = document.getElementById("address").value;
		
	geo.getLocations(search, function (result) {
 		
		if (result.Status.code == G_GEO_SUCCESS) {
			if (result.Placemark.length > 1) { 
            	document.getElementById("message").innerHTML = "Meinten Sie:";
            	for (var i=0; i<result.Placemark.length; i++) {
					var p = result.Placemark[i].Point.coordinates;
					document.getElementById("message").innerHTML += "<br>"+(i+1)+ ': <a href="javascript:setAddress(\'' +result.Placemark[i].address+'\')">'+ result.Placemark[i].address+"</a>";
				}
				return false;
			} else {
				document.getElementById("message").innerHTML = "";

				if(result.Placemark[0].Point.address === undefined){
					if(result.Placemark[0].address === undefined){
						setAddress("Berlin, Deutschland");	
					}else{
						setAddress(result.Placemark[0].address);	
					}
				}else{
					
					setAddress(result.Placemark[0].Point.address);
				}
			}
		}else {
			var reason="Code "+result.Status.code;
            if (reasons[result.Status.code]) {
              reason = reasons[result.Status.code]
            } 
            alert('Could not find "'+search+ '" ' + reason);
		}
	});

	return false;
}