var TwitterGitter = new Class( {

  // implements
  Implements : [ Options, Events ],

  // options
  options : {
    count : 5,
    sinceID : 1,
    link : true,
    onRequest : $empty,
    onComplete : $empty
  },

  // initialization
  initialize : function(username, options) {
    // set options
    this.setOptions(options);
    this.info = {};
    this.username = username;
  },

  // get it!
  retrieve : function() {
    new JsonP('http://api.twitter.com/1/statuses/user_timeline.json', {
      data : {
        screen_name: this.username,
        count : this.options.count,
        since_id : this.options.sinceID
      },
      onRequest : this.fireEvent('request'),
      onComplete : function(data) {
        // linkify?
      if (this.options.link) {
        data.each(function(tweet) {
          tweet.text = this.linkify(tweet.text);
        }, this);
      }
      // complete!
      this.fireEvent('complete', [ data, data[0].user ]);
    }.bind(this)
    }).request();
    return this;
  },

  // format
  linkify : function(text) {
    // courtesy of Jeremy Parrish (rrish.org)
    return text.replace(/(https?:\/\/\S+)/gi, '<a href="$1">$1</a>').replace(/(^|\s)@(\w+)/g,
        '$1<a href="http://twitter.com/$2">@$2</a>').replace(/(^|\s|\()#(\w+)/g,
        '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
  }
});
window.addEvent('domready', function() {
  var inj_a = document.getElementById('tweets_inj');
  var inj = new Element('ul').inject(inj_a);
  new TwitterGitter('contronix', {
    count : 5,
    onComplete : function(tweets, user) {
      var twitter_el = document.getElementById('twitter');
      $(twitter_el).erase('class');
      tweets.each(function(tweet, i) {
        var date = new Date;
        date.parse(tweet.created_at);
        new Element('li', {
          html : '<div class="tweettitle"><a href="http://twitter.com/contronix/status/' + tweet.id + '">'
              + date.format("db") + '</a></div><div class="tweettext">' + tweet.text + "</div>"
        }).inject(inj);
      });
    }
  }).retrieve();
});

