
google.load("jquery", '1.3.2');
google.load("feeds", "1");


var max_displayed = 5;  // max tweets to show
var pid = 0;			// unique post id
var tweets = [];		// array of tweets
var rpp = 5;			// number of results to return



google.setOnLoadCallback(function() {
	
  $(function() {

  });
  
  loadFeeds();
  
});





// GOOGLE SEEMS TO CACHE FEEDS ABOUT ONCE PER HOUR
function loadFeeds(){
	
	var t = new Date().getTime()
	var q = "%401PercentFTP+OR+music.onepercentfortheplanet.org+OR+%231percent+-munchies+-%401percent+-www.1percent.com+-glass";
	//var q = "apple";
	var url = "http://search.twitter.com/search.json?q="+q+"&rpp="+window.rpp+"&t="+t+"&since_id="+pid+"&callback=?";
	//console.log(url);
	
	$.getJSON(url,function(data, status){

			//console.log("data: ");		// data will be a jsonObj
			//console.log(data);
			//console.log(status);
					
			var c = $("#container");
			var loader =$("#lifestream_loader");
			
			// newest posts at the top
			if(data.results.length > 1){
				data.results.reverse();
			}
			
			// loop over results, add to page
			for(var i=0; i < data.results.length; i++ ){
				var tweet = data.results[i];
				window.pid = tweet.id;
				//console.log(tweet);
				
				
				if(jQuery.inArray(window.pid, window.tweets) == -1){
					window.tweets.push(window.pid);
					c.prepend(composePost(pid, data.results[i]));
					$('#p'+pid).hide();
					$('#p'+pid).fadeIn('slow');
					
					// clean up fuction
					if(window.tweets.length > window.max_displayed){
						var d = window.tweets.shift();
						$('#p'+d).fadeOut('slow');
					}
					
					c.height(500); 
					loader.fadeOut('fast');
				}
				
			}

			
			// after initial page load, just get the most recent post
			if(window.tweets.length == window.max_displayed){
				window.rpp = 1;
			}
			
			
					
		});	
		
		
		setTimeout(function(){loadFeeds()},5000);		// wait for 5 sec
}

setInterval(function(){updateTimes()}, 60000);		// wait for 60 sec

function updateTimes(){
	console.log("updateTimes "+new Date().toUTCString());

	// update timestamps
	$(".raw_date").each(function(i){
		//console.log($(this).html());
		var d = $(this).html();
		var id = $(this).parent().attr("id");
		$("#"+id+" .date").html( prettyDate(d) );
	});

}



function composePost(id, t){	
	thedatestr = prettyDate(t.created_at);
	
	var p = '<div class="article" id="p'+t.id+'">';
	p += '<div class="user"><a target="_blank" href="http://twitter.com/'+t.from_user+'">'+t.from_user+'</a></div>';
	p += '<a target="_blank" href="http://twitter.com/'+t.from_user+'"><img src="'+t.profile_image_url+'" /></a>';
	p += '<p class="text">'+t.text.linkify().linkuser().linkuser().linktag().linktag().linktag()+'</p>';
	p += '<a class="retweet" href="http://twitter.com/home?status=RT:@'+t.from_user+' '+t.text+'">retweet this</a>';
	p += '<div class="date">'+thedatestr+' </div>';
	p += '<div class="raw_date">'+t.created_at+'</div>';
	p += '</div>';

	return p;
}






function scanForLinks(str){
	return str
    .replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,
'<a href="$&" class="feedlink" target="_blank">$&</a>')
    .replace(/([^\/])(www[\S]+(\b|$))/gim,
'$1<a href="http://$2" class="feedlink" target="_blank">$2</a>');

}


String.prototype.linkify = function() 
{
  return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) 
  {
  	m = m.link(m);
  	m = m.replace('href="','target="_blank" href="');
  	return m;
  });
};

String.prototype.linkuser = function() 
{
  return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(us) 
  {
    var username = us.replace("@","");
    
    us = us.link("http://twitter.com/"+username);
  	us = us.replace('href="','target="_blank" onclick="loadProfile(\''+username+'\');return(false);"  href="');
    return us;
  });
};

String.prototype.linktag = function() 
{
  return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) 
  {
    var tag = t.replace("#","%23");
    t = t.link("http://summize.com/search?q="+tag);
  	t = t.replace('href="','target="_blank" href="');
  	return t;
  });

};



/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	
	var date = new Date(Date.parse(time));
	//var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
