function AddSubmitParameter(paramName, paramValue)
{
	var params;
	
	params = unescape(document.thisform.elements["SUBMIT_PARAMS"].value);
	params += "<var name=\"" + paramName + "\"><![CDATA[" + paramValue + "]]></var>";
	document.thisform.elements["SUBMIT_PARAMS"].value = escape(params);
}

function Enumerate(alias)
{
	var object,
		list;

	if ((object = getElementByAlias(alias)) != null)
	{
		if (typeof(object.length) == "undefined" || object.type == "select-one")
		{
			list = new Array(1);
			list[0] = object;
		}
		else
			list = object;
	}
	return list;
}

function EnumerateByID(id)
{
	var object,
		list;

	object = getElementByID(id);
	if (typeof(object.length) == "undefined")
	{
		list = new Array(1);
		list[0] = object;
	}
	else
		list = object;
	return list;
}

function EnumerateByName(name)
{
	var object,
		list;

	object = document.getElementsByName(name);
	if (typeof(object.length) == "undefined")
	{
		list = new Array(1);
		list[0] = object;
	}
	else
		list = object;
	return list;
}

function UpdateField(alias, value)
{
	var list;
	
	list = Enumerate(alias);
	for (var i = 0; i < list.length; i++)
		list[i].value = value;
}

function getElementByID(id)
{
	return document.thisform.elements[id];
}

function getElementByName(name)
{
	//return document.thisform.elements[name];
	return document.getElementsByName(name)[0];
}

function getElementByAlias(alias)
{
	return getElementByID(ID(alias));
}

function SetRedirect(redirect)
{
	document.thisform._STATE.value = document.thisform._STATE.value.substring(0, 2) + 
		(redirect ? "1" : "0");
}

function SetPostback(postback)
{
	document.thisform._STATE.value = (postback ? "1" : "0") + 
		document.thisform._STATE.value.substring(1);
}

function SetReload(reload)
{
	document.thisform._STATE.value = document.thisform._STATE.value.substring(0, 1) + 
		(reload ? "1" : "0") + document.thisform._STATE.value.substring(2, 1);
}

function ClearForm()
{
	window.location.reload();
}

function ClearMessage(id)
{	
	var element,
		object;	
	
	if ((element = getElementByID(id)) != null)
	{
		element.className = "";
		if ((object = document.getElementById("div" + element.id)) != null)
		{
			object.innerHTML = "";
			object.style.display = "none";
		}
	}
}

function UpdateMessage(element, message, valid, show)
{
	var object,
		id;

	id = "div" + element.id;
	if (valid)
	{
		if (show) 
			element.className = "";
		if ((object = document.getElementById(id)) != null && object.innerHTML != "")
		{
			object.innerHTML = "";
			object.style.display = "none";
		}
	}
	else
	{
		if (firstElement == null || element.tabIndex < firstElement.tabIndex)
			firstElement = element;
		if (show) 
			element.className = "clsInvalid";
		if ((object = document.getElementById(id)) != null)
		{
			object.innerHTML = message;
			object.style.display = "block";
		}
	}
	return valid;
}

function _DateValidator(e, s)
{
	var expDate = /\d{2}-\d{2}-\d{4}/,
		nMonth,
		nYear,
		nDay,
		bOK,
		m;
	
	bOK = false;
	if (expDate.test(e.value))
	{
		if ((m = e.value.split("-")) != null)
		{
			nMonth = parseInt(m[1], 10);
			nDay = parseInt(m[0], 10);
			nYear = parseInt(m[2], 10);
			if (nYear > 1900)
			{
				switch (nMonth)
				{
					case 1:
					case 3:
					case 5:
					case 7:
					case 8:
					case 10:
					case 12:
						bOK = (nDay > 0 && nDay <= 31);
						break;
						
					case 2:
						if (nYear % 4 == 0)
							bOK = (nDay > 0 && nDay <= 29);
						else
							bOK = (nDay > 0 && nDay <= 28);
						break;
					
					case 4:
					case 6:
					case 9:
					case 11:
						bOK = (nDay > 0 && nDay <= 30);
						break;
				}
			}
		}
	}

	return UpdateMessage(e, s, bOK, true);
}

