(function()
{
    'use strict';

    var page = jQuery(document);

    var maskDefaults = {
        mask: Number,
        scale: 0
    };

    var prevent_value_scroll = function(event)
    {
        event.preventDefault();
    };

    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        var number_inputs = block.find('input[type="number"]');

        // normalize input behavior
        number_inputs.each(function()
        {
            jQuery(this).trigger('number:attach');
        });
    });

    page.on('number:attach', function(event)
    {
        var input = jQuery(event.target);

        input.on('focus', function()
        {
            input.on('mousewheel', prevent_value_scroll);
        });

        input.on('blur', function()
        {
            input.off('mousewheel', prevent_value_scroll);
        });

        var isDecimal = input.is('[data-decimal]');

        var maskOptions = jQuery.extend( true, {}, maskDefaults );

        input.attr({
            type: 'text',
            autocomplete: 'off',
            autocorrect: 'off',
            inputmode: 'numeric',
            pattern: '[0-9]*' // triggers numeric keyboard on ios safari
        });

        if (isDecimal)
        {
            input.attr({
                inputmode: 'decimal',
                pattern: null
            });

            maskOptions['scale'] = 2;
        }


        var min = input.attr('min');
        var max = input.attr('max');

        if (min)
        {
            maskOptions['min'] = min;
        }

        if (max)
        {
            maskOptions['max'] = max;
        }


        var mask = new IMask(input[0], maskOptions);

        input.data('mask', mask);
    });

}());
