function average (array)
{
    total = 0;

    for (var i in array) {
        total += array[i];
    }

    return (total / array.length);
}


function strip_spurious_characters ()
{
    document.getElementById ("username").value =
        document.getElementById ("username").value.replace (/[^A-Za-z0-9]/g,
                                                           '');
}


function input_intervals (input_times)
{
    result = new Array ();

    for (i = 0; i < input_times.length - 2; i++) {
        result.push (input_times[i + 1].getTime () -
                     input_times[i].getTime ())
    }

    return result;
}


function is_human (input_times)
{
    return (input_times.length < 10 ||
            average (input_intervals (input_times).slice (-10)) > 50);
}


{
    var input_times = new Array ();

    function barcode_reader ()
    {
        document.onkeydown = function (e) {
            if (!e) {
                e = window.event;
            }
            if (e.keyCode == 13) {
                var target = (e.target || e.srcElement);

                if (target.name == 'username') {
                    if (is_human (input_times)) {
                        document.getElementById ("loginForm").submit ();
                    } else {
                        clear_readings ();
                        strip_spurious_characters ();
                        return false;                   
                    }
                } else {
                    return true;
                }
            } else {
                input_times.push (new Date ());
            }
        }
    }


    function clear_readings()
    {
        input_times = new Array ();
    }
}
