<!DOCTYPE html>
<html>
<body>
<p>Tests for moving focus by pressing tab key across label and legend elements.<br>
To manually test, press tab key seven times then shift+tab six times.<br>
It should traverse focusable elements in the ascending order from 1 to 7 and then in the descending order back to 1.</p>
</p>
<input id="startingNode">
<div id="test-content">
    <label title="FAIL - a non-focusable label with an input should not be focused">
        <input title="1. An input element inside a non-focusable label element">hello
    </label>
    <label tabindex="0" title="2. A label element with an input element">
        <input title="3. An input elment inside a focusable label element">world</label>
    <label tabindex="0" title="4. A label element with just text">webkit</label>
    <label title="FAIL - an label element without tabindex should not be focused">rocks</label>
    <fieldset tabindex="0" title="5. A fieldset element with tabindex">
        <legend tabindex="0" title="6. A focusable legend element inside a fieldset element">foo</legend>
        <input title="7. An input element inside a fieldset element">
    </fieldset>
</div>
<style> :focus { background: red; } </style>
<pre id="result"></pre>
<script>

function moveFocusForward(focusCount)
{
    setTimeout(function () {
        if (!focusCount)
            return moveFocusBackward(7);
        eventSender.keyDown('\t');
        setTimeout(function () {
            moveFocusForward(focusCount - 1);            
        }, 1);
    }, 1);
}

function moveFocusBackward(focusCount)
{
    setTimeout(function () {
        if (!focusCount) {
            testContent.style.display = 'none';
            testRunner.notifyDone();
            return;
        }
        eventSender.keyDown('\t', ['shiftKey']);
        setTimeout(function () {
            moveFocusBackward(focusCount - 1);            
        }, 1);
    }, 1);
}

let testContent = document.getElementById('test-content');

window.onload = () => {
    document.getElementById('startingNode').focus();
    if (window.eventSender) {
        testRunner.dumpAsText();
        testRunner.waitUntilDone();
    }
    moveFocusForward(7);
}

testContent.querySelectorAll('*').forEach((element) => {
    element.onfocus = function () {
        document.getElementById('result').textContent += (element.title || 'FAIL - focused an unexpected element') + '\n';
    }
});

</script>
</body>
</html>
