var bad_word = 1;

function toolbar_mousedown(button)
{
	if (currently_opened != button)
	{
		get_floaty().innerHTML = '';
	}
}

function toolbar_mouseup(button)
{
	switch (button)
	{
		case 'bold':
			insert_around_selection('<b>', '</b>');
			break;
		case 'italic':
			insert_around_selection('<i>', '</i>');
			break;
		case 'underline':
			insert_around_selection('<u>', '</u>');
			break;
		case 'strike':
			insert_around_selection('<s>', '</s>');
			break;
		case 'superscript':
			insert_around_selection('<sup>', '</sup>');
			break;
		case 'subscript':
			insert_around_selection('<sub>', '</sub>');
			break;
		default:
			open_floaty(button);
			break;
	}
}



var currently_opened = '';

function get_floaty()
{
	return document.getElementById('float_box');
}

function show_suggestions(word_id)
{
	var word = document.getElementById(word_id);
	var floaty = get_floaty();
	var loc = getLocation(word);
	var x = loc[0];
	var y = loc[1] + 20;
	
	currently_opened = '';
	var code = '<div style="position:absolute; left:' + x + 'px; top:' + y + 'px; border:1px solid #f00; background-color:#d88;">';
	
	for (var i = 0; i < suggestions.length; ++i)
	{
		if (suggestions[i][0] == word_id)
		{
			for (var j = 0; j < suggestions[i][1].length; ++j)
			{
				code += '<div>' + suggestions[i][1][j] + '</div>';
			}
			
			if (suggestions[i][1].length == 0)
			{
				code += 'No suggestions';
			}
			break;
			
		}
	}
	
	code += '</div>';
	floaty.innerHTML = code;
}

function open_floaty(button)
{

	var image = document.getElementById('toolbar_button_'+button);
	var loc = getLocation(image);
	var x = loc[0];
	var y = loc[1] + 32;
	var width = 250;
	var floaty = get_floaty();
	var title = "???";
	
	switch (button)
	{
		case 'link':
			title = "Insert Link";
			code = link_popup();
			break;
		case 'color':
			title = "Text Color";
			width = 370;
			code = color_popup();
			break;
		case 'symbol':
			title = "Insert Symbol";
			code = symbols_popup();
			break;
		case 'equation':
			title = "Insert Equation";
			code = 'Equation editor is still under construction.';
			break;
		case 'smiley':
			title = "Insert Smiley";
			code = '<table cellpadding="4">';
			for (var i = 0; i < emoticons.length; ++i)
			{
				code += '<tr>';
				for (var j = 0; j < 4; ++j)
				{
					if (i < emoticons.length)
					{
						code += '<td><img onmousedown="insert_emote('+"'" + add_slashes(emoticons[i][0])+"'"+')" src="/ui/forum/emoticons/' + emoticons[i][1] + '.png" /></td>';
					}
					else
					{
						code += '<td></td>';
					}
					++i;
				}
				code += '</tr>';
			}
			code += '</table>';
			break;
		case 'code':
			title = "Syntax Highlighter";
			var options = ['Html', 'Xml', 'C#', 'Java', 'Python', 'C', 'C++', 'PHP', 'JavaScript', 'MySQL', 'Other'];
			var optkeys = ['html', 'xml', 'csharp', 'java', 'python', 'c', 'cpp', 'php', 'javascript', 'mysql', 'other'];
			
			code = '<div style="color:#888; font-weight:bold;">Select Language...</div>';
			for (var i = 0; i < options.length; ++i)
			{
				code += '<div style="padding:4px; font-size:14px;; font-weight:bold;"><a style="color:#fff;" href="javascript:insert_code_tag('+"'"+optkeys[i]+"'"+')">' + options[i] + '</a></div>';
			}
			code += '</div>';
			break;
		case 'quote':
			title = "Insert Quote";
			code = 'Quote popup is still under construction.';
			break;
		case 'files':
			title = "Insert Image/File";
			width = 550;
			code = insert_file();
			break;
		default:
			code = 'unknown popup';
			break;
	}
	
	code = '<div style="color:#fff; font-size:16px; font-weight:bold;"><div style="width:50px; float:right;text-align:right;"><img src="/ui/buttons/button_close.png" onmouseup="close_popup()"/></div>' + title + '</div><div style="clear:both;">' + code + '</div>';
	
	floaty.innerHTML = '<div style="color:#fff; border:1px solid #888; background-image:url(/ui/dim_fill.png); position:absolute; left:' + x + 'px; top:' + y + 'px; width:'+width+'px;">' + code + '</div>';
	
	if (button == 'files')
	{
		change_file_filter();
	}
	else if (button == 'color')
	{
		document.getElementById("color_bg").onmousemove = color_field_move;
		document.getElementById("color_bg").onmousedown = color_field_down;
		document.getElementById("color_bg").onmouseup = color_field_up;
		document.getElementById("color_bg").onmouseout = color_field_up;
		document.getElementById("color_dot").onmousemove = color_field_move;
		document.getElementById("color_dot").onmousedown = color_field_down;
		document.getElementById("color_dot").onmouseup = color_field_up;
		document.getElementById("color_dot").onmouseout = color_field_up;
		document.getElementById("wainbow").onmousemove = hue_move;
		document.getElementById("wainbow").onmousedown = hue_down;
		document.getElementById("wainbow").onmouseup = hue_up;
		document.getElementById("wainbow").onmouseout = hue_up;
	}
}

