var phones_extensions = null;
var freshstates = null;

/*
 * Country changed:
 * - fill phone extension
 * - restrict state elements if country have states
 * IN: load(boolean) sent true on initial load
 */
function whois_obfuscated_changed(whois_ob_button){
    if (whois_ob_button.value == "yes") {
        var ob = document.getElementById('Obfuscated_radio_0');
        if (ob)
            ob.checked = 'checked';
    }
}

function country_changed(load){
    var country = $('#Country')[0];

    var country_id = parseInt(country.value);

    if (country_id <= 0)
        return;

    if (!load) {
        if (!phones_extensions) {
            $.getJSON('/static/js/phones.json.txt', function(data){
                phones_extensions = data;
                set_phone_code();
            });
        }
        else {
            set_phone_code();
        }
    }

    var state = $('#State')[0];
    if (freshstates == undefined && state) {
        freshstates = state.cloneNode(true);
    }

    if (freshstates) {
        var label = country[country.selectedIndex].text;
        var groups = freshstates.getElementsByTagName('optgroup');
        var hasState = false;
        for (var i = 0, l = groups.length; i < l; i++) {
            var group = groups[i];

            // We have an option group for this country
            if (group.label == label) {
                hasState = true;

                // Display only country states:
                // replace node by a clone of the initial one [ use replaceChild ? ]
                var tmp = state.parentNode.insertBefore(freshstates.cloneNode(true), state);
                state.parentNode.removeChild(state);

                state = tmp;
                delete tmp;

                // New reference to the real nodes
                groups = state.getElementsByTagName('optgroup');

                for (var j = 0; j < l; j++) {
                    if (j != i) {
                        groups[j].parentNode.removeChild(groups[j]);
                        // Decrement length value and index values
                        i--;
                        j--;
                        l--;
                    }
                }


                break;
            }
        }

        state.disabled = !hasState;
        if (!load) {
            state.selectedIndex = 0;
        }
    }
}

// Set phone field after getting the list
function set_phone_code(){
    var ext;
    var phone = $('#Phone')[0];
    var country = $('#Country')[0];
    var country_id = country.value;

    if (ext = phones_extensions[country_id]) {
        if (phone.value.length < 6) {
            phone.value = '+' + ext + '.';
        }
    }
}
