Vetstoria.twitter = new(new Class({
    __construct: function () {
		
        this.reports = [];
		
        this.default_cache_count = 1;
        
        this.tweets = [];
        
    },
	
	init: function() {
		console.log('Vetstoria.twitter:', 'twitter init');
		
		this.cache_tweets(this.cache_count);
	},
	
	/**
	 * Get -count- tweet(s) form the backend and cache them
	 */
	get: function(count) {
		
		if(!count) count = this.default_cache_count;
		
		console.log('Vetstoria.twitter:', 'caching tweets ('+ count +')');
		
		this.tweets = Vetstoria.json_command('twitter/' + count);
		
	},
	
	/**
	 * @deprecated : bad name
	 */
	cache_tweets: function(count) {
		return this.get(count);
	},
	
	/**
	 * Parse some text to replace the links
	 */
	parse_links: function(text) {
		var reg = [
		           	new RegExp("(((f|ht){1}tp://)([-a-zA-Z0-9@:%_\+.~#?&//=]+))", 'g'),
		           	new RegExp("([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)", 'g'),
		           	new RegExp("([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})", 'g')
		          ];
		
		var rep = [
		           	'<a href="$1">$4</a>',
		           	'$1<a href="http://$2">$2</a>',
		           	'<a href="mailto:$1">$1</a>'
		          ];
		
		for(var i = 0; i < reg.length; i++)
			text = text.replace(reg[i], rep[i])
		
		return text;
		
	},
		
	/**
	 * Return the -count- last tweets, if cached. Format them before
	 */
	last_tweets_formatted: function(count) {
		
		if(!count) {
			console.log('Vetstoria.twitter:', 'last_tweets_formatted(), no count parameter');
			return;
		}
		
		if(!this.tweets) {
			console.error('Vetstoria.twitter : either you don\'t have php_cli enabled or we have a little network error')
			return;
		}
		
		var html = $('<div />'), text, tweet, content;
		
		if(this.tweets.length > 0) {
			
			if(count > this.tweets.length) {
				
				count = this.tweets.length;
			}
			
			for(var i = 0; i < count; i++) {
				
				tweet = this.tweets[i];
				text = this.parse_links(tweet.text);
				time = prettyDate(tweet.created_at);
				content = text + ' - ' + time;
				
				html.append(
					$('<p />').append(content)
				);
			}
			
		}
		else {
			console.log('Vetstoria.twitter:', 'last_tweets_formatted() error, no cached tweet');
		}		
		
		return $(html.html());
	}

}));
