//
// 'twittertot' Copyright (c) 2009 Andy Atkinson http://webandy.com
// twittertot is a jquery plugin that fetches a user's unprotected tweets for display on a website. 
// Configure the username and number of tweets. Tweets are displayed as a list by default or can
// be cycled one at a time by passing {cycle: true} as an option.
//
// Usage: (1) with default options: $('#tweets').twittertot();
//       (2) pass options with a hash $('#tweets').twittertot({username: 'biz', count: 10, cycle: true});
//
(function($) {
  $.fn.twittertot = function(options) {
    var defaults = {
        username: 'ev',
        cycle: false,
        count: 5
      };  
    var options = $.extend(defaults, options);
    return this.each(function() {
      $this = $(this).hide();
      $('<p/>').html('Follow @<a href="http://twitter.com/'+options.username+'">'+options.username+
                    '</a> on <a href="http://twitter.com">twitter</a>').appendTo($this);
      var tweets = '';
      $.getJSON('http://twitter.com/statuses/user_timeline/'+options.username+'.json?count='+options.count+'&callback=?',
       function(data){
         $.each(data, function(i,item){
           var tweet = item.text;
           if(tweet.search(/(https?:\/\/[-\w\.]+:?\/[\w\/_\.]*(\?\S+)?)/) > -1) {
             tweet = tweet.replace(/(https?:\/\/[-\w\.]+:?\/[\w\/_\.]*(\?\S+)?)/, "<a href='$1'>$1</a>");
           }
           if(tweet.search(/@\w+/) > -1) {
             tweet = tweet.replace(/(@)(\w+)/g, "$1<a href='http://twitter.com/$2'>$2</a>");
           }
           var date = new Date(item.created_at);
           date = (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
           var href = 'http://twitter.com/'+options.username+'/statuses/'+item.id;
           var link = '<a href="'+href+'">'+date+'</a>';
           tweets += '<li>'+tweet+' '+link+'</li>';
        });
      $('<ul/>').html(tweets).appendTo($this);
      options.cycle ? cycle() : $this.fadeIn();
      });
      function cycle() {
        $this.show();
        $this.find('ul > li').hide();
        $this.find('ul > li:first').fadeIn();
        var i = 1;
        setInterval(function() {
          var items = $this.find('li');
          items.hide();
          items.eq(i).fadeIn();
          if(i == items.length) {
            $this.find('ul > li:first').fadeIn();
            i = 1;
          } else { i++; }
        }, 6000);        
      }
    });
  }  
})(jQuery);
