/**
 * JavaScript per la creazione delle mappe Google.
 * 
 * Diego Vicentini
 */
 
/**
 * Oggetto utilizzato per creare e gestire la mappa.
 */    
var map = null;

/**
 * Oggetto per la richiesta delle coordinate in base all'indirizzo specificato.
 */ 
var geocoder = null;

/**
 * Oggetto per la creazione delle indicazioni stradali.
 */
var gdir = null;

/**
 * Inizializza la mappa.
 * 
 */    
function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    gdir = new GDirections(map, document.getElementById("directions"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);
    geocoder = new GClientGeocoder();
    map.addControl(new GSmallMapControl());
   }
}

/**
 * Inizializza la mappa per la visualizzazione di più marker.
 * 
 * @param addGrp
 * @param msgGrp
 */
function initializeMapGrp(addGrp, msgGrp) {
    if (GBrowserIsCompatible()) {
          map = new GMap2(document.getElementById("map_canvas"));
          gdir = new GDirections(map, document.getElementById("directions"));
          GEvent.addListener(gdir, "load", onGDirectionsLoad);
          GEvent.addListener(gdir, "error", handleErrors);
          geocoder = new GClientGeocoder();
          map.addControl(new GLargeMapControl());
          map.setMapType(G_NORMAL_MAP);
          map.enableScrollWheelZoom();
          var mapControl = new GMapTypeControl();
          map.addControl(mapControl);
          for (i=0; i < addGrp.length; i++) {
              addMarkerGrp(addGrp[i], msgGrp[i]);
          }
    }
}

/**
 * Visualizza un marker all'indirizzo specificato centrandolo nella mappa.
 * 
 * @param address l'indirizzo da visualizzare
 * @param message da visualizzare
 * @param zoom il livello di zoom della mappa
 */   
function showAddress(address, message, zoom) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          //alert(address + " not found");
        } else {
          map.setCenter(point, zoom);
          var marker = new GMarker(point);
          map.addOverlay(marker);
          marker.openInfoWindowHtml(message);
          GEvent.addListener(marker, "mouseover", function() {
             marker.openInfoWindowHtml(message);
          });
        }
      }
    );
  }
}

/**
 * Centra la mappa alle coordinate specificate.
 * 
 * @param lat latitudine
 * @param lng longitudine
 * @param zoom
 */
function centerMapAt(lat, lng, zoom) {
  map.setCenter(new GLatLng(lat, lng), zoom);
}
 
/**
 * Aggiunge un marker alla mappa nell'indirizzo specificato.
 * 
 * @param address l'indirizzo
 * @param message il testo da visualizzare
 */
function addMarker(address, message) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          //alert(address + " not found");
        } else {
          var marker = new GMarker(point);
          GEvent.addListener(marker, "mouseover", function() {
             marker.openInfoWindowHtml(message);
          });
          map.addOverlay(marker);
        }
      }
    );
  }
}

/**
 * Aggiunge un marker con l'immagine specificata all'indirizzo scelto.
 * 
 * @param address l'indirizzo
 * @param message il testo da visualizzare
 * @param imgLink
 */
function addImgMarker(address, message, imgLink) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          //alert(address + " not found");
        } else {
          var imgicon = new GIcon(G_DEFAULT_ICON);
          imgicon.image = imgLink;
          markerOptions = { icon:imgicon };
          var marker = new GMarker(point, markerOptions);
          GEvent.addListener(marker, "click", function() {
             marker.openInfoWindowHtml(message);
          });
          map.addOverlay(marker);
        }
      }
    );
  }      
}

/**
 * Aggiunge un gruppo di marker con indirizzo e messaggio specificati.
 * L'iimagine è quella di default.
 * 
 * @param address
 * @param message
 */
function addMarkerGrp(address, message) {
	if (geocoder) {
		geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				//alert(address + " not found");
			} else {
				map.setCenter(point, 14);
				var imgicon = new GIcon(G_DEFAULT_ICON);
				markerOptions = { icon:imgicon };
				var marker = new GMarker(point, markerOptions);
				GEvent.addListener(marker, "mouseover", function() {
					marker.openInfoWindowHtml(message);
				});
				map.addOverlay(marker);
			}
        });
    }
}

/**
 * Imposta il percorso per la visualizzazione delle inidicazioni stradali.
 * 
 * @param fromAddress l'indirizzo di partenza
 * @param toAddress l'indirizzo di arrivo
 * @param locale
 */
function setDirections(fromAddress, toAddress, locale) {
  gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.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: " + gdir.getStatus().code);
   
   else if (gdir.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: " + gdir.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 (gdir.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: " + gdir.getStatus().code);

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

function onGDirectionsLoad() {
}
