
var hasTheIntervalBeenSet=false;
var latitude,longitude,altitude;

document.addEventListener('DOMContentLoaded', function(){

	// Make Connection
	var socket = io();
	
	// Query DOM
	var btn = document.getElementById('send'),
	output = document.getElementById('output'),
	debug = document.getElementById('debug-info');

	// Emit Events Button
	btn.addEventListener('click',geoLocateMe);

	// Listen for Location Events
	socket.on('location', function(data){
		output.innerHTML += '<p>  '+data.lat +' , '+ data.long +' , '+ data.alt +' , id : '+ data.id +'</p>';
	});


	// listen for other new Connected Clients
	socket.on('connected', function(data){

		debug.innerHTML += '<p> new client connection id : '+data.id +'</p>';
		// alert('new client connection !' + data.id);
	});

	function geoLocateMe(){

		if(!hasTheIntervalBeenSet){
			setInterval(geoLocateMe, 500);
			hasTheIntervalBeenSet=true;
		}


		function success(position){
			// do something if geolocation succeeds
			latitude = position.coords.latitude;
			longitude = position.coords.longitude;
			altitude = position.coords.altitude;

			socket.emit('location', {
				lat: latitude,
				long: longitude,
				alt: altitude,
				id: socket.id
			});


		}


		function error(){
			// do something if geolocation fails
		}

		if(!navigator.geolocation){
			// do something if navigator not available on browser or device
			alert('not available');

		}else{
			navigator.geolocation.getCurrentPosition(success,error);
		}
	}




}, false);