/* new JavaScript AV */

// add Object.create for legacy browsers
if (typeof Object.create !== 'function') {
	Object.create = function (o) {
		function F() {}
		F.prototype = o;
		return new F();
	};
}


/* Date difference functions to calculate age
* Adapted from Ultimate Age calculator script- By JavaScript Kit (http://www.javascriptkit.com) by Ryan Florence (http://clockfour.com)
* Over 200+ free scripts here!
* Credit must stay intact for use
*/
(function(){

	function calculateDifference(year, month, day, unit, decimal, round) {
		var one_day 	= 1000 * 60 * 60 * 24,
			one_monthth 	= 1000 * 60 * 60 * 24 * 30,
			one_year 		= 1000 * 60 * 60 * 24 * 30 * 12,
			today				= new Date(),
			pastdate		= new Date(year, month - 1, day),
			countunit 	= unit,
			decimals 		= decimal,
			rounding 		= round,
			finalunit 	= (countunit == "days") ? one_day: (countunit == "monthths") ? one_monthth: one_year,
			decimals 		= (decimals <= 0) ? 1: decimals * 10
		;

		if (unit != "years") {
			if (rounding == "rounddown"){
				return (Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals);
			} else {
				return (Math.ceil((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals);
			}
		}	else {
			var yearspast = today.getFullYear() - year - 1;
			var tail = (today.getMonth() > month - 1 || today.getMonth() == month - 1 && today.getDate() >= day) ? 1: 0;
			pastdate.setFullYear(today.getFullYear());
			var pastdate2 = new Date(today.getFullYear() - 1, month - 1, day);
			tail = (tail == 1) ? tail + Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals: Math.floor((today.getTime() - pastdate2.getTime()) / (finalunit) * decimals) / decimals;
			return (yearspast + tail);
		}
	}
	
	Date.prototype.yearsSince = function(pastDate){
		var decimal = decimal || 0, rounding = rounding || 'rounddown';
		return calculateDifference(pastDate.getFullYear(), pastDate.getMonth(), pastDate.getDay(), 'years', decimal, rounding);
	}

})();

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

	// key and value given, set cookie...
	if (arguments.length > 1 && (value === null || typeof value !== "object")) {
		options = jQuery.extend({}, options);

		if (value === null) {
			options.expires = -1;
		}

		if (typeof options.expires === 'number') {
			var days = options.expires, t = options.expires = new Date();
			t.setDate(t.getDate() + days);
		}

		return (document.cookie = [
			encodeURIComponent(key), '=',
			options.raw ? String(value) : encodeURIComponent(String(value)),
			options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
			options.path ? '; path=' + options.path : '',
			options.domain ? '; domain=' + options.domain : '',
			options.secure ? '; secure' : ''
			].join(''));
		}

		// key and possibly options given, get cookie...
		options = value || {};
		var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
		return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/* Class to verify the age of the user.
* reads the cookie ondomready, if no cookie is present, displays av form
* uses classnames on the html element to hide and display elements on the page
* `no-auth` is default, cookie nor form have been checked, all elements hidden
* `auth-fail` no cookie is present, form is displayed, content remains hidden
* `auth-pass` age verified, form hidden, content displayed

* author: Ryan Florence (http://clockfour.com)
*/

var AgeVerifier = Object.create({
	
	initialize: function(){
		var cookieVal = $.cookie('corona_av');
		if (cookieVal && cookieVal == '21+') {
			this.pass();
		} else {
			this.failCookie();
		}
	},
	
	pass: function(){
		$('html').removeClass('no-auth').removeClass('auth-fail').addClass('auth-pass');
		this.setCookie();
		return this;
	},
	
	failCookie: function(){
		$('html').removeClass('no-auth').addClass('auth-fail');
		this.attach();
	},
	
	failAge: function(){
		window.location.href = "http://www.centurycouncil.org/";
		return this;
	},
	
	attach: function(attribute){
		var self = this;
		$('#av').bind('submit', function(event){
			event.preventDefault();
			self.submitHandler();
		});
		// IE 6 & 7 don't find this even after domready, this keeps trying until it finally gets it
		if ($('#av').length < 1){
			setTimeout(function(){ self.attach(); }, 200);
		}
		return this;
	},
	
	submitHandler: function(){
		var month = document.av.av_month.value;
		var day = document.av.av_day.value;
		var year = document.av.av_year.value;

		if (month == 0 || day == 0 || year == 0) {
			alert ("Please select a value from each field");
			return false;
		}
		
		var dob = day + '/' + month + '/' + year;
		this.verifyAge(dob);
	},
	
	verifyAge: function(dob){
		var age = new Date().yearsSince(new Date(dob));
		(age < 21) ? this.failAge() :	this.pass();
		return this;
	},
	
	setCookie: function(){
		$.cookie('corona_av', '21+', { path: '/' });
		return this;
	}
	
});

$(document).ready(function(){
	AgeVerifier.initialize();
});
