// For this script to work properly, the value of monthElementId should be a one-based index.
// i.e. January = 01, December = 12. Typically, dates in JS are zero-based. Since credit cards expire on the last day
// of a given month, by passing in 01 for January (which JS treats as February), the getLastDayOfMonthByMonthAndYear
// function will return 1/31. This will work automatically with no additional effort when using the CreditCardPayment
// card as our expiration dates are stored as one-based months.
var monthElementId, yearElementId, errorElementId;

function getJQueryFriendlyId(oldId) {
    return oldId.replace( /(:|\.|\[|\]|,)/g, "\\$1" );
}

function fetchElementById(elementId) {
    return $('#' + getJQueryFriendlyId(elementId));
}

function fetchElementValueById(elementId) {
    return fetchElementById(elementId).val();
}

function getLastDayOfMonthByMonthAndYear(chosenMonthVal, chosenYearVal) {
    var chosenMonth = parseInt(chosenMonthVal);
    var chosenYear = parseInt(chosenYearVal);

    // stackoverflow.com/questions/222309
    return new Date(chosenYear, chosenMonth, 0);
}

function isCreditCardExpirationValid(chosenMonthVal, chosenYearVal) {
    var isExpirationValid = false;

    if (chosenMonthVal !== undefined && chosenYearVal !== undefined) {
        var chosenDate =
            getLastDayOfMonthByMonthAndYear(chosenMonthVal, chosenYearVal);
        var todaysDate = new Date();

        if (chosenDate > todaysDate) {
            isExpirationValid = true;
        }
    }

    return isExpirationValid;
}

$(function() {
    $('form').submit(function(event) {
        var chosenMonth = fetchElementValueById(monthElementId);
        var chosenYear = fetchElementValueById(yearElementId);
        var errorIdElement = fetchElementById(errorElementId);

        if (!isCreditCardExpirationValid(chosenMonth, chosenYear)) {
            errorIdElement.show();
            event.preventDefault();
        } else {
            errorIdElement.hide();
        }
    });
});