
TerminalShell.commands['cd'] = function(terminal, path) {
	if (path in this.pwd) {
		if (this.pwd[path].type == 'dir') {
			this.pwd[path].enter(terminal);
		} else if (this.pwd[path].type == 'file') {
			terminal.print('cd: '+path+': Not a directory');
		}
	} 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') {
			name += '/';
		}
		name_list.append($('<li>').addClass(obj.type).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 {
            terminal.print('cat: '+path+': Is a '+this.pwd[path].type+' file');
        }
	} else {
		terminal.print('You\'re a kitty!');
	}
};

TerminalShell.commands['play'] = function(terminal, path) {
	if (path in this.pwd) {
		if (this.pwd[path].type == 'movie') {
			this.pwd[path].play(terminal);
		} else if (this.pwd[path].type == 'dir') {
			terminal.print('play: '+path+': Is a directory');
		} else {
            terminal.print('play: '+path+': Is not a media file');
        }
	} else {
		terminal.print('play what?');
	}
};

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['chat'] =
TerminalShell.commands['irc'] = function(terminal, nick) {
	$('.irc').slideUp('fast', function() {
		$(this).remove();
	});
	var url = "http://intangir.org/pjirc";
	TerminalShell.commands['curl'](terminal, url).addClass('irc');
}

TerminalShell.commands['shoutmix'] = function(terminal, nick) {
	$('.irc').slideUp('fast', function() {
		$(this).remove();
	});
	var url = "http://www2.shoutmix.com/?intangir";
	TerminalShell.commands['curl'](terminal, url).addClass('irc');
};

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['startx'] =
TerminalShell.commands['gui'] = function(terminal, dest) {
    window.location = '/index.php';
//    Filesystem['forum'].enter();
};
			
TerminalShell.commands['sudo'] = function(terminal) {
	var cmd_args = Array.prototype.slice.call(arguments);
	cmd_args.shift(); // terminal
	if (cmd_args.join(' ') == 'make me a sandwich') {
		terminal.print('Okay.');
	} else {
		var cmd_name = cmd_args.shift();
		cmd_args.unshift(terminal);
		cmd_args.push('sudo');
		if (TerminalShell.commands.hasOwnProperty(cmd_name)) {
			this.sudo = true;
			this.commands[cmd_name].apply(this, cmd_args);
			delete this.sudo;
		} else if (!cmd_name) {
			terminal.print('sudo what?');
		} 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 guest@intangir.org');
		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.');
	}
};

TerminalShell.tabSuggestions = function() {
    return $.extend({}, this.commands, this.pwd);
};

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

function linkMovie(url, width, height) {
	return {type:'movie', play:function(terminal) {
        code = '<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="' + width + '" height="' + height + '"> ' +
            '<param name="movie" value="/video/player-viral.swf" /> ' +
            '<param name="allowfullscreen" value="true" /> ' +
		    '<param name="allowscriptaccess" value="always" /> ' +
		    '<param name="flashvars" value="file=/video/' + url + '" /> ' +
    		'<embed ' +
	    		'type="application/x-shockwave-flash" ' +
	    		'id="player2" ' +
	    		'name="player2" ' +
	    		'src="/video/player-viral.swf" ' +
	    		'width="' + width + '" ' +
	    		'height="' + height + 'irc" ' +
	    		'allowscriptaccess="always" ' +
	    		'allowfullscreen="true" ' +
    			'flashvars="file=/video/' + url + '" ' +
		    '/> ' +
    	    '</object>'

         
        terminal.print($('<p>').html(code));
	}};
}

