$(document).ready(function() {

	//field restriction
	$('.textMin').numeric();
	
	//custom autotab
	$('#day,#month').keyup(function(e){
		if ((e.keyCode == 9) || (e.keyCode == 16) || (e.keyCode == 20)) {
			return false;
		} else {
			var max = $(this).attr('maxlength');
			var l = $(this).val().length;
			if (l == max) {
				var $this = $(this);
				if ($this.attr('id') == "month") {
					$('#day').focus();
				} else if ($this.attr('id') == "day") {
					$('#year').focus();
				}
			}
		}
	});	

	//validation methods
	$.validator.addMethod('validMonth', function (v) {
		return ((v == undefined) || (v == "") || isNaN(v) || (v < 1) || (v > 12)) ? false : true;
	});
	
	$.validator.addMethod('validDay', function (v) {
		return ((v == undefined) || (v == "") || isNaN(v) || (v < 1) || (v > 31)) ? false : true;
	});	
	
	$.validator.addMethod('validYear', function (v) {
		var now = new Date();
		var thisYear = now.getFullYear();		
		return ((v == undefined) || (v == "") || isNaN(v) || (v < (thisYear-120)) || (v > thisYear)) ? false : true;						
	});				

	// validate contact form on keyup and submit
	$("#agegateForm").validate({
		errorLabelContainer: '#agegateError',		
		wrapper: 'li',
		rules: {
			month: { validMonth: true },
			day: { validDay: true },
			year: { validYear: true },
			state: { required: true }
		},
		messages: {
			month: "Please enter a valid month.",
			day: "Please enter a valid day.",
			year: "Please enter a valid year.",
			state: "Please enter a valid state."
		}
	});

	$("#agegateForm").submit(function() {
	
		if ($("#agegateForm").valid()) {
			var month = $('#month').val();
			var day = $('#day').val();
			var year = $('#year').val();
			var state = $('#state').val();		
			var date = new Date(year, month-1, day);
			
			if (mc.av.isValidAge(date)) {
				mc.av.save(month, day, year, state);
				//mc.omniture.call("Coors Banquet AV","Coors Banquet AV: Success")
				var returnTo = $.cookie('returnTo');
				if (returnTo && (typeof returnTo == 'string')) {				
					$.cookie('returnTo', null, { path: "/" });
					window.location.href = returnTo;
				} else {
					var q = (typeof window.location.search !== "undefined") ? window.location.search : "";
					window.location.href = "../home/" + q;				
				}
			} else {
				window.location.href = "../underage/";
			}
			return false;
		} 
	});
	
	$('.textMin').each(function() {
		var e = $(this);
		if (e.val().length < 1) {		
			var t = e.attr('title');
			e.val(e.attr('title'));	
			e.focus(function() {
				if (e.val() == t) {
					e.val('');
				} else {
					this.select();
				}			
			}).blur(function() {
				if (e.val() == "") {
					e.val(t);
				}
			});
		}
	});

});
