var alphabet = {
	A:["Alpha","Adams"],
	B:["Bravo","Boston"],
	C:["Charlie","Chicago"],
	D:["Delta","Denver"],
	E:["Echo","Easy"],
	F:["Foxtrot","Frank"],
	G:["Golf","George"],
	H:["Hotel","Henry"],
	I:["India","Ida"],
	J:["Juliet","John"],
	K:["Kilo","King"],
	L:["Lima","Lincoln"],
	M:["Mike","Mary"],
	N:["November","New York"],
	O:["Oscar","Ocean"],
	P:["Papa","Peter"],
	Q:["Quebec","Queen"],
	R:["Romeo","Roger"],
	S:["Sierra","Sugar"],
	T:["Tango","Thomas"],
	U:["Uniform","Union"],
	V:["Victor","Victor"],
	W:["Whiskey","William"],
	X:["X-ray","X-ray"], 
	Y:["Yankee","Young"],
	Z:["Zulu","Zero"]
}

function isLetter(letter) {
	var re = /[A-Z]/;
	return re.test(letter);
}

function trim(str) {
	return str.replace(/\s+$/,"").replace(/^\s+/,"");
}

function toPhonetic(str) {
	var type = 0;
	// Set to Western Union, if selected
	if ( document.getElementById("WU").checked ) {
		type = 1;
	}
	// Convert text to uppercase
	var textToConvert = str.toUpperCase();
	// For every character in the text, convert it to its phonetic equivalent
	// For non-alpha chars, display the char (e.g. space, punctuation, number, etc.)
	for ( i = 0; i < textToConvert.length; i++ ) {
		if ( isLetter(textToConvert[i]) ) {
			document.getElementById("result").innerHTML += alphabet[textToConvert[i]][type] + " ";
		} else {
			document.getElementById("result").innerHTML += textToConvert[i];
		}
	}		
}

function toNormal(str) {
	// Eliminate extraneous characters
	str.replace(/[^A-Za-z\s]/g,"");
	// Replace the space in New York, the only case that contains a space char
	str.replace(/[Nn]ew [Yy]ork/g,"New+York");
	// Turn the text into an array of terms
	var text = str.split(/\b/);
	// For each term, display the leading character
	for ( var i = 0; i<text.length; i++ ) {
		document.getElementById("result").innerHTML += text[i][0];
	}
}

function convert() {
	// Reset the result window to blank
	document.getElementById("result").innerHTML = "";
	// Get the value of the appropriate text box
	textToConvert = trim(document.getElementById("text").value);
	// Select from conversion to normal (from phonetic) or to phonetic (from normal)
	if ( document.getElementById("normal").checked ) {
		toNormal(textToConvert);
	} else {
		toPhonetic(textToConvert);
	}
}
