/*
 *  Additions to jQuery Tools Validator
 */
$(function(){
    $.tools.validator.fn("[data-equals]", "Value not equal with the $1 field", function(input) {
        var name = input.attr("data-equals"),
        field = this.getInputs().filter("[name=" + name + "]");
        return input.val() == field.val() ? true : [name];
    });

    /*
     *  Validate states by country region id
     *
     *  Add data-countryregionid attribute to state select element
     *  with value of id for corresponding country select element
     */
    $.tools.validator.fn("select[data-countryregionid]", "Value not allowed for selected country", function(input) {
        var validity;
        
        var countryRegionIdSelector = '#' + $(input).attr("data-countryregionid");

        var countryRegionId = $(countryRegionIdSelector).val();
        var state = $(input).find(":selected").val();

        if( countryRegionId === 'US' || countryRegionId === 'CA' ) {
            validity = state.length > 0;
        } else {
            validity = state.length === 0;
        }

        return validity;
    });

    /*
     *  Validate radio buttons
     *
     *  For each required radio button, verify that its group has a selection
     */
    $.tools.validator.fn("input[data-radio]","Please make a selection",function(input) {
        var name = $(input).attr('name');

        var checked = $('input[name="' + name + '"]:checked').size();

        return checked > 0;
    });

    /*
     * Cayman business year: must be a number representing a year
     */
    $.tools.validator.fn("[data-caymanyear]","Please enter a year",function(input) {
        var year = $(input).val();

        var integer = (year == Math.floor(year));

        var inception = (year >= 1980.0);

        return integer && inception;
    });

    /*
     * Text field dependent on checkbox TODO
     */

    /*
     * Luhn check
     * <http://stackoverflow.com/questions/1690057/credit-card-validation-with-jquery>
     */
    $.tools.validator.fn("[data-luhn]","Please enter a valid credit card number",function(input) {
        var n = $(input).val();
        
        var l = n.length;

        if ( l < 15 || l > 16 )
            return false;

        var sum = 0;
        var mul = 1;

        for (var i = 0; i < l; i++) {
            var digit = n.substring(l-i-1,l-i);

            var tproduct = parseInt(digit ,10) * mul;

            if (tproduct >= 10)
                sum += (tproduct % 10) + 1;
            else
                sum += tproduct;

            if (mul == 1)
                mul++;
            else
                mul--;
        }
        
        return (sum % 10) == 0;
    });

    //  Disallow whitespace
    $.tools.validator.fn("[required]", "Please complete this mandatory field.", function(el, v) {
		if (el.is(":checkbox"))  { return el.is(":checked"); }
		return !!$.trim(v);
	});

    //  add data-expirationyear="expirationMonthId" to apply this validator
    $.tools.validator.fn("[data-expirationyear]","Please enter a valid expiration year", function(el, v) {
        var now = new Date();
        var month = 1.0 + now.getMonth();
        var year = now.getFullYear();

        var expirationMonthSelector = '#' + $(el).attr('data-expirationyear');
        var expirationMonth = parseInt($(expirationMonthSelector).val(),10);

        //  Any future year is valid
        if( v > year )
            return true;

        if( typeof(console) === 'object') console.log('Read month as ' + expirationMonth + ' comparing to ' + month + ': ' + (expirationMonth > month));

        //  Current year is valid if month is not past
        if( expirationMonth >= month )
            return true;

        return false;
    });

    //  add data-expirationmonth="expiraitonYearId" to apply this validator
    $.tools.validator.fn("[data-expirationmonth]","Please enter a valid expiration month", function(el,v) {
        var now = new Date();
        var month = 1.0 + now.getMonth();
        var year = now.getFullYear();

        var expirationYearSelector = '#' + $(el).attr('data-expirationmonth');
        var expirationYear = $(expirationYearSelector).val();

        //  Any month is valid if year is in the future
        if( expirationYear > year )
            return true;

        //  Month versus year
        if( expirationYear == year && v >= month )
            return true;

        //  No month is valid if year is invalid
        return false;
    });
});
