/**
 * twitter.js
 *
 * Some Javascript functions to play with the Twitter API
 * All functions depend on the jQuery JavaScript library, version >= 1.3.1
 *
 * @author b00giZm <b00giZm@gmail.com>
 * @version 0.1.0
 *
 */
 
 var recentTweetId = 0;

/**
 * This function parses a tweet's text and returns a completly formatted
 * HTML string
 *
 * @param {String} text The text to be parsed
 * @return The formatted text
 * @type String
 *
 */
function parseTweetText(text)
{
  var urlRegex = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/ig;
  var userRegex = /@[a-z0-9]+/ig;
  var hashtagRegex = /#[a-z0-9]+/ig;
  
  var repl;
  
  // Check for URLs
  $.each($.makeArray(text.match(urlRegex)), function(i, match)
  {
    repl = '<a href="' + match + '" target="_blank">' + match + '<\/a>';
    text = text.replace(match, repl);
  });
  
  // Check for mentions (like '@foobar')
  $.each($.makeArray(text.match(userRegex)), function(i, match)
  {
    repl = '<a href="http://www.twitter.com/' + match.substr(1, match.length) + '" target="_blank">' + match + '<\/a>';
    text = text.replace(match, repl);
  });
  
  // Check for hashtags (like '#foobar')
  $.each($.makeArray(text.match(hashtagRegex)), function(i, match)
  {
    repl = '<a href="http://twitter.com/#search?q=' + encodeURIComponent(match) + '" target="_blank">' + match + '<\/a>';
    text = text.replace(match, repl);
  });
  
  return text;
}

/**
 * This function fetches the last tweet by making a JSONP request call to the
 * Twitter API and displays it
 *
 */
function fetchRecentTweet()
{
  var url = "http://twitter.com/statuses/user_timeline/b00giZm.json?count=1&callback=?";
  
  // Fetch the last tweet via JSONP request
  $.getJSON(url, function(data)
  {
    if (data.length >= 1)
    {
      var tweet = data[0];
      
      if (tweet.id > recentTweetId)
      {
        var date = new Date(tweet.created_at);

        var tweetInfo = ' - posted by <a href="http://www.twitter.com/b00giZm" target="_blank">@b00giZm</a> on ' + date.toLocaleString();
        $('#tweet-contents').html(parseTweetText(tweet.text) + tweetInfo);
        
        recentTweetId = tweet.id;
      }
    }
  });
}
