var InternationalAgeLimits = {
	'AU': 18,
	'US': 21,
	'CA': 19,
	'UK': 18,
	'XX': 21
}

var AgeCheck = {
	
	ageLimit: 18,
	
	lookup_country: function () {
		new DataStore("http://ws.blocksglobal.com/ip_locations", 'AgeCheck.setAge' );
	},
	
	setAge: function (response) {
		country = response;
		var limit = InternationalAgeLimits[country];
		if(limit != undefined){
			AgeCheck.ageLimit = limit;
		}
	},
	
	calculateAge: function (date, month, year) {
		var birthDate = new Date(year, month - 1, date);
		var currentDate = new Date();

		var ms = currentDate - birthDate
		var minutes = ms / 1000 / 60;
		var hours = minutes / 60;
		var days = hours / 24;
		var years = days/365;

		return years;
	},
	
	response: function (user_age) {
		if(user_age >= AgeCheck.ageLimit) {
			createCookie("overAge", "true", 30);
			AgeCheck.hideValidation();
		} else {
			eraseCookie("overAge");
			document.location = "/underage.html";
		}
	},
	
	showValidation: function() {
		$('#page').hide();
		$('#footer').hide();
		$('#ageverification').show();
		$('#ageverification .message').hide();
	},
	
	hideValidation: function() {
		$('#page').show();
		$('#footer').show();
		$('#ageverification').hide();
	}
}

// ---- Form Validation ----

function setErrorMessage(message) {
	if (message) {
		$('#ageverification .message').append('<p>'+message+'</p>');
		$('#ageverification .message').fadeIn(500);
	} 
}

function checkDay() {
	value = $('input#day').val();
	if(value < 1 || value > 31 || isNaN(value) ) {
		$('#ageverification .message').append('<p>Please enter a valid day between 1 - 31</p>');
	}
}

function checkMonth() {
	value = $('input#month').val();
	if(value < 1 || value > 12 || isNaN(value) ) {
		$('#ageverification .message').append('<p>Please enter a month between 1 - 12</p>');
	}
}

function checkYear() {
	var currDate = new Date();
	var currYear = currDate.getFullYear();
	
	value = $('input#year').val();
	if(value < 1900 || value > 2008 || isNaN(value) ) {
		$('#ageverification .message').append('<p>Please enter a year between 1900 - '+ currYear + '</p>');
	}
}


function validate_form() {
	$('#ageverification .message').html('');
	checkDay(); 
	checkMonth();
	checkYear();
	if ( $('#ageverification .message').html() == '' ) {
		return true;
	} else {
		$('#ageverification .message').fadeIn(500);
		return false;
	} 

}

$(function () {
	var c = readCookie("overAge");
	
	if(c) {
		AgeCheck.hideValidation();
	} else {
		AgeCheck.showValidation();
	}
	
	AgeCheck.lookup_country();
	
	$('#letmein').click( function(e) {
		if(validate_form()) {
			var user_age = AgeCheck.calculateAge($('#day').val(), $('#month').val(), $('#year').val());
			AgeCheck.response(user_age);
			return false;
		}else {
			return false;
		}
	});
});