
// Location
//
var Location = {
	
	map: '',
	
	get_places:	function() {
	
		var bounds = Location.map.getBounds();
		var southWest = bounds.getSouthWest();
	  var northEast = bounds.getNorthEast();
		
		$.get(url.base+'ajax/search/places', 
					{latitude: southWest.lat()+','+northEast.lat(), longitude: southWest.lng()+','+northEast.lng()}, 
					function(places) { Location.mark_places(places); }, 
					'json');

	},
	
	mark_places: function(places) {
	
	  for (var i in places) {	
			var point = new google.maps.LatLng(places[i].latitude, places[i].longitude);
		 	var marker = new google.maps.Marker({
				position:	point,
				map: Location.map,
				title: places[i].title
			});
			Location.add_marker_event(marker);	
		}	
	
	},
	
	add_marker_event: function(marker) {
		google.maps.event.addListener(marker, 'click', function(event) {
			Location.get_leagues_from_marker(marker);
		});	
	},
	
	get_leagues_from_marker: function(marker) {
	
		var position  = marker.getPosition();
		var latitude  = position.lat();
		var longitude = position.lng();

		$('#leagues_places h2').html(marker.title);
		$('#leagues_places ul').html('');
		$('#leagues_places ul').hide();
		$('#leagues_places img').show();	
		$('#leagues_places').show();
		
		$.get(url.base+'ajax/search/leagues',
					{latitude: latitude, longitude:	longitude},
					function(leagues) { Location.show_leagues_from_marker(leagues); },
					'json');		

	},
	
	show_leagues_from_marker:	function(leagues) {	
	
		$('#leagues_places img').hide();
	
		for (var i in leagues) {	
			$('#leagues_places ul').append('<li><a class="avatar_small" href="'+url.base+leagues[i].permalink+'"><img src="'+leagues[i].logo+'" alt="" /></a><h3><a href="'+url.base+leagues[i].permalink+'" title="'+leagues[i].description+'">'+leagues[i].title+'</a></h3></li>');
		}
	
		$('#leagues_places ul').show();	
		$('#leagues_places').focus();
	
	}	

};
	
/**
 * Location
 */
	
$(document).ready(function() {
	
	if (document.getElementById('map') != null) {
	
   	var myOptions = {
  	  mapTypeId: google.maps.MapTypeId.ROADMAP,
  		mapTypeControl: false		
  	};
    Location.map = new google.maps.Map(document.getElementById("map"), myOptions);

  	// zoom to current location
  	if (navigator.geolocation) {  
  		navigator.geolocation.getCurrentPosition(function(position) {
  		  Location.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
  			Location.map.setZoom(11);
  	 	});
  	} else {
  		  Location.map.setCenter(new google.maps.LatLng(34, 0));
  			Location.map.setZoom(2);	
  	}
		
  	google.maps.event.addListener(Location.map, 'bounds_changed', function() {
  		Location.get_places();
  	});
	
	}
	
  $('form input.city').focus(function() {
	  $(this).val('');
	});

	City.applyAutoComplete();  
		
});

