$(document).ready(function() {
  var start_date = '2011-08-04';
  var url = 'http://search.twitter.com/search.json?&q='+escape('#3cities')+'&since='+escape(start_date)+'&rpp=100&callback=?',
		avatar_size = 32,
		markers = new Array(),
    locations = new Array(),
    tweet_info = new Array(),
    tweet_content = new Array(),
    curr_infw;
	$.getJSON(url, function(data) {
		var tweets = (data.results || data);
		$.each(tweets, function(i, item) {
			if (window.console && window.console.firebug) {
        console.log(item);
			}
			var classes = '';
			var profile_image_url = item.profile_image_url || item.user.profile_image_url;
			var avatar_template = '<a class="tweet_avatar" href="http://twitter.com/'+item.from_user+'"><img src="'+profile_image_url+'" height="'+avatar_size+'" width="'+avatar_size+'" alt="'+item.from_user+'\'s avatar" title="'+item.from_user+'\'s avatar" border="0"/></a>';
      var avatar = (avatar_size ? avatar_template : '');
			var content = avatar +''+ replaceURL(item.text) +'<br /><span><a href="http://twitter.com/'+ item.from_user +'" target="_blank">'+ item.from_user +'</a> - <a href="http://twitter.com/'+ item.from_user +'/statuses/'+ item.id +'" title="view tweet on twitter" target="_blank">'+ relative_time(item.created_at) +'</a></span>';
      var content2 = avatar +''+ replaceURL(item.text) +'<br /><span><a href="http://twitter.com/'+ item.from_user +'" target="_blank">'+ item.from_user +'</a></span>';
			if (item.geo) {
        // Save this item to the database
        $.post("http://3cities.action.org.uk/save.php", { lat: item.geo.coordinates[0], lng: item.geo.coordinates[1], html: content2, tweet_id: item.id_str, username: item.from_user } );
				classes = ' geo';
        //content = content +'<p style="display: none;">'. item.geo.coordinates[0] .':'. item.geo.coordinates[1] .'</p>';
			}
      
			$(".tweets ul").append('<li><div class="tweet'+ classes +'">'+ content +'</div></li>');
		});
	});
  
  $.getJSON('http://3cities.action.org.uk/get_map_items.php', {since: 0}, function(data) {
    $.each(data, function(i, loc) {
      locations.push(new google.maps.LatLng(loc.lat, loc.lng));
      tweet_info.push(loc.username);
      tweet_content.push('<div class="tweet">'+ loc.html +'</div>');
    });
    initialize();
  });

  function parse_date(date_str) {
		// The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
		// cannot handle in IE. We therefore perform the following transformation:
		// "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
		return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
	}

	function relative_time(time_value) {
		var parsed_date = parse_date(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		var pluralize = function (singular, n) {
			return '' + n + ' ' + singular + (n == 1 ? '' : 's');
		};
		if(delta < 60) {
		return 'less than a minute ago';
		} else if(delta < (60*60)) {
		return pluralize("minute", parseInt(delta / 60)) + ' ago';
		} else if(delta < (24*60*60)) {
		return pluralize("hour", parseInt(delta / 3600)) + ' ago';
		} else {
		return pluralize("day", parseInt(delta / 86400)) + ' ago';
		}
	}

  function replaceURL(text) {
		var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
		return text.replace(exp,"<a href='$1' target='_blank'>$1</a>");
	}

  function initialize() {
    var latlng = new google.maps.LatLng(51.8205,2.59414);
    var myOptions = {
      zoom: 7,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    for(i=0;i<locations.length;i++) {
      markers[i] = createMarker(locations[i], tweet_info[i], tweet_content[i], map);
    }
  }
  
  function createMarker(point, title, content, map) {
		var image = 'icon.png';
		var marker = new google.maps.Marker({
      position: point,
      map: map,
      title: title,
      icon: image
    });
    var infowindow = new google.maps.InfoWindow({
      content: content,
      maxWidth: 360
    });
    google.maps.event.addListener(marker, 'click', function() {
      if(curr_infw) { curr_infw.close();}
      curr_infw = infowindow;
      infowindow.open(map, marker);
    });
		return marker;
	};

}); 
