// Twitter

(function ($) {
  var userLink = function (user, content) {
    return $('<a />').attr('href', 'http://twitter.com/' + user).append(content);
  };

  var buildTweet = function (tweet) {
    var meta = $('<span class="meta" />');
    if (tweet.to_user) {
      meta.append(userLink(tweet.to_user, ''));
    }

    return $('<li />').

    // image
   /* append(
      $('<span class="author" />').
      append(userLink(tweet.from_user, $('<img />').attr('src', tweet.profile_image_url)))
    ).*/

    // content
    append(
      $('<span class="body" />').

      // author
      append(
        $('<strong />').
        append(userLink(tweet.from_user, tweet.from_user))
      ).

      append(' ').

      // text
      append(
        $('<span />').
        append(tweet.text)
      ).

      // meta
      append(meta)
    );
  };

  $.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).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

