$(function(){
	$('#input').keyup(entifyInput).focus();
});

function entifyInput() {
	var input = $('#input');
	var output = $('#output');
	var outputLabel = $('#output_label');
	var inputValue = input.attr('value');
	if (inputValue.length > 0) {
		if (inputValue != 'Enter text') {
			if (output.length == 0) {
				$('#fieldset').append($('<label for="output" id="output_label"><em>O</em>utput</label>')
				.fadeIn().click(function(){output.focus();}))
				.append($('<textarea id="output" cols="40" rows="10" title="Special characters have been replaced"></textarea>').attr('value', entify(inputValue)).fadeIn());
				input.attr('title', 'An entified version of this text will appear in the output box').css('color','#000000');
			} else {
				output.attr('value', entify(inputValue));
				if(output.is(':not(:visible))')) {
					output.fadeIn();
					outputLabel.fadeIn();
				}
			}
		}
	} else {
		output.attr('value', '').fadeOut();
		outputLabel.fadeOut();
	}
}

function entify(input) {
	var chars = Array();
	var char = '';
	for (var x = 0; x < input.length; x ++) {
		var replacer = '';
		charCode = input.substr(x, 1).charCodeAt(0);
		if (charCode == 10) replacer = "\n";
		if (charCode == 8216 || charCode == 8217) replacer = '&#39;';
		if (charCode == 8220 || charCode == 8221) replacer = '&#34;';
		if ((charCode != 44 && charCode != 46 && charCode < 48) || (charCode > 57 && charCode < 65) || (charCode > 90 && charCode < 97) || (charCode > 122)) {
			if (charCode > 31 && charCode < 256) {
				if (charCode == 32) {
					replacer = ' ';
				} else {
					replacer = '&#' + charCode + ';';
				}
			}
		} else {
			if (charCode > 31 && charCode < 256) {
				replacer = input.substr(x, 1);
			}
		}
		chars[x] = replacer;
	}
	var output = '';
	for (var x = 0; x < chars.length; x ++) {
		output = output + chars[x];
	}
	return output;
}