var map;
var latlngs = {
  rockdale : new GLatLng(-33.950596, 151.139120),
  kogarah : new GLatLng(-33.963286, 151.133938),
  milton : new GLatLng(-35.315616, 150.434887),
  cessnock: new GLatLng(-32.839699, 151.35585)
};
var markers = {};

$(function() {
  // First, add the links to all sections
  $('.venue_title').wrapInner('<a></a>').children()
    .each(function(i, elem) {
      var venue = $(elem).parents('.venue').attr('id').substring(2);
      var func = function() { showVenue(venue); };
      $(elem).attr('href', '#' + venue).click(func);
    });

  // Create the map div.
  $('#sMain').append('<div class="map"></div>');
  map = new GMap2($('.map').get(0));

  // Set up the map.
  map.setCenter(latlngs['rockdale'], 15);
  map.addControl(new GSmallMapControl());
  map.addControl(new GHierarchicalMapTypeControl());
  map.enableGoogleBar();

  // Add the markers to the map.
  for (var venue in latlngs) {
    makeMarker(venue);
  }

  // Now, see what we have.
  var href = window.location.toString();
  var hash_loc = href.indexOf('#');
  var venue = 'rockdale';
  if (hash_loc > 0) {
    venue = href.substring(hash_loc + 1);
  }
  $(window).load(function() { showVenue(venue); });
  $('.venue').not('#v_' + venue).children('.venue_detail').hide();
});


function makeMarker(venue) {
  // Get the map centre, and move the map there.
  var centre = latlngs[venue];

  // Get a description for the marker / info window.
  var title = $('#v_' + venue).children('.venue_title').text();
  var details = $('#v_' + venue).children('.venue_detail').html();

  // Create the marker and store.
  var options = { title : title };
  var marker = new GMarker(centre, options);
  map.addOverlay(marker);
  marker.bindInfoWindowHtml('<p><strong>' + title + '</strong><br/>' +
      details + '</p>');
  markers[venue] = marker;
}


function showVenue(venue) {
  // Get the map centre, and move the map there.
  var centre = latlngs[venue];
  if (! centre) {
    centre = latlngs['rockdale'];
    venue = 'rockdale';
  }
  map.setCenter(centre);

  // Show only the sections we care about.
  $('.venue').not('#v_' + venue).children('.venue_detail').hide();
  $('#v_' + venue).children('.venue_detail').show();

  // Now highlight the marker.
  marker = markers[venue];
  var title = $('#v_' + venue).children('.venue_title').text();
  var details = $('#v_' + venue).children('.venue_detail').html();
  var options = { title : title };
///  marker.openInfoWindowHtml('<p><strong>' + title + '</strong><br/>' +
///      details + '</p>');
  GEvent.trigger(marker, 'click');
}