var tweetsnearme = {
	map: null,
	query: '?q=',
	tweets: [],
	queue: [],
	geocoder: null
};

$(document).ready(function() {
	google.load('maps', '2.x', {'callback': mapsLoaded});
});		

function mapsLoaded() {
	if (GBrowserIsCompatible()) {
		tweetsnearme.map = new GMap2(document.getElementById('map'));
		tweetsnearme.map.addControl(new GLargeMapControl3D());
		tweetsnearme.map.addControl(new GMapTypeControl());
		$(document).everyTime('30s', getTweets);
		$(document).everyTime('100ms', processQueue);
		tweetsnearme.geocoder = new GClientGeocoder();
		findLocation();
	}
	else {
		alert('Sorry, Google Maps cannot be displayed.');
	}
}  

function findLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			centerMap(new GLatLng(position.coords.latitude, position.coords.longitude));
		});	
	}
	else if (google.loader.ClientLocation) {
		centerMap(new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude));
	}	
	else {	
		centerMap(new GLatLng(51.5, 0));
	}
}

function centerMap(latLng) {
	tweetsnearme.queue.length = 0;
	tweetsnearme.map.setCenter(latLng, 9);
	getTweets();
}

function generateSearchUrl() {
	var center = tweetsnearme.map.getCenter();
	return 'http://search.twitter.com/search.json'+tweetsnearme.query+'&geocode='+center.lat()+'%2C'+center.lng()+'%2C50km&rpp=100&callback=?';
}

function getTweets() {
	$.getJSON(generateSearchUrl(), function(data) {
		if (data.results) {
			$.each(data.results, function(i, tweet) {
				if (tweet.geo || tweet.location) {
					tweetsnearme.queue.push(tweet);
				}
			});
		}
		tweetsnearme.query = data.refresh_url;
	});	
}

function processQueue() {
	if (tweetsnearme.queue.length > 0) {
		var tweet = tweetsnearme.queue.pop();
		if (tweet.geo) {
			tweet.latlng = new GLatLng(tweet.geo.coordinates[0], tweet.geo.coordinates[1]);
			plotTweet(tweet);
		}
		else {
			tweetsnearme.geocoder.getLatLng(tweet.location, function(latlng) {
				if (latlng) {
					tweet.latlng = latlng;
					plotTweet(tweet);
				}
			});
		}
	}
}

function plotTweet(tweet) {
	tweet.marker = new GMarker(tweet.latlng);
	GEvent.addListener(tweet.marker, 'click', function() {
		tweet.marker.openInfoWindowHtml('<div class="popup"><img alt="*" src="'+tweet.profile_image_url+'" /><h3>'+tweet.from_user+'</h3><p>'+tweet.text+'</p></div>');
	});
	tweetsnearme.tweets.push(tweet);
	tweetsnearme.map.addOverlay(tweet.marker);
	if (tweetsnearme.tweets.length > 100) {
		var tweet = tweetsnearme.tweets.shift();
		tweetsnearme.map.removeOverlay(tweet.marker);
	}
}
