var problem_timeout = false;

function run()
{
	$("div#tweets_container").show();
	$("div#replies_container").show();
	
	get_userinfo();
	
	// initialize message
	$("div#message").click(
		function (e)
		{
			$("div#message").slideUp(500);
		}
	);
}
window.onload = run;

function get_userinfo()
{
	var url = 'http://twitter.com/users/show/' + username + '.json'
		+ '?suppress_response_codes=1'
		+ '&callback=process_userinfo&_c=' + Math.random();
	
	show_loading();
	
	problem_timeout = window.setTimeout('show_problem()', 20 * 1000);
	$('div#hdn_tweets').html('<script type="text/javascript" src="' + url + '"></' + 'script>');
}

function get_tweets()
{
	var url = 'http://twitter.com/statuses/user_timeline/' + username + '.json'
		+ '?suppress_response_codes=1&count=' + count;
	if (since_id_tweets != 0 && since_id_tweets != null)
		url += '&since_id=' + since_id_tweets;
	url += '&callback=process_tweets&_c=' + Math.random();
	
	show_loading();
	
	problem_timeout = window.setTimeout('show_problem()', 20 * 1000);
	$('div#hdn_replies').html('<script type="text/javascript" src="' + url + '"></' + 'script>');
}

function get_replies()
{
	var url = 'http://search.twitter.com/search.json?q=%40' + username + ''
		+ '&rpp=' + Math.round(count / 2);
	if (since_id_replies != 0 && since_id_replies != null)
		url += '&since_id=' + since_id_replies;
	url += '&callback=process_replies&_c=' + Math.random();

	show_loading();
	
	problem_timeout = window.setTimeout('show_problem()', 20 * 1000);
	$('div#hdn_replies').html('<script type="text/javascript" src="' + url + '"></' + 'script>');
}

function process_userinfo(data)
{
	if (problem_timeout)
		window.clearTimeout(problem_timeout);
	
	hide_loading();
	
	if (!(data.error == undefined))
	{
		show_problem();
		
		return;
	}
	
	hide_problem();
	
	get_tweets();
	
	if (data.length == 0)
		return;

	$("span#my_profile_pic").css('background-image', 'url(\'' + data.profile_image_url + '\')');
	$("span#my_profile_pic").css('display', 'block');
}

function process_tweets(data)
{
	if (problem_timeout)
		window.clearTimeout(problem_timeout);
	
	hide_loading();
	
	if (!(data.error == undefined))
	{
		show_problem();
		
		return;
	}
	
	hide_problem();
	
	get_replies();
	
	if (data.length == 0)
		return;
	
	var h = '';
	for (var i = 0; i < data.length; i++)
	{
		var tweet = data[i];
		
		if (tweet['id'] > since_id_tweets)
			since_id_tweets = tweet['id'];

		tweet['from_screen_name']	= tweet['user']['screen_name'];
		tweet['from_user']			= tweet['user']['name'];
		tweet['profile_image_url']	= tweet['user']['profile_image_url'];
		
		h += tweet_to_html(tweet, 'tweet');
	}
	
	$("div#tweets").prepend(h);
	
	// add new-tweets-message
	if (data.length == 1)
		$("div#message span#tweets_total").html('1 neues Update');
	else
		$("div#message span#tweets_total").html(data.length + ' neue Updates');
	$("div#message").slideDown(
		500,
		function (e)
		{
			window.setTimeout('$("div#message").slideUp(500);', 10 * 1000);
		}
	);
	
	// post-processing
	post_process_tweets();
}

