/*
* general functions
*/
function show(element)
{
	if (typeof element == 'string')
	{
		element = document.getElementById(element);
	}
	
	if (element != null)
	{
		element.style.display = 'inline';
	}
}

function hide(element)
{
	if (typeof element == 'string')
	{
		element = document.getElementById(element);
	}
	
	if (element != null)
	{
		element.style.display = 'none';
	}
}

function isInteger(value)
{
	if (value == null || value.length == 0 || value == '')
	{
		return false;
	}
	
	for (var i = 0; i < value.length; i++)
	{
		var c = value.charAt(i);
		
		if (c < '0' || c > '9')
		{
			return false;
		}
	}
	
	return true;
}

function enableOther(element, otherelement)
{	
	if (typeof otherelement == 'string')
	{
		otherelement = otherelement.replace(' ', '');
		
		if (otherelement.indexOf(',') > 0) // multiple fields
		{
			otherelements = otherelement.split(',');
			
			for (i in otherelements)
			{
				otherelement = document.getElementById(otherelements[i]);
				
				if (otherelement != null)
				{
					otherelement.disabled = !element.checked;
				}
			}
		}
		else // one field
		{
			otherelement = document.getElementById(otherelement);
			
			if (otherelement != null)
			{
				otherelement.disabled = !element.checked;
			}
		}
	}
	else if (otherelement != null) // field itself instead of field name
	{
		otherelement.disabled = !element.checked;
	}
}

function enableElements(elements)
{	
	if (typeof elements == 'string')
	{
		elements = elements.replace(/ /g, '');
		
		elements = elements.split(',');
		
		for (i in elements)
		{
			element = document.getElementById(elements[i]);
			
			if (element != null)
			{
				element.disabled = false;
			}
		}
	}
}

function disableElements(elements)
{	
	if (typeof elements == 'string')
	{
		elements = elements.replace(/ /g, '');
		
		elements = elements.split(',');
		
		for (i in elements)
		{
			element = document.getElementById(elements[i]);
			
			if (element != null)
			{
				element.disabled = true;
			}
		}
	}
}

/*
* input checks
*/
function checkEmpty(element, minlength, errorgroup)
{
	if (minlength == null)
	{
		minlength = 1;
	}
	
	errorempty = document.getElementById(element.id + 'Empty');
	
	if (element != null && element.value.split(' ').join('').length < minlength)
	{
		if (errorgroup == null) // errorgroup showing should be handled by server-side code
		{
			show(errorempty);
		}
	}
	else
	{
		hide(errorempty);
		hide(errorgroup);
	}
}

function checkDate(element, minyearsago, maxyearsago)
{
	var id = element.id.replace('Year', '').replace('Month', '').replace('Day', '');
	
	var year = document.getElementById(id + 'Year').value;
	var month = document.getElementById(id + 'Month').value;
	var day = document.getElementById(id + 'Day').value;
		
	errorinvalid = document.getElementById(id + 'Invalid');
	errorempty = document.getElementById(id + 'Empty');
	
	hide(errorinvalid);
	hide(errorempty);
	
	var currentDate = new Date();
	var currentYear = currentDate.getFullYear();
	
	var intYear = parseInt(year);
	
	if (year > 0 && year < 100)
	{
		if (currentYear - (2000 + parseInt(year)) > minyearsago)
		{
			year = 2000 + parseInt(year);
		}
		else
		{
			year = 1900 + parseInt(year);
		}
		
		document.getElementById(id + 'Year').value = year;
	}
	
	if (year == '' && month == '' && day == '')
	{
		show(errorempty);
	}
	else if (year != '' && year >= 2038) // 32-bit php can only handle dates until 2038-01-19
	{
		show(errorinvalid);
		alert('max: 2038');
	}
	else if (year != '' && (!isInteger(year) || year > currentYear + 100 || year < currentYear - 100))
	{
		show(errorinvalid);
	}
	else if (minyearsago > 0 && maxyearsago > 0 && year != '' && (!isInteger(year) || year > currentYear - minyearsago || year < currentYear - maxyearsago))
	{
		show(errorinvalid);
	}
	else if (month != '' && (!isInteger(month) || month < 1 || month > 12))
	{
		show(errorinvalid);
	}
	else if (day != '' && (!isInteger(day) || day < 1 || day > 31))
	{
		show(errorinvalid);
	}
	else if (isInteger(day) && isInteger(month) && isInteger(year))
	{
		var date = new Date(year, month - 1, day);
		
		if (date.getDate() != day || date.getMonth() != month - 1 || date.getFullYear() != year)
		{
			show(errorinvalid);
		}
	}
}

