$(document).ready(function()
{
    init();
});

/* these are now set in the jslanguage files and set with PHP in the header
var n_noDob = "You need to enter your date of birth below.";
var n_noLocation = "Please select where you are from";
var n_noConsent = "Please make sure to tick the box";
var n_AgeError = "You are too young to enter this site";
*/

//amount of time (in milliseconds) messages are shown
var notificationUpTime = 5000;
// a list of all input id's
var inputIds = [	"day",
                	"month",
                	"year",
                	"location",
                	"consent"
                ];
// default values for input id's
var defaultInputValues = {"day":"dd",
							"month":"mm",
							"year":"yyyy",
							"location": undefined,
							"consent":"consent"
						 };
// values for various notifications
var reminderNotifications = {"no-dob":n_noDob,
								"no-location":n_noLocation,
								"no-consent":n_noConsent,
								"age-error":n_AgeError
							};

function init() 
{
	addFocusEvents();
	addClickEvents();
	addFormEvents();
}

/**
 * Add Focus events for input fields
 * @return null
 */
function addFocusEvents()
{
	// add focus events to add remove default value
	$.each(inputIds, function(index, value) {
		// add focus
		$("#" + value).focus(function () {
			if(this.value==defaultInputValues[this.id]) {
				this.value= "";
			}
		});
		// add focus out
		$("#" + value).focusout(function () {
			if(this.value=="") {
				this.value = defaultInputValues[this.id];
			}
		});
	});
}

/**
 * Add click events to the form
 * @return null
 */
function addClickEvents()
{
	// add click event for reminder email
    
	$("#age-submit").click(function(event) {
        submitAge($('#day').val(), $('#month').val(), $('#year').val(), $('#location'));
		return false;
	});
}

/**
 * Add submit events for the form
 * @return
 */
function addFormEvents()
{
	// add email capture submit event
	$("#age_check").submit(function(event) {
        submitAge($('#day').val(), $('#month').val(), $('#year').val(), $('#location'));
		return false;
	});
}

/**
 * Attempt to add user 
 * @param day
 * @return null
 */
function submitAge(day, month, year, location)
{
    // GA Tracking - When user has submitted the form
//	pageTracker._trackEvent('Age Verification', 'form-submit');
    _gaq.push(['_trackPageview', 'Age Verification','form-submit']);

    // get rel from dropdown obj
    var ageToCheck = location.find('option:selected').attr('rel');

	if ($('#consent').attr('checked'))
	{
		// check if the user has selected a country
		if(ageToCheck == defaultInputValues["location"])
		{
			addNotification("location",reminderNotifications["no-location"]);
			return false;
		}

        // check if sumission matches default or blank
		if(day == defaultInputValues["day"] || month == defaultInputValues["month"] || year == defaultInputValues["year"])
		{
			addNotification("age",reminderNotifications["no-dob"]);
			return false;
		}
		
		// check if the user is old enough
		var theirDate = new Date((parseInt(year) + parseInt(ageToCheck)), parseInt(month), parseInt(day));
		var today = new Date;

		if ( (today.getTime() - theirDate.getTime()) < 0) {
			// user is not old enough to use the website

            addNotification("age","You are too young to enter this site and will now be redirected");
			
			// Redirect the user after 2 seconds after reading the message
			setTimeout(redirectUser,2000);
			
			return false;
		}
		
		// lets check the user is
		checkInUser( theirDate.getTime(), location.val() );
	}
	else
	{
		addNotification("consent",reminderNotifications["no-consent"]);
		return false;
	}
}


function checkInUser(birthdayDate, location)
{
	// GA Tracking - When user is old enough
//	pageTracker._trackEvent('Age Verification', 'form-old-enough');
    _gaq.push(['_trackPageview', 'Age Verification','form-old-enough']);

	// set cookie with birtday timestamp and country
    var cookieStr = birthdayDate+'-'+location;

    // set cookie
	$.cookie('old_enough',cookieStr, {expires: 365, domain: document.domain});

	// close overlay
	window.parent.$.prettyPhoto.close();
}

function redirectUser()
{
	window.parent.location = "http://www.responsibledrinking.eu";
	
	// GA Tracking - When user is too young
//	pageTracker._trackEvent('Age Verification', 'form-too-young');
    _gaq.push(['_trackPageview', 'Age Verification','form-too-young']);
}


/**
 * Add notification to an input field
 * 
 * @param inputId - string - id of input field
 * @param message - string - message in notification
 * @return null
 */
function addNotification(inputId,message) {
	// amount of time (in milliseconds) messages are shown
	var notificationUpTime = 5000;
	var notifyElementId = "#" + inputId + "-notification p.notification"; 
	// check we have notify markup
	if($(notifyElementId).length==0) {
		$("#" + inputId + "-notification").append("<p class=\"notification\">" + message + "</p>");
	} else {
		$(notifyElementId).html(message);
	}
	$(notifyElementId).stop().stop().stop();
	$(notifyElementId).clearQueue();
	// add error style to input field
	$("#" +inputId).addClass('error');
	$(notifyElementId).fadeIn()
    				  .animate({opacity: 1.0}, notificationUpTime)
    				  .fadeOut(800, function() {
    					  	$(this).hide();
    					  	$("#" + inputId).removeClass('error');
    				  });
}
