(function($) {
    $.fn.bootstrapValidator.i18n.imo = $.extend($.fn.bootstrapValidator.i18n.imo || {}, {
        'default': 'Please enter a valid IMO number'
    });

    $.fn.bootstrapValidator.validators.imo = {
        /**
         * Validate IMO (International Maritime Organization)
         * Examples:
         * - Valid: IMO 8814275, IMO 9176187
         * - Invalid: IMO 8814274
         *
         * @see http://en.wikipedia.org/wiki/IMO_Number
         * @param {BootstrapValidator} validator The validator plugin instance
         * @param {jQuery} $field Field element
         * @param {Object} options Can consist of the following keys:
         * - message: The invalid message
         * @returns {Boolean}
         */
        validate: function(validator, $field, options) {
            var value = $field.val();
            if (value === '') {
                return true;
            }

            if (!/^IMO \d{7}$/i.test(value)) {
                return false;
            }
            
            // Grab just the digits
            var sum    = 0,
                digits = value.replace(/^.*(\d{7})$/, '$1');
            
            // Go over each char, multiplying by the inverse of it's position
            // IMO 9176187
            // (9 * 7) + (1 * 6) + (7 * 5) + (6 * 4) + (1 * 3) + (8 * 2) = 147
            // Take the last digit of that, that's the check digit (7)
            for (var i = 6; i >= 1; i--) {
                sum += (digits.slice((6 - i), -i) * (i + 1));
            }

            return sum % 10 === parseInt(digits.charAt(6), 10);
        }
    };
}(window.jQuery));
