result_onload = function() {
    init_iframe('result-view');
    switch_tab(document.getElementById('result-source-tab'));
    document.getElementById('result-source').appendChild(document.createTextNode(document.getElementById('form').source.value));
}
index_onload = function() {
    document.getElementById('form').onsubmit = function() {
        document.getElementById('form').source.value = document.getElementById('word-input').contentWindow.document.body.innerHTML;
    }
    init_iframe('word-input');
}
bugreport_onload = function() {
    document.getElementById('form').onsubmit = function() {
        document.getElementById('form').source.value = document.getElementById('word-input').contentWindow.document.body.innerHTML;
    }
    init_iframe('word-input');
}
function init_iframe(iframe_name) {
    var iframe = document.getElementById(iframe_name);
    try {
        iframe.contentWindow.document.designMode = "on";
        iframe.contentWindow.document.body.contentEditable = "true";
        iframe.contentWindow.focus();
        if (document.getElementById('form').source.value) {
            iframe.contentWindow.document.body.innerHTML = document.getElementById('form').source.value;
        } else {
            iframe.contentWindow.document.execCommand('selectall', false, null);
        }
    } catch (e) {
        if (/is null or not an object/.test(e.message)) {
            window.setTimeout(function () { init_iframe(iframe_name) }, 200);
        }
        else {
            throw e;
        }
    }
}

function remove_child_nodes(node) {
    for (var ix = node.childNodes.length - 1; ix >= 0; ix--) {
       node.removeChild(node.childNodes[ix]);
    }
}
function switch_tab(link) {
    var selected_li = link;
    while (selected_li.nodeName.toLowerCase() != 'li') {
        selected_li = selected_li.parentNode;
    }
    var all_tabs = [];
    var ul = selected_li.parentNode;
    var li, tab_name;
    for (var ix = 0; ix < ul.childNodes.length; ix++) {
        li = ul.childNodes[ix];
        if (typeof(li.getAttribute) == "undefined") {
            continue;
        }

        tab_name = li.getAttribute('id').replace(/-tab$/, '');
        if (li === selected_li) {
            li.className = 'selected';
            document.getElementById(tab_name).style.display = '';
        } else {
            li.className = '';
            document.getElementById(tab_name).style.display = 'none';
        }
    }
}

function update_source() {
    remove_child_nodes(document.getElementById('result-source'));
    document.getElementById('result-source').appendChild(
        document.createTextNode(
            document.getElementById('result-view').contentWindow.document.body.innerHTML
        )
    );
}