function close_popup()
{
	get_floaty().innerHTML = '';
}

function link_popup()
{
	var code = '<table>';
	code += '<tr><td>URL: </td><td><input id="link_url" type="text" value="http://"/></td></tr>';
	code += '<tr><td>Text: </td><td><input id="link_text" type="text" /></td></tr>';
	code += '</table>';
	code += '<div style="text-align:right;">';
	code += '<a href="javascript:insert_link()">Insert</a>';
	code += '</div>';
	return code;
}

function insert_link()
{
	var url = document.getElementById('link_url').value;
	var text = document.getElementById('link_text').value;
	
	insert_text('<link url="' + url + '">' + text + '</link>');
}

function insert_code_tag(language)
{
	get_floaty().innerHTML = '';
	if (language == "Other")
	{
		insert_text('<code></code>');
	}
	else
	{
		insert_text('<code language="' + language + '"></code>');
	}
}

function add_slashes(text)
{
	return text.replace('\\', '\\\\').replace("'", "\\'").replace('"', '\\"');
}

function insert_emote(emote)
{
	get_floaty().innerHTML = '';
	insert_text('<emote>' + emote + '</emote>')
}

function get_textbox()
{
	return document.getElementById('post_textbox');
}

function doGetCaretPosition()
{
	var ctrl = get_textbox();
	var CaretPos = 0;
	if (document.selection)
	{
		// IE
		ctrl.focus();
		var sel = document.selection.createRange();
		sel.moveStart('character', -ctrl.value.length);
		CaretPos = sel.text.length;
	}
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
	{
		// Firefox
		CaretPos = ctrl.selectionStart;
	}
	return (CaretPos);
}


function getLocation(obj)
{
	var curleft = curtop = 0;
	
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft, curtop];
}


function insert_around_selection(start, end)
{
	var textarea = get_textbox();
	textarea.focus();
	if (document.selection)
	{
		//THIS IS BROKEN FOR IE
		var foo = document.selection.createRange();
		foo.text = text;
	}
	else
	{
		var startPos = textarea.selectionStart;
		var endPos = textarea.selectionEnd;
		var before = textarea.value.substr(0, startPos);
		var selected = textarea.value.substr(textarea.selectionStart, (textarea.selectionEnd - textarea.selectionStart));
		var after = textarea.value.substr(textarea.selectionEnd, (textarea.value.length - textarea.selectionEnd));
		textarea.value = before + start + selected + end + after;
	}
}

function insert_text(text)
{
	var textarea = get_textbox();
	textarea.focus();
	if (document.selection)
	{
		//THIS IS BROKEN FOR IE
		var foo = document.selection.createRange();
		foo.text = text;
	}
	else
	{
		var startPos = textarea.selectionStart;
		var endPos = textarea.selectionEnd;
		var before = textarea.value.substr(0, startPos);
		var selected = textarea.value.substr(textarea.selectionStart, (textarea.selectionEnd - textarea.selectionStart));
		var after = textarea.value.substr(textarea.selectionEnd, (textarea.value.length - textarea.selectionEnd));
		textarea.value = before + text + after;
	}
}

