<!DOCTYPE html>
<html charset="utf-8">
<body>
<p>This tests clicking on the left of RTL text puts the caret at the end of the line.</p>
<pre id="console"></pre>
<script>

if (window.testRunner)
    testRunner.dumpAsText();

var tests = [
    {content: "&#1498; &#1500;&#1499;", expected: [2, 4]},
    {content: "&#1499;&#1499; &#1499;&#1499;&#1499;&#1499; &#1499;&#1499;&#1499;", expected: [3, 8, 11]},
    {content: "&#1490;&#1499; &#1497;&#1490;&#1499; &#1497;&#1490;&#1499; &#1497;&#1490;&#1499; &#1497;&#1490;&#1499;", width: "5ex",
        expected: [3, 7, 11, 15, 18]},
];

function failed(message) {
    console.innerHTML += 'FAIL: ' + message + '\n';
}

function passed(message) {
    console.innerHTML += 'PASS: ' + message + '\n';
}

function runTest(container, test) {
    container.style.width = '100%';
    container.innerHTML = test.content;

    // Starting from 5px, slowly increase the width until each word fits in one line.
    var heightOfLine = container.offsetHeight;
    var width = 5;
    do {
        container.style.width = width + 'px';
        width++;
    } while (container.offsetHeight > heightOfLine * test.expected.length);        
    container.style.width = (width + 1) + 'px';

    var x = 0;
    var y = heightOfLine / 2;
    var yIncrement = container.offsetHeight / test.expected.length;
    var lines = ['st', 'nd', 'rd', 'th'];

    if (!window.eventSender)
        return;

    for (var i = 0; i < test.expected.length; i++) {
        eventSender.mouseMoveTo(container.offsetLeft + x, container.offsetTop + y);
        eventSender.mouseDown();
        eventSender.leapForward(100);
        eventSender.mouseUp();
        eventSender.leapForward(1000);

        var line = (i + 1) + lines[Math.min(i, lines.length - 1)];
        var action = 'clicking on the left of the ' + line + ' line of ' + test.content;

        if (!window.getSelection().isCollapsed)
            return failed(action + ' put selection instead of caret');

        var range = window.getSelection().getRangeAt(0);
        if (range.startContainer != container.firstChild)
            return failed(action + ' put the caret at a wrong container');

        action += ' put the caret at ' + range.startOffset;
        if (range.startOffset != test.expected[i])
            return failed(action + ' but expected at ' + test.expected[i]);
        y += yIncrement;
        passed(action);
    }

}

var console = document.getElementById('console');

var container = document.createElement('div');
container.contentEditable = true;
container.setAttribute('dir', 'rtl');
document.body.appendChild(container);

if (!window.eventSender)
    failed('Clicking tests require eventSender');
else {
    for (var i = 0; i < tests.length; i++)
        runTest(container, tests[i]);
    container.innerHTML = '';
}

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