/**
 * twitter.js
 * 
 * Displays tweets in a container box
 * It's called from an embedded piece of code
 * It places itself at the place the call to putTweets() is made
 * 
 * load: head
 * 
 * Depends
 * 	jQuery (1.4.2)
 * 
 * @author JP | Peppered
 * @author AK | Peppered
 */

var twitter = {};

twitter.options = {};
twitter.$container = '';

twitter.createContainer = function(){
	if (this.$container === undefined || !this.$container.length) {
		this.$container = $('<div id="twitter" class="item loading"><h2 class="ir">Twitter</h2><div class="tweets"><a href="http://www.twitter.com/vredenburg_" class="follow" target="_blank">volg ons</a></div></div>');
		var $tmp = $('<div/>').append(this.$container);
		document.write($tmp.html());
		this.$container = $('#twitter');
		this.$tweets_container = $('#twitter .tweets');
	}
};

twitter.putTweets = function(){
	var options = this.options;
	//twitter.createContainer();
	$.getJSON(options.url, function(json){
		var $ul = $('<ul/>');
		twitter.$container.removeClass('loading');
		$.each(json.results, function(i,tweet){
			var $li = $('<li class="tweet"/>');
			if(i == 0 && !isEmpty(options.channel_header)){
				// @todo: each channel own list (& custom header bit)
			}
			$li.append( '<div class="author"><a href="http://twitter.com/' + tweet.from_user + '" target="_blank">' + tweet.from_user + '_</a></div><div class="redDash">' + twitter.tweet.parse(tweet.text) + '</div>' );
			$li.appendTo($ul);
		});
		twitter.$tweets_container
			.append($ul)
			.find('li:first').addClass('tweet-first')
			.end()
			.find('li:last').addClass('tweet-last')
			.end()
			.parent()
			.show();
	});
};

twitter.tweet = {};

twitter.tweet.time = function(input){
	// Calculate how many hours ago was the tweet posted
	var date_tweet = new Date(input);
	var date_now = new Date();
	var date_diff = date_now - date_tweet;
	var days = Math.round(date_diff/(1000*60*60*24));
	var hours = Math.round(date_diff/(1000*60*60));
	var minutes = Math.round(date_diff/(1000*60));
	var seconds = Math.round(date_diff/(1000));
	if(seconds < 60){
		var time_output = seconds + ' seconden geleden'
	} else if (minutes < 60 && minutes > 1){
		var time_output = minutes + ' minuten geleden'
	} else if (minutes < 60 && minutes < 2){
		var time_output = minutes + ' minuut geleden'	
	} else if (hours < 24){
		var time_output = hours + ' uur geleden'
	} else if (days == 1){
		var time_output = days + ' dag geleden'
	} else {
		var time_output = days + ' dagen geleden'
	}
		
	return time_output;
};

twitter.tweet.parse = function(text){
	var txt = text.replace(
		/(https?:\/\/[-a-z0-9._~:\/?#@!$&\'()*+,;=%]+)/ig,
		'<a href="$1">$1</a>'
	).replace(
 		/@+([_A-Za-z0-9-]+)/ig, 
		'<a href="http://twitter.com/$1">@$1</a>'
	).replace(
		/#+([_A-Za-z0-9-]+)/ig,
		'<a href="http://search.twitter.com/search?q=$1">#$1</a>'
	);
	return txt;
};