var symbol_categories = [
['Math', 'times divide forall part exist empty nabla isin notin ni prod sum minus lowast radic prop infin ang and or cap cup int there4 sim cong asymp ne equiv le ge sub sup nsub sube supe oplus otimes perp sdot'],
['Uppercase accents', 'Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml Oslash Ugrave Uacute Ucirc Uuml Yacute THORN Yuml'],
['Lowercase accents', 'agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml oslash ugrave uacute ucirc uuml yacute thorn yuml szlig'],
['Greek Uppercase', 'Alpha Beta Gamma Delta Epsilon Zeta Eta Theta Iota Kappa Lambda Mu Nu Xi Omicron Pi Rho Sigma Tau Upsilon Phi Chi Psi Omega'],
['Greek Lowercase', 'alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega'],
['Currency', 'cent pound yen euro'],
['Miscellaneous', 'larr uarr rarr darr trade copy reg spades clubs hearts diams']];

function symbol_table(n)
{
	var grid = document.getElementById('symbol_grid');
	if (grid)
	{
		var output = '<table style="font-size:20px; font-weight:bold;">';
		var symbols = symbol_categories[n][1].split(' ');
		var width = 6;
		var i = 0;
		
		while (i < symbols.length)
		{
			output += '<tr>';
			
			for (var column = 0; column < width; ++column)
			{
				output += '<td>';
				
				if (i < symbols.length)
				{
					output += '<a style="color:#bbb;" href="javascript:insert_text(' + "'" + '&'+symbols[i]+';' + "'" + ')">';
					output += '&'+symbols[i]+';'
					output += '</a>';
					++i;
				}
				
				output += '</td>';
			}
			
			output += '</tr>';
		}
		output += '</table>';
		
		grid.innerHTML = output;
	}
}

function symbols_popup()
{
	var output = '<table><tr valign="top"><td width="70">';
	
	for (var i = 0; i < symbol_categories.length; ++i)
	{
		output += '<div style="padding:4px; font-size:14px; font-weight:bold;"><a style="color:#fff;" href="javascript:symbol_table('+"'"+i+"'"+')">' + symbol_categories[i][0] + '</a></div>';
	}
	
	output += '</td><td>';
	output += '<div id="symbol_grid">';
	
	output += '</div>';
	output += '</td></tr></table>';
	return output;
}

function color_popup()
{
	var output = '<table><tr align="center" valign="top"><td width="210">';
	
	output += '<div style="width:200px; height:200px; background-image:url(/ui/hsl_layer.png); background-color:'+hue_hex()+';" id="color_bg">';
	output += '<div style="width:200px; height:200px; background-image:url(/ui/color_dot.png); background-repeat:no-repeat; background-position:20px 80px;" id="color_dot">';
	output += '</div>';
	output += '</div>';
	
	output += '</td><td width="25">';
	
	output += '<table cellspacing="0" cellpadding="0"><tr><td>';
	output += '<div id="wainbow" style="background-image:url(/ui/rainbow.png); height:200px; width:20px;"></div>';
	output += '</td><td>';
	output += '<div id="hue_pointer" style="width:11px; height:200px; background-image:url(/ui/color_hue_pointer.png); background-repeat:no-repeat; background-position:0px 116px;"></div>';
	output += '</td></tr></table>';
	
	output += '</td><td width="100" style="text-align:left;">';
	
	output += '<div style="background-color:' + active_hex() + '; width:100px; height:50px;" id="color_preview">&nbsp;</div>';
	
	output += '<div style="color:#fff; font-weight:bold; font-size:16px;">';
	output += '<div id="col_r" style="padding:10px;">Red:&nbsp;' + active_red + '</div>';
	output += '<div id="col_g" style="padding:10px;">Green:&nbsp;' + active_green + '</div>';
	output += '<div id="col_b" style="padding:10px;">Blue:&nbsp;' + active_blue + '</div>';
	output += '</div>';
	
	output += '</td></tr>';
	
	output += '<tr><td colspan="3">';
	// insert this color
	output += '</td></tr></table>';
	
	output += '<div style="padding:10px; text-align:right; font-size:16px; font-weight:bold;"><a href="javascript:insert_color_tag()" style="color:#fff;">Insert Color Tag &gt;</a></div>';
	
	return output;
}