function process_replies(data)
{
	if (problem_timeout !== false)
		window.clearTimeout(problem_timeout);
	
	hide_loading();
	
	if (!(data.error == undefined))
	{
		show_problem();
		
		return;
	}
	
	hide_problem();
	window.setTimeout('get_tweets()', reload_seconds * 1000);
	
	since_id_replies = data['max_id'];
	data = data['results'];
	
	if (data.length == 0)
		return;
	
	var h = '';
	for (var i = 0; i < data.length; i++)
	{
		var tweet = data[i];
		
		tweet['from_screen_name']	= tweet['from_user'];
		
		h += tweet_to_html(tweet, 'reply');
	}
	
	$("div#replies").prepend(h);
	
	// post-processing
	post_process_tweets();
}

function post_process_tweets()
{
	// check replies
	// if no answering tweet, check if answering tweet available
	// if available: add
	
	var replies = $('div#replies div.tweet');
	for (var i = 0; i < replies.length; i++)
	{
		var reply	= replies[i];
		
		if ($('div#' + reply.id + '-reply').length > 0 &&
			$('div#' + reply.id + '-reply').html() == '')
		{
			var id		= reply.id.substr(6);
			
			if ($('span#reply-to-' + id).length > 0)
			{
				$('div#' + reply.id + '-reply').html(
					  '<div class="text"><div class="text">'
					+ $($('span#reply-to-' + id)[0].parentNode).html()
					+ '</div></div>'
				);
			}
		}
	}
}

function tweet_to_html(tweet, type)
{
	var id = tweet['id'];
	
	var h = '';
	
	var dt = new Date(tweet['created_at']);
	
	h += '<div class="tweet" id="' + type + '-' + id + '">';
	
	if (type == 'reply')
		h +=  '<span class="arrow_left"><!----></span>'
			+ '<img class="profile_pic" src="'
			+ tweet['profile_image_url'] + '" alt="'
			+ tweet['from_user'] + '" />';
	
	h +=  '<div class="text';
	if (type != 'reply')
		h += ' text-no-reply';
	h +=  '"><div class="text">'
		+ '<span class="from_user">'
		+ '<span class="meta">'
		+ '<a href="http://twitter.com/' + tweet['from_screen_name']
 		+ '/statuses/' + id + '">'
		+ dt.getDate() + '.'
		+ (dt.getMonth() + 1) + '.'
		+ dt.getFullYear() + ' '
		+ dt.getHours() + ':'
		+ dt.getMinutes() + ' Uhr</a>'
		+ '</span>'
		+ 'von <a href="http://twitter.com/'
		+ tweet['from_screen_name'] + '"><strong>'
		+ tweet['from_user'] + '</strong></a>:</span>';
	
	h += format_tweet(tweet['text']);
	
	if (type != 'reply' &&
		tweet['in_reply_to_screen_name'] != '' &&
		tweet['in_reply_to_screen_name'] != null)
	{
		h += '<span class="reply-to" id="reply-to-'
			+ tweet['in_reply_to_status_id'] + '">'
			+ '<a href="http://twitter.com/'
			+ tweet['in_reply_to_screen_name'];
		
		if (isNaN(tweet['in_reply_to_status_id']) === false)
			h += '/statuses/' + tweet['in_reply_to_status_id'];
		
		h += '">Antwort auf ' + tweet['in_reply_to_screen_name'] + '</a></span>';
	}

	h += '</div></div>';
	
	if (type == 'reply')
		h += '<div class="reply-to" id="reply-' + id + '-reply"></div>';
	
	h += '</div>';
	
	return h;
}

function format_tweet(text)
{
	// detect names
	text = text.replace(
		/\@([a-zA-Z0-9_]+)/gi,
		'<a href="http://twitter.com/$1">@$1</a>'
	);
	
	// detect urls
	text = (' ' + text).replace(
		/(\s)http\:\/\/([^\s]+)/gi,
		'$1<a href="http://$2">http://$2</a>'
	);
	
	return text;
}

function show_problem()
{
	hide_loading();
	$('#problem').show();
}

function hide_problem()
{
	$('#problem').hide();
}

function show_loading()
{
	$('#loading').show();
}

function hide_loading()
{
	$('#loading').hide();
}
