$(function(){
	twitterFeed()
});
function twitterFeed(){
	var twitterUserName = "q1labs";
	var url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+twitterUserName+"&include_rts=true&count=1&callback=?"
	
	var urirex = /(https?):\/\/+([\w\d:#@%\/;$()~_?\+-=\\\.&]*)/g;
	var hashrex = /\#+([\w\d:#@%/;$()~_?\+-=\\\.&]*)/g;
	
	var thashuri = "http://search.twitter.com/search?q=%23";
	var twitterLogo = '<img src="graphics/icon/twitter_icon.png" width="19" height="18" alt="twitter" /><strong>Q1 blogs Tweets:</strong>';
	var twitterFloowLink = '<a target="_blank" href="http://twitter.com/' + twitterUserName + '">Follow Q1 blogs on Twitter</a>';
	var display = "";
	
	 $.getJSON(url,function(json){
		 	$.each(json, function(i,tweet){
					$(".twitterFeed img.profilePic").attr("src", tweet.user.profile_background_image_url);
					
					ttext = tweet.text.replace(urirex, '<a target="_blank" href="$1://$2" title="">$2</a>');
					//ttext = ttext.replace(hashrex, '<a href="' + thashuri  + '$1" title="">#$1</a>');
					ttext = ttext.replace(hashrex, '');
					
					display += ttext
				$(".twitterFeed span.timeAgo").html(prettyDate(tweet.created_at));	
				$(".twitterFeed a.reply").attr("href", "http://twitter.com/intent/tweet?in_reply_to=" + tweet.id);
			});
		$("span.tweets").html(display );
	});
	
	//$(".twitterFeed a.twitterFollow").attr("href", "http://twitter.com/"+twitterUserName);
}

function prettyDate(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 );
		});
	};
}


