$(document).ready(function() {
	$('input[name=age_d]').focus();
	$('#agecheck form').submit(function() {
		return checkAge();
	});
	
	$('#agecheck-button a').click(function() {
		return checkAge();
	});
	
	$('input[name=age_d]').keyup(function(event) { if ($(this).val().length == 2 && event.keyCode != '8') { $('input[name=age_m]').focus(); } });
	$('input[name=age_m]').keyup(function(event) { if ($(this).val().length == 2 && event.keyCode != '8') { $('input[name=age_y]').focus(); } });
	
	$('input[name=age_m]').keydown(function(event) { if ($(this).val().length == 0 && event.keyCode == '8') { $('input[name=age_d]').select(); } });
	$('input[name=age_y]').keydown(function(event) { if ($(this).val().length == 0 && event.keyCode == '8') { $('input[name=age_m]').select(); } });
});

function calcAge(birthDate, birthMonth, birthYear)
{
	if (birthDate == '' || birthMonth == '') {
		yearsOld = 'bad';
	} else {
		dDate  = parseInt(birthDate, 10);
		dMonth = parseInt(birthMonth, 10);
		dYear  = parseInt(birthYear, 10);
		
		if (isNaN(dDate) || dDate < 1 || dDate > 31)    return 'badDate';
		if (isNaN(dMonth) || dMonth < 1 || dMonth > 12) return 'badMonth';
		if (isNaN(dYear) || dYear < 1)                  return 'badYear';
				
		curDate   = new Date();
		yearsOld  = curDate.getFullYear() - dYear;
		monthsOld = (curDate.getMonth() + 1) - dMonth;
		daysOld   = curDate.getDate() - dDate;
		
		if ((monthsOld < 0) || (monthsOld == 0 && daysOld < 0)) yearsOld --;
		if (yearsOld < 0) yearsOld = 'badYear';
	} 
	
	return yearsOld;
}

function checkAge()
{
	var birthDate  = $('input[name=age_d]').val();
	var birthMonth = $('input[name=age_m]').val();
	var birthYear  = $('input[name=age_y]').val();
	
	dAge = calcAge(birthDate, birthMonth, birthYear);
	
	if (dAge == 'bad' || dAge == 'badYear' || dAge == 'badMonth' || dAge == 'badDate'){
		alert('Voer aub een geldige geboortedatum in.');
		return false;
		
	} else { 
		if (dAge < 16) {
			alert('Sorry, om http://' + window.location.hostname + ' te bezoeken moet je 18 jaar of ouder zijn.');
			return false;
		}
		
		//$.get("?age=18plus");
		return true;
	}

	return false;
}
