var rygge, mapCenter, cities, routes = {}, infoWindows = {}, map, visibleRoute, visibleInfoWindow;

function onLoad() {
  initRouteMap();
}

function initRouteMap() {
  if(!GBrowserIsCompatible()) {
    return;
  }
  rygge = new GLatLng(59.397661, 10.728176);
  mapCenter = new GLatLng(52.536273, 18);

  cities = {
    Moscow: new GLatLng(55.755786, 37.617633),
    Bologna: new GLatLng(44.494219, 11.346482),
    Kiev: new GLatLng(50.457504, 30.585938),
    Paris: new GLatLng(48.856667, 2.350987),
    London: new GLatLng(51.500152, -0.126236),
    Nice: new GLatLng(43.7034273, 7.2662656),
    Milan: new GLatLng(45.4636889, 9.1881408),
    Palma: new GLatLng(39.5695059, 2.649966),
    Rome: new GLatLng(41.8954656, 12.4823243),
    Berlin: new GLatLng(52.5234051, 13.4113999)		
  };

  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: cityNames[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();
}
