/**
 * integer validator
 *
 * @link        http://formvalidation.io/validators/integer/
 * @author      https://twitter.com/formvalidation
 * @copyright   (c) 2013 - 2016 Nguyen Huu Phuoc
 * @license     http://formvalidation.io/license/
 */
(function($) {
    FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
        'en_US': {
            integer: {
                'default': 'Please enter a valid number'
            }
        }
    });

    FormValidation.Validator.integer = {
        html5Attributes: {
            message: 'message',
            thousandsseparator: 'thousandsSeparator',
            decimalseparator: 'decimalSeparator'
        },

        enableByHtml5: function($field) {
            return ('number' === $field.attr('type')) && ($field.attr('step') === undefined || $field.attr('step') % 1 === 0);
        },

        /**
         * Return true if the input value is an integer
         *
         * @param {FormValidation.Base} validator The validator plugin instance
         * @param {jQuery} $field Field element
         * @param {Object} options Can consist of the following key:
         * - message: The invalid message
         * - thousandsSeparator: The thousands separator. It's empty by default
         * - decimalSeparator: The decimal separator. It's '.' by default
         * @returns {Boolean}
         */
        validate: function(validator, $field, options, validatorName) {
            if (this.enableByHtml5($field) && $field.get(0).validity && $field.get(0).validity.badInput === true) {
                return false;
            }

            var value = validator.getFieldValue($field, validatorName);
            if (value === '') {
                return true;
            }

            var decimalSeparator   = options.decimalSeparator   || '.',
                thousandsSeparator = options.thousandsSeparator || '';
            decimalSeparator       = (decimalSeparator   === '.') ? '\\.' : decimalSeparator;
            thousandsSeparator     = (thousandsSeparator === '.') ? '\\.' : thousandsSeparator;

            var testRegexp         = new RegExp('^-?[0-9]{1,3}(' + thousandsSeparator + '[0-9]{3})*(' + decimalSeparator + '[0-9]+)?$'),
                thousandsReplacer  = new RegExp(thousandsSeparator, 'g');

            if (!testRegexp.test(value)) {
                return false;
            }

            // Replace thousands separator with blank
            if (thousandsSeparator) {
                value = value.replace(thousandsReplacer, '');
            }
            // Replace decimal separator with a dot
            if (decimalSeparator) {
                value = value.replace(decimalSeparator, '.');
            }

            if (isNaN(value) || !isFinite(value)) {
                return false;
            }
            // TODO: Use Number.isInteger() if available
            value = parseFloat(value);
            return Math.floor(value) === value;
        }
    };
}(jQuery));
