<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<script src="../../resources/js-test-pre.js"></script>
</head>
<body>
<div id="test" contenteditable>
<p id="p1">the car is the good the The world.</p>
<p id="p2">中文字是中文字</p>
<bdo dir="rtl" id="p3">the best</bdo>
</div>
<div id="console"></div>
<script>

if (!window.internals)
    testFailed('This test requires internals object');
else {
    var container = document.getElementById('test');

    function range(startContainer, startOffset, endContainer, endOffset) {
        var range =  document.createRange();
        range.setStart(startContainer, startOffset);
        range.setEnd(endContainer, endOffset);
        return range;
    }

    function rangeOfNodeContent(referenceNode) {
        var range = document.createRange();
        range.selectNodeContents(referenceNode);
        return range;
    }

    Range.prototype.toArray = function () {
        return [this.startContainer, this.startOffset, this.endContainer, this.endOffset];
    }

    var p1 = document.getElementById("p1");
    var p2 = document.getElementById("p2");
    var p3 = document.getElementById("p3");

    var firstThe = [p1.firstChild, 0, p1.firstChild, 3];
    var secondThe = [p1.firstChild, 11, p1.firstChild, 14];
    var upperThe = [p1.firstChild, 24, p1.firstChild, 27];
    var chineseMatch = [p2.firstChild, 4, p2.firstChild, 6];
    var germanMatch = [p3.firstChild, 5, p3.firstChild, 6];
    var rtlMatch = [p3.firstChild, 0, p3.firstChild, 3];

    // When the target position is correct, at the beginning of the matched range.
    shouldBe('internals.rangeOfStringNearLocation(rangeOfNodeContent(p1), \'the\', 11).toArray()', 'secondThe');

    // Cases that the matched range is on either side of the target position.
    shouldBe('internals.rangeOfStringNearLocation(rangeOfNodeContent(p1), \'the\', 9).toArray()', 'secondThe');    
    shouldBe('internals.rangeOfStringNearLocation(rangeOfNodeContent(p1), \'the\', 6).toArray()', 'firstThe');

    // In this case, target position is at the beginning of "oog", make sure it's picking the 
    // left side "the" as the closest match.
    shouldBe('internals.rangeOfStringNearLocation(rangeOfNodeContent(p1), \'the\', 16).toArray()', 'secondThe');

    // Upper case.
    shouldBe('internals.rangeOfStringNearLocation(rangeOfNodeContent(p1), \'The\', 11).toArray()', 'upperThe');

    // CJK
    shouldBe('internals.rangeOfStringNearLocation(rangeOfNodeContent(p2), \'中文\', 5).toArray()', 'chineseMatch');

    // RtL
    shouldBe('internals.rangeOfStringNearLocation(rangeOfNodeContent(p3), \'the\', 5).toArray()', 'rtlMatch');

    container.style.display = 'none';
}

</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html>
