<script>

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

function getPixel(canvas, x, y) {
    var context = canvas.getContext("2d");
    var data = context.getImageData(x, y, 1, 1);
    if (!data)
        return [-1, -1, -1, -1];

    var result = new Array(data.data.length)
    for (var i = 0; i < data.data.length; i++)
        result[i] = data.data[i];

    return result;
}

function checkArrayValues(a1, a2, tolerance) {
    for (var i = 0, length = a1.length; i < length; i++) {
        if (Math.abs(a1[i] - a2[i]) > tolerance)
            return false;
    }
    return true;
}

function pixelShouldBe(canvas, x, y, color, tolerance) {
    var output = document.createElement("p");
    var value = getPixel(canvas, x, y);
    if (checkArrayValues(color, value, tolerance))
        output.innerText = "PASS: Pixel (" + x + ", " + y + ") was close to " + color;
    else
        output.innerText = "FAIL: Pixel (" + x + ", " + y + ") was " + value + ". Expected " + color;
    document.body.appendChild(output);
}

function run() {
    var canvas = document.createElement("canvas");
    document.body.appendChild(canvas);
    canvas.width = 400;
    canvas.height = 400;
    var ctx = canvas.getContext("2d");
    var img = new Image()
    img.addEventListener("load", function() {
        ctx.fillStyle = "red";
        ctx.fillRect(0, 0, 400, 400);
        ctx.drawImage(img, 0, 0, 400, 400);
        pixelShouldBe(canvas, 10, 10, [255, 0, 0, 255], 5);
        pixelShouldBe(canvas, 200, 200, [0, 255, 0, 255], 5);
        pixelShouldBe(canvas, 390, 390, [0, 0, 255, 255], 5);

       if (window.testRunner)
           testRunner.notifyDone();
    }, false)
    img.src = "resources/image-6400x6400.jpg";
}

window.addEventListener("load", run, false);
</script>
