<!DOCTYPE html>
<html>
<body>
<p>This test ensures beforeunload event does NOT fire for a subframe that has been adopted by a document outside of the frame hierarchy that is about to unload.</p>
<pre id="log"></pre>
<script>

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

function createFrame(id, parent) {
    var iframe = document.createElement('iframe');
    if (parent)
        parent.contentDocument.body.appendChild(iframe);
    else
        document.body.appendChild(iframe);
    if (!iframe.contentDocument.body)
        iframe.contentDocument.appendChild(iframe.contentDocument.createElement('body'));
    iframe.contentDocument.body.appendChild(iframe.contentDocument.createTextNode(id));    
    iframe.contentDocument.body.appendChild(iframe.contentDocument.createElement('br'));
    iframe.contentWindow.onbeforeunload = function () { fired(iframe.contentWindow, id); return null; }
    iframe.style.width = '70%';
    iframe.style.height = '40%';
    return iframe;
}

function log(message) {
    var log = document.getElementById('log');
    log.innerHTML += message + '\n';
}

var expectedOrder = ['parent', 'a', 'b'];
var i = 0;

function fired(contentWindow, id) {
    if (expectedOrder[i] == id)
        log('PASS: fired on ' + id);
    else
        log('FAIL: fired on ' + id + ' but expected on ' + expectedOrder[i]);
    i++;

    if (contentWindow == a.contentWindow) {
        log('adopting');
        document.body.appendChild(document.adoptNode(adoptee));
        log('adopted');
    }
}

var container = createFrame('parent');
var a = createFrame('a', container);
var adoptee = createFrame('adoptee', a);
var b = createFrame('b', container);

container.onload = function () {
    if (i == expectedOrder.length)
        log('DONE');
    else
        log('Received ' + i + ' events but expected ' + expectedOrder.length);

    // Hide the frames to work around timing dependencied in layout tree creation,
    // see <https://bugs.webkit.org/show_bug.cgi?id=140061>.
    var frames = document.getElementsByTagName("iframe");
    for (var frameIndex = 0; frameIndex < frames.length; ++frameIndex)
        frames[frameIndex].style.display = "none";        
        
    if (window.testRunner)
        testRunner.notifyDone();
}
container.src = 'resources/before-unload-in-subframe-destination.html';

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