
function dbg(txt) { if (window.console) console.log(txt); }

var Terminal = new Class({

	commandHistory: [],
	commandHistoryIndex: -1,

	initialize: function(container) {
		this.terminal = container;
		this.out('Welcome to <a id="welcomelink" href="http://enekoalonso.com">enekoalonso.com</a>.');
		this.out('Type \'help\' for a list of available commands.');
		this.out('&nbsp;');
		this.prompt();

		$('welcomelink').focus();

		this.path = '.';

		// Hook events
		$(document).addEvent('keydown',  function(event) { this.keydown(event); }.bind(this));
		$(document).addEvent('keypress', function(event) { this.keypress(event); }.bind(this));
	},

	// Process keystrokes
	keydown: function(event) {
		dbg('keydown> ' + event.key + '(' + event.code + ') ' + event.control + ' - ' + event.shift + ' - ' + event.alt + ' - ' + event.meta);
		if (event.control /*|| event.shift*/ || event.alt || event.meta) return;
		//var command = this.currentCommand.get('html');

		if (event.key == 'enter') {
			event.preventDefault();
			this.run();
			return;
		}
	},

	keypress: function(event) {
		dbg('keypress> ' + event.key + '(' + event.code + ') ' + event.control + ' - ' + event.shift + ' - ' + event.alt + ' - ' + event.meta);
		if (event.control /*|| event.shift*/ || event.alt || event.meta) return;
		var command = this.currentCommand.get('html');

		//$('body').focus();

		if (event.key == 'enter') {
			event.preventDefault();
		//	this.run();
			return;
		}

		if (event.key == 'backspace') {
			event.preventDefault();
			if (command.substr(command.length-6) == '&nbsp;') {
				command = command.substr(0, command.length-6);
			} else {
				command = command.substr(0, command.length-1);
			}
			this.currentCommand.set('html', command);
			return;
		}

		// if (event.key == 'tab') {
		// 	event.preventDefault();
		// 	this.guess();
		// 	return;
		// }

		if (event.key == 'space') {
			event.preventDefault();
			command += '&nbsp;';
			this.currentCommand.set('html', command);
			return;
		}

		if (event.code == 38) { // Up arrow
			event.preventDefault();
			dbg(this.commandHistoryIndex + ', ' + this.commandHistory.length);
			if (this.commandHistoryIndex > 0) {
				this.commandHistoryIndex--;
				this.currentCommand.set('html', this.commandHistory[this.commandHistoryIndex]);
			}
			return;
		}

		if (event.code == 40) { // Down arrow
			event.preventDefault();
			dbg(this.commandHistoryIndex + ', ' + this.commandHistory.length);
			if (this.commandHistoryIndex < this.commandHistory.length) {
				this.commandHistoryIndex++;
				this.currentCommand.set('html', this.commandHistory[this.commandHistoryIndex]);
				// This can overflow the array by 1, which will clear the command line
			}
		}

		// For all typing keys
		if (this.validkey(event.code)) {
			event.preventDefault();
			if (event.code == 46) {
				command += '.';
			} else {
				command += event.key;
			}
			this.currentCommand.set('html', command);
			return;
		}
	},

	validkey: function(code) {
		return  (code > 64 && code < 91)  ||	// [A-Z]
				(code > 96 && code < 123) ||	// [a-z]
				(code == 95) || // _
				(code > 44 && code < 58);		// -./[0-9]
	},

	// Outputs a line of text
	out: function(text) {
		var p = new Element('div');
		p.set('html', text);
		this.terminal.grab(p);
	},

	// Displays the prompt for command input
	prompt: function() {
		if (this.currentPrompt)
			this.currentPrompt.getElement('.cursor').destroy();

		this.currentPrompt = new Element('div');
		this.currentPrompt.grab(new Element('span').addClass('prompt').set('text', '[enekoalonso.com]$'));
		this.currentCommand = new Element('span').addClass('command');
		this.currentPrompt.grab(this.currentCommand);
		this.currentPrompt.grab(new Element('span').addClass('cursor'));
		this.terminal.grab(this.currentPrompt);
		$(window).scrollTo(0, this.currentPrompt.getPosition().y);
	},

	guess: function() {
		var command = this.currentCommand.get('html');
		if (command.substr(0,1) == 'c')
			command = 'copy';
		this.currentCommand.set('html', command);
	},

	// Executes a command
	run: function() {
		var command = this.currentCommand.get('text');

		this.commandHistory.push(command);
		this.commandHistoryIndex = this.commandHistory.length;

		if (command == 'help') {
			this.out('List of available commands:');
			this.out('<span class="commandhelp">blog</span>Eneko\'s blog.')
			this.out('<span class="commandhelp">clear</span>Clear screen.')
			this.out('<span class="commandhelp">contact</span>Contact info.')
			this.out('<span class="commandhelp">copy</span>Copyright info.')
			this.out('<span class="commandhelp">date</span>Displays the current date.');
			this.out('<span class="commandhelp">goto</span>Jump to other pages.');
			this.out('<span class="commandhelp">help</span>Displays this list.');
			this.out('<span class="commandhelp">linkedin</span>Link to LinkedIn profile.');
			this.out('<span class="commandhelp">ls</span>List directories.');
			this.out('<span class="commandhelp">press</span>Press related links.');
			this.out('<span class="commandhelp">projects</span>List of projects Eneko is involved on.');
			this.out('<span class="commandhelp">skills</span>Professional skills.');
			this.out('<span class="commandhelp">svn</span>SVN repository address.')
			this.out('<span class="commandhelp">resume</span>Displays a compact resume.');
			this.out('<span class="commandhelp">whois</span>Who is Eneko Alonso?');
			this.prompt();
			return;
		}

		// ---------------------
		
		if (command == 'blog') {
			this.out('<a target="_blank" href="http://dev.enekoalonso.com">dev.enekoalonso.com</a> - Having fun with code');
			this.prompt();
			return;
		}

		if (command == 'clear') {
			this.currentPrompt = null;
			this.terminal.empty();
			this.prompt();
			return;
		}

		if (command == 'contact') {
			this.out('mail@enekoalonso.com');
			this.prompt();
			return;
		}

		if (command == 'copy') {
			this.out('Copyright &copy; 2008 Eneko Alonso');
			this.prompt();
			return;
		}
		
		if (command == 'date') {
			this.out(new Date());
			this.prompt();
			return;
		}

		if (command.substr(0,4) == 'goto') {
			var dest = command.substr(5);
			if (dest == 'blog')      { window.location.href = 'http://dev.enekoalonso.com'; }
			if (dest == 'linkedin')  { window.location.href = 'http://www.linkedin.com/in/eneko'; }
			if (dest == 'spaniards') { window.location.href = 'http://www.spaniards.es'; }
			if (dest == '') { this.out('destination: blog, linkedin, spaniards'); }
			this.prompt();
			return;
		}

		if (command == 'linkedin') {
			this.out('<a target="_blank" href="http://www.linkedin.com/in/eneko" target="_blank">http://www.linkedin.com/in/eneko</a>');
			this.prompt();
			return;
		}

		if (command.substr(0,2) == 'ls') {
			var dest = command.substr(3).trim();
			var request = new Request.HTML().get('terminal.php?command=ls&path='+this.path+'/'+dest);
			request.addEvent('complete', function() {
				if (request.isSuccess()) {
					this.out(request.response.html);
				} else {
					this.out('Error: server request failed.');
				}
				this.prompt(); // Do not show prompt until ajax call is complete
			}.bind(this));
			return;
		}

		if (command == 'press') {
			this.out('<span class="date">Mar 03, 2008</span> <span class="title">Interview with Elia</span> <a class="mp3" target="_blank" href="/press/20080303_entrevista_elia_eneko.mp3">mp3</a> <a class="www" target="_blank" href="http://www.elia.ws/blog/paso_por_paso_robles/">www</a>');
			this.out('<span class="date">Sep 30, 2007</span> <span class="title">Spaniards.es at Galicia Hoxe</span> <a class="pdf" target="_blank" href="/press/20070930_spaniards.es_galiciahoxe_page1.pdf">pdf1</a> <a class="pdf" target="_blank" href="/press/20070930_spaniards.es_galiciahoxe_page2.pdf">pdf2</a>');
			this.out('<span class="date">Sep 25, 2007</span> <span class="title">Spaniards.es at 5lineas.com</span> <a class="png" target="_blank" href="/press/20070925_spaniards.es_5lineas.com.png">png</a> <a class="www" target="_blank" href="http://5lineas.com/archivo/entrevistas/entrevista-a-eneko-alonso-spaniards/">www</a>');
			this.out('<span class="date">Mar 30, 2007</span> <span class="title">Spaniards.es at Infoempleo</span> <a class="pdf" target="_blank" href="/press/20070330_spaniards.es_infoempleo.pdf">pdf</a>');
			this.out('<span class="date">Feb 08, 2006</span> <span class="title">Spaniards.es at Diario de Navarra</span> <a class="pdf" target="_blank" href="/press/20060208_spaniards.es_diariodenavarra.pdf">pdf</a>');
			this.prompt();
			return;
		}

		if (command == 'projects') {
			this.out('<b>spaniards.es</b> - An online community for Spanish people living abroad (<a target="_blank" href="http://www.spaniards.es">www.spaniards.es</a>)');
			this.out('<b>vaka-framework</b> - A Mootools based set of classes (<a target="_blank" href="http://vaca-framework.googlecode.com">vaca-framework.googlecode.com</a>)');
			this.prompt();
			return;
		}

		if (command == 'skills') {
			this.out('<b><i>Eneko Alonso’s Specialties:</i></b>');
			this.out('PHP, Javascript, AJAX, jQuery, Mootools, Prototype, Scriptaculous, Drupal');
			this.out('C/C++, Delphi, Python and Cocoa/Objective-C');
			this.out('MySQL, Sybase and Oracle');
			this.prompt();
			return;
		}

		if (command == 'svn') {
			this.out('<a target="_blank" href="http://enekoalonso.com/svn">enekoalonso.com/svn</a> - SVN code repository I use for research and development');
			this.prompt();
			return;
		}
		
		if (command == 'resume') {
			this.out(' - <b><i>Senior UI Developer</i></b> at LEVEL Studios since June 2008');
			this.out(' - <b><i>Founder/CEO</i></b> at Spaniards.es LLC since November 2005');
			this.out(' - <b><i>Lead Programmer/Analyst</i></b> at 3i Infotech from January 2005 to June 2008');
			this.out(' - <b><i>Programmer/Analyst</i></b> at Fedetec from October 2002 to December 2004');
			this.out(' - <b><i>Senior Programmer</i></b> at Cap Gemini Ernst &amp; Young from April 2001 to August 2002');
			this.out(' - <b><i>Programmer</i></b> at Axpe Consulting &amp; Price Waterhouse Coopers from October 2000 to April 2001');
			this.prompt();
			return;
		}
		
		if (command == 'whois') {
			this.out('<img src="/img/eneko.jpg"/><b>Eneko Alonso</b> is a software enginner with more than eight years of experience in web, desktop and server software:<br/><i class="bio">I am a software engineer who likes beautiful code and good design. I love debugging and digging into the code, finding out how things work. During my career I have worked on client/server environments, both Unix and Windows, developing multi threaded services and DB driven software. I have also been in contact with web development, both front and back end, learning from the latest technologies and putting them in practice in multiple projects.</i>');
			this.prompt();
			return;
		}

		if (command)
			this.out('-bash: ' + command + ': command not found');

		this.prompt();
	}
});

$(window).addEvent('domready', function() {
	window.terminal = new Terminal($('terminal'));
});
