// Credit to: http://phpcamp.net/toolbar/a-jquery-twitter-ticker

$(document).ready(function(){
  var fileref = document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", "http://search.twitter.com/search.json?q=from:fringley&callback=twitter.ticker&rpp=10");
  document.getElementsByTagName("head")[0].appendChild(fileref);
});

twitter = {
  tweets : [],
  counter : 0,
  container : null,
  
  ticker : function(ob) {
    this.container = $('#twitter-feed');
    this.tweets = ob.results;
    this.container.innerHtml = '';
    this.nextTweet();
    setInterval("twitter.nextTweet()", 5000);
  },

  nextTweet : function() {
    var tweet = this.tweets[this.counter];
    this.container.append(this.createTweetDiv(tweet));
    $('#tweet-'+tweet.id).fadeIn('slow');
    if (this.container.children().length > 1) {
      $(this.container.children()[0]).fadeOut('slow', function() {
        $(this).remove();
      });
    }
    this.counter++;
    if (this.tweets[this.counter] === undefined) { this.counter = 0; }
  },

  createTweetDiv : function(tweet) {
    return '<div class="tweet" style="display: none;" id="tweet-' + tweet.id + '">\
    <span class="txt">'+this.formatTwitString(tweet.text)+'</span>\
    <span class="time">'+utilities.relativeTime(tweet.created_at)+'</span>\
    </div>';
  },

  formatTwitString : function(str) {
    str=' '+str;
    // The this.tweets arrive as plain text, so we replace all the textual URLs with hyperlinks
    str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
    // Replace the mentions
    str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
    // Replace the hashtags
    str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
    return str;
  }
}
