/*
 * string_match.js by Henk Jan Nootenboom, 15 Oct 2007
 * Copyright 2007 SUMit. All Rights Reserved.
 *
 * See English demo at: 
 * http://www.sum-it.nl/en200720.html
 *
 * See Dutch demo at: 
 * http://www.sum-it.nl/no200720.html
 *
 * Permission to use, copy, modify, and distribute this source code
 * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
 * without fee is hereby granted.
 *
 * See http://www.sum-it.nl/security/index.html for copyright laws.
 */
 
function getCommand(n)
{	sCommandId = "command" + n;

	oCommandTd = getElement(sCommandId);
	return oCommandTd.innerHTML;
}

function getElement(sElementId)
{	return document.getElementById(sElementId);
}

function getRow(n)
{	sRowId = "row" + n;
	return getElement(sRowId);
}

function getShortcutField()
{	return getElement('navShortcut');
}

function init()
{	var oShortcutField;

	oShortcutField = getShortcutField();
	oShortcutField.focus();

	selectMatchingChoice();
}

function selectMatchingChoice()
{	var oShortcutField;
	var sShortcut;
	var sCommand;
	var nCommandLength;
	var nLevenshtein;
	var nLengthDifference;
	var nDeviation;
	var nSmallestDeviation = 1000;

	oShortcutField = getShortcutField();
	sShortcut = oShortcutField.value.toLowerCase();
	nShortcutLength = sShortcut.length;

	for(var n=1; n<=9; n++)
	{	sCommand = getCommand(n);
		nLevenshtein = getLevenshtein(sShortcut, sCommand);
		showLevenshtein(n, nLevenshtein);

		nCommandLength = sCommand.length;
		nLengthDifference = nCommandLength - nShortcutLength;
		showLengthDifference(n, nLengthDifference);

		nDeviation = nLevenshtein - nLengthDifference;
		showDeviation(n, nDeviation);

		if (nDeviation < nSmallestDeviation)
		{	nBestMatch = n;
			nSmallestDeviation = nDeviation;
		    // Optimisation for real application: return bestMatch if deviation equals 0
		}
		getRow(n).className = "";
	}
	getRow(nBestMatch).className = "selected";
}

function showDeviation(n, nDeviation)
{	sDeviationId = "deviation" + n;
	oDeviationTd = getElement(sDeviationId);
	oDeviationTd.innerHTML = nDeviation;
}

function showLengthDifference(n, nLengthDifference)
{	sLengthDifferenceId = "lengthDifference" + n;
	oLengthDifferenceTd = getElement(sLengthDifferenceId);
	oLengthDifferenceTd.innerHTML = nLengthDifference;
}

function showLevenshtein(n, nLevenshtein)
{	sLevenshteinId = "levenshtein" + n;
	oLevenshteinTd = getElement(sLevenshteinId);
	oLevenshteinTd.innerHTML = nLevenshtein;
}
