var coords = {};

function loadMap(ildiv) {
  if (GBrowserIsCompatible()) {
    mapDiv = document.getElementById(ildiv);
    center = new GLatLng(centri[0].lat, centri[0].long);
    map = new GMap2(mapDiv, {logoPassive: true});
    map.setCenter(center, 14);
    map.addControl(new GLargeMapControl());
    map.enableScrollWheelZoom();
 
    for (var i = 0; i < centri.length; i++) {
      var marker = createMarker(i);
      var latlng = marker.getLatLng();
      var pixel = map.fromLatLngToDivPixel(latlng);
      map.addOverlay(marker);
    }
  }
}

function createMarker(ind) {
  var centro = centri[ind];
  //if(centro.lat=='' && centro.long==''){
  //} else {
    point = new GLatLng(centro.lat, centro.long);
  //}
  var marker = new GMarker(point, setIcon(centro.tipo));

  if(centro.url!='') {
    clink = '<a href="'+centro.url+'" onclick="window.open(this.href); return false">website</a>'
  } else {
    clink = '';
  }
  marker.html = [
    '<h3>', centro.nome, '</h3>',
    centro.img, centro.indirizzo, '<br /> ',
    centro.desc, '<br />',
    clink, '<br />'
  ].join('');
  
  GEvent.addListener(marker, 'click', function() {
    currentMarker = marker;
    marker.openInfoWindowHtml(marker.html);
  });

  if(ind==0) marker.openInfoWindowHtml(marker.html);
  return marker;
}

function zoomToAll() {
  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

function setIcon(tipo) {
  var icon = new GIcon();
  if(tipo=='teatro') {
    icon.image = "/public/img/marker_theater.png";
  } else if(tipo=='museo') {
    icon.image = "/public/img/marker_museum.png";
  } else if(tipo=='chiesa') {
    icon.image = "/public/img/marker_church.png";
  } else if(tipo=='fontana') {
    icon.image = "/public/img/marker_fountain.png";
  } else if(tipo=='monumento') {
    icon.image = "/public/img/marker_monument.png";
  } else if(tipo=='ristorante') {
    icon.image = "/public/img/marker_restaurant.png";
  } else if(tipo=='shopping') {
    icon.image = "/public/img/marker_shop.png";
  } else if(tipo=='stazione_ferroviaria') {
    icon.image = "/public/img/marker_train.png";
  } else if(tipo=='autobus') {
    icon.image = "/public/img/marker_bus.png";
  } else if(tipo=='porto') {
    icon.image = "/public/img/marker_port.png";
  } else {
    icon.image = "/public/img/marker_default.png";  
  }
  icon.iconAnchor = new GPoint(16, 32);
  icon.infoWindowAnchor = new GPoint(32, 0);
  icon.iconSize = new GSize(32, 37);

  return icon;
}

function geocode(indirizzo){
  geocoder = new GClientGeocoder();
  geocoder.getLocations(indirizzo, addToMap);
}

function addToMap(response) {
  place = response.Placemark[0];

  //point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
  coords = {lat:place.Point.coordinates[1], lng:place.Point.coordinates[0]}
  alert('1. '+coords.lat);
  return coords;
}