function insert_color_tag()
{
	insert_around_selection('<color value="' + active_hex() + '">', '</color>');
	get_floaty().innerHTML = '';
}

function hue_hex()
{
	return '#' + dec2hex(hue_red) + dec2hex(hue_green) + dec2hex(hue_blue);
}

function active_hex()
{
	return '#' + dec2hex(active_red) + dec2hex(active_green) + dec2hex(active_blue);
}

function get_mouse_color_field_coords(field, mouseEvent)
{
	var obj = document.getElementById(field);
	var obj_left = 0;
	var obj_top = 0;
	var xpos;
	var ypos;
	
	while (obj.offsetParent)
	{
		obj_left += obj.offsetLeft;
		obj_top += obj.offsetTop;
		obj = obj.offsetParent;
	}
	
	if (mouseEvent)
	{
		//FireFox
		xpos = mouseEvent.pageX;
		ypos = mouseEvent.pageY;
	}
	else
	{
		//IE
		xpos = window.event.x + document.body.scrollLeft - 2;
		ypos = window.event.y + document.body.scrollTop - 2;
	}
	
	xpos -= obj_left;
	ypos -= obj_top;
	
	return [xpos / 200.0, ypos / 200.0];
}

var is_color_field_down = false;
var hue_red = 0;
var hue_green = 128;
var hue_blue = 255;

var active_red = 0;
var active_green = 128;
var active_blue = 255;

function color_field_down(mouseEvent)
{
	is_color_field_down = true;
	color_field_move(mouseEvent);
}

function color_field_up(mouseEvent)
{
	is_color_field_down = false;
	color_field_move(mouseEvent);
}

var brightness = 1.0;
var asaturation = 0;

function color_field_move(mouseEvent)
{
	if (is_color_field_down)
	{
		var coords = get_mouse_color_field_coords("color_bg", mouseEvent);
		brightness = coords[0];
		asaturation = coords[1];
		update_colors();
		document.getElementById('color_dot').style.backgroundPosition = parseInt(brightness * 200 - 9) + 'px ' + parseInt(asaturation * 200 - 9) + 'px';
	}
}

function update_colors()
{
	var anti = 1 - brightness;
	var r = hue_red * brightness + 255 * anti;
	var g = hue_green * brightness + 255 * anti;
	var b = hue_blue * brightness + 255 * anti;
	anti = 1 - asaturation;
	active_red = ensure_range(r * anti);
	active_green = ensure_range(g * anti);
	active_blue = ensure_range(b * anti);
	update_color_display();
}

var is_hue_down = false;

function hue_down(mouseEvent)
{
	is_hue_down = true;
	hue_move(mouseEvent);
}

function hue_up(mouseEvent)
{
	is_hue_down = false;
	hue_move(mouseEvent);
}

