
	/*
	 * Get today's date
	 */
	function today() {
		return $.datepicker.formatDate('dd/M/yy', new Date());
	}
	
	/*
	 * Build the where clause
	 */
	function buildWhere() {
		var where = '';
		
		/*
		 * From
		 */
		var start = $('#startDate').val();
		if (start == null || start.length == 0) {
			start = today();
		}
		where = where + "'Date 1' > '"+start+"'";
		
		/*
		 * To
		 */
		var end = $('#endDate').val();
		if (end) {
			if (where.length > 0) {
				where =  where + " and ";
			}
			
			where = where + "'Date 1' < '"+end+"'";
		}
		
		/*
		 * Distance slider
		 */
		var minDist = $( "#slider-range" ).slider( "values", 0 );
		where = where + " and 'Distance (km)' >= "+minDist;
		
		var maxDist = $( "#slider-range" ).slider( "values", 1 );
		where = where + " and 'Distance (km)' <= "+maxDist;
		
		/*
		 * Event name check boxes
		 */
		var events = $('#filter input[name=eventName]:checked').map(function(i, n){
			return "'" + $(n).val() + "'";
		}).get().join(',');
		
		if (events.length == 0) {
			events = "''";
		}
		
		where = where + " and 'Company' IN (" + events + ")";
		
		//console.log("where clause="+where);
		
		return where;
	};
	
	/*
	 * Update the map
	 */
	function updateMap(layer, tableId, locationColumn) {
		layer.setOptions({
          query: {
            select: locationColumn,
            from: tableId,
            where: buildWhere()
          }
        });
	};
	
	function addEventsList() {
		var companies = [
			'Camp Pendleton Mud Run'
			,'Dirty Girl'
			,'Gladiator Rockn Run'
			,'Go Ruck Challenge'
			,'Go Ruck Scavenger Hunt'
			,'Hero Rush'
			,'Hoppin Mad Mud Run'
			,'Irvine Lake Mud Run'
			,'Loose Wheels'
			,'Mad Mountain Mud Run'
			,'Madison Mud Run'
			,'Merrell Down and Dirty Mud Run'
			,'Metro Dash'
			,'Mud Crusade'
			,'Primal Mud Run'
			,'Racing Humans'
			,'Ragin Warrior'
			,'Rugged Maniac'
			,'Run For Your Lives'
			,'RunAmuck'
			,'San Diego Mud Run'
			,'SBSD Mud Run'
			,'Spartan Race'
			,'Survivor Mud Run'
			,'Swamp Dash and Bash'
			,'The Dirty Dash'
			,'Tough Mudder'
			,'Tundra Challenge'
			,'UltiFit Challenge'
			,'Ultimate Mud Run'
			,'Warrior Dash'
			,'Zombie Race'
		];
		
		var html = '<ul id="events-list" class="unstyled">';
		for (var i=0; i<companies.length; i++) {
			html += ''
			+'<li>'
	      	+'<label><input name="eventName" type="checkbox" checked="checked" class="event" value="'+companies[i]+'" />'
	      	+'<span class="not-bold">'+companies[i]+'</span>'
	      	+'</label>'
	      	+'</li>';
	      	console.log(html);
		}
		html += '</ul>';
		$('#events-container').append(html);
	}
	
	$(function() {
		var tableId = 2497296;
        var locationColumn = 'Location';
        var distMin = 0;
        var distMax = 150;
		
		//addEventsList();
	    
	    $('#startDate').change(function(){
	    	updateMap(layer, tableId, locationColumn);
	    });
		
		$('#startDate').datepicker({
			numberOfMonths: 2,
			showOtherMonths: true,
			selectOtherMonths: true
		});
		
		$( "#slider-range" ).slider({
			range: true,
			min: distMin,
			max: distMax,
			values: [ distMin, distMax ],
			step: 5,
			slide: function( event, ui ) {
				$( "#distanceAmount" ).text( ui.values[ 0 ] + " km - " + ui.values[ 1 ]+" km" );
			},
			change: function( event, ui ) {
				updateMap(layer, tableId, locationColumn);
			}
		});
		$( "#distanceAmount" ).text( $( "#slider-range" ).slider( "values", 0 ) + " km - " 
				+ $( "#slider-range" ).slider( "values", 1 ) +" km" );
		function resetSlider() {
			$( "#slider-range" ).slider( "values", 0, distMin );
			$( "#slider-range" ).slider( "values", 1, distMax );
			$( "#distanceAmount" ).text( distMin + " km - " + distMax+" km" );
			
		}
		
		$('input[name=eventName]').click(function(){
			updateMap(layer, tableId, locationColumn);
		});
		
		$('#reset').click(function(){
			resetSlider();
			
			updateMap(layer, tableId, locationColumn);
		});
		
		$('#events-container a').click(function(){
			var bool = $(this).text() === 'All';
			
			$('input[name=eventName]').attr('checked', bool);
			
			updateMap(layer, tableId, locationColumn);
		});
		
	    var map = new google.maps.Map(document.getElementById('map-canvas'), {
	      center: new google.maps.LatLng(37.0625,-95.677068),
	      zoom: 4,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    });
	    
	    var layer = new google.maps.FusionTablesLayer({
	      query: {
	        select: locationColumn,
	        from: tableId,
	        where: buildWhere()
	      },
	      map: map
	    });

		function html5GeoSuccess(position) {
			var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			map.setCenter(latlng);
			map.setZoom(7);
		};
		
		if (navigator.geolocation) {
		  navigator.geolocation.getCurrentPosition(html5GeoSuccess);
		};
	});
