/**
 * Constructor for validation object.
 * @param objField the field to add validation to
 * @param strRegExp a string or object containing a regular expression to validate against
 * @param objAdditional a string or array of additional functions to use for input validation
 */
function Validation(objField, objValExp)
{
	this.m_objField = objField;
	this.m_objValExp = new Array();

	if (typeof(objValExp) == "string")
	{ // objValExp is a string we assume it is a string with a RegExp
		this.m_objValExp[this.m_objValExp.length] = new RegExp(objValExp,"g");
	}
	else if (typeof(objValExp) == "function")
	{
		this.m_objValExp[this.m_objValExp.length] = objValExp;
	}
	else if (typeof(objValExp) == "object")
	{
		if ("" + objValExp.global != "undefined")
		{ // Assume regExp
			this.m_objValExp[this.m_objValExp.length] = objValExp;
		}
		else if ("" + objValExp.length != "undefined")
		{ // Assume Array
			this.m_objValExp = objValExp;
		}
	}
	var objThis = this;
	this.m_objField.validate = function(event) {return objThis.validate(event);};
}

Validation.prototype.validate = function(event)
{
	for (var i = 0; i < this.m_objValExp.length; i++)
	{
		if (typeof(this.m_objValExp[i]) == "function")
		{
			if (!this.m_objValExp[i](this.m_objField.value))
			{
				this.onFail(event);
				return false;
			}
		}
		else if (!this.m_objField.value.match(this.m_objValExp[i]))
		{ // Validation of value failed regex
			this.onFail(event);
			return false;
		} 
	}
	this.onSuccess(event);
	return true;
}

/**
 * This function is executed if validation of a field fails. This function must be overridden
 * by the specific field, if additional functionality is required.    
 */
Validation.prototype.onFail = function(event)
{
}

/**
 * This function is executed if validation of a field succeeds. This function must be overridden
 * by the specific field, if additional functionality is required.    
 */
Validation.prototype.onSuccess = function(event)
{
}

/**
 * Adds or appends an event-listener to the field. Use the syntax below.  
 * addListener("onload", function() { myFunction(); });
 */
function addListener(oElm, event, listener, bubble)
{
	if (typeof(oElm) == 'string')
	{
		oElm = document.getElementById(oElm);
	}
	if(oElm.addEventListener)
	{
		if(typeof(bubble) == "undefined")
		{
			bubble = false;
		}
		oElm.addEventListener(event.substring(2), listener, bubble);
	}
	else if(oElm.attachEvent)
	{
		oElm.attachEvent(event, listener);
	}
	else 
	{ // Older browsers 
		var currentEventHandler = oElm[event];
		if (currentEventHandler == null) 
		{
			oElm[event] = listener;
		} 
		else 
		{
			oElm[event] = function(event) { currentEventHandler(event); listener(event); }
		}
	}
}