function FutureDateValidator(id, daySpan, s)
{
	var enteredDate,
		today,
		valid,
		parts,
		month,
		days,
		year,
		day,
		e;
	
	valid = false;
	if ((e = getElementByID(id)) != null)
	{
		parts = e.value.split("-");
		if (parts.length == 3)
		{
			// subtract number of days in the future to compare
			// to today
			day = parseInt(parts[0], 10) - daySpan;
			month = parseInt(parts[1], 10);
			year = parseInt(parts[2], 10);
			// reset today to 00:00:00
			today = new Date();
			today.setHours(0);
			today.setMinutes(0);
			today.setSeconds(0);
			today.setMilliseconds(0);
			// Note that months start from 0 (0=jan, 1=feb etc.)
			enteredDate = new Date(year, month - 1, day);
			valid = (enteredDate >= today);
		}
	}
	return UpdateMessage(e, s, valid, true);
}

function DateValidator(id, s)
{
	var valid = false,
		e;
		
	if ((e = getElementByID(id)) != null)
	{	
		if (e.value.length > 0)
			valid = _DateValidator(e, s);
		else
			valid = true;
	}
	else
		alert("DateValidator: element with id '{0}' not found".replace("{0}", id));

	return valid;
}

function ZipCodeValidator(id, country, message)
{
	var expression,
		valid = true,
		object,
		value;
	
	switch (country)
	{
		case "NL":
			expression = /^\d{4}\s?[a-zA-Z]{2}$/;
			break;
		
		default:
			expression = /^\d{4}\s?[a-zA-Z]{2}$/;
			break;
	}
	if ((object = getElementByID(id)) != null)
	{
		if ((valid = UpdateMessage(object, message, expression.test(object.value), true)) == true)
		{
			// format the zipcode
			if (country == "NL")
			{
				value = object.value.toUpperCase();
				if (value.length == 6)
				{
					// Make sure space is inserted
					value = value.substr(0, 4) + 
						" " + value.substr(4, 2);
				}
				object.value = value;
			}
		}
	}
	return valid;
}

function ExpressionValidator(id, expression, message)
{
	var valid = true,
		object;

	if ((object = getElementByID(id)) != null)
		valid = UpdateMessage(object, message, object.value.length == 0 |  expression.test(object.value), true);
	else {
		alert("ExpressionValidator: element with id '{0}' not found".replace("{0}", id));
		valid = false;
	}
	
	return valid;
}

function IsEmpty(value)
{
	return /^\s*$/.test(value);
}

function EmptyValidator(id, message)
{
	var watermark,
		isEmpty, 
		object,
		valid;
		
	valid = true;
	if ((object = getElementByID(id)) != null) {
		if (typeof (object.length) != "undefined" && TypeOf(object) != "select-one") {
			for (var i = 0; i < object.length && object[i].checked == false; i++);
			valid = UpdateMessage(object[0], message, (i < object.length), false);
		}
		else {
			if (TypeOf(object) == "checkbox") {
				valid = UpdateMessage(object, message, object.checked, true);
			}
			else {
				if ((watermark = object.attributes.getNamedItem("watermark")) != null)
					isEmpty = (object.value == watermark.nodeValue);
				valid = UpdateMessage(object, message, !isEmpty && !IsEmpty(object.value), true);
			}
		}
	}

	return valid;
}

function ValueValidator(id, message, value) {
	var valid = false,
		object;

	if ((object = getElementByID(id)) != null)
		valid = UpdateMessage(object, message, (object.value != "" && object.value == value), true);
	else
		alert("ValueValidator: element with id '{0}' not found".replace("{0}", id));

	return valid;
}

