<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test-pre.js"></script>
<script src="../resources/common.js"></script>
</head>
<body>
<p>Test if selected options are correctly restored even if their positions were changed.</p>
<div id="console"></div>

<input id="emptyOnFirstVisit">
<div id="parent">
<form action="data:text/html,&lt;script>history.back()&lt;/script>" id=form1>
<select id="select1" multiple>
  <option id="opt-ca-1" value="CA">California 1</option>
  <option id="opt-ca-2" value="CA" selected>California 2</option>
  <option id="opt-la">LA</option>
  <optgroup>
    <option id="opt-tk" selected>Tokyo</option>
    <option id="opt-os">Osaka</option>
  </optgroup>
  <option id="opt-ak" value="AK">Alaska</option>
  <option id="opt-wy" selected>WY</option>
</select>
</form>
</div>

<script>

jsTestIsAsync = true;

function runTest()
{
    var state = document.getElementById('emptyOnFirstVisit');
    if (!state.value) {
        // First visit.
        setTimeout(function() {
            state.value = 'visited';
            $('opt-tk').selected = false;
            $('opt-os').selected = true;
            $('select1').insertBefore($('opt-ak'), $('opt-ca-1'));
            $('select1').removeChild($('opt-wy'));
            var newOption = document.createElement('option');
            newOption.textContent = 'NY';
            $('select1').appendChild(newOption);
            newOption.selected = true;
            $('form1').submit();
        }, 0);
    } else {
        // Went back to this page again, and form state should be restored.
        shouldBeFalse('$("opt-la").selected');
        shouldBeFalse('$("opt-tk").selected');
        shouldBeTrue('$("opt-os").selected');
        shouldBeFalse('$("opt-ak").selected');
        shouldBeFalse('$("opt-wy").selected');
        debug('We don\'t care which one is selected because their values are identical:');
        shouldBeTrue('!!($("opt-ca-1").selected ^ $("opt-ca-2").selected)');
    
        $('parent').innerHTML = '';
        setTimeout(function() {
            finishJSTest();
        }, 0);
    }
}

window.onload = runTest;
</script>
<script src="../../../resources/js-test-post.js"></script>
</body>
