/**
 * @author Scott Kyle, few updates by jp74
 * @url http://appden.com/javascript/get-tweets-with-mootools/
 */

Request.Twitter = new Class({

	Extends: Request.JSONP,

	options: {
		linkify: true,
		url: 'http://api.twitter.com/1/statuses/user_timeline/{term}.json',
		data: {
			count: 5
		},
		includeRT: true
	},
	
	initialize: function(term, options){
		this.parent(options);
		this.options.url = this.options.url.substitute({term: term});
		if (this.options.url) {
			this.options.url += '?include_rts=1';
		}
	},
	
	success: function(data, script){
		// data updated to data[0] (JP74)
		if (this.options.linkify) data[0].each(function(tweet){
			tweet.text = this.linkify(tweet.text);
		}, this);
		
		if (data[0]) this.options.data.since_id = data[0].id; // keep subsequent calls newer
		
		this.parent(data, script);
	},
	
	linkify: function(text){
		// modified from TwitterGitter by David Walsh (davidwalsh.name)
		// courtesy of Jeremy Parrish (rrish.org)
		// first regex modified to exclude dots at the end of the matched URL
		return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+[\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>');
	}
	
});
