var mapCenter, cities, infoWindows = {}, map, visibleInfoWindow;

function onLoad() {
  initMap();
}

function initMap() {
  if(!GBrowserIsCompatible()) {
    return;
  }
  mapCenter = new GLatLng(60.8, 10.7);
	
  cities = {
    Moss: new GLatLng(59.4716, 10.6907),
    Frogner: new GLatLng(60.0242, 11.1018),
    Kongsberg: new GLatLng(59.6855,	9.5843),
    Risdal: new GLatLng(58.6720, 8.1288),
    Bønes: new GLatLng(60.3264, 5.2998),
    Ålesund: new GLatLng(62.4680, 6.2920),
    Trondheim: new GLatLng(63.4305, 10.3951)
  };

  map = new GMap2($("#frontpage-mapcanvas")[0]);
  map.setCenter(mapCenter);
  map.disableDragging();
  map.disableDoubleClickZoom();
  map.disablePinchToZoom();
  map.setZoom(4);
  map.setMapType(G_PHYSICAL_MAP);

  createCityMarkers();
//  createRoutes();
}

function createCityMarkers() {
  for(city in cities){
    var marker = new GMarker(cities[city], {
      title: city
    });
//    GEvent.addListener(marker, 'click', onMarkerClicked);
    map.addOverlay(marker);
  }
}

function onMarkerClicked(latlng) {
  var city = cityFromName[this.getTitle()];
  var lowerCaseCity = city.toLowerCase();
  var infoWindowPoint = new GLatLng(rygge.lat() + (latlng.lat()-rygge.lat())/2, rygge.lng() + (latlng.lng()-rygge.lng())/2);

  map.openInfoWindowTabs(infoWindowPoint, 
                         [
                           new GInfoWindowTab(infoWindowTabLabels['info'], $('#infowindow-' + lowerCaseCity + '-info').clone()[0])
                         ],
                         {onCloseFn: centerMap});
  showRouteTo(city);
  //setInfoWindowTabContentsFor(city);
}

function setInfoWindowTabContentsFor(city) {
}

function centerMap() {
  if(visibleRoute) {
    visibleRoute.hide();
  }
  map.setCenter(mapCenter);
}

function createRoutes() {
  for(city in cities) {
    var route = new GPolyline([rygge, cities[city]], "#FF0000", 8, 0.5, {clickable: false});
    route.hide();
    map.addOverlay(route);
    routes[city] = route;
  }
}

function showRouteTo(city) {
  if(visibleRoute) {
    visibleRoute.hide();
  }
  visibleRoute = routes[city];
  visibleRoute.show();
}

