<!DOCTYPE html>
<html>
<body>
<script src="../../resources/js-test-pre.js"></script>
<div class="testDiv"></div>
<script>
description("Tests that dispatchEvent raises INVALID_STATE_ERR if the event being dispatched is already being dispatched.");

jsTestIsAsync = true;

// try redispatching an event in the process of being dispatched with dispatchEvent

function redispatchCustom(event) {
    shouldThrowErrorName("window.dispatchEvent(event)", "InvalidStateError");

    redispatchCustom.wasInvoked = true;
}

var customEvent = document.createEvent('CustomEvent');
customEvent.initCustomEvent('foo', true, true, null);
var p = document.querySelector('.testDiv');
p.addEventListener('foo', redispatchCustom);
p.dispatchEvent(customEvent);
shouldBeTrue('redispatchCustom.wasInvoked');

// try redispatching an event that has already finished being dispatched

function checkCustom(event) {
    checkCustom.wasInvoked = true;
}

p.removeEventListener('foo', redispatchCustom, true);
p.addEventListener('foo', checkCustom, true);
p.dispatchEvent(customEvent);
shouldBeTrue('checkCustom.wasInvoked');

// try redispatching an event in the process of being dispatched by
// the browser

function redispatchLoad(event) {
    if (redispatchLoad.dispatching) {
        testFailed('dispatchEvent of an event being dispatched should not dispatch the event again');
        return;
    }

    redispatchLoad.dispatching = true;
    shouldThrowErrorName("document.dispatchEvent(event)", "InvalidStateError");
    delete redispatchLoad.dispatching;

    finishJSTest();
}

window.addEventListener('load', redispatchLoad, true);
</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html>
