countryStates = {}

countryStates.countryElement = null;
countryStates.stateElement   = null;

countryStates.countryId = null;
countryStates.stateId   = null;

countryStates.initialized = false;

countryStates.init = function() {
    if (countryStates.countryElement == null || countryStates.stateElement == null) {
        return;
    }

    if (countryStates.initialized) {
        return;
    }

    var countries = imos.element(document.getElementById(countryStates.countryElement));
    var states    = imos.element(document.getElementById(countryStates.stateElement));

    // onchange Funktion auf Länder binden
    countries.addEvent('change', countryStates.change);

    if (countries.value.length > 0) {
        countryStates.countryId = countries.value;
    } else {
        countryStates.countryId = null;
    }

    if (states.value.length > 0) {
        countryStates.stateId = states.value;
    } else {
        countryStates.stateId = null;
    }

    // Select Box bei vorhandener Auswahl initialisieren
    if (countryStates.countryId != null) {
        var request = imos.ajax.request(cdata.projectUrl + cdata.iso2 + '/ajax/states/' + countryStates.countryId + '/');
        request.onSuccess = countryStates.replace;
        request.send();
    }
}

countryStates.change = function() {
    var country_id = document.getElementById(countryStates.countryElement).value;
    var states     = imos.element(document.getElementById(countryStates.stateElement));

    // Auswahl zurücksetzen
    states.selectedIndex = 0;

    var request = imos.ajax.request(cdata.projectUrl + cdata.iso2 + '/ajax/states/' + country_id + '/');
    request.onSuccess = countryStates.replace;
    request.send();
}

countryStates.replace = function() {
    var selectbox = imos.element(document.getElementById(countryStates.stateElement));
    selectbox.innerHTML = '';

    var states = this.XMLHttpRequest.responseText.split('#split#');

    for (i = 0; i < states.length; i++) {
        var state = states[i];

        var state_id = state.split('#sep#')[0].replace (/^\s+/, '').replace (/\s+$/, '');
        var label    = state.split('#sep#')[1];

        if (typeof state_id != 'undefined' && typeof label != 'undefined') {
            if (countryStates.stateId != null && countryStates.stateId == state_id) {
                var selected = true;
            } else {
                var selected = false;
            }

            selectbox.options[i] = new Option(label, state_id, selected, selected);
        }
    }
}

imos.element(window).addEvent('load', countryStates.init);