/*
regexCheck.js

These functions use a regex expression to limit the input on a text field.
When using this on a text field, you should have the onfocus event call
appendLiterals and have the onKeyPress event call filterKeyPress.

Known issues:
When setting focus to the text field, the cursor will appear at the start
of the text field.

You can break the text field by using a multi select to delete multiple characters
thus breaking the pattern.

Regex expressions that use [ | | | ] cases won't work properly.
Regex expressions that use () won't work properly.
*/

function getKeyPressed(e)
{
	if(window.event)
		keyNum = e.keyCode;
	else if(e.which)
		keyNum = e.which;
	return String.fromCharCode(keyNum);
}

function filterKeyPress(obj, regex, e)
{
	var brow=((navigator.appName) +
			(parseInt(navigator.appVersion)));

	if(brow == 'Microsoft Internet Explorer4')
	{
		return false;
	}
	
	if(e.which == 0 || e.keyCode == 8 || e.keyCode == 9 )
	{
		return true;
	}
	else 
	{
		var keyPressed = getKeyPressed(e);
		var text = obj.value + keyPressed;
		var regexMatchIndex = regexIndexOf(regex, text);
	
		if(regexMatchIndex > -1)
			obj.value = text;
		appendLiterals(obj, regex);
	}

	return false;
}

function regexIndexOf(regexString, text)
{
	var regex;

	for(index = 0; index < regexString.length + 1; index++)
	{
		try
		{
			regex = new RegExp("^" + regexString.substring(0, index) + "$");
			if(regex.test(text))
				return index;
		}
		catch(e)
		{
		}
	}
	return -1;
}

function appendLiterals(obj, regex)
{
	var text = obj.value;
	var regexMatchIndex = regexIndexOf(regex, text);
	var restOfRegex;
	var nextNonLiterals;

	if(regexMatchIndex == -1)
		text = "";

	if(text.length == 0 || !isRepeating(regex.substring(0, regexMatchIndex)))
	{
		restOfRegex = regex.substring(regexMatchIndex);
		nextNonLiterals = getNextNonLiterals(restOfRegex);
		text = text + removeSlashes(nextNonLiterals);
	}
	obj.value = text;
}

function isRepeating(regex)
{
	return /[\}\*\+]$/.test(regex);
}

function getNextNonLiterals(regex)
{
	var nextNonLiteralIndex = getNextNonLiteralIndex(regex);

	if(nextNonLiteralIndex == -1)
		return regex;
	return regex.substring(0, nextNonLiteralIndex);
}

function getNextNonLiteralIndex(regex)
{
	var nextEscapeCharIndex = regex.search(/[^\\][\(\)\.\^\$\*\+\{\}\[\]\|]/);
	var nextSpecialCharIndex = regex.search(/(\\[\(\)\.\^\$\*\+\{\}\[\]\|]\?)|(\\\?\?)|(\w\?)|(\\\w)/);

	if(regex.search(/[\(\)\.\^\$\*\?\+\{\}\[\]\|]/) == 0)
		return 0;
	if((nextSpecialCharIndex != -1 && nextSpecialCharIndex < nextEscapeCharIndex) || nextEscapeCharIndex == -1)
		return nextSpecialCharIndex;
	return nextEscapeCharIndex + 1;
}

function removeSlashes(regex)
{
	return regex.replace(/\\/g, "");
}
