<html>
<head>
<script>
function log(message)
{
    document.getElementById("console").innerHTML += message + "<br>";
}

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

function runTest()
{
    if (window.testRunner) {
        testRunner.clearAllDatabases();
        testRunner.setDatabaseQuota(327680);
        testRunner.dumpDatabaseCallbacks();
        testRunner.dumpAsText();
        testRunner.waitUntilDone();
    }

    var transactionsRun = 0;

    // Open a new database with a creation callback, and make sure the creation callback is queued
    var creationCallbackCalled1 = false;
    var db1Name = "OpenDatabaseCreationCallback1" + (new Date()).getTime();
    var db1 = openDatabase(db1Name, "1.0", "", 1,
                           function(db) {
                               creationCallbackCalled1 = true;
                               if (db.version != "") {
                                   log("Creation callback was called with a database with version " +
                                       db.version + "; empty string expected.");
                                   finishTest();
                               }
                           });

    // Putting this code inside a transaction on 'db1' makes sure that it is executed after
    // the creation callback is.
    db1.transaction(function(tx) {
        if (!creationCallbackCalled1) {
            log("Creation callback for db1 was not called.");
            finishTest();
        }
        if (++transactionsRun == 2)
            finishTest();
    });

    // Try to open another handle to the same database.
    // Since the version of this database is "" (empty string), openDatabase() should return
    // a null handle and throw a INVALID_STATE_ERR exception.
    var db1Fail = null;
    try {
        db1Fail = openDatabase(db1Name, "1.0", "", 1);
        log("This statement should not have been executed; an INVALID_STATE_ERR exception should've been thrown.");
        finishTest();
    } catch(err) {
        if (db1Fail) {
            log("db1Fail should have been null.");
            finishTest();
        }
    }

    // Open a handle to another database, first without a creation callback, then with one.
    // Make sure the creation callback is not called.
    var creationCallbackCalled2 = false;
    var db2 = openDatabase("OpenDatabaseCreationCallback2", "1.0", "", 1);
    db2 = openDatabase("OpenDatabaseCreationCallback2", "1.0", "", 1,
                       function(db) { creationCallbackCalled2 = true; });
    db2.transaction(function(tx) {
        if (creationCallbackCalled2) {
            log("Creation callback for db2 should not have been called.");
            finishTest();
        }
        if (++transactionsRun == 2)
            finishTest();
    });
}

</script>
</head>

<body onload="runTest()">
This test tests openDatabase()'s creation callback.
<pre id="console">
</pre>
</body>

</html>
