<!DOCTYPE html>
<body>
<pre id="console"></pre>
<script>
function log(s) {
    document.getElementById("console").innerHTML += s + "\n";
}

function createEditableMultilineDiv(text, numLines) {
    // Put text in a span so that the width can be measured.
    var span = document.createElement("span");
    span.innerHTML = text;
    document.body.appendChild(span);
    var widthPx = span.offsetWidth;
    document.body.removeChild(span);

    // Make div with those dimensions so that the text wraps predictably regardless of platform.
    var lines = text;
    for (var i = 1; i < numLines; i++)
        lines += " " + text;

    var div = document.createElement("div");
    div.setAttribute("style", "width: " + widthPx + "px");
    div.contentEditable = true;
    div.innerHTML = lines;

    return div;
}

function selectSecondLine(element) {
    getSelection().setPosition(element.childNodes[0], 0);
    getSelection().modify("move", "forward", "line");
    getSelection().modify("extend", "forward", "lineboundary");
}

function unescapeRtl(rtlText) {
    var e = document.createElement("span");
    e.innerHTML = rtlText;
    return e.innerHTML;
}

ltrText = "the quick brown fox jumps";
ltrTextContainer = createEditableMultilineDiv(ltrText, 3);
document.body.appendChild(ltrTextContainer);
selectSecondLine(ltrTextContainer);

if (getSelection().toString() === ltrText + " ")
    log("PASS for LTR");
else
    log("FAIL for LTR, selection is '" + getSelection() + "' but should be '" + ltrText + " '");

rtlText = unescapeRtl("&#x05E9;&#x05D5;&#x05BC;&#x05E8;&#x05D4; " +
                      "&#x05E9;&#x05D5;&#x05BC;&#x05E8;&#x05D4; " +
                      "&#x05E9;&#x05D5;&#x05BC;&#x05E8;&#x05D4;");
rtlTextContainer = createEditableMultilineDiv(rtlText, 3);
rtlTextContainer.setAttribute("dir", "rtl");
document.body.appendChild(rtlTextContainer);
selectSecondLine(rtlTextContainer);

if (getSelection().toString() === rtlText + " ")
    log("PASS for RTL");
else
    log("FAIL for RTL, selection is '" + getSelection() + "' but should be '" + rtlText + " '");

log("");

if (window.testRunner)
    testRunner.dumpAsText();
</script>
</body>
