/*
 * Twidget v1.0
 * Frank
 * 
 * Zie Twitter doc: 	http://dev.twitter.com/doc/get/statuses/user_timeline
 * Zie date functie: 	http://mootools.net/docs/more/Types/Date
 */


var Twidget = new Class({
    Implements: [Options, Events],
    
	options: {
        user: 		'mootools',
        element: 	'tweets',
        count: 		null,
		page: 		null,
		dateformat: '%d-%m-%Y %H:%M',
		markup: 	'<p><span class="tweets">By {screen_name}</span><br />{text}<br /><span class="date">{created_at}</span></p>'
    },
    
	toElement: function(){
        return $(this.options.element)
    },
    
	initialize: function(options){
        this.setOptions(options);
        this.element = $(this.options.element);
        try {
            $(this)
        } 
        catch (b) {
            (typeof console == "object") && console.error("Twidget element not found");
            return
        }
        this.getTweets()
    },
    
	getTweets: function(){
        // data
		var data = { include_rts: false, include_entities: false };
		if(this.options.page != null){
			data.page = this.options.page;
		}else if(this.options.count != null){
			data.count = this.options.count;
		}else{
			data.page = 1;
		}
		
		new Request.JSONP({
            url: "http://twitter.com/statuses/user_timeline/" + this.options.user + ".json",
            data: data,
            onComplete: function(data){
				this.tweets = data;
				this.createTweets();
			}.bind(this),
            onRequest: function(){
                this.fireEvent("request")
            }.bind(this),
            onCancel: function(){
                this.fireEvent("cancel")
            }.bind(this),
            timeout: 5000
        }).send()
    },
	
    createTweets: function(){
		if(this.tweets.length > 0){
			this.tweets.each(function(tweet, i){
				if ((this.options.page == null ||(this.options.page != null && i < this.options.count)) && tweet.text != '') {
					tweet.text = this.linkify(tweet.text); // anders werken de linkjes niet
					tweet.created_at = new Date().parse(tweet.created_at).format(this.options.dateformat);
					tweet.screen_name = tweet.user.screen_name;
					tweet.profile_image = tweet.user.profile_image_url;
					
					var tweet = this.options.markup.substitute(tweet);
					this.element.set('html', $(this.options.element).get('html') + tweet);
				}
			}.bind(this));
		}
    },
    
	linkify: function(a){
        return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/(https?:\/\/\S+)/gi, '<a href="$1" target="_blank">$1</a> ').replace(/(^|\s|\(|\[)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>').replace(/(^|\s)#(\S+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>')
    }
});
