var map;
var mgr;
var icons = {};
var allmarkers = [];

function gmap_initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(30,150), 1);
    map.setUIToDefault();

    mgr = new MarkerManager(map, {trackMarkers:true});
    window.setTimeout(setupOfficeMarkers, 0);
  }
}

 
function getIcon(images) {
  var icon = null;
  if (images) {
    if (icons[images[0]]) {
      icon = icons[images[0]];
    } else {
      icon = new GIcon();
      icon.image = "/gmaps/images/" + images[0] + ".png";
      var size = iconData[images[0]];
      icon.maxHeight = 0;
      icon.iconSize = new GSize(size.width, size.height);
      coordinate_x = size.width >> 1;
      coordinate_y = size.height >> 1;
      if(images[0] == 'pin' ){ // pin 36x36
        coordinate_x = 21;
        coordinate_y = 33;
      }
      icon.iconAnchor = new GPoint(coordinate_x, coordinate_y);
      icon.infoWindowAnchor = new GPoint(coordinate_x, coordinate_y);
      if(images[1]){
        icon.shadow = "/gmaps/images/" + images[1] + ".png";
        size = iconData[images[1]];
        icon.shadowSize = new GSize(size.width, size.height);
      }
      icons[images[0]] = icon;
    }
  }
  return icon;
}

function setupOfficeMarkers() {
  allmarkers.length = 0;
  for (var i in officeLayer) {
    var layer = officeLayer[i];
    var markers = [];
    for (var j in layer["places"]) {
      var place = layer["places"][j];
      var icon = getIcon(place["icon"]);
      var title = place["name"];
      var info = place["info"];
      var posn = new GLatLng(place["posn"][0], place["posn"][1]);
      var marker = createMarker(posn,title,icon,info); 
      markers.push(marker);
      allmarkers.push(marker);
    }
    mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
  }
  mgr.refresh();
}

function createMarker(posn, title, icon, info) {
  var marker = new GMarker(posn, {title: title, icon: icon, draggable: false });
  GEvent.addListener(marker, 'click', function() {marker.openInfoWindowHtml(info, {maxWidth:50}); } );  
  return marker;
}