function PhoneNumberValidator(id, s, c)
{
	var stripped,
		valid,
		e;
	
	if (typeof(c) == "undefined" || c == "")
		c = "NL";
	
	valid = false;
	if ((e = getElementByID(id)) != null)
	{
		stripped = e.value.replace(/[\(\.\-\ ]/g, '');
		valid = UpdateMessage(e, s, stripped.length == 0 || (isNaN(parseInt(stripped)) == false && 
				c == "BE" ? stripped.length >= 8 && stripped.length <= 10 : stripped.length == 10), 
			true);
	}
	else
		alert("PhoneNumberValidator: element with id '{0}' not found".replace("{0}", id));

	return valid;
}

function LengthValidator(id, message, maxLength, ignore)
{
	var valid = false,
		object;
	
	if ((object = getElementByID(id)) != null)
		valid = UpdateMessage(object, message, (object.value.length <= maxLength), true);
	else if (typeof(ignore) == "undefined" || ignore == false)
		alert("LengthValidator: element with id '{0}' not found".replace("{0}", id));
	else
		valid = true;

	return valid;
}

function ZeroValidator(id, message)
{
	var valid = false, 
		object;
	
	if ((object = getElementByID(id)) != null)
		valid = UpdateMessage(object, message, (object.value != "" && object.value != "0"), 
			true);
	else
		alert("ZeroValidator: element with id '{0}' not found".replace("{0}", id));
	
	return valid;
}

function MultipleEMailValidator(id, message)
{
	var exp = new RegExp("^(([a-zA-Z0-9\_\-]+[\.]?)+\@([a-zA-Z0-9\_\-]+[\.])+([a-zA-Z]{2,4})[\s;]*)+$"),
		valid,
		e;
		
	valid = false;
	if ((e = getElementByID(id)) != null)
		valid = UpdateMessage(e, message, IsEmpty(e.value) || exp.test(e.value), true);
	else
		alert("MultipleEMailValidator: element with id '{0}' not found".replace("{0}", id));
	
	return valid;
}

function EMailValidator(id, message)
{
	var exp = new RegExp("^([a-zA-Z0-9\_\-]+[\.]?)+\@([a-zA-Z0-9\_\-]+[\.])+([a-zA-Z]{2,4})$"),
		valid, 
		e;
	
	valid = true;
	if ((e = getElementByID(id)) != null)
		valid = UpdateMessage(e, message, IsEmpty(e.value) || exp.test(e.value), true);
	
	return valid;
}

function TypeOf(e)
{
	if (typeof(e.type) != "undefined")
		return e.type;
	else
		return "undefined";
}

function GetValue(alias)
{
	var value,
		list;
	
	if ((list = Enumerate(alias)) != null)
	{
		for (var i = 0; i < list.length; i++)
		{
			switch (TypeOf(list[i]))
			{
				case "checkbox":
					value = list[i].checked ? "1" : "0";
					break;
				
				case "radio":
					if (list[i].checked)
						value = list[i].value;
					break;
					
				default:
					value = list[i].value;
					break;
			}
		}
	}
	else
		alert("GetValue: element with alias '{0}' not found".replace("{0}", alias));

	return value;
}

//function GetValue(alias)
//{
//	var value, 
//		e;
//	
//	if ((e = getElementByAlias(alias)) != null)
//	{
//		if (TypeOf(e) == "checkbox")
//			value = e.checked ? "1" : "0";
//		else
//			value = e.value;
//	}
//	else
//		alert("GetValue: element with alias '{0}' not found".replace("{0}", alias));
//
//	return value;
//}

function SetDefaultSubmitAction(targetID, submitAction)
{
	document.thisform.elements["SUBMIT_ACTION"].value = submitAction;
	document.thisform.elements["SUBMIT_TARGETID"].value = targetID;
}

function Submit(targetID, submitAction)
{
	document.thisform.elements["SUBMIT_ACTION"].value = submitAction;
	document.thisform.elements["SUBMIT_TARGETID"].value = targetID;
	if (OnSubmit())
		document.thisform.submit();
}

function OnSubmit()
{
	var submitAction,
		targetID,
		valid;

	submitAction = document.thisform.elements["SUBMIT_ACTION"].value;
	targetID = document.thisform.elements["SUBMIT_TARGETID"].value;
	if (typeof(submitAction) == "undefined" || submitAction == "")
	{
		alert("No submit action specified. Use SetDefaultSubmitAction() in OnInitForm()");
		return false;
	}
	ClearAllMessages();
	firstElement = null;
	if ((valid = ValidateAll(targetID, submitAction)))
	{
		if (typeof(OKToSubmit) == "function")
			valid = OKToSubmit(submitAction);
		if (valid)
		{
			if (document.thisform.action == "")
				document.thisform.action = window.location;
			SetPostback(true);
		}
		else
			valid = false;
	}
	else
	{
		if (typeof(OnValidationFailed) == "function")
			OnValidationFailed(firstElement);
		else
		{
			if (firstElement != null && firstElement.type != "hidden" 
					&& firstElement.disabled == false)
			{
				try
				{
					firstElement.focus();
				}
				catch (e)
				{
					document.body.focus();
				}
			}
		}
		document.thisform.elements["SUBMIT_PARAMS"].value = "";
	}
	return valid;
}

function OnIsUsed(alias, path)
{
	if (typeof(IsUsed) == "function")
		return IsUsed(alias, path);
	else
		return false;
}

function XmlToDate(value)
{
	var parts,
		month,
		year,
		day;

	parts = value.split("-");
	year = parseInt(parts[0], 10);
	month = parseInt(parts[1], 10);
	day = parseInt(parts[2], 10);
	// Note that months start from 0 (0=jan, 1=feb etc.)
	return new Date(year, month - 1, day);
}		

function StringToDate(value)
{
	var parts,
		month,
		year,
		day;

	parts = value.split("-");
	year = parseInt(parts[2], 10);
	month = parseInt(parts[1], 10);
	day = parseInt(parts[0], 10);
	// Note that months start from 0 (0=jan, 1=feb etc.)
	return new Date(year, month - 1, day);
}		

function getElementsByClass(searchClass, tag, node) 
{
	var classElements = new Array(),
		elements,
		pattern,
		i, j;
  
	if (typeof(node) == "undefined")
		node = document;
	
	if (typeof(tag) == "undefined")
		tag = "*";

	if ((elements = node.getElementsByTagName(tag)) != null)
	{
		pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
		for (i = 0, j = 0; i < elements.length; i++) 
		{
			if (pattern.test(elements[i].className)) 
			{
				classElements[j] = elements[i];
				j++;
			}
		}
	}
	return classElements;
}

function ToXmlString(value)
{
	var text = "";

	if (typeof(value) == "number")
		text = value.toString();
	else
	{
		// Prevent null values from crashing the app
		if (value != null && value.length > 0)
		{
			if (/\r|>|<|&/.test(value))
				text = "<![CDATA[" + value + "]]>";
			else
				text = value;
		}
	}
	return text;
}

function PreventDefault(e) {
    e.preventDefault();
}

function OnWatermark(control, entering) {
    var watermark = $(control).attr("watermark");

    if (watermark != null) {
        if (entering) {
            if (watermark == $(control).val()) {
                $(control).select();
                //$(control).val("");
            }
        }
        else {
            if ($(control).val().length == 0) {
                $(control).val(watermark);
                $(control).css({ color: "#999999" });
            }
            else if ($(control).val() != watermark)
                $(control).css({ color: "#000" });
        }
    }
}

function IntFrc(frc, algorithm) 
{ 
	// often for X > -0.5e-N
	with (Math) switch (algorithm) 
	{
		case 0: // Trunc
			return floor(frc)
		case 1: // Round
			return round(frc)
		case 2: // Alternate Round
			if (frc%1 >= 0.5) frc++ ; return frc | 0
		case 3: // Simple Bankers'
			return frc%1 != 0.5 ? round(frc) : 2*round(frc/2)
		case 6: // Ceil
			return ceil(frc)
		case 7: // Statistical
			return (frc + random()) | 0
		default: 
			return "TypeError";
	} 
}

function FloatToString(f, n) 
{ 
	// X to String with N decimal places
	var int = Math.floor(f), 
		frc = ((f-int)+1.0) * Math.pow(10, n)
	frc = String(IntFrc(frc, 1)) // Put chosen rounding algorithm here
	return (int + +(frc.charAt(0)=="2")) + '.' + frc.substring(1);
}

