var mapPoints = new Object();
 
var map = '';
var gd = '';
var gc = '';
 
var selectedPoint = 0;
 
$(document).ready( function () {
 
  map = new GMap2( document.getElementById("map") );
    
  map.setCenter(new GLatLng(57.183901, 13.930664), 4);
  map.enableScrollWheelZoom();
  
  $("#map").find("span:eq(0)").hide();
 
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());  
  map.addControl(new GOverviewMapControl());
  map.setZoom(5);
 
  gc = new GClientGeocoder();
  
/* Debug?
  GEvent.addListener(map, "click", function (overlay, point) {
    if (point != undefined) alert(point);
  });
*/

  
  var show;
  $.each(mapPoints, function (id, mapPoint) {
    if (mapPoint.googlemaps) {
      show = true;
      var pnt = mapPoint.googlemaps.split(", ");
      mapPoints[id].point = new GLatLng(parseFloat(pnt[0]), parseFloat(pnt[1]));
    } 
    else {
      show = false;
      /*
      gc.getLatLng(mapPoint.address, function (gLatLng) {
        mapPoints[id].point = gLatLng;
        $("body").append( mapPoint.name +" ("+ mapPoint.address +") = "+ gLatLng +"<br />");
      });
      */
    }
    
    if (show) {
      mapPoints[id].marker = new GMarker(
        mapPoints[id].point,
        new Object({title: mapPoint.name})
      );
          
      map.addOverlay( mapPoints[id].marker );
      mapPoints[id].marker.bindInfoWindowHtml( createInfoHtml(id) );
      
      $("#show").append('<option value="'+ id +'">'+ mapPoint.name +', '+ mapPoint.city +'</option>');
    
      // Point selected, focus & show infowindow
      if (mapPoint.selected) {
        selectedPoint = id;
        map.setCenter(mapPoints[ id ].point, 14);
        setTimeout(showInfoWindow, 1000);
      }
    }
  });
  
  $(".showOnMap").each( function () {
    var id = (this.id.split("_"))[1];
    $(this).click( function () {
      var mapPoint = mapPoints[ id ];
      map.panTo(mapPoint.point);
      map.setZoom(15);
      mapPoint.marker.openInfoWindowHtml( createInfoHtml(id) );
    });
  });
    
  $("#show").change( function () {
    var id = $(this).val();
    var mapPoint = mapPoints[ id ];
    map.panTo(mapPoint.point);
    map.setZoom(15);
    mapPoint.marker.openInfoWindowHtml( createInfoHtml(id) );
  });
});

 
function showInfoWindow () {
  mapPoints[ selectedPoint ].marker.openInfoWindowHtml( createInfoHtml(selectedPoint) );
}
 
function createInfoHtml (id) {
  var mapPoint = mapPoints[id];
  var html = '';
  html += '<b>'+ mapPoint.name +'</b><br />' + mapPoint.address +'<br />';
  html += '<a href="#" onclick="javascript:map.setZoom(15)">&raquo; Zoom in</a> ';
  html += '<a href="#" onclick="javascript:map.setZoom(4)">&raquo; Zoom out</a>';
  return html;
}
 
$(window).unload( function () {
  GUnload();
});
