//var locations = getLocations("");

function getLocations(lat, lng) {
    $.getJSON(mapLocation.replace(-5, lat).replace(-6, lng), {}, function(data) {
        initialise(data);
    });
}
var bounds;
var map;
var image;

function initialise(postcodes) {

    var center = new google.maps.LatLng(51.5081, -0.0758);
    
    var options = {
    zoom: 15,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map"), options);

    bounds = new google.maps.LatLngBounds();

    $.each(postcodes, function(i, location) {
        var latlng = new google.maps.LatLng(location.lat, location.lng);
        bounds.extend(latlng);

        setupLocationMarker(map, location, latlng);
    });

    map.fitBounds(bounds);
    google.maps.event.addListener(map, 'bounds_changed', function() {
      if ( map.getZoom() > 15 ) {
        map.setZoom(15);
      }
    }); 
  
}

function setupLocationMarker(map, location, latlng) {
    if (location == null)
        return;

    if (new String(location.maptype) == "Property")
    {
        image = new google.maps.MarkerImage('/content/images/mapred2.png',
        new google.maps.Size(18, 18),
	    new google.maps.Point(0, 0),
	    new google.maps.Point(9, 9));
    }
    else
    {
        image = new google.maps.MarkerImage('/content/images/mapblue2.png',
        new google.maps.Size(18, 18),
	    new google.maps.Point(0, 0),
	    new google.maps.Point(9, 9));
    }     
      var marker = new google.maps.Marker({
          position: latlng, 
          map: map, 
          title: location.name,
          icon: image
      });

      google.maps.event.addListener(marker, "click", function(latlng) {
          show(map, marker, location);
      });
      
}

function show(map, marker, location) {
    var image = '';
    var infowindow = new google.maps.InfoWindow(
      { content: "<h3 class=\"popup\">" + location.name + "</h3><p>" + location.address + "<br />" + location.postcode + "</p><p>Website: <a href=\"" + location.website + "\" target=\"_blank\">" + location.name + "</a></p>",
          size: new google.maps.Size(200, 200)
      });

    infowindow.open(map, marker);
}
