/**
 * Tweet Feed retrieval Class
 * integrates the following search api: 
 * 
 * Containing a word: http://search.twitter.com/search.atom?q=twitter
 * From a user: http://search.twitter.com/search.atom?q=from%3Aal3x
 * Replying to a user (tweet starts with @mzsanford): http://search.twitter.com/search.atom?q=to%3Amzsanford
 * Mentioning a user (tweet contains @biz): http://search.twitter.com/search.atom?q=%40biz
 * Containing a hashtag (up to 16 characters): http://search.twitter.com/search.atom?q=%23haiku
 * Combine any of the operators together: http://search.twitter.com/search.atom?q=happy+hour&until=2009-03-24
 * Originating from an application: http://search.twitter.com/search.atom?q=landing+source:tweetie
 */

var TwitterFeed = new Class({
	
		//implements
		Implements: [Options,Events],
	
		//options: by default, user mode, 3 tweets
		options: {
			mode: '@', 
			query: 'twitter', 
			rpp: 3,
			sinceID: 1,
			link: true,
			onComplete: null
		},
		
		//initialization
		initialize: function(options) {
			
			//set options
			this.setOptions(options);
			
			this.info = {};
			
			this.searchApi = "http://search.twitter.com/search.json";
			
			this.endpoints = new Array();
			this.endpoints["search"]   = this.searchApi + "?q={q}";                               // retrieve feeds containing a word
			this.endpoints["from"]     = this.searchApi + "?q=from%3A{q}";                        // retrieve feeds from a user
			this.endpoints["to"]       = this.searchApi + "?q=to%3A{q}";                          // retrieve feeds to a user
			this.endpoints["@"]        = this.searchApi + "?q=%40{q}";                            // retrieve feeds referencing a user
			this.endpoints["#"]        = this.searchApi + "?q=%23{q}";                            // retrieve feeds containing a hashtag
			
			this.onComplete = options.onComplete || null;
			
		},
		
		//get it!
		retrieve: function() {
			
			var actualEndpoint = this.endpoints[this.options.mode];
			if (null != actualEndpoint){
				var parsedEndpoint = actualEndpoint.replace("{q}", this.options.query);
				var req = new Request.JSONP({
					url: parsedEndpoint,
					data: {
						rpp: this.options.rpp,
						count: this.options.rpp,
						since_id: this.options.sinceID
					},
					onComplete: function(data){
						this.onComplete(data);
					}.bind(this)
				});
				req.send();
			} else {
				alert("wrong configuration");
			}
			
			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>');
		}
	});
