/*
Thanks to Ben Marsh at uksnow.benmarsh.co.uk 
and .net Magazine!

Gavin Sayce:
- Improved handling of second load
- Combined Tweets at single location
*/

var abertweets={
				  map:null,
				  query:'?=',
				  tweets:[],
				  geocode:null,
				  queue:[],
					aberLatLng:null,
					arrTweetMarkers:[],
					datNow:null
};

var now=new Date();
var yesternow=new Date(now.getFullYear(), now.getMonth(), now.getDate()-1);
abertweets.datNow=yesternow.getFullYear() + "-" + (addZero(yesternow.getMonth()+1)) + "-" + (addZero(yesternow.getDate()));

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

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

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

	function centreMap(latLng) {
		abertweets.map.setCenter(latLng,9);
	}
	
	getTweets();
}

function generateSearchUrl() {
	//var center=abertweets.map.getCenter();
	//only get aber tweets
	return 'http://search.twitter.com/search.json' + abertweets.query + '&geocode=' + abertweets.aberLatLng.lat() + '%2C' + abertweets.aberLatLng.lng() + '%2C40km&rpp=100' + '&since=' + abertweets.datNow + '&callback=?';
}

function getTweets() {
	$.getJSON(generateSearchUrl(), function(data) {
											if(data.results) {
												$.each(data.results,function(i,tweet) {
																		//strip out any tweets with location matching *-town
																		var loc=tweet.location;
																		regex=/[a-zA-Z]-town/gi;
																		if(loc!=undefined && loc!=null && regex.test(loc)) { return;}
																		if(tweet.geo||tweet.location){
																				abertweets.queue.push(tweet);
																			 } //end else
																			 
																			 });
											}
											abertweets.query=data.refresh_url;
						});
}

function processQueue() {
	if(abertweets.queue.length>0)
	{
		var tweet=abertweets.queue.pop();
			 if(tweet.geo) {
											 tweet.latlng=new GLatLng(tweet.geo.coordinates[0],tweet.geo.coordinates[1]);
											 plotTweet(tweet);
										 }
										 else if (isGPSLocation(tweet.location))
										 {
													//iPhone: 51.858963,-2.972570
													var ilat=tweet.location.substring(tweet.location.indexOf(": ")+2,tweet.location.indexOf(","));
													var ilng=tweet.location.substring(tweet.location.indexOf(",")+1,tweet.location.length);
													tweet.latlng=new GLatLng(ilat,ilng);
													plotTweet(tweet);
													
										 }
										 else if (isAberLocation(tweet.location))
										 {
												tweet.latlng=abertweets.aberLatLng;
												plotTweet(tweet);
										 }
										 else {
											abertweets.geocoder.getLatLng(tweet.location,function(latlng)
											{
													 if(latlng)
													 {
														 tweet.latlng=latlng;
														 plotTweet(tweet);
													 }
											});
										 }
	}
}

function plotTweet(tweet) {
	
	tweet.html='<div class="tweetitem"><img alt="*" src="' + tweet.profile_image_url +'" /><h3><a href="http://www.twitter.com/' + tweet.from_user + '">'+tweet.from_user+'</a></h3><p>' + cleanText(tweet.text) + '</p></div>';
	
	var newTweet=tweet;
	newTweet.marker=new GMarker(newTweet.latlng);
	
	var tmpHTML='';
	var markerExists=false;
	
	if(abertweets.arrTweetMarkers[newTweet.latlng]==undefined)
	{
		//add marker to array
		abertweets.arrTweetMarkers[newTweet.latlng]=newTweet.html;
	}
	else {
		//marker already exists
		markerExists=true;
		abertweets.arrTweetMarkers[newTweet.latlng]=newTweet.html + abertweets.arrTweetMarkers[newTweet.latlng];
		//add to marker array or update with additional HTML.
	}

		
	GEvent.addListener(newTweet.marker,'click',function() {
													 newTweet.marker.openInfoWindowHtml('<div class="tweetpopup">' +abertweets.arrTweetMarkers[newTweet.latlng] +'</div>');
													 });
	
	
	abertweets.tweets.push(newTweet);
	if(!markerExists)
	{
		abertweets.map.addOverlay(newTweet.marker);
	}

	if(abertweets.tweets.length>100)
	{
		//should only remove HTML here, then remove marker if this it the last tweet being removed...
		//TBD! Each Tweet has an ID...
		var tweet=abertweets.tweets.shift();
		
		if (abertweets.arrTweetMarkers[tweet.latlng]==tweet.html)
		{
			abertweets.map.removeOverlay(tweet.marker);
		}
		//else remove HTML from arrTweetMarkers
		else {
			abertweets.arrTweetMarkers[tweet.latlng]=abertweets.arrTweetMarkers[tweet.latlng].replace(tweet.html,'');
		}
	}
}
	
function isAberLocation(location)
{
	strLCLocation=location.toLowerCase();
	if(strLCLocation.indexOf("abergavenny")>-1)
	{
			return true;
	}
	return false;
}

function isGPSLocation(location)
{
	strLCLocation=location.toLowerCase();
	if(strLCLocation.indexOf("iphone: ")==0)
	{
		return true;
	}
	else if (strLCLocation.indexOf("ÜT: ")==0)
	{
		return true;
	}
		return false;
}
	
function cleanText(str)
{
	str=str.replace(/fuck/gi, "f*ck");
	str=str.replace(/shit/gi,"sh*t");
	str=str.replace(/cunt/gi,"c*nt");
	return str;
}
	
	  var publisher_id = "pub-6819924471474574";
	  
	  var mapOptions = {
		googleBarOptions : {
		  style : "new",
		  adsOptions: {
			client: publisher_id,
			channel: '7895482311',
			adsafe: "high",
			language: "en"
		  }
		}
		}


function setupMapAds() {
		abertweets.map.enableGoogleBar();


		var adsManagerOptions = {
		  maxAdsOnMap : 3,
		  style: 'adunit',
		  // The channel field is optional - replace this field with a channel number 
		  // for Google AdSense tracking
		  //channel: 'your_channel_id'  
			channel:'6244317665'
		};
		
		adsManager = new GAdsManager(abertweets.map, publisher_id, adsManagerOptions);
		adsManager.enable();
}
		
		
	