Filesystem = {
	'welcome.txt': {type:'file', read:function(terminal) {
		terminal.print($('<h4>').text('Welcome to the intangir.org network console.'));
		terminal.print('Use "ls", "cat", "play", and "cd" to navigate the filesystem.');
		terminal.print('Use "gui" to use graphical interface. Use "help" to list more commands.');
	}},

	'favorites.txt': {type:'file', read:function(terminal) {
		terminal.print($('<h4>').text('Favorites'));
		terminal.print($('<p>').html('Linux Distro :: <a href="http://www.linuxmint.com/">Linux Mint - http://www.linuxmint.com</a>'));
		terminal.print($('<p>').html('Philosophy Site :: <a href="http://www.freedomainradio.com/">Free Domain Radio - http://www.freedomainradio.com</a>'));
		terminal.print($('<p>').html('Politics Blog :: <a href="http://freedominourtime.blogspot.com/">Pro Libertate - http://freedominourtime.blogspot.com</a>'));
		terminal.print($('<p>').html('Society for Peace :: <a href="http://http://www.vforvoluntary.com/">V for Voluntary - http://www.vforvoluntary.com</a>'));
		terminal.print($('<p>').html('Liberty Podcast :: <a href="http://completeliberty.com/">Complete Liberty - http://completeliberty.com</a>'));
		terminal.print();
	}},

	'license.txt': {type:'file', read:function(terminal) {
		terminal.print($('<p>').html('Client-side logic for Wordpress CLI theme :: <a href="http://thrind.xamai.ca/">R. McFarland, 2006, 2007, 2008</a>'));
		terminal.print($('<p>').html('jQuery rewrite and overhaul :: <a href="http://www.chromakode.com/">Chromakode, 2010</a>'));
		terminal.print($('<p>').html('Adapted for intangir.org by intangir'));
		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);
		});
	}}
};

Filesystem['wowvid1.mp4'] = linkMovie('wowvid1.mp4', 840, 525);
Filesystem['wowvid2.mp4'] = linkMovie('wowvid2.mp4', 840, 525);

Filesystem['liberty'] = linkFile('http://intangir.org/liberty/');
Filesystem['delinquentminds'] = linkFile('http://www.delinquentminds.com');
Filesystem['facebook'] = linkFile('http://www.facebook.com/intangir.org');
Filesystem['forum'] = linkFile('http://intangir.org/index.php?action=forum');
Filesystem['returners'] = linkFile('http://returners.soulfire.cc');
Filesystem['soulfire'] = linkFile('http://www.soulfire.cc');
TerminalShell.pwd = Filesystem;

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

TerminalShell.fallback = function(terminal, cmd) {
	oneliners = {
		'make me a sandwich': 'What? Make it yourself.',
		'make love': 'I put on my robe and wizard hat.',
		'i read the source code': '<3',
		'pwd': 'You are in a maze of twisty passages, all alike.',
		'lpr': 'PC LOAD LETTER',
		'hello joshua': 'How about a nice game of Global Thermonuclear War?',
		'xyzzy': 'Nothing happens.',
		'hello': 'Why hello there!',
		'who': 'Doctor Who?',
		'intangir': 'Yes?',
		'su': 'God mode activated. Remember, with great power comes great ... aw, screw it, go have fun.',
		'fuck': 'I have a headache.',
		'nano': 'Seriously? Why don\'t you just use Notepad.exe? Or MS Paint?',
		'top': 'It\'s up there --^',
		'moo':'moo',
		'ping': 'There is another submarine three miles ahead, bearing 225, forty fathoms down.',
		'find': 'What do you want to find? Kitten would be nice.',
		'hello':'Hello.','more':'Oh, yes! More! More!',
		'your gay': 'Keep your hands off it!',
		'hi':'Hi.',
        'echo': 'Echo ... echo ... echo ...',
		'bash': 'You bash your head against the wall. It\'s not very effective.',
        'ssh': 'ssh, this is a library.',
		'uname': 'Illudium Q-36 Explosive Space Modulator',
		'finger': 'Mmmmmm...',
		'kill': 'Terminator deployed to 1984.',
		'use the force luke': 'I believe you mean source.',
		'use the source luke': 'I\'m not luke, you\'re luke!',
		'serenity': 'You can\'t take the sky from me.',
		'enable time travel': 'TARDIS error: Time Lord missing.',
		'ed': 'You are not a diety.'
	};
	oneliners['emacs'] = 'You should really use vim.';
	oneliners['vi'] = oneliners['vim'] = 'You should really use emacs.';
	
	cmd = cmd.toLowerCase();
	if (!oneLiner(terminal, cmd, oneliners)) {
		if (cmd == 'time travel') {
			xkcdDisplay(terminal, 630);
		} else if (/:\(\)\s*{\s*:\s*\|\s*:\s*&\s*}\s*;\s*:/.test(cmd)) {
			Terminal.setWorking(true);
		} else {
//			$.get("/unixkcd/missing", {cmd: cmd});
			return false;
		}
	}
	return true;
};

$(document).ready(function() {
	Terminal.promptActive = false;
	$('#screen').bind('cli-load', function(e) {
        Terminal.runCommand('cat welcome.txt');
	});

});

