var map, icon;
var geocoder = new GClientGeocoder();
var query = '?q=%23ukheat';
var tweets = new Array();

$(document).ready(function() {
	$.ajaxSetup({ 
		timeout: 10000,
		error: function(xhr, status, err){ 
			$('#status').text('Update failed...').oneTime('2s', function() { 
				$(this).fadeOut('slow');
			});
		}
	}); 
	gmapsLoad();
	getTweets();
	$(document).everyTime('30s', getTweets);
	$(document).everyTime('300ms', processTweets);
});		

function gmapsLoad() {
	if (GBrowserIsCompatible()) {
		var mapOptions = { googleBarOptions: { style: 'new' } }
		map = new GMap2(document.getElementById('map'), mapOptions);
		map.setMapType(G_HYBRID_MAP);
		map.setCenter(new GLatLng(54.8, -3), 6);
		map.addControl(new GLargeMapControl3D());
		map.addControl(new GMapTypeControl());
		map.enableGoogleBar();
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		
		icon = new GIcon(G_DEFAULT_ICON);
		icon.shadow = '';
		icon.iconSize = new GSize(32, 32);
		icon.iconAnchor = new GPoint(16, 16);
	}
}  

function getTweets() {
	$('#status').text('Updating...').fadeIn('slow');
	$.getJSON('http://search.twitter.com/search.json'+query+'&rpp=100&callback=?', function(data) {
		$.each(data.results, function(i, tweet) {
			var found = tweet.text.match('#ukheat ([A-Za-z]{1,2}[0-9][A-Za-z0-9]?) ([0-9]{1,2})');
			if (found) {
				tweet.postcode = found[1];
				tweet.score = found[2];
				if (tweet.score > 40) tweet.score = Math.Round(((tweet.score - 32)/9)*5); // Convert °C to °F
			}
			tweets.push(tweet);
			tweets.sort(sortTweets);
		});
		query = data.refresh_url;
		$('#status').text(data.results.length+' new tweet'+((data.results.length==1) ? '' : 's')+' found...').oneTime('2s', function() { $(this).fadeOut('slow'); });
	});	
}

function sortTweets(x, y) {
	return y.id - x.id;
}

function processTweets() {
	if (tweets.length > 0) {
		var tweet = tweets.pop();
		
		var urls = tweet.text.match(/http\S+/ig);
		if (urls) {
			for (u = 0; u < urls.length; u++) {
				var url = urls[u];
				var atext = (url.length > 30) ? url.substr(0, 27)+'...' : url;
				var a = '<a href="'+url+'" target="_blank">'+atext+'</a>';
				tweet.text = tweet.text.replace(url, a);
			}
		}
		
		var twitpic = tweet.text.match('http://(www\.)?twitpic.com/[0-9a-z]{5}');
		
		if (tweet.postcode) {
			var search = tweet.postcode.toUpperCase() + ', UK';
			geocoder.getLatLng(search, function(point) {
				if (point) {
					if (tweet.score > 29) {
						icon.image = "6.png";
					} else if (tweet.score > 27) {
						icon.image = "5.png";
					} else if (tweet.score > 25) {
						icon.image = "4.png";
					} else if (tweet.score > 23) {
						icon.image = "3.png";
					} else if (tweet.score > 21) {
						icon.image = "2.png";
					} else if (tweet.score > 19) {
						icon.image = "1.png";
					} else {
						icon.image = "0.png";
					}				
					var marker = new GMarker(point, { icon: icon });
					GEvent.addListener(marker, "click", function() {
						var popUpHtml = '<div class="popup"><a href="http://twitter.com/'+tweet.from_user+'" target="_blank"><img class="profilepic" height="48" src="'+tweet.profile_image_url+'" width="48" /></a><div><a href="http://twitter.com/'+tweet.from_user+'" target="_blank"><h3>'+tweet.from_user+'</h3></a>'+tweet.text;
						if (twitpic) {
							var thumbUrl = 'http://twitpic.com/show/thumb/'+twitpic[0].replace('http://www.', 'http://').substr(19);
							popUpHtml = popUpHtml + '<br/><br/><a href="'+thumbUrl+'" target="_blank"><img class="twitpic" src="'+thumbUrl+'.jpg" height="150" width="150" /></a>';
						}
						popUpHtml = popUpHtml + '</div></div>';
						marker.openInfoWindowHtml(popUpHtml);
					});
					map.addOverlay(marker);
				}
			});
		}
		var logHtml = '<a href="http://twitter.com/'+tweet.from_user+'" target="_blank"><img height="12" src="'+tweet.profile_image_url+'" width="12" /></a> ' + tweet.text;
		if (twitpic) logHtml = logHtml + ' <a href="' + twitpic[0] + '" target="_blank"><img alt="pic" src="pic.png" /></a>';
		$("#tweets").prepend("<li>" + logHtml + "</li>").children('li:first').hide().slideDown('slow');	
	}
}