<!DOCTYPE HTML>
<html>
  <head>
    <title>Test mid-flight cross site redirects are blocked</title>
    <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
    <script src="/tests/SimpleTest/SimpleTest.js"></script>
    <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
    <script type="text/javascript" src="manifest.js"></script>
  </head>
  <body>
    <pre id='test'>
    <script class="testbody" type='application/javascript'>

      function testIfLoadsToMetadata(test, useCors) {
        return new Promise(function(resolve, reject) {
          var elemType = getMajorMimeType(test.type);
          var element = document.createElement(elemType);

          if (useCors) {
            element.crossOrigin = "anonymous";
          }

          // Log events for debugging.
          [
            "suspend", "play", "canplay", "canplaythrough", "loadstart",
            "loadedmetadata", "loadeddata", "playing", "ended", "error",
            "stalled", "emptied", "abort", "waiting", "pause"
          ].forEach((eventName) => {
            element.addEventListener(eventName, (event)=> {
              info(test.name + " " + event.type);
            });
          });

          element.addEventListener("loadedmetadata", ()=>{
            resolve(true);
            removeNodeAndSource(element);
          });

          element.addEventListener("error", ()=>{
            resolve(false);
            removeNodeAndSource(element);
          });

          // Note: request redirect before the end of metadata, otherwise we won't
          // error before metadata has loaded if mixed origins are allowed.
          element.src = "midflight-redirect.sjs?resource=" + test.name
                      + (useCors ? "&cors" : "")
                      + "&type=" + test.type
                      + "&redirectAt=200";
          element.preload = "metadata";
          document.body.appendChild(element);
          element.load()
        });
      }

      let v = document.createElement("video");
      const testCases = gSmallTests.filter(t => v.canPlayType(t.type));

      async function testMediaLoad(message, {useCors}) {
        for (let test of testCases) {
          let loaded = await testIfLoadsToMetadata(test, useCors);
          is(loaded, useCors, test.name + " " + message);
        }
      }

      async function runTest() {
        try {
          SimpleTest.info("Test that all media do not play without CORS...");
          await testMediaLoad("expected to be blocked", {useCors: false});

          SimpleTest.info("Test that all media play if CORS used...");
          await testMediaLoad("expected to play with CORS", {useCors: true});
        } catch (e) {
          info("Exception " + e.message);
          ok(false, "Threw exception " + e.message);
        }
        SimpleTest.finish();
      }

      SimpleTest.waitForExplicitFinish();

      addLoadEvent(runTest);

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