TT = (function() {

	var Y = YAHOO.util,
		FIND = 191;

	var busy,
		elUser, elStatus,
		shift,
		statuses;

	var game = {
		offset : 0,
		statusId : 0,
		text : ''
	};

	var init = function(o) {

		elStatus = Y.Dom.get('status');
		elUser = Y.Dom.get('user');

		Y.Event.addListener(document, 'keydown', keyDown);
		Y.Event.addListener(document, 'keyup', keyUp);

		load();

	};

	var error = function(msg) {
		busy = true;
		elStatus.className = 'error';
		elStatus.innerHTML = 'Oops! An error occurred: ' + msg;
		elUser.href = 'http://scriptnode.com/';
		elUser.innerHTML = '';
	};

	var forward = function() {

		game.offset++;

		elStatus.innerHTML = '<span>' + game.text.substr(0, game.offset) + '</span>' + game.text.substr(game.offset, game.text.length);

		if (game.offset >= game.text.length) {
			showNext();
		}

	};

	var getChar = function(e) {

		var c = String.fromCharCode(e.keyCode).toLowerCase();

		if (e.shiftKey) {

			switch (c) {
				case '1': c = '!'; break;
				case '2': c = '@'; break;
				case '3': c = '#'; break;
				case '4': c = '$'; break;
				case '5': c = '%'; break;
				case '6': c = '^'; break;
				case '7': c = '&'; break;
				case '8': c = '*'; break;
				case '9': c = '('; break;
				case '0': c = ')'; break;
				case '-': c = '_'; break;
				case '=': c = '+'; break;
				case ';': c = ':'; break;
				case "'": c = '"'; break;
				case "'": c = '"'; break;
				case '/': c = '?'; break;
			}

		}

		switch (c) {
			case '¿': c = '/'; break;
			case '¾': c = '.'; break;
		}

		return c;

	};

	var keyDown = function(e) {

		if (e.keyCode == FIND) {
			Y.Event.stopEvent(e);
		}

		if (busy) {
			return;
		}

		// Don't listen to the shift key by itself
		if (e.shiftKey && !shift) {
			shift = true;
			return;
		}

		if (e.keyCode == 27) {
			forward();
			return;
		}

		var key = getChar(e),
			next = game.text.substr(game.offset, 1).toLowerCase();

		if (key == next) {
			forward();
		}

	};

	var keyUp = function(e) {
		shift = e.shiftKey;
	};

	var load = function() {

		busy = true;
		elStatus.innerHTML = 'Loading…';
		elUser.innerHTML = '';

		Y.Connect.asyncRequest('GET', 'ajax.php', {
			failure : function(o) {
				busy = false;
				error(o.statusText);
			},
			success : function(o) {

				busy = false;

				try {

					eval('statuses = ' + o.responseText);
					game.statusId = 0;
					show();

				} catch(e){
					error(e);
				}

			}
		});		

	};

	var show = function() {

		var o = statuses[game.statusId];

		elStatus.innerHTML = o.text;
		elUser.href = 'http://twitter.com/' + o.user.screen_name;
		elUser.innerHTML = '<img src="' + o.user.profile_image_url + '"> ' + o.user.screen_name;
		game.offset = 0;
		game.text = o.text;
		
	};

	var showNext = function() {

		if (++game.statusId == statuses.length) {
			load();
		} else {
			show();
		}

	};

	return {
		init : init
	};

})();
