(function()
{
    'use strict';

    var body = jQuery(document.body);

    var attribute = 'data-focus-method';

    var method_touch = 'touch';
    var method_mouse = 'mouse';
    var method_key   = 'key';

    var focus_method      = false;
    var last_focus_method = false;

    var on_key_down = function()
    {
        focus_method = method_key;
    };

    var on_mouse_down = function(event)
    {
        if (focus_method === method_touch)
        {
            return;
        }

        focus_method = method_mouse;
    };

    var on_touch_start = function()
    {
        focus_method = method_touch;
    };

    var on_focus = function(event)
    {
        if (!focus_method)
        {
            focus_method = last_focus_method;
        }

        jQuery(event.target).attr(attribute, focus_method);

        last_focus_method = focus_method;
        focus_method = false;
    };

    var on_blur = function(event)
    {
        jQuery(event.target).removeAttr(attribute);
    };

    var on_window_blur = function()
    {
        focus_method = false;
    };

    var bind_events = function()
    {
        body.on('keydown', on_key_down);
        body.on('mousedown', on_mouse_down);
        body.on('touchstart', on_touch_start);
        body.on('focusin', on_focus);
        body.on('focusout', on_blur);

        jQuery(window).on('blur', on_window_blur);
    };

    bind_events();

}());
