var layers;
var filterMarkers = [];
var req;

var flgDownloading = false;

$(document).ready(function () {
	
	var radius = 0;
	
	// Add a "loading" element to the map and hide ready for use
	$('<div />', {
	  'id': 'gmap-loading'
	  , 'text': "Loading..."
	  , 'css': { 'display': 'none' }
	}).appendTo('#map');
	
	// Add an instruction to zoom in when displaying bus stops and hide ready 
	// for use
	$('<div />', {
	  'id': 'gmap-zoom-in-instruction'
	  , 'text': "Please zoom in on the map to view local bus stops"
	  , 'css': { 'display': 'none' }
	}).appendTo('#map');
	
	// Add an instruction to zoom in when displaying bus stops and hide ready 
	// for use
	$('<div />', {
	  'id': 'gmap-zoom-out-instruction'
	  , 'text': "You may need to zoom out to view all the selected locations on the map"
	  , 'css': { 'display': 'none' }
	}).appendTo('#map');
	
	$("#featured_layers input[type=checkbox].marker").bind("click", function () {
		
		// If the bus stops button is activated, automatically zoom in on the map
		if ($(this).val()==3 && $(this).attr('checked')==true) { map.setZoom(15); }
		
		fetchFilteredMarkers();

	});
	
	// On page load, reset the buttons
	$('form#featured_layers input').removeAttr('checked');
	// Make checkbox labels work like on/off buttons by toggling the active class
	$('form#featured_layers label').click(function(){
	  $(this).hasClass('active') ? $(this).removeClass('active') : $(this).addClass('active');
	});
	
	// Fetch new markers when the map is dragged or zoomed
	GEvent.addListener(map, "dragend", function () {	
			fetchFilteredMarkers();
	});
	GEvent.addListener(map, "zoomend", function () {	
			fetchFilteredMarkers();
	});
	
	
});

function fetchFilteredMarkers(lat, lng, radius) {
  
  // Get the current zoom level for the map
  var zoom = map.getZoom();

  // Select the filter radius based on current zoom level
  if (zoom>14) {
    radius = 0.5;
  } else if (zoom>12) {
    radius = 5;
  } else {
    radius = 30;
  }
  
  lat = map.getCenter().lat();
  lng = map.getCenter().lng();

	// hide any current markers	
	if ($("#featured_layers input:checked").length == 0) {
		clearMarkers();
	}
	else {

	  /* Add a loading indicator to the map to show user something is happening */
	  $('#gmap-loading').show();
		
		// load all new markers apart from bus stops
		var layerData = $("#featured_layers").serialize();
		
		// Is the bus stop button active?
		var bus = ($('#busStops-filter').attr('checked')==true) ? true : false;
		
		// If we're working with bus stops inform the user that they will need to 
		// zoom in on the map to view them.
		if (bus==true && zoom<=14) {
		  $('#gmap-zoom-out-instruction').hide(); 
		  $('#gmap-zoom-in-instruction').fadeIn('slow');
		} else { 
		  $('#gmap-zoom-in-instruction').hide();
		  $('#gmap-zoom-out-instruction').hide(); 
		  if (zoom>14 
		  && $("#featured_layers input[id!='busStops-filter']:checked").length!=0) {
		    $('#gmap-zoom-out-instruction').fadeIn('slow');
		  }
		}
		
		if (req !== undefined) {
			req.abort();
		}
		
		req = $.ajax({
			url: rootUrl + "locations/filter/" + lat + "/" + lng + "/" + radius,
			data: layerData,
			type: "POST",
			cache: false,
			dataType: "json",
			success: function(data) {
			
				if (data !== null) {
					clearMarkers();
				
					// show filter markers
					var len = data.length; 					
				
				  for(var i = 0; i< len; i++) {
				
					  var location = data[i].Location;
					  
					  filterMarkers[i] = location.id;

            // Is this a bus stop?
            var stop = (location.name.toLowerCase().indexOf("bus stop") >= 0) ? true : false;

					  if (markers[location.id] == undefined && ( zoom>14 || stop==false ) ) {
						
						  var icon;
						
						  if ("" + location.icon_url == "") {
							  icon = "http://google-maps-icons.googlecode.com/files/blackblank.png";
						  }
						  else {
							  icon = location.icon_url;
						  }
						
						  markers[location.id] = addMarker({
							  'map': map,
							  'icon': icon
						  });
						

						  markers[location.id].type="known";
						  markers[location.id].id = location.id;
						
						  markers[location.id].setLatLng(new GLatLng(location.lat, location.lng));
						
					  }
					  // If not a bus stop, or zoomed in on map show the marker
					  if ( zoom>14 || stop==false ){ markers[location.id].show(); }

				  }
				}
				/* Markers loaded, removing the loading indicator */
				$('#gmap-loading').hide();
						
			},
			error: function(request, status, message) {
				alert(message);
			}
		});
				

	}
}

function clearMarkers() {

	var len = filterMarkers.length;
	
	for(var i=0; i< len; i++) {
		if (markers[filterMarkers[i]] && markers[filterMarkers[i]].hide) {
			markers[filterMarkers[i]].hide();
		}
	}
	
	filterMarkers = [];
}

