
var map, bounds, blue_icon, yellow_icon;

function reset_map_bounds() {
  map.setZoom(map.getBoundsZoomLevel(bounds));
  map.setCenter(bounds.getCenter());
}

function open_info(id, marker) {
  ifrm = document.createElement("iframe");
  ifrm.setAttribute("src", info_url + id);
  ifrm.style.height = 400+"px";
  ifrm.style.border = "0";
  // Damn IE non-conformant case-sensitive nonsense
  ifrm.setAttribute("frameBorder", "0");
  marker.openInfoWindow(ifrm);
}

function update_location(id, lat, lng) {
  url = setloc_url + id + "?lat=" + lat + "&lng="+lng;
  req = GXmlHttp.create();
  req.open("GET", url, true);
  req.onreadystatechange = function() {
    if (req.readyState == 4) {
      if (req.status != 200) {
        alert("Error updating photo position: " + req.responseText);
      }
    }
  };
  req.send(null);
}

function add_point(lat, lng, id, title, open_it, blue) {
  var point, marker, this_icon;
  point = new GLatLng(lat, lng);
  if (blue) {
    this_icon = blue_icon;
  } else {
    this_icon = yellow_icon;
  }
  if (admin) {
    marker = new GMarker(point, {"title": title, icon: this_icon,
                                 draggable: true});
  } else {
    marker = new GMarker(point, {"title": title, icon: this_icon});
  }
  marker.photo_id = id;
  map.addOverlay(marker);
  GEvent.addListener(marker, "click", function() { open_info(id, marker); });
  if (open_it) { open_info(id, marker); }
  bounds.extend(point);
  if (admin) {
    GEvent.addListener(marker, "dragstart", function() {
      map.closeInfoWindow();
    });
    GEvent.addListener(marker, "dragend", function() {
      update_location(marker.photo_id, marker.getLatLng().lat(),
                      marker.getLatLng().lng());
    });
  }
}

function create_map(focus) {
  blue_icon = new GIcon(G_DEFAULT_ICON);
  blue_icon.image = "http://www.andy-pearce.com/album/images/flag_blue.png";
  blue_icon.shadow = "http://www.andy-pearce.com/album/images/flag_shadow.png";
  blue_icon.iconSize = new GSize(32, 32);
  blue_icon.shadowSize = new GSize(32, 32);
  blue_icon.infoWindowAnchor = new GPoint(10, 14);
  blue_icon.iconAnchor = new GPoint(4, 30);
  blue_icon.transparent = "http://www.andy-pearce.com/album/images/flag_transparent.png";
  blue_icon.imageMap = [2,2, 12,6, 20,4, 20,15, 12,17, 5,15, 5,30, 2,30];
  yellow_icon = new GIcon(blue_icon);
  yellow_icon.image = "http://www.andy-pearce.com/random/flag_yellow.png";
  map = new GMap2(document.getElementById("map_canvas"));
  bounds = new GLatLngBounds();
  if (focus == null) {
    map.setCenter(new GLatLng(0, 0), 1);
  } else {
    map.setCenter(focus, 16);
  }
  map.setMapType(G_HYBRID_MAP);
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  map.enableScrollWheelZoom();
  map.disableDoubleClickZoom();
}