function checkNationalnumber(element)
{
	var id = element.id.replace('Year', '').replace('Month', '').replace('Day', '').replace('Serial', '').replace('Check', '');
	
	var year = document.getElementById(id + 'Year').value;
	var month = document.getElementById(id + 'Month').value;
	var day = document.getElementById(id + 'Day').value;
	var serial = document.getElementById(id + 'Serial').value;
	var check = document.getElementById(id + 'Check').value;
	
	errorinvalid = document.getElementById(id + 'Invalid');
	errorempty = document.getElementById(id + 'Empty');
	
	hide(errorinvalid);
	hide(errorempty);
	
	if (year == '' && month == '' && day == '' && serial == '' && check == '')
	{
		show(errorempty);
	}
	else if (isInteger(year) && isInteger(month) && isInteger(day) && isInteger(serial) && isInteger(check))
	{
		var nationalNumber = parseInt('' + year + month + day + serial);
		var remainder = nationalNumber % 97;
		
		if (check != remainder && check != 97 - remainder)
		{
			show(errorinvalid);
		}
	}
}

function checkTelephoneNumber(element)
{
	var number = element.value.split(' ').join('');
	errorinvalid = document.getElementById(element.id + 'Invalid');
	
	hide(errorinvalid);
	
	if (number.length > 0)
	{
		if (number.length < 8)
		{
			show(errorinvalid);
		}
		else if (number.charAt(0) != '0' && number.charAt(0) != '+')
		{
			show(errorinvalid);
		}
	}
}

function checkEmailAddress(element)
{
	var email = element.value.split(' ').join('');
	errorinvalid = document.getElementById(element.id + 'Invalid');
	
	hide(errorinvalid);
	
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	
	if (email.length > 0)
	{
		if (email.length < 6)
		{
			show(errorinvalid);
		}
		else if (!filter.test(email))
		{
			show(errorinvalid);
		}
	}
}

/*
* key checks
*/
function getCode(evt)
{
	if (!evt)
	{
		evt = event; // IE uses the global window.event
	}
	
	/*
	* note: keydown and keyup events return keyboard codes,
	*       keypress events return ASCII character codes
	*/
	if (evt.charCode)
	{
		return evt.charCode;
	}
	else
	{
		return evt.keyCode;
	}
}

function specialKey(code)
{
	if (code <= 31		// non-printing character
		|| code == 35	// end
		|| code == 36	// home
		|| code == 37	// left
		|| code == 39	// right
		|| code == 46)	// delete
	{
		return true; // keycode allowed
	}
	
	return false;
}

function integerChar(evt)
{
	var code = getCode(evt);
	
	if (specialKey(code)
		|| (code >= 48 && code <= 57))	// 0 to 9
	{
		return true; // keycode allowed
	}
	
	return false;
}

function numericChar(evt)
{
	var code = getCode(evt);
	
	if (specialKey(code)
		|| (code >= 48 && code <= 57)	// 0 to 9
		|| code == 46)					// .
	{
		return true; // keycode allowed
	}
	
	return false;
}

function telephoneNumberChar(evt)
{
	var code = getCode(evt);
	
	if (specialKey(code)
		|| (code >= 48 && code <= 57)	// 0 to 9
		|| code == 32					// space
		|| code == 43					// +
		|| code == 45					// -
		|| code == 46					// .
		|| code == 47)					// /
	{
		return true; // keycode allowed
	}
	
	return false;
}

function emailAddressChar(evt)
{
	var code = getCode(evt);
	
	if (specialKey(code)
		|| (code >= 48 && code <= 57)	// 0 to 9
		|| (code >= 65 && code <= 90)	// A to Z
		|| (code >= 97 && code <= 122)	// a to z
		|| code == 45					// -
		|| code == 46					// .
		|| code == 64					// @
		|| code == 95)					// _
	{
		return true; // keycode allowed
	}
	
	return false;
}

/*
* tab/focus functions
*/
function noTab(evt)
{
	if (getCode(evt) == 9)
	{
		return false;
	}
}

function noTabEmpty(element, evt, minlength)
{
	if (minlength == null)
	{
		minlength = 1;
	}
	
	if (element.value.length < minlength && getCode(evt) == 9)
	{
		return false;
	}
}

function noFocus(element) // always focus on the next element
{
	for (i = 0; i < element.form.length; i++)
	{
		if (element.form.elements[i] == element)
		{
			element.form.elements[i + 1].focus();
			return;
		}
	}
}

