function pathFilename(path) {
	match = /\/([^\/]+)$/.exec(path);
	if (match) {
		return match[1];
	}
}

function linkFile(url) {
	return {type:'dir', enter:function() {
		window.location = url;
	}};
}

window.GET = function(){
    var array = window.location.search.substring(1).split(/&;/);
        /* URLs can be like either
        "sample.html?test1=hi&test2=bye" or
        "sample.html?test1=hi;test2=bye" */
    window._GET = {};
    for(var i = 0; i < array.length; i++){
        var assign = array[i].indexOf('=');
        if(assign == -1){
            _GET[array[i]] = true;//if no value, treat as boolean
        }else{
            _GET[array[i].substring(0, assign)] = array[i].substring(assign + 1);
        }
    }
}

Filesystem = {
	'welcome.txt': {type:'file', read:function(terminal) {
		terminal.print($('<h4>').text('Welcome to iwannahack.'));
		terminal.print('Try "help" for more information.');
	}},
	'manifesto.txt': {type:'file', read:function(terminal) {
		$.each([
			'=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=',
			'The following was written shortly after my arrest...',
			'',
			'                       \\/\\The Conscience of a Hacker/\\/',
			'',
			'                                      by',
			'',
			'                               +++The Mentor+++',
			'',
			'                          Written on January 8, 1986',
			'=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=',
			'',
			'        Another one got caught today, it\'s all over the papers.  "Teenager',
			'Arrested in Computer Crime Scandal", "Hacker Arrested after Bank Tampering"...',
			'        Damn kids.  They\'re all alike.',
			'',
			'        But did you, in your three-piece psychology and 1950\'s technobrain,',
			'ever take a look behind the eyes of the hacker?  Did you ever wonder what',
			'made him tick, what forces shaped him, what may have molded him?',
			'        I am a hacker, enter my world...',
			'        Mine is a world that begins with school... I\'m smarter than most of',
			'the other kids, this crap they teach us bores me...',
			'        Damn underachiever.  They\'re all alike.',
			'',
			'        I\'m in junior high or high school.  I\'ve listened to teachers explain',
			'for the fifteenth time how to reduce a fraction.  I understand it.  "No, Ms.',
			'Smith, I didn\'t show my work.  I did it in my head..."',
			'        Damn kid.  Probably copied it.  They\'re all alike.',
			'',
			'        I made a discovery today.  I found a computer.  Wait a second, this is',
			'cool.  It does what I want it to.  If it makes a mistake, it\'s because I',
			'screwed it up.  Not because it doesn\'t like me...',
			'                Or feels threatened by me...',
			'                Or thinks I\'m a smart ass...',
			'                Or doesn\'t like teaching and shouldn\'t be here...',
			'        Damn kid.  All he does is play games.  They\'re all alike.',
			'',
			'And then it happened... a door opened to a world... rushing through',
			'the phone line like heroin through an addict\'s veins, an electronic pulse is',
			'sent out, a refuge from the day-to-day incompetencies is sought... a board is',
			'found.',
			'        "This is it... this is where I belong..."',
			'        I know everyone here... even if I\'ve never met them, never talked to',
			'them, may never hear from them again... I know you all...',
			'        Damn kid.  Tying up the phone line again.  They\'re all alike...',
			'',
			'You bet your ass we\'re all alike... we\'ve been spoon-fed baby food at',
			'school when we hungered for steak... the bits of meat that you did let slip',
			'through were pre-chewed and tasteless.  We\'ve been dominated by sadists, or',
			'ignored by the apathetic.  The few that had something to teach found us will-',
			'ing pupils, but those few are like drops of water in the desert.',
			'',
			'        This is our world now... the world of the electron and the switch, the',
			'beauty of the baud.  We make use of a service already existing without paying',
			'for what could be dirt-cheap if it wasn\'t run by profiteering gluttons, and',
			'you call us criminals.  We explore... and you call us criminals.  We seek',
			'after knowledge... and you call us criminals.  We exist without skin color,',
			'without nationality, without religious bias... and you call us criminals.',
			'You build atomic bombs, you wage wars, you murder, cheat, and lie to us',
			'and try to make us believe it\'s for our own good, yet we\'re the criminals.',
			'',
			'        Yes, I am a criminal.  My crime is that of curiosity.  My crime is',
			'that of judging people by what they say and think, not what they look like.',
			'My crime is that of outsmarting you, something that you will never forgive me',
			'for.',
			'',
			'        I am a hacker, and this is my manifesto.  You may stop this individual,',
			'but you can\'t stop us all... after all, we\'re all alike.',
			'',
			'                               +++The Mentor+++'
		], function(num, line) {
			terminal.print(line);
		});
	}},
	'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();
		$.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['retro'] = Filesystem['retro'] = linkFile('http://iwannahack.com/retro');
TerminalShell.pwd = Filesystem;

var Url = {
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	}, 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
}

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['ls'] = function(terminal, path) {
	name_list = $('<ul>');
	$.each(this.pwd, function(name, obj) {
		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.print('You\'re a kitty!');
	}
};

TerminalShell.commands['apt-get'] = function(terminal, subcmd, sudo) {
	if ((sudo!='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 if (subcmd == 'moo') {
			terminal.print('        (__)');
			terminal.print('        (oo)');
			terminal.print('  /------\\/ ');
			terminal.print(' / |    ||  ');
			terminal.print('*  /\\---/\\  ');
			terminal.print('   ~~   ~~  '); 
			terminal.print('...."Have you mooed today?"...');
		} else if (!subcmd) {
			terminal.print('This APT has Super Cow Powers.');
		} else {
			terminal.print('E: Invalid operation '+subcmd);
		}
	}
};

TerminalShell.commands['shutdown'] = TerminalShell.commands['poweroff'] = function(terminal, sudo) {
	if(sudo!='sudo') {
		terminal.print("Must be root.");
	} else {
		terminal.print("Broadcast message from guest@xkcd");
		terminal.print();
		terminal.print("The system is going down for maintenance NOW!");
		return $("#screen").fadeOut();
	}
};

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['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, sudo)
{
    if (sudo!='sudo')
    {
		terminal.print("Must be root.");
    }
    else
    {
        TerminalShell.commands.poweroff(terminal, sudo).queue(function (b)
        {
            window.location.reload();
        })
    }
};

TerminalShell.commands['su'] = function(terminal, subcmd) {
    if(subcmd == undefined) subcmd = 'root';
	terminal.config.prompt = subcmd+'@iwannahack:/$ ';
	terminal.print('You\'ve been logged in as '+subcmd);
}

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 (cmd_name in TerminalShell.commands) {
			this.commands[cmd_name].apply(this, cmd_args);
		} else {
			terminal.print('sudo: '+cmd_name+': command not found');
		}
	}
};

