function pathFilename(path) {
	var match = /\/([^\/]+)$/.exec(path);
	if (match) {
		return match[1];
	}
}

function getRandomInt(min, max) {
	// via https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/random#Examples
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomChoice(items) {
	return items[getRandomInt(0, items.length-1)];
}

var mig = {
	latest: null,
	last: null,
	cache: {},
	base: 'url=http://meningrey.net/images',
	
	get: function(num, success, error) {
		if (num == null) {
			path = 'info.0.json';
		} else if (Number(num)) {
			path = num+'/info.0.json';
		} else {
			error(false);
			return false;
		}
		
		if (num in this.cache) {
			this.last = this.cache[num];
			success(this.cache[num]);
		} else {
			return $.ajax({
				url: this.base+path,
				dataType: 'json',
				success: $.proxy(function(data) {
					this.last = this.cache[num] = data;
					success(data);
				}, this),
				error: error});
		}
	}
};

var migDisplay = TerminalShell.commands['display'] = function(terminal, path) {
	function fail() {
		terminal.print($('<p>').addClass('error').text('display: unable to open image "'+path+'": No such file or directory.'));
		terminal.setWorking(false);
	}
			
	if (path) {
		path = String(path);
		num = Number(path.match(/^\d+/));
		filename = pathFilename(path);
		
		if (num > mig.latest.num) {
			terminal.print("Time travel mode not enabled.");
			return;
		}
	} else {
		num = mig.last.num;
	}
	
	terminal.setWorking(true);
	mig.get(num, function(data) {
		if (!filename || (filename == pathFilename(data.img))) {
			$('<img>')
				.hide()
				.load(function() {
					terminal.print($('<h3>').text(data.num+": "+data.title));
					$(this).fadeIn();
					
					var comic = $(this);
					if (data.link) {
						comic = $('<a>').attr('href', data.link).append($(this));
					}
					terminal.print(comic);
					
					terminal.setWorking(false);
				})
				.attr({src:data.img, alt:data.title, title:data.alt})
				.addClass('comic');
		} else {
			fail();
		}
	}, fail);
};

TerminalShell.commands['next'] = function(terminal) {
	migDisplay(terminal, mig.last.num+1);
};

TerminalShell.commands['previous'] =
TerminalShell.commands['prev'] = function(terminal) {
	migDisplay(terminal, mig.last.num-1);
};

TerminalShell.commands['first'] = function(terminal) {
	migDisplay(terminal, 1);
};

TerminalShell.commands['latest'] =
TerminalShell.commands['last'] = function(terminal) {
	migDisplay(terminal, mig.latest.num);
};

TerminalShell.commands['random'] = function(terminal) {
	migDisplay(terminal, getRandomInt(1, mig.latest.num));
};


TerminalShell.commands['sudo'] = function(terminal) {
	var cmd_args = Array.prototype.slice.call(arguments);
	cmd_args.shift(); // terminal
	if (cmd_args.join(' ') == 'You cannot be God on this computer') {
		terminal.print('Okay.');
	} else {
		var cmd_name = cmd_args.shift();
		cmd_args.unshift(terminal);
		cmd_args.push('sudo');
		if (cmd_name in TerminalShell.commands) {
			this.sudo = true;
			this.commands[cmd_name].apply(this, cmd_args);
			delete this.sudo;
		} else if (!cmd_name) {
			terminal.print('sudo attempt logged');
		} else {
			terminal.print('sudo: '+cmd_name+': command not found');
		}
	}
};

TerminalShell.filters.push(function (terminal, cmd) {
	if (/!!/.test(cmd)) {
		var newCommand = cmd.replace('!!', this.lastCommand);
		terminal.print(newCommand);
		return newCommand;
	} else {
		return cmd;
	}
});

TerminalShell.commands['shutdown'] = TerminalShell.commands['poweroff'] = function(terminal) {
	if (this.sudo) {
		terminal.print('Broadcast message from remote@mig');
		terminal.print();
		terminal.print('The system is going down for maintenance NOW!');
		return $('#screen').fadeOut();
	} else {
		terminal.print('Must be root.');
	}
};

TerminalShell.commands['logout'] =
TerminalShell.commands['exit'] = 
TerminalShell.commands['quit'] = function(terminal) {
	terminal.print('Bye.');
	$('#prompt, #cursor').hide();
	terminal.promptActive = false;
};

TerminalShell.commands['restart'] = TerminalShell.commands['reboot'] = function(terminal) {
	if (this.sudo) {
		TerminalShell.commands['poweroff'](terminal).queue(function(next) {
			window.location.reload();
		});
	} else {
		terminal.print('Must be root.');
	}
};

function linkFile(url) {
	return {type:'dir', enter:function() {
		window.location = url;
	}};
}

Filesystem = {type:'dir',name:'/',
	'welcome.txt': {type:'file', read:function(terminal) {
		terminal.print('Welcome to PaperClipMonkeys');
		terminal.print("Im an independant Web Developer based in the south west.");
		terminal.print("Mobile: 07595 030008");
		terminal.print("Email: mike@paperclipmonkeys.co.uk");
		//terminal.print('Use "ls", "cat", and "cd" to navigate the filesystem.');
	}},
	'license.txt': {type:'file', read:function(terminal) {
		terminal.print();
		$.each([
			'This program is free software; you can redistribute it and/or',
			'modify it under the terms of the GNU General Public License',
			'as published by the Free Software Foundation; either version 2',
			'of the License, or (at your option) any later version.',
			'',
			'This program is distributed in the hope that it will be useful,',
			'but WITHOUT ANY WARRANTY; without even the implied warranty of',
			'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the',
			'GNU General Public License for more details.',
			'',
			'You should have received a copy of the GNU General Public License',
			'along with this program; if not, write to the Free Software',
			'Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.',
		], function(num, line) {
			terminal.print(line);
		});
		
	}},
	'cv.doc': {type:'file', read:function(terminal) {
	setTimeout('$.colorbox({href:"cv.html",iframe:true,width:"70%", height:"90%"})',1500);//title:"Mendip Caving Group",
	Terminal.runCommand('Loading .  .  .  .  .  .  .')
	}}
};
Filesystem['projects'] = {type:'dir',name:'projects',
	'spaceinvaders.html': {type:'file', read:function(terminal) {
	setTimeout('$.colorbox({href:"http://www.paperclipmonkeys.co.uk/spaceinvaders.html",iframe:true,width:"80%", height:"80%"})',1500);//title:"Mendip Caving Group",
	Terminal.runCommand('Loading .  .  .  .  .  .  .')
	}},
	'ledscreen.html': {type:'file', read:function(terminal) {
	setTimeout('$.colorbox({href:"http://www.paperclipmonkeys.co.uk/ledscreen.html",iframe:true,width:"80%", height:"80%"})',1500);
	Terminal.runCommand('Loading .  .  .  .  .  .  .')
	}},
	'caving.html': {type:'file', read:function(terminal) {
	setTimeout('$.colorbox({href:"http://mendipcavinggroup.org.uk/sections/upperflood/access.html",iframe:true,width:"80%", height:"80%"})',1500);
	Terminal.runCommand('Loading .  .  .  .  .  .  .')
	}}
}
Filesystem['websites'] = Websites = {type:'dir',name:'websites',
	'millbarn.html': {type:'file', read:function(terminal) {
	setTimeout('$.colorbox({href:"http://www.millbarnsomerset.co.uk",iframe:true,width:"80%", height:"80%"})',1500);
	Terminal.runCommand('Loading .  .  .  .  .  .  .');
	}},
	'assemblyrooms.html': {type:'file', read:function(terminal) {
	setTimeout('$.colorbox({href:"http://www.assemblyrooms.org.uk",iframe:true,width:"80%", height:"80%"})',1500);
	Terminal.runCommand('Loading .  .  .  .  .  .  .');
	}},
	'woodenbooks.html': {type:'file', read:function(terminal) {
	setTimeout('$.colorbox({href:"http://www.woodenbooks.co.uk",iframe:true,width:"80%", height:"80%"})',1500);
	Terminal.runCommand('Loading .  .  .  .  .  .  .');
	}}
}
//Filesystem['projects'] = Filesystem['projects'] = linkFile('http://meningrey.net/%5C/home/mig');
TerminalShell.pwd = Filesystem;

TerminalShell.commands['cd'] = function(terminal, path) {
    if (path in this.pwd) {
        if (this.pwd[path].type == 'dir') {
            //this.pwd[path].enter(terminal);
            TerminalShell.pwd = this.pwd[path];
			Terminal.config.prompt = "remote@Pcm:"+TerminalShell.pwd.name+"$ ";
			Terminal.updateInputDisplay();
        } else if (this.pwd[path].type == 'file') {
            terminal.print('cd: '+path+': Not a directory');
        
		}
    } else if (path == '/' || path == '../') {//Move to root Dir
            TerminalShell.pwd = Filesystem;
			Terminal.config.prompt = "remote@Pcm:"+TerminalShell.pwd.name+"$ ";
			Terminal.updateInputDisplay();
        }
	else {
        terminal.print('cd: '+path+': No such file or directory');
    }
};

TerminalShell.commands['dir'] =
TerminalShell.commands['ls'] = function(terminal, path) {
	var name_list = $('<ul>');
	$.each(this.pwd, function(name, obj) {
		if (obj.type == 'dir'||obj.type=='file') {
		if (obj.type == 'dir') {
			name += '/';
		}
		name_list.append($('<li>').text(name));
		}
	});
	terminal.print(name_list);
};

TerminalShell.commands['cat'] = function(terminal, path) {
	if (path in this.pwd) {
		if (this.pwd[path].type == 'file') {
			this.pwd[path].read(terminal);
		} else if (this.pwd[path].type == 'dir') {
			terminal.print('cat: '+path+': Is a directory');
		}
	} else if (pathFilename(path) == 'alt.txt') {
		terminal.setWorking(true);
		num = Number(path.match(/^\d+/));
		mig.get(num, function(data) {
			terminal.print(data.alt);
			terminal.setWorking(false);
		}, function() {
			terminal.print($('<p>').addClass('error').text('cat: "'+path+'": No such file or directory.'));
			terminal.setWorking(false);
		});
	} else {
		terminal.print('\'cat\' requires a file as argument.');
	}
};

TerminalShell.commands['rm'] = function(terminal, flags, path) {
	if (flags && flags[0] != '-') {
		path = flags;
	}
	if (!path) {
		terminal.print('rm: missing operand');
	} else if (path in this.pwd) {
		if (this.pwd[path].type == 'file') {
			delete this.pwd[path];
		} else if (this.pwd[path].type == 'dir') {
			if (/r/.test(flags)) {
				delete this.pwd[path];
			} else {
				terminal.print('rm: cannot remove '+path+': Is a directory');
			}
		}
	} else if (flags == '-rf' && path == '/') {
		if (this.sudo) {
			TerminalShell.commands = {};
		} else {
			terminal.print('rm: cannot remove /: Permission denied');
		}
	}
};
TerminalShell.commands['proxy'] = function(terminal, path) {
	terminal.runCommand('Loading . . . . . . . . . . . . ');	
	setTimeout('document.location = \'/cgi-bin/cgiproxy/nph-proxy.pl\'',1500);
};

TerminalShell.commands['wget'] = TerminalShell.commands['curl'] = function(terminal, dest) {
	if (dest) {
		terminal.setWorking(true);
		var browser = $('<div>')
			.addClass('browser')
			.append($('<iframe>')
					.attr('src', dest).width("100%").height(600)
					.one('load', function() {
						terminal.setWorking(false);
					}));
		terminal.print(browser);
		return browser;
	} else {
		terminal.print("Please specify a URL.");
	}
};

TerminalShell.commands['write'] =
TerminalShell.commands['irc'] = function(terminal, nick) {
	if (nick) {
		$('.irc').slideUp('fast', function() {
			$(this).remove();
		});
		var url = "http://riaa.com";
		if (nick) {
			url += "&nick=" + encodeURIComponent(nick);
		}
		TerminalShell.commands['curl'](terminal, url).addClass('irc');
	} else {
		terminal.print('usage: irc <nick>');
	}
};

TerminalShell.commands['fuck'] = function(terminal, nick) {
	TerminalShell.commands['curl'](terminal, "http://www.riaa.com/physicalpiracy.php?content_selector=piracy_online_the_law");
};

TerminalShell.commands['apt-get'] = function(terminal, subcmd) {
	if (!this.sudo && (subcmd in {'update':true, 'upgrade':true, 'dist-upgrade':true})) {
		terminal.print('E: Unable to lock the administration directory, are you root?');
	} else {
		if (subcmd == 'update') {
			terminal.print('Reading package lists... Done');
		} else if (subcmd == 'upgrade') {
			if (($.browser.name == 'msie') || ($.browser.name == 'firefox' && $.browser.versionX < 3)) {
				terminal.print($('<p>').append($('<a>').attr('href', 'http://abetterbrowser.org/').text('To complete installation, click here.')));
			} else {
				terminal.print('This looks pretty good to me.');
			}
		} else if (subcmd == 'dist-upgrade') {
			var longNames = {'win':'Windows', 'mac':'OS X', 'linux':'Linux'};
			var name = $.os.name;
			if (name in longNames) {
				name = longNames[name];
			} else {
				name = 'something fancy';
			}
			terminal.print('You are already running '+name+'.');
		} else {
			terminal.print('E: Invalid operation '+subcmd);
		}
	}
};

function oneLiner(terminal, msg, msgmap) {
	if (msg in msgmap) {
		terminal.print(msgmap[msg]);
		return true;
	} else {
		return false;
	}
}

TerminalShell.commands['man'] = function(terminal, what) {
	pages = {
		'last': 'Man, last night was AWESOME.',
		'help': 'Man, help me out here.',
		'next': 'Request confirmed; you will be reincarnated as a man next.',
		'cat':  'You are now riding a half-man half-cat.'
	};
	if (!oneLiner(terminal, what, pages)) {
		terminal.print('Oh, I\'m sure you can figure it out.');
	}
};

TerminalShell.commands['locate'] = function(terminal, what) {
	keywords = {
		'ninja': 'Ninja can not be found!',
		'keys': 'Have you checked your coat pocket?',
		'joke': 'Joke found on user.',
		'problem': 'Problem exists between keyboard and chair.',
		'raptor': 'BEHIND YOU!!!'
	};
	if (!oneLiner(terminal, what, keywords)) {
		terminal.print('Locate what?');
	}
};


// No peeking!
TerminalShell.commands['help'] = TerminalShell.commands['halp'] = function(terminal) {
	terminal.print('Refer to handbook H81: Introduction to the Bourne Shell');
}; 

TerminalShell.fallback = function(terminal, cmd) {
	oneliners = {
		'pwd': '/root/watchtower/audits/civ/pending/by_addr/',
		'lpr': 'The buffer has been printed.\nRetrieve on return to your bureau of service.',
		'date': 'April 7, 1969',
		'hello': 'This is not Internet Relay Chat.\nPersist with your task Officer.',
		'who': 'This is not IRC. Persist with your task Officer.',
		'su': 'Remote privilege elevation is denied.',
		'whoami': 'You are an officer of the Men In Grey.',
		'hi':'Hi.',
		'bash': '\n',
		'ssh': 'sshh',
		'uname': '2.7.42-1-686-bigmem',
		'finger': 'Fingers are for typing commands.\nPersist with your task Officer.',
		'kill': 'Remote termination of processes is denied.',
		'ed': 'You are not a diety.'
	};
	oneliners['emacs'] = 'I think you mean vim.';
	oneliners['vi'] = oneliners['vim'] = 'Use of text editors by remote agents is prohibited.\n Lookup and auditing only.';
	
	cmd = cmd.toLowerCase();
	return true;
};
	function shake(elems) {
			elems.css('position', 'relative');
			return window.setInterval(function() {
								if(Math.random()>'0.75'){

				elems.css({top:getRandomInt(-1, 1), left:getRandomInt(-1, 1)});
								}
			}, 300);	
		}
var konamiCount = 0;
$(document).ready(function() {
	Terminal.promptActive = false;
	$('#screen').bind('cli-load', function(e) {
			Terminal.runCommand('Connecting to paperclipmonkeys.co.uk:23 . . . . . . . . . .\n Connection established \n Your actions are being logged for later analysis\n Use "ls", "cat", and "cd" to navigate the filesystem.');
			//Terminal.runCommand('cat welcome.txt');
			Terminal.promptActive = true;
			shake($('#screen'))
	});
	
	$(document).konami(function(){
		function shake(elems) {

		}
		
		if (konamiCount == 0) {
			$('#screen').css('text-transform', 'uppercase');
		} else if (konamiCount == 1) {
			$('#screen').css('text-shadow', 'gray 0 0 2px');
		} else if (konamiCount == 2) {
			$('#screen').css('text-shadow', 'orangered 0 0 10px');
		} else if (konamiCount == 3) {
			shake($('#screen'));
		} else if (konamiCount == 4) {
			$('#screen').css('background', 'url(../mig.png) center no-repeat');
		}
		
		$('<div>')
			.height('100%').width('100%')
			.css({background:'white', position:'absolute', top:0, left:0})
			.appendTo($('body'))
			.show()
			.fadeOut(1000);
		
		if (Terminal.buffer.substring(Terminal.buffer.length-2) == 'ba') {
			Terminal.buffer = Terminal.buffer.substring(0, Terminal.buffer.length-2);
			Terminal.updateInputDisplay();
		}
		TerminalShell.sudo = true;
		konamiCount += 1;
	});
});