function hue_move(mouseEvent)
{
	if (is_hue_down)
	{
		var coords = get_mouse_color_field_coords('wainbow', mouseEvent);
		var hue = coords[1] * 6;
		
		//0-1, red->yellow
		//1-2, yellow->green
		//2-3, green->cyan
		//3-4, cyan->blue
		//4-5, blue->magenta
		//5-6, magenta->red
		if (hue < 1) // 0 red -> 1 yellow
		{
			hue_red = 255;
			hue_green = hue * 255.0;
			hue_blue = 0;
		}
		else if (hue < 2) // 1 yellow -> 2 green
		{
			hue_red = 255 * (2.0 - hue)
			hue_green = 255;
			hue_blue = 0;
		}
		else if (hue < 3) // 2 green -> 3 cyan
		{
			hue_red = 0;
			hue_green = 255;
			hue_blue = 255 * (hue - 2.0);
		}
		else if (hue < 4) // 3 cyan -> 4 blue
		{
			hue_red = 0;
			hue_green = 255 * (4.0 - hue);
			hue_blue = 255;
		}
		else if (hue < 5) // 4 blue -> 5 magenta
		{
			hue_red = 255 * (hue - 4.0);
			hue_green = 0;
			hue_blue = 255;
		}
		else // 5 magenta -> 6 red
		{
			hue_red = 255;
			hue_green = 0;
			hue_blue = 255 * (6.0 - hue);
		}
		
		hue_red = parseInt(hue_red);
		hue_green = parseInt(hue_green);
		hue_blue = parseInt(hue_blue);
		
		document.getElementById('hue_pointer').style.backgroundPosition = "0px "+parseInt(200 * coords[1] - 6) + 'px';
		document.getElementById('color_bg').style.backgroundColor = '#' + dec2hex(hue_red) + dec2hex(hue_green) + dec2hex(hue_blue);
		update_colors();
	}
}

function ensure_range(num)
{
	num = parseInt(num + .5);
	return num < 0 ? 0 : (num > 255 ? 255 : num);
}

function update_color_display()
{
	var preview = document.getElementById('color_preview');
	preview.style.backgroundColor = active_hex();
	document.getElementById('col_r').innerHTML = "Red:&nbsp;" + active_red;
	document.getElementById('col_g').innerHTML = "Green:&nbsp;" + active_green;
	document.getElementById('col_b').innerHTML = "Blue:&nbsp;" + active_blue;
	
	preview.focus();
}

function dec2hex(num)
{
	var digits = '0123456789abcdef';
	return digits[parseInt(num / 16)] + digits[num % 16];
	
}

var selected_file_sort = '';

function insert_file()
{
	output = '<div style="padding:10px;">';
	
	output += '<div style="width:270px; float:left; margin-bottom:10px;">';
	output += '<a href="javascript:download_window()">Upload More Files</a> | ';
	output += '<a href="javascript:refresh_files()">Refresh file listing</a>';
	output += '</div>';
	
	output += '<div style="width:220px; text-align:right;float:right;">';
	output += '<select onchange="change_file_filter()" onkeyup="change_file_filter()" id="file_filter">';
	var choices = [
		['unreferenced', "Files You Haven't Used Yet"],
		['images', "All Image Files"],
		['type/jpg', "JPEG Images"],
		['type/png', "PNG Images"],
		['type/gif', "GIF Images"],
		['type/mp3', "MP3 Files"]];
	for (var i = 0; i < choices.length; ++i)
	{
		output += '<option value="' + choices[i][0] + '"'+((selected_file_sort == choices[i][0]) ? ' selected="selected"':'')+'>' + choices[i][1] + '</option>';
	}
	output += '</select>';
	output += '</div>';
	
	output += '<div style="clear:both;margin-bottom:5px; border:1px solid #888; height:320px; overflow-y:auto;" id="file_list">Loading...</div>';
	
	output += '<div>';
	output += '<input type="radio" '+((file_insert_style == 'tile') ? 'checked="checked" ' : '')+'name="insertion" onclick="set_insertion_method()" id="insertasimage"/> Insert as Image or Tile</div>';
	
	output += '<div>';
	output += '<input type="radio" '+((file_insert_style == 'link') ? 'checked="checked" ' : '')+'name="insertion" onclick="set_insertion_method()" id="insertaslink"/> Insert as Link</div>';
	
	output += '</div>';
	
	output += '</div>';
	return output;
}

function set_insertion_method()
{
	var mode = document.getElementById('insertasimage').checked ? 'tile' : 'link';
	file_insert_style = mode;
}

function download_window()
{
	var newwindow = window.open("http://www.nerdparadise.com/members/upload/", '', "width=450,height=200");
	if (window.focus)
	{
		newwindow.focus();
	}
}

var file_filter = 'unreferenced';

function refresh_files()
{
	refresh_file_list('unreferenced');
}

function change_file_filter()
{
	refresh_file_list(document.getElementById('file_filter').value);
}

