var GeoLocate = function() {

  var pub = {};
  var marker = null;
  var map = null;

  pub.initMap = function() {
    map = new L.Map('map_canvas');
    var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/034786f0201a4115bfd298cce9b34cdd/997/256/{z}/{x}/{y}.png',
        cloudmadeAttrib = 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade',
        cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18, attribution: cloudmadeAttrib});
    map.addLayer(cloudmade);
    map.locateAndSetView(16);
    map.on('locationfound', setLocationDetails);
    map.on('locationerror', handleNoGeoLocation);
		map.on('click', handleMouseClick);
  }

	handleMouseClick = function(mouseData) {
		$.ajax({
      dataType: 'jsonp',
      data: "",
      jsonp: 'callback',
      url: '/postcode/' + mouseData.latlng.lat + '/' + mouseData.latlng.lng,
      success: function(data) {
        var markerLocation = new L.LatLng(mouseData.latlng.lat, mouseData.latlng.lng);
        var marker = new L.Marker(markerLocation);
        map.addLayer(marker);
        marker.bindPopup("The nearest postcode is " + data.Postcode).openPopup();
      }
    });
	}

  handleNoGeoLocation = function(error) {
    // error
    // 
    $('#map_info h4').text("Geo-location failed on your browser.");
		$('#postcode_details p:first').remove();
    var london = new L.LatLng(51.505, -0.09);
    map.setView(london, 10);
    var marker = new L.Marker(london);
    map.addLayer(marker);
    marker.bindPopup("We don't know where you are, try clicking around the map to see some postcodes.").openPopup();
  }

  setLocationDetails = function(p) {
		$.ajax({
      dataType: 'jsonp',
      data: "",
      jsonp: 'callback',
      url: '/postcode/' + p.latlng.lat + '/' + p.latlng.lng,
      success: function(data) {
        //console.log('Got postcode', data.Postcode);
        $('#postcode').text(data.Postcode);
        var markerLocation = new L.LatLng(p.latlng.lat, p.latlng.lng);
        var marker = new L.Marker(markerLocation);
        map.addLayer(marker);
        marker.bindPopup("Your postcode is " + data.Postcode + "!").openPopup();
        var radius = p.accuracy / 2;
        var circle = new L.Circle(p.latlng, radius);
        map.addLayer(circle);
      }
    });

    $('#accuracy').text(p.accuracy / 2 + ' metres.');
  }


  pub.init = function() {
    return;
  }


  return pub;

}();


$(document).ready(function() {
  GeoLocate.init();
  GeoLocate.initMap();
});

