function countrySelected() {
    /* get references to country and states selects */
    var countrySel = document.getElementById("country_id");
    var stateSel = document.getElementById("state_id");
    var stateBox = document.getElementById("fbox_state_id");
    if (!countrySel || !stateSel) {
        return;
    }
    /* search for the selected country in the states array */
    var curCountry = countrySel.options[countrySel.selectedIndex].value;
    var curState = stateSel.options[stateSel.selectedIndex].value;
    var found = false;
    for (var i = 0; i < statesArr.length; i++) {
        if (statesArr[i][0] == curCountry) {
            /* found states for this country */
            /* load states select with states corresponding to this country */
            stateSel.options.length = 1;
            var j = 1;
            for (var k = 0; k < statesArr[i][1].length; k++) {
                /* add option */
                stateSel.options[j] = new Option(statesArr[i][1][k][1], statesArr[i][1][k][0]);
                if (curState == statesArr[i][1][k][0]) {
                    // mark as selected
                    stateSel.selectedIndex = j;
                }
                j++;
            }
            found = true;
            break;
        }
    }
    /* enable or disable states select */
    if (found) {
        stateSel.disabled = false;
        stateBox.style.color = "#333";
    } else {
        stateSel.selectedIndex = 0;
        stateSel.disabled = true;
        stateBox.style.color = "#999";
    }
}

function statesInit() {
    /* set current list of states */
    countrySelected();
    /* attach event to country select */
    var countrySel = document.getElementById("country_id");
    if (countrySel) {
        if (countrySel.addEventListener) {
            countrySel.addEventListener('change', countrySelected, false);
        } else if(countrySel.attachEvent) {
            countrySel.attachEvent('onchange', countrySelected);
        }        
    }
}
