
var wpid=false, prev_lat, prev_long, min_speed=0, max_speed=0, min_altitude=0, max_altitude=0, distance_travelled=0, min_accuracy=150, date_pos_updated="", info_string="", pos_accuracy=0;

//will use geolocaton to make a call and get nearby places to current device
function processNearBy(){
	if (navigator.geolocation) {  
      /* geolocation is available */  
	  wpid = navigator.geolocation.watchPosition(geo_success, geo_error, {enableHighAccuracy:true, maximumAge:30000, timeout:27000});
    } else {  
      $('near_me').innerHTML = "I'm sorry, but geolocation services are not supported by your browser. Try <a href=\"bars.aspx\">searching.</a>";  
    }  
}

// This is the function which is called each time the Geo location position is updated
function geo_success(position)
{
	info_string="";
	var d=new Date(); // Date object, used below for output messahe
	var h=d.getHours();
	var m=d.getMinutes();
	var s=d.getSeconds();
		
	var current_datetime=format_time_component(h)+":"+format_time_component(m)+":"+format_time_component(s);
		
	// Check that the accuracy of our Geo location is sufficient for our needs
	if(position.coords.accuracy<=min_accuracy)
	{
		// We don't want to action anything if our position hasn't changed - we need this because on IPhone Safari at least, we get repeated readings of the same location with 
		// different accuracy which seems to count as a different reading - maybe it's just a very slightly different reading or maybe altitude, accuracy etc has changed
		if(prev_lat!=position.coords.latitude || prev_long!=position.coords.longitude)
		{
			if(position.coords.speed>max_speed)
				max_speed=position.coords.speed;
			else if(position.coords.speed<min_speed)
				min_speed=position.coords.speed;
				
			if(position.coords.altitude>max_altitude)
				max_altitude=position.coords.altitude;
			else if(position.coords.altitude<min_altitude)
				min_altitude=position.coords.altitude;
						
			prev_lat=position.coords.latitude;
			prev_long=position.coords.longitude;
			
			pos_accuracy = Math.round(position.coords.accuracy, 1);
						
			info_string="Current positon: lat="+position.coords.latitude+", long="+position.coords.longitude+" (accuracy "+Math.round(position.coords.accuracy, 1)+"m)<br />Speed: min="+(min_speed?min_speed:"Not recorded/0")+"m/s, max="+(max_speed?max_speed:"Not recorded/0")+"m/s<br />Altitude: min="+(min_altitude?min_altitude:"Not recorded/0")+"m, max="+(max_altitude?max_altitude:"Not recorded/0")+"m (accuracy "+Math.round(position.coords.altitudeAccuracy,1)+"m)<br />last reading taken at: "+current_datetime;
			$('near_me').innerHTML = ($('near_me').innerHTML.length < 10) ? "Please wait while we search whats near you..." : $('near_me').innerHTML;
			//now make ajax call with positino info and get things close
			new Ajax.Request("/ajax.aspx", { 'parameters': { 'lat': position.coords.latitude, 'lon': position.coords.longitude, 'action': 'get_near_me' }, 'onComplete': ProcessAjaxNearMe });	
		}
	}
	else{
		//info_string="Accuracy not sufficient ("+Math.round(position.coords.accuracy, 1)+"m vs "+min_accuracy+"m) - last reading taken at: "+current_datetime + ". <a href=\"bars.aspx\">Click here to search.</a>";
		info_string="We were unable to pin-point your location. <a href=\"bars.aspx\">Click here to search.</a>";
		$('near_me').innerHTML = info_string;
	}
}


function ProcessAjaxNearMe(http, json)
{
	// the js from this response contains variables
	var str = http.responseText;
	//alert(str);
	if (!isError(str)) 
	{
		if (doParse(str))
		{
			str = str.replace("<status>1</status>", "");
			$('near_me').innerHTML = str + "<br/><i>Distance is accurate within "+pos_accuracy+" meters</i>";		
		}
		else{
			$('near_me').innerHTML = 'Nothing was found near you. Try <a href="bars.aspx">searching.</a>';
		}
	}
	else
	{
		$('near_me').innerHTML = 'Error trying to compute results. Try <a href="bars.aspx">searching.</a>';
	}
}


// This function is called each time navigator.geolocation.watchPosition() generates an error (i.e. cannot get a Geo location reading)
function geo_error(error)
{
	$('near_me').innerHTML = error.code;
}

// This function just adds a leading "0" to time/date components which are <10 (because there is no cross-browser way I know of to do this using the date object)
function format_time_component(time_component)
{
	if(time_component<10)
		time_component="0"+time_component;
	else if(time_component.length<2)
		time_component=time_component+"0";
		
	return time_component;
}


function isError(str)
{
	if (str.indexOf('<status>0</status>') >= 0)
		return true;
}

function doParse(str)
{
	if (str.indexOf('<status>1</status>') >= 0)
		return true;
}

