// Twitter

(function ($) {
  var userLink = function (user, content) {
    return $('<a />').attr('href', 'http://twitter.com/' + user).append(content);
  };

  var buildTweet = function (tweet, options) {
    var meta = $('<span class="meta" />');
    var li = $('<li />')
	var author = $('<span class="author" />')
	var text = tweet.text
	
	if (tweet.to_user)
	{
		meta.append(userLink(tweet.to_user, ''));
	}

	if (options.stripHashes===true)
	{
		text = text.replace(/#\S+/g,"")
	}
	
	if (options.linkUrls===true)
	{
		text = text.replace(/(http:\/\/\S+)/g,"<a href=\"$1\">$1</a>")
	}
	
    // content
    li.append( $('<span class="body" />') )


   // author image
    if (options.showAuthorIcon===true) 
	{
		author.append(
		  userLink(tweet.from_user, $('<img />').attr('src', tweet.profile_image_url))
		)
		li.append(author)
	}

	// author link
	if (options.showAuthorLink===true) 
	{
		author.append(
			$('<strong />').
			append(userLink(tweet.from_user, tweet.from_user))
		)
		li.append(author)
	}

    li.append(' ')

    // text
    
	
	li.append(
        $('<span />').
        html( text )
      )

    // meta
    li.append(meta);
	
	return li
  };

  $.fn.twitter = function (options) {
    var tweets = $(this);

    var query = options.query;
    var loadInterval = options.loadInterval;
    var showInterval = options.showInterval;
    var maxTweets = options.maxTweets;

    var loadTweets = function (since) {
	if (typeof(since) === 'undefined') {
		since = 0;
	}

      $.getJSON('http://search.twitter.com/search.json?callback=?', { q: query, rpp: maxTweets, since_id: since }, function (json) {
        // stash hidden tweets at the top
        $.each(json.results.reverse(), function (i, tweet) {
          buildTweet(tweet, options).hide().prependTo(tweets);
        });

        window.setTimeout(function () { loadTweets(json.max_id); }, loadInterval);
      });
    };

    var showTweet = function () {
      if (tweets.children(':visible').length > 0) {
        // reveal a hidden tweet at the top
        tweets.children(':hidden:last').slideDown();

        // hide any surplus tweets at the bottom
        tweets.children(':visible:gt(' + (maxTweets - 1) + ')').slideUp(function () { $(this).remove(); });
      } else {
        tweets.children().fadeIn();
      }
    };

    $(function () {
      loadTweets();
      window.setInterval(showTweet, showInterval);
    });

    return this;  // return the jQuery object
  };
})(jQuery);

/*global jQuery, window */ // for jslint.com

