var twiEntries = 2;
var twiLoadEntries = 20;
var twiAccount = 'dzsTurtleBeach';
var twiCacheTime = 5; //in minutes
var twiTimeout = 5; //in seconds

var twiMonth = new Array('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez');

var twiCache, twiCurrent, twiDisTimeout;

function twiDisplay(index) {
	if(!$.isArray(twiCache) || $("#twiContent:animated").length) return;
	var inAnimation;
	if (index == "next") {
		if (twiCurrent + twiEntries > twiLoadEntries - twiEntries) return;
		twiCurrent += twiEntries;
		$("#twiContent").css("top", 0);
		inAnimation = {"height": "hide", "top": 95};
	}
	else if (index == "previous") {
		if (twiCurrent - twiEntries < 0) return;
		twiCurrent -= twiEntries;
		inAnimation = {"height": "hide", "top": 0};
	}
	else {
		twiCurrent = index;
		inAnimation = {"opacity": "show"};
	}
	$("#twiContent").animate(inAnimation, 200, function() {
		for(var i = 0; i < twiEntries; i++) {
			var values = twiCache[twiCurrent + i].created_at.split(" ");
			var date = new Date(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]);
			var hours = date.getHours() + "", minutes = date.getMinutes() + "", seconds = date.getSeconds() + "";
			if (hours.length == 1) hours = "0" + hours;
			if (minutes.length == 1) minutes = "0" + minutes;
			if (seconds.length == 1) seconds = "0" + seconds;
			$("#twiBox .date:eq("+i+")").html("<strong>"+twiMonth[date.getMonth()]+" "+date.getDate()+"</strong> "+hours+":"+minutes+":"+seconds);
			$("#twiBox .text:eq("+i+")").text(twiCache[twiCurrent + i].text);
		}
		
		if (index == "next") {
			$("#twiContent").css("top", 0);
			$("#twiContent").animate({"height": "show"});
		}
		else if (index == "previous") {
			$("#twiContent").css("top", 95);
			$("#twiContent").animate({"height": "show", "top": 0});
		}
	});
}
function twiLoad() {
	$.getJSON("http://api.twitter.com/1/statuses/user_timeline/"+twiAccount+".json", "count="+twiLoadEntries+"&suppress_response_codes&callback=?", function(data) {
		twiCache = data;
		if(data.error) {
			twiError(data.error);
		}
		else if($.isArray(data)) {
			$("#twiBox div.error").fadeOut("fast", function() {
				$("#twiBox div.error").remove();
			});
			twiDisplay(0);
		}
		setTimeout(twiLoad, twiCacheTime * 60 * 1000)
	});
}
function twiError(msg) {
	$("#twiBox *").fadeOut(200);
	setTimeout(function() {
		if(!$("#twiBox div.error").length) $("#twiBox").prepend('<div class="error"></div>');
		$("#twiBox div.error").html("<br /><strong>Twitter:</strong><br />"+msg);
		$("#twiBox div.error").fadeIn();
	}, 210);
}

$(document).ready(function() {
	twiLoad();
	window.setTimeout(function() {
		if(!twiCache) {
			twiError("No response");
		}
	}, twiTimeout*1000);
	
	$("#up").click(function() {
		twiDisplay("previous");
	});
	$("#down").click(function() {
		twiDisplay("next");
	});
	
});

