google.setOnLoadCallback(function() {
	var patterns = {
		normal: /^\s*(?:<?(.*?)[>:]+)?\s*(.*)$/,
		action: /^\s*\*+\s*(\w+)\s*(.*)$/
		};
	var nickColors = [
		'ffaeae', 'ffc9ad', 'ffe4ad', 'ffffad', 'e4ffad', 'c9ffad',
		'adffe4', 'adffff', 'ade4ff', 'c9adff', 'e4adff', 'ffadff'
		];
	
	$("div.quote > p").each(function() {
		lines = $(this).text().split(/\n/);
		lines.pop(); // Last element is always empty
		
		data = [];
		nicks = {};
		nicks_placeholder = [];
		
		// Pull and organize data
		for (i in lines) {
			line = lines[i], arr = {
				type: null, nick: null, message: null
			};
			
			if (line.match(patterns.action)) {
				match = line.match(patterns.action);
				arr.type = 'action';
				arr.nick = match[1];
				arr.message = match[2];
			} else {
				match = line.match(patterns.normal);
				arr.type = 'normal';
				arr.nick = match[1] ? match[1] : '';
				arr.message = match[2] ? match[2] : '';
			}
			
			data.push(arr);
			if (arr.nick.length != 0)
				nicks_placeholder.push(arr.nick);
		}
		
		// Assign colors to nicks
		shuffle(nickColors);
		nicks_placeholder = unique(nicks_placeholder);
		for (i = 0, j = 0; i < nicks_placeholder.length; i++, j++) {
			if (j >= nickColors.length) {
				j = 0;
			}
			
			nick = nicks_placeholder[i];
			color = nickColors[j];
			nicks[nick] = color;
		}
		
		// Generate HTML and spit out newly-formatted content
		html = '<table class="quote">';
		for (i in data) {
			line = data[i];
			html += "<tr><th>";
			
			switch (line.type) {
				case 'action':
					html += '*</th><td><span style="color: #' + nicks[line.nick] + '; font-weight: bold;">' +
							htmlentities(line.nick) + '</span> ' + htmlentities(line.message) + '</td></tr>';
					break;
				default:
					// Treat like normal line
					if (line.nick.length == 0) {
						html += "";
					} else {
						html += '<span style="color: #' + nicks[line.nick] + '">&lt;' +
								htmlentities(line.nick) + '&gt;</span>';
					}
					html += "</th><td>" + htmlentities(line.message) + "</td></tr>";
					break;
			}
		}
		html += "</table>";
		
		$(this).parent().html(html).slideDown();
	});
});

function unique(a) {
	var r = new Array();
	o:for(var i = 0, n = a.length; i < n; i++) {
		for(var x = 0, y = r.length; x < y; x++) {
			if (r[x] == a[i]) continue o;
		}
		r[r.length] = a[i];
	}
	return r;
}
