Request.Twitter = new Class({

  Extends: Request.JSON,

  options: {
    linkify: true,
    url: 'http://twitter.com/statuses/user_timeline/{term}.json',
    data: {
      count: 5
    }
  },
  
  initialize: function(term, options){
    this.parent(options);
    this.options.url = this.options.url.substitute({term: term});
  },
  
  success: function(data, script){
    if (this.options.linkify) data.each(function(tweet){
      tweet.text = this.linkify(tweet.text);
    }, this);
    
    // keep subsequent calls newer
    if (data[0]) this.options.data.since_id = data[0].id;
    this.parent(data, script);
  },
  
  linkify: function(text){
    return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>')
               .replace(/(^|\W)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
               .replace(/(^|\W)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
  }
});

var TwitterGitter = new Class({
	
			//implements
			Implements: [Options,Events],
		
			//options
			options: {
				count: 2,
				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://twitter.com/statuses/user_timeline/' + this.username + '.json',{
					data: {
						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>');
			}
		});
		
		
		/* usage */
/*		window.addEvent('domready',function() {
			$('git').addEvent('click',function(e) {
				e.stop();
				$('tweets-here').set('html','');
				//get information
				var myTwitterGitter = new TwitterGitter($('username').value,{
					count: 5,
					onComplete: function(tweets,user) {
						tweets.each(function(tweet,i) {
							new Element('div',{
								html: '<img src="' + user.profile_image_url.replace("\\",'') + '" align="left" alt="' + user.name + '" /> <strong>' + user.name + '</strong><br />' + tweet.text + '<br /><span>' + tweet.created_at + ' via ' + tweet.source.replace("\\",'') + '</span>',
								'class': 'tweet clear'
							}).inject('tweets-here');
						});
					}
				}).retrieve();
			});
		});
*/
