var map;
var gdir;
var geocoder;
var geocoder = null;
var addressMarker;
var tlat = 0;
var tlon = 0;
var marker = null;
function initialize(canvas) {
  if (!canvas) {
    canvas = "map_canvas";
  }
  if (GBrowserIsCompatible()) {
    
    map = new GMap2(document.getElementById(canvas));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    gdir = new GDirections(map, document.getElementById("directions"));
    geocoder = new GClientGeocoder();
  }
}
function setMappa(lat, lon, htmlText) {
    if (!map) {
      initialize();
    }
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);
    map.setCenter(new GLatLng(lat, lon), 15);
    var point = new GLatLng(lat, lon);
    if (!marker) {
      var baseIcon = new GIcon();
      //baseIcon.shadow = "/immagini/icona_google_maps_ombra.png";
      baseIcon.iconSize = new GSize(16, 16);
      baseIcon.shadowSize = new GSize(16, 16);
      baseIcon.iconAnchor = new GPoint(8, 16);
      baseIcon.infoWindowAnchor = new GPoint(9, 2);
      //baseIcon.infoShadowAnchor = new GPoint(9, 34);
      baseIcon.image = "/img/google_i.png";

      markerOptions = { icon:baseIcon };
      marker = new GMarker(point, markerOptions);

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(htmlText);
      });

      map.addOverlay(marker);
    } else {
      marker.setLatLng(point);
    }
}

function setDirections(address, locale) {
  if (!map) {
    alert("Selezionare il numero di sezione prima di creare un percorso");
    return false;
  }
  locale = "it";
  gdir.load("from: "+address+" to: "+tlat+", "+tlon, { "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(){ 
      // 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 cerca_mappa(address, form, canvas) {
  if (!geocoder) {
    if (!canvas) {
      canvas = "map_canvas";
    }
    document.getElementById(canvas).style.display = 'block';
    initialize();
  }
  if (!address) {
    address = form.indirizzo.value + ', ' + form.cap.value + ', ' + form.comune.value + form.provincia.options[form.provincia.selectedIndex].value + ', ' + form.paese.options[form.paese.selectedIndex].text;
  }
  geocoder.getLatLng(address,  function (geo) {
    if (geo) {
      setMappa(geo.lat(), geo.lng(), '');
      form.latitude.value = geo.lat();
      form.longitude.value = geo.lng();
    }
  });
}

function cerca_address(address, form) {
  geocoder.getLatLng(address,  function (geo) {
    if (geo) {
      setMappa(geo.lat(), geo.lng(), '');
      form.latitude.value = geo.lat();
      form.longitude.value = geo.lng();
    }
  });
}

function setGeoItaly(latlon, canvas, center, setzoom) {
    if (!map) {
      initialize(canvas);
    }
    var latcenter = 41.87194;
    var loncenter = 12.56738;
    var zoom = 5;
    if (center == 1) {
      latcenter = latlon[0];
      loncenter = latlon[1];
    }
    if (setzoom) {
      zoom = setzoom;
    }
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);
    map.setCenter(new GLatLng(latcenter,loncenter), zoom);

    var baseIcon = new GIcon();
    //baseIcon.shadow = "/immagini/icona_google_maps_ombra.png";
    baseIcon.iconSize = new GSize(16, 16);
    baseIcon.shadowSize = new GSize(16, 16);
    baseIcon.iconAnchor = new GPoint(8, 16);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    //baseIcon.infoShadowAnchor = new GPoint(9, 34);
    var i = 0;
    while (i < latlon.length) {
      var point = new GLatLng(latlon[i], latlon[i + 1]);
      if (latlon[i + 3] == 'E') {
        baseIcon.image = "/img/google_i.png";
      } else {
        baseIcon.image = "/img/google_r.png";
      }
      markerOptions = { icon:baseIcon };
      var marker = new GMarker(point, markerOptions);
      marker.id = latlon[i + 2];
      marker.tipo = latlon[i + 3];
      if (latlon[i + 3] == 'E') {
        GEvent.addListener(marker, "click", function() {
          GeoMarker(this);
        });
      }
      map.addOverlay(marker);
      i += 4;
    }
}

function setUserGeoItaly(latlon, canvas, center, setzoom) {
    if (!map) {
      initialize(canvas);
    } else {
      return false;
    }
    var latcenter = 41.87194;
    var loncenter = 12.56738;
    var zoom = 5;
    if (center == 1) {
      latcenter = latlon[0];
      loncenter = latlon[1];
    }
    if (setzoom) {
      zoom = setzoom;
    }
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);
    map.setCenter(new GLatLng(latcenter,loncenter), zoom);

    var baseIcon = new GIcon();
    //baseIcon.shadow = "/immagini/icona_google_maps_ombra.png";
    baseIcon.iconSize = new GSize(16, 16);
    baseIcon.shadowSize = new GSize(16, 16);
    baseIcon.iconAnchor = new GPoint(8, 16);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    //baseIcon.infoShadowAnchor = new GPoint(9, 34);
    baseIcon.image = "/img/icona_google_maps_i.png";

    markerOptions = { icon:baseIcon };
    var point = new GLatLng(latlon[0], latlon[1]);
    marker = new GMarker(point, markerOptions);
    marker.id = latlon[2];
    /*GEvent.addListener(marker, "click", function() {
      GeoMarker(this);
    });*/
    map.addOverlay(marker);
    GEvent.bind(this.map, "zoomend", this, function(overlay) {
      document.getElementById('_zoom').value = map.getZoom();
    });
    GEvent.bind(this.map, "click", this, function(overlay, latlng) {
      map.setCenter(latlng, map.getZoom());
      marker.setLatLng(latlng);
      document.getElementById('_latitude').value = latlng.lat();
      document.getElementById('_longitude').value = latlng.lng();
      document.getElementById('_zoom').value = map.getZoom();
    }); 
}


function GeoMarker(marker, id) {
  Ext.Ajax.request({
    url: '/adon.pl',
      success: function (con) {
        marker.openInfoWindowHtml(con.responseText);
      },
      headers: {
      },
      params: {
        act: 'GeoEvents',
        Mode: 'GeoMarker',
        id: marker.id
      }
  });
}