TerminalShell.commands['man'] = function(terminal, what) {
	terminal.print('Oh, I\'m sure you can figure it out.');
};

// No peeking!
TerminalShell.commands['help'] = function(terminal) {
	terminal.print('You can do this.');
}; 

TerminalShell.commands['touch'] = function(terminal) {
	//terminal.print('touch me');
};

TerminalShell.commands['echo'] = function(terminal, input) {
	alert( TerminalShell.thisCommand );
};

TerminalShell.commands['status'] = function(terminal)
{
	terminal.setWorking(true);
	var test = $.ajax({
				url: 'resources/status.php',
				dataType: 'json',
				success: function(stats){
					if(stats.HTTP === true)
					{
						for(test in stats)
						{
							if(stats[test] === true)
							{
								terminal.print($('<span>').addClass('success').text(test +"\t[Running]\n"));
							} else {
								terminal.print($('<span>').addClass('error').text(test +"\t[Stopped]\n"));
							}
						}
					}
					terminal.print();
					terminal.print($('a').attr('href', 'http://iwannahack.com/extra/iwhstats.exe').text('For desktop App click here.'));
				terminal.setWorking(false);
			}
		});
	
}

TerminalShell.fallback = function(terminal, cmd) {
	cmd = cmd.toLowerCase();
	if (cmd == 'find kitten') {
		terminal.print($('<iframe width="800" height="600" src="http://www.robotfindskitten.net/rfk.swf"></iframe>'));
	} else if(cmd == 'date') {
		terminal.print(new Date());
	} else {
		return false;
	}
return true;
};


$(document).ready(function() {
	Terminal.promptActive = false;
	$('#screen').bind('cli-load', function(e) {
		$('#screen').one('cli-ready', function(e) {

		});
	window.GET();
	if(_GET['cmd'])
	{
		Terminal.runCommand(Url.decode(_GET['cmd']));
	} else {
		Terminal.runCommand('cat welcome.txt');
	}
	});
});
