/*!
{
  "name": "IndexedDB",
  "property": "indexeddb",
  "caniuse": "indexeddb",
  "tags": ["storage"],
  "polyfills": ["indexeddb"],
  "async": true
}
!*/
/* DOC
Detects support for the IndexedDB client-side storage API (final spec).
*/
define(['Modernizr', 'prefixed', 'addTest'], function(Modernizr, prefixed, addTest) {
  // Vendors had inconsistent prefixing with the experimental Indexed DB:
  // - Webkit's implementation is accessible through webkitIndexedDB
  // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
  // For speed, we don't test the legacy (and beta-only) indexedDB

  Modernizr.addAsyncTest(function() {

    var indexeddb;

    try {
      // Firefox throws a Security Error when cookies are disabled
      indexeddb = prefixed('indexedDB', window);
    } catch (e) {
    }

    if (indexeddb) {
      var testDBName = 'modernizr-' + Math.random();
      var req;
      try {
        req = indexeddb.open(testDBName);
      } catch (e) {
        addTest('indexeddb', false);
        return;
      }

      req.onerror = function(event) {
        if (req.error && (req.error.name === 'InvalidStateError' || req.error.name === 'UnknownError')) {
          addTest('indexeddb', false);
          event.preventDefault();
        } else {
          addTest('indexeddb', true);
          detectDeleteDatabase(indexeddb, testDBName);
        }
      };

      req.onsuccess = function() {
        addTest('indexeddb', true);
        detectDeleteDatabase(indexeddb, testDBName);
      };
    } else {
      addTest('indexeddb', false);
    }
  });

  function detectDeleteDatabase(indexeddb, testDBName) {
    var deleteReq = indexeddb.deleteDatabase(testDBName);
    deleteReq.onsuccess = function() {
      addTest('indexeddb.deletedatabase', true);
    };
    deleteReq.onerror = function() {
      addTest('indexeddb.deletedatabase', false);
    };
  }

});