<head>
<script>

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

function log(msg)
{
    document.getElementById("logger").innerHTML += msg + "<br>";
}

function finishTest()
{
    if (testRunner)
        testRunner.notifyDone();
}

var rafCount = 0;
var increasingTimestampsSeen = 0;
var timestamp = 0;
var gamepad2Timestamp = -1;

function rafCallback()
{
    var gamepad = navigator.getGamepads()[0];
    var gamepad2 = navigator.getGamepads()[1];

    if (gamepad2Timestamp == -1)
        gamepad2Timestamp = gamepad2.timestamp;

    if (gamepad2Timestamp != gamepad2.timestamp) {
        log("Timestamp of gamepad 2 should never change throughout this test, but it did!");
        finishTest();
    }

    if (gamepad.timestamp < timestamp) {
        log("Timestamp on gamepad is " + gamepad.timestamp + " which is less than " + timestamp);
        finishTest();
    }

    if (gamepad.timestamp > timestamp)
        ++increasingTimestampsSeen;

    if (increasingTimestampsSeen == 10) {
        log("Increasing timestamp values seen for 10 RAF cycles");
        finishTest();
    }

    if (++rafCount == 120) {
        log("Went 120 RAF cycles without seeing 10 increasing timestamp values... yikes!");
        log("Number of actual timestamp increases seen: " + increasingTimestampsSeen);
        finishTest();
    }

    timestamp = gamepad.timestamp;

    if (gamepad.buttons[0] == 1.0)
        testRunner.setMockGamepadButtonValue(0, 0, 0.0);
    else
        testRunner.setMockGamepadButtonValue(0, 0, 1.0);
    
    requestAnimationFrame(rafCallback);
}

function handleGamepadConnect()
{
    requestAnimationFrame(rafCallback);
}

function runTest() {
    addEventListener("gamepadconnected", handleGamepadConnect);

    testRunner.setMockGamepadDetails(0, "Test Joystick", "", 2, 2, false);
    testRunner.setMockGamepadAxisValue(0, 0, 0.7);
    testRunner.setMockGamepadAxisValue(0, 1, -1.0);
    testRunner.setMockGamepadButtonValue(0, 0, 1.0);
    testRunner.setMockGamepadButtonValue(0, 1, 1.0);
    testRunner.connectMockGamepad(0);
    testRunner.setMockGamepadDetails(1, "Test Joystick 2", "", 2, 2, false);
    testRunner.setMockGamepadAxisValue(1, 0, 0.7);
    testRunner.setMockGamepadAxisValue(1, 1, -1.0);
    testRunner.setMockGamepadButtonValue(1, 0, 1.0);
    testRunner.setMockGamepadButtonValue(1, 1, 1.0);
    testRunner.connectMockGamepad(1);
}

</script>
</head>
<body onload="runTest();">
<div id="logger"></div>
</body>