function focusNext(element, evt, len) // to be called by onkeyup
{
	var code = getCode(evt);
	
	if ((element.value.length >= len && code >= 48 && code <= 126)		// printable keycode
		|| (element.value.length >= 1 && code == 39)					// right arrow
		|| (element.value.length >= 1 && code >= 189 && code <= 191))	// - . /
	{
		for (i = 0; i < element.form.length - 1; i++)
		{
			if (element.form.elements[i] == element)
			{
				if (element.form.elements[i + 2].value.length == 0)
				{
					element.form.elements[i + 2].focus();
					return;
				}
			}
		}
	}
}

function focusPrevious(element, evt) // to be called by onkeyup
{
	var code = getCode(evt);
	
	if (element.value.length == 0 && (code == 8 || code == 37)) // backspace or left arrow
	{
		for (i = element.form.length; i > 0; i--)
		{
			if (element.form.elements[i] == element)
			{
				if (navigator.appVersion.indexOf('MSIE ') >= 0)
				{
					var range = element.form.elements[i - 2].createTextRange();
					range.collapse(false);
					range.select();
				}
				else
				{
					element.form.elements[i - 2].focus();
				}
				return;
			}
		}
	}
}

/*
* ajax list functions
*/
function showMunicipalities(element, evt)
{
	var id = element.id.replace('Code', '').replace('Name', '').replace('Auto', '').replace('List', '');
	
	postalcode = document.getElementById(id + 'Code');
	municipality = document.getElementById(id + 'Name');
	
	auto = document.getElementById(id + 'Auto');
	list = document.getElementById(id + 'List');
	
	if (postalcode.value.length > 0 || municipality.value.length > 0)
	{
		var code = getCode(evt);
		
		if (code == 8 || code == 46) // backspace, delete
		{
			if (element == postalcode && postalcode.value.length >= 3)
			{
				municipality.value = '';
			}
		}
		
		if (code == 9 && list.selectedIndex > 0) // tab
		{
			hideMunicipalities(element);
			
			return;
		}
		
		if (code == 13 || code == 27) // tab, enter, escape
		{
			hideMunicipalities(element);
			
			return;
		}
		
		if (code == 40) // down arrow
		{
			if (list.selectedIndex < list.length - 1)
			{
				list.selectedIndex++;
			}
			
			return;
		}
		
		if (code == 38) // up arrow
		{
			if (list.selectedIndex > 0)
			{
				list.selectedIndex--;
			}
			
			return;
		}
		
		var url = 'ajax_municipalities.php?postalcode=' + postalcode.value + '&municipality=' + municipality.value;
		
		//alert(url); // debug
		
		var AjaxReady = function(auto, list)
		{
			this.auto = auto;
			this.list = list;
			
			this.show = function()
			{
				if (list.options.length > 0)
				{
					auto.style.display = 'block';
				}
				else
				{
					auto.style.display = 'none';
				}
			}
		}
		
		var ajaxReady = new AjaxReady(auto, list);
		
		ajax(url, list, ajaxReady.show);
	}
	else
	{
		auto.style.display = 'none';
	}
}

function hideMunicipalities(element)
{
	var id = element.id.replace('Code', '').replace('Name', '').replace('Auto', '').replace('List', '');
	
	auto = document.getElementById(id + 'Auto');
	
	if (auto.style.display != 'none')
	{
		list = document.getElementById(id + 'List');
		
		postalcode = document.getElementById(id + 'Code');
		municipality = document.getElementById(id + 'Name');
		
		if (list.selectedIndex >= 0)
		{
			postalcode.value = list.options[list.selectedIndex].text.substr(0, 4);		
			municipality.value = list.options[list.selectedIndex].text.substr(9);
			
			office = document.getElementById('office');
			if (office != null && office.value == '')
			{
				getOffices(0, postalcode.value, office);
			}
		}
		
		auto.style.display = 'none';
		
		// focus to next empty text field
		for (i = 0; i < element.form.length - 1; i++)
		{
			if (element.form.elements[i] == element)
			{
				for (j = i + 1; j < element.form.length; j++)
				{
					if (element.form.elements[j].type == 'text' && element.form.elements[j].value.length == 0)
					{
						element.form.elements[j].focus();
						return;
					}
				}
			}
		}
	}
}

/*
* use ajax to fill the office selection with a sorted list of offices,
* based on the nearest office or postalcode
*/
function getOffices(officenr, postalcode, list)
{
	if (postalcode.length >= 4)
	{
		var url = 'ajax_offices.php?officenr=' + officenr + '&postalcode=' + postalcode;
		
		//alert(url); // debug
		
		ajax(url, list);
	}
}