function refresh_file_list(filter)
{
	var magicPotato;
	var supportsAjax = false;
	
	if (window.ActiveXObject) // Good ol' Internet Explorer
	{
		magicPotato = new ActiveXObject("Microsoft.XMLHTTP");
		supportsAjax = true;
	}
	else if (window.XMLHttpRequest) // Everyone else
	{
		magicPotato = new XMLHttpRequest();
		supportsAjax = true;
	}
	
	if (supportsAjax)
	{
		magicPotato.open("GET", 'http://www.nerdparadise.com/members/filelist/' + filter+'/', true);
   
		magicPotato.onreadystatechange = function()
		{
			// 4 means complete. the other numbers are various stages
			// in the request sending process. You can check for those if you
			// want to make a spinning progress bar or something, but ideally
			// these should be relatively instant page requests.
			
			if (magicPotato.readyState == 1)
			{
				show_file_spinny();
			}
			else if (magicPotato.readyState == 4)
			{
				var result = magicPotato.responseText;
				
				load_file_icons(result);
			}
		}
		
		magicPotato.send(null);
	}
}

function show_file_spinny()
{
	// TODO: animate?
	document.getElementById('file_list').innerHTML = "Loading . . .";
}

var id2name = {};
var idIsImage = {};

function load_file_icons(page_text)
{
	
	var lines = page_text.split("\n");
	var icons = [];
	var code;
	
	id2name = {};
	
	for (var i = 0; i < lines.length; ++i)
	{
		if (lines[i].length == 0)
		{
			icons.push('No files found');
			break;
		}
		var pieces = lines[i].split("\t");
		
		var file_id = pieces[0];
		var url = pieces[1];
		var filename = pieces[2];
		var bytes = parseInt(pieces[3]);
		var width = max(1, parseInt(pieces[4]));
		var height = max(1, parseInt(pieces[5]));
		var ext = pieces[6].toLowerCase();
		var type = pieces[7];
		var is_image = parseInt(pieces[8]);
		
		id2name['_' + file_id] = filename;
		idIsImage['_' + file_id] = is_image;
		
		var action = 'insert_image(' + file_id + ')';
		var onclick = 'onclick="' + action + '"';
		
		
		code = '<div style="text-align:center;width:110px;padding:5px;">';
		
		if (is_image == 1)
		{
			var ratio = width / height;
			if (width > height)
			{
				if (width > 80)
				{
					width = 80;
					height = parseInt(80.0 / ratio);
				}
			}
			else
			{
				if (height > 80)
				{
					width = parseInt(80.0 * ratio);
					height = 80;
				}
			}
			
			code += '<img src="/uploads/' + url +'" width="' + width + '" height="'+height+'" '+onclick+' />';
		}
		else
		{
			if (ext == 'mp3')
			{
				code += '<img src="/ui/file_icons/file_mp3.png" '+onclick+' />';
			}
		}
		
		code += '<div><a href="javascript:' + action +'">';
		code += filename;
		code += '</a></div>';
		code += '<div style="color:#aaa; font-weight:bold;">' + type + '</div>';
		bytes = parseInt((100 * bytes / 1024)) / 100.0;
		code += '<div style="color:#666;">' + bytes + '&nbsp;KB</div>';
		
		code += '</div>';
		
		icons.push(code);
	}
	
	code = '<table>';
	
	var i = 0;
	
	while (i < icons.length)
	{
		code += '<tr>';
		for (var j = 0; j < 4; ++j)
		{
			code += '<td>';
			if (i < icons.length)
			{
				code += icons[i];
				++i;
			}
			code += '</td>';
		}
		code += '</tr>';
	}
	
	code += '</table>';
	
	document.getElementById('file_list').innerHTML = code;
}

var file_insert_style = 'tile';

function insert_image(file_id)
{
	var file_name = id2name['_' + file_id];
	
	if (file_insert_style == 'tile')
	{
		if (idIsImage['_' + file_id] == 1)
		{
			insert_text('<image id="'+file_id+'">' + file_name + '</image>');
		}
		else
		{
			insert_text('<file id="' + file_id+'">' + file_name + '</file>');
		}
	}
	else
	{
		insert_text('<link id="' + file_id + '">' + file_name + '</link>');
	}
}