/*
 * twitter.js
 *
 * 29/08/2011
 *
 * Copyright 2011 A. H. Baldwin & Sons Ltd.
 * Based on code from http://www.pcpro.co.uk/blogs/2010/09/13/adding-your-twitter-feed-to-your-website-with-jquery/
 */

function getTweets(sSelector, nTweets, sTitle, sSubtitle, sLink)
{
  jQuery.getJSON(window.location.protocol + "//twitter.com/statuses/user_timeline.json?screen_name=baldwinscoins&count="+(nTweets+1)+"&callback=?", function(tweetdata)
  {
    var tl = jQuery(sSelector);
    jQuery.each(tweetdata, function(i,tweet)
    {
      tl.append("<li><a href='" + sLink + "' class='title no-print-url'target='_blank'>"+sTitle+"</a> <span class='subtitle'>"+sSubtitle+"</span><br />" + mentionToLink(hashtagToLink(urlToLink(tweet.text))) + "<br /><span class='date'>" + relTime(tweet.created_at) + "</span></li>");
    });
  });
}

function hashtagToLink(text)
{
	var exp = /(#([A-Za-z]+))/ig;
	return text.replace(exp, "<a class='no-print-url' href='http://twitter.com/#!/search?q=%23$2' target='_blank'>$1</a>");
}

function mentionToLink(text)
{
	var exp = /(@([A-Za-z]+))/ig;
	return text.replace(exp, "<a class='no-print-url' href='http://twitter.com/$2' target='_blank'>$1</a>");
}

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

function relTime(time_value)
{
  time_value = time_value.replace(/(\+[0-9]{4}\s)/ig,"");
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);
  if (timeago < 60) return 'less than a minute ago';
  else if(timeago < 120) return 'about a minute ago';
  else if(timeago < (45*60)) return (parseInt(timeago / 60)).toString() + ' minutes ago';
  else if(timeago < (90*60)) return 'about an hour ago';
  else if(timeago < (24*60*60)) return 'about ' + (parseInt(timeago / 3600)).toString() + ' hours ago';
  else if(timeago < (48*60*60)) return '1 day ago';
  else return (parseInt(timeago / 86400)).toString() + ' days ago';
}




