/**
 * Twitter Client
 *
 * @copyright: (c) 2010, André Fiedler <kontakt@visualdrugs.net>
 * @version: 1.0
 * @license: The MIT License
 */

var TwitterClient = new Class({
    Implements: [Options, Events],
    options: {
        count: 1,
        sinceID: 1,
        link: true
    },
    initialize: function(username, container, options){
        this.setOptions(options);
        this.info = {};
        this.username = username;
        this.container = $(container);
    },
    retrieve: function(){
		(new Request.JSONP({
            url: "http://twitter.com/statuses/user_timeline/" + this.username + ".json",
            data: {
                count: this.options.count,
                since_id: this.options.sinceID,
                include_rts: true
            },
            onComplete: function(response){
				if(response.length == 0) return;
                if(this.options.link)
                    response.each(function(tweet){
                        tweet.text = this.linkify(tweet.text);
                    }, this);
				this.container.empty();
                var tweet = response[0];
				new Element("div", {
					html: "<strong>" + Date.parse(tweet.created_at).format("%d. %B %Y&nbsp;&nbsp;I&nbsp;&nbsp;%H:%m") + " Uhr</strong><br/>" + tweet.text
				}).inject(this.container).fade("hide").fade("in");
				this.container.removeClass('loading');
				this.fireEvent('success');
            }.bind(this)
        })).send();
        return this;
    },
    linkify: function(tweet){
        return tweet.replace(/(https?:\/\/\S+)/gi, '<a target="_blank" href="$1">$1</a>').replace(/(^|\s)@(\w+)/g, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>').replace(/(^|\s)#(\w+)/g, '$1<a target="_blank" href="http://search.twitter.com/search?q=%23$2">#$2</a>');
    }
});

