var form = document.getElementById('form1');
var categories = form.elements['category'];
var quote = form.elements['quote_dropdown'];
initGroups(quote);
attachToRadios(categories, updateQuoteSelect);
categories[0].click();
quote.onchange = function () {
    document.getElementById('form1').submit();
}

function attachToRadios(name, fn) {
    var i;
    for (i = 0; i < name.length; i += 1) {
        name[i].onclick = fn;
    }
}
function initGroups(select) {
    var els = select.childNodes;
    select.groups = [];
    for (i = 0; i < els.length; i += 1) {
        if (els[i].nodeName === 'OPTGROUP') {
            select.groups.push(els[i]);
        }
    }
}

function updateQuoteSelect() {
    var label = this.value;
    var form = document.getElementById('form1');
    var quote = form.elements['quote_dropdown'];
    updateOptionsFromGroup(quote, label);
}
function updateOptionsFromGroup(select, label) {
    var group = getGroup(select, label);
    removeOptions(select);
    addOption(select, label);
    addOptionsFromGroup(select, group);
}
function getGroup(select, label) {
    var groups = select.groups;
    var i;
    for (i = 0; i < groups.length; i += 1) {
        if (groups[i].label === label) {
            return groups[i];
        }
    }
}
function removeOptions(select) {
    while (select.hasChildNodes()) {
        select.removeChild(select.firstChild);
    }
}
function addOption(select, text, value) {
    var option = document.createElement('option');
    option.appendChild(document.createTextNode(text));
    if (value) {
        option.value = value;
    }
    select.appendChild(option);
}
function addOptionsFromGroup(select, group) {
    var option;
    var i;
    for (i = 0; i < group.childNodes.length; i += 1) {
        option = group.childNodes[i].cloneNode(true);
        if (option.nodeName === 'OPTION') {
            select.appendChild(option);
        }
    }
}
