//Default search radius
var radius = 10;

//This will help us parse URL parameters
jQuery.query = function(s) {
  var r = {};
  if (s){
    var q = s.substring(s.indexOf('?')+ 1);
    q = q.replace(/\&$/,'');
    jQuery.each(q.split('&'), function(){
      var splitted = this.split('=');
      var key = splitted[0];
      var val = splitted[1];
      if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
      if (val == 'true') val = true;
      if (val == 'false') val = false;
      if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
    });
  }
  return r;
};

function showMessage(message){
  $("#messagetext").html(message);
  $("#message").slideDown(500);
}

function hideMessage(){
  $("#message").slideUp(500);
}
  //Let's us default to HTML5 geolocation, but
  //will fallback to Google Gears if it is installed
function getLocationProvider()
{
	if (navigator.geolocation) return navigator.geolocation;
			var geo = google.gears.factory.create('beta.geolocation');
	if (geo) return geo;
}

//This function actually loads tweets to the display
function loadTweets(latitude, longitude){
  jQuery.getJSON("http://search.twitter.com/search.json?geocode=" + latitude + "," + longitude + "," + radius + "mi&callback=?",
    function(data){
   	 		$.each(data.results, function(i,item){
    		  $("#tweets ul").append("<li class=\"tweet\">"
			      + "<span class=\"profileimage\">"
			      + "<img src=\"" +  item.profile_image_url + "\" alt=\"userimage\" />"
			      + "</span>"
			      + "<span class=\"status\">"
			      + "<span class=\"username\">" + item.from_user + ": </span>"
			      + "<span class=\"text\">" + item.text + "</span>"
			      + "</span>"
			      + "</li>"
			    );
    		});
    	hideMessage();
  		});
}

//The Callback function that the getJSON async request will call
function success(position){	
  console.info(position.coords.latitude);
  console.info(position.coords.longitude);	
  showMessage("Loading Tweets");
  loadTweets(position.coords.latitude,position.coords.longitude);
}

$(document).ready(function(){
	//The first bit of work that gets done.  
	//First, let's see if the default radius has been changed
	var userRad = $.query(window.location.search);
	if (userRad["radius"])
	  radius = userRad["radius"];
	//Next, we get a location provider (either HTML5 or Gears for now)
	var myGeo = getLocationProvider();
	if (myGeo == null) {
	    //This little error message doesn't work for most browsers, as they
	    //stop executing this JS once they don't see Google (if HTML5 geo isn't available)
		$("#tweets").html("Your device doesn't support location services.");
	}
	else {
	    //Create the actual call to the geolocation service.
		showMessage("Getting Location")
		myGeo.getCurrentPosition(success);
	}
 });