<html>
<head>
<script src="../../resources/js-test-pre.js"></script>
<script>

window.jsTestIsAsync = true;

var iteration = 0;
var sheet, rules;

function step1(opt_media)
{
    var doc = document.implementation.createHTMLDocument();
    var style = doc.createElement('style');
    doc.head.appendChild(style);
    sheet = style.sheet;
    if (opt_media) {
        sheet.insertRule('@media screen { body { background: red; } p { color: white; } }', 0);
        rules = sheet.rules[0];
        sheet.removeRule(0);
        sheet = 0;
    }

    doc.head.removeChild(style);
    document.adoptNode(style);
    delete doc;
    gc();
    setTimeout(opt_media ? step2a : step2b, 10);
}

function step2a()
{
    try {
        rules.insertRule('a { }', 1);
        if (iteration++ == 10) {
            iteration = 0;
            step1(true);
            return;
        }
        
        setTimeout('step1(false)', 0);
    }
    catch(e) {
        document.body.innerText = 'FAIL, threw exception.';
        if (window.testRunner)
            testRunner.notifyDone();

    }    
}

function step2b()
{
    try {
        sheet.insertRule('a { }', 0);
        if (iteration++ == 10) {
            document.body.innerText = 'PASS';
            if (window.testRunner)
                testRunner.notifyDone();
            return;
        }
        
        setTimeout('step1(true)', 0);
    }
    catch(e) {
        document.body.innerText = 'FAIL, threw exception.';
        if (window.testRunner)
            testRunner.notifyDone();

    }
}

</script>
<script src="../../resources/js-test-post.js"></script>
</head>
<body onload="step1()">
    Running...
</body>
</html>
