MillerCoors.AgeVerification = function(serverVars) {
    this.ServerVars = serverVars || {};
    this.Initialize();
};
MillerCoors.AgeVerification.prototype = {
    Initialize: function() {
        var MESSAGE = this.ServerVars.message || "Enter your birth date";
        var WATERMARK_MM = this.ServerVars.watermarkMM || "MM";
        var WATERMARK_DD = this.ServerVars.watermarkMM || "DD";
        var WATERMARK_YY = this.ServerVars.watermarkMM || "YYYY";
        var AGE_MINIMUM = (this.ServerVars.ageMinimum != null) ? this.ServerVars.ageMinimum : 21;
        var AGE_MAXIMUM = (this.ServerVars.ageMaximum != null) ? this.ServerVars.ageMaximum : 120;

        var initializeDateField = function(field, watermark, autoTabLimit, autoTabField) {
            if (field !== null) {

                // Set the initial value of the field to its watermark and 
                // store the watermark on the field itself for later use.
                field.val(watermark);
                field.attr('watermark', watermark);

                // Restrict input to numbers only
                field.keypress(function(e) {
                    var keyCode = getKeyCodeForEvent(e);
                    return isNumericKey(keyCode) || isControlKey(keyCode);
                });

                // If we have fullfilled the data entry for the field
                // attempt to auto tab to the next field.
                field.keyup(function(e) {
                    var keyCode = getKeyCodeForEvent(e);
                    var pattern = new RegExp("^[0-9]{" + autoTabLimit + "}$");
                    if (autoTabField !== null && !isControlKey(keyCode) && field.val().match(pattern)) {
                        autoTabField.focus();
                    }
                });

                // When focused we want to auto select any data so that
                // the user can immediately being data entry
                field.focus(function() {
                    field.select();
                    showNotification();
                });

                // When we leave a field set the value back to the 
                // watermark if no data is entered
                field.blur(function() {
                    if (field.val().length == 0) {
                        field.val(field.attr('watermark'));
                    }
                });
            }
        };

        var getKeyCodeForEvent = function(e) {
            var keyCode = -1;
            if (window.event) {						// IE
                keyCode = window.event.keyCode;
            } else if (e.which && e.which != 0) {	// Netscape/Opera/Mozilla
                keyCode = e.which;
            } else {								// All Others
                if (e.charCode == 0) {				// Firefox
                    keyCode = e.keyCode;
                } else {
                    keyCode = e.charCode;
                }
            }
            return keyCode;
        }

        var isNumericKey = function(keyCode) {
            return keyCode >= 48 && keyCode <= 57;
        };

        var isControlKey = function(keyCode) {
            console.log(keyCode);
            return (keyCode > 0 && keyCode <= 13) || keyCode == 16 || keyCode == 37 || keyCode == 39;
        }

        var isValidDateOfBirth = function(e) {

            var mm = $('.avMonth').val();
            var dd = $('.avDay').val();
            var yy = $('.avYear').val();

            if (!isValidDate(yy, mm, dd)) {
                showNotification('Please enter a valid date of birth.');
                return false;
            }

            if (yy.length < 4) {
                showNotification('Please enter a 4-digit year.');
                return false;
            }

            return true;
        }

        var isValidDate = function(year, month, day) {
            var yy = year.toString();
            var mm = month.toString();
            var dd = day.toString();

            switch (yy.length) {
                case 3:
                    yy = yy.substring(1, 3);
                    // Allow dropcasing here to let the 2-digit
                    // code apply to the chomped 3-digit

                case 2:
                    if (yy.charAt(0) == '0') {
                        yy = '20' + year;
                    } else {
                        yy = '19' + year;
                    }
                    break;

                case 1:
                    yy = '200' + yy;
                    break;
            }

            // Parse the integers out ensuring base 10 to prevent octal parsing
            yy = parseInt(yy, 10);
            mm = parseInt(mm, 10) - 1;
            dd = parseInt(dd, 10);

            var input = new Date(yy, mm, dd);
            var today = new Date();
            var years = today.getFullYear() - input.getFullYear();

            // Ensure that the date given is actually a real date, is equal to or
            // less than today, and that the person is less than or equal to 120 
            // years old.
            return (input.getMonth() == mm && input.getFullYear() == yy)
			&& (input <= today)
			&& (years <= AGE_MAXIMUM);
        }

        var showNotification = function(message) {
            if (message !== null) {
                $('.avPrompt').text(message);
            } else {
                $('.avPrompt').text(MESSAGE);
            }
        };

        // Initialize the behavior for the date fields
        initializeDateField($('input.avMonth'), 'MM', 2, $('input.avDay'));
        initializeDateField($('input.avDay'), 'DD', 2, $('input.avYear'));
        initializeDateField($('input.avYear'), 'YYYY', 4, $('.avFormSubmit'));

        // Setup the main data validation hook
        $('.avFormSubmit').click(function() {
            return isValidDateOfBirth();
        });

        // Auto focus the first field
        $('input.avMonth').focus();
    }
};
MillerCoors.Extend(MillerCoors.AgeVerification, MillerCoors.Core);
