<!DOCTYPE HTML>
<html>
<script src='test.js'></script>
<script src='focus.js'></script>
<script>

function testInactiveElement() {
  var a = document.getElementById('a');
  a.value = 'abc';
  a.setSelectionRange(0, 2);
  assertEquals(0, a.selectionStart);
  assertEquals(2, a.selectionEnd);
  var c = document.getElementById('c');
  c.focus();
  assertEquals(c, document.activeElement);
  focus(a);
  assertEquals(3, a.selectionStart);
  assertEquals(3, a.selectionEnd);
}

function testActiveElement() {
  var a = document.getElementById('a');
  a.focus();
  var is_blurred = false;
  var onBlur = function() {
    is_blurred = true;
  }
  a.addEventListener('blur', onBlur, false);
  try {
    focus(a);
    assert(!is_blurred);
  } catch (error) {
    a.removeEventListener('blur', onBlur, false);
    throw error;
  }
}

function testNonTextInput() {
  var a = document.getElementById('a');
  a.focus();
  assertEquals(a, document.activeElement);
  var c = document.getElementById('c');
  focus(c);
  assertEquals(c, document.activeElement);
}

function testEditableDiv() {
  var a = document.getElementById('a');
  a.focus();
  assertEquals(a, document.activeElement);
  var d = document.getElementById('d');
  focus(d);
  assertEquals(d, document.activeElement);
}

function testNonFocusableChildOfEditableDiv() {
  var a = document.getElementById('a');
  a.focus();
  assertEquals(a, document.activeElement);
  try {
    focus(document.getElementById('e'));
    assert(false);
  } catch (error) {
  }
}

function testFocusableChildOfEditableDiv() {
  var a = document.getElementById('a');
  a.focus();
  assertEquals(a, document.activeElement);
  var f = document.getElementById('f');
  focus(f);
  assertEquals(f, document.activeElement);
}

function testTransparentElement() {
  var a = document.getElementById('a');
  a.focus();
  assertEquals(a, document.activeElement);
  var g = document.getElementById('g');
  focus(g);
  assertEquals(g, document.activeElement);
}

</script>
<body>
  <input type="text" id="a">
  <br>
  <textarea id="b">
  </textarea>
  <br>
  <input type="button" value="c" id="c">
  <br>
  <div id="d" contentEditable="true">
  </div>
  <div contentEditable="true">
    <div id="e">editable</div>
  </div>
  <div contentEditable="true">
    <input id="f" type="text">
  </div>
  <div>
    <input id="g" style='opacity: 0' type='text'>
  </div>
</body>
</html>