function Region(id, name) {
    this.id = id;
    this.name = name;
}

function City(id, regionId, name) {
    this.id = id;
    this.regionId = regionId;
    this.name = name;
}

/**
 * @constructor
 * @param Select regionSelect
 * @param Select citySelect
 * @param Array of Region regions
 * @param Array of City cities
 * @param int selectedRegionId
 * @param int selectedCityId
 */
function RegionCitySelectPair(regionSelect, citySelect, regions, cities, selectedRegionId, selectedCityId, allLabel) {
    this.emptyValue = 0;
    this.emptyLabel = allLabel;
    this.regionSelect = regionSelect;
    this.citySelect = citySelect;
    this.regions = regions;
    this.cities = cities;
    this.selectedRegionId = selectedRegionId;
    this.selectedCityId = selectedCityId;
    this.regionSelect.pair = this;
    this.citySelect.pair = this;
    this.regionSelect.onchange = this.onRegionSelectChange;
    this.citySelect.onchange = this.onCitySelectChange;
    this.fillRegionSelect();
    this.fillCitySelect();
}
RegionCitySelectPair.prototype.fillRegionSelect = function() {
    this.regionSelect.options.length = 0;
    this.regionSelect.options[0] = new Option(this.emptyLabel, this.emptyValue);
    for (var i = 0; i < this.regions.length; i++) {
        this.regionSelect.options[i+1] = new Option(this.regions[i].name, this.regions[i].id, false, this.regions[i].id == this.selectedRegionId);
    }
}
RegionCitySelectPair.prototype.fillCitySelect = function() {
    this.citySelect.options.length = 0;
    this.citySelect.options[0] = new Option(this.emptyLabel, this.emptyValue);
    for (var i = 0; i < this.cities.length; i++) {
        if (this.selectedRegionId != this.emptyValue) {
            if (this.cities[i].regionId == this.selectedRegionId) {
                this.citySelect.options[this.citySelect.options.length] = new Option(this.cities[i].name, this.cities[i].id, false, this.cities[i].id == this.selectedCityId);
            }
        }
        else {
            this.citySelect.options[this.citySelect.options.length] = new Option(this.cities[i].name, this.cities[i].id, false, this.cities[i].id == this.selectedCityId);
        }
    }
}
RegionCitySelectPair.prototype.setRegion = function(regionId) {
    this.selectedRegionId = regionId;
//    if (this.selectedRegionId != this.emptyValue) {
//        this.selectedCityId = this.emptyValue;
//    }
    this.selectedCityId = this.emptyValue;
    this.fillCitySelect();
}
RegionCitySelectPair.prototype.setCity = function(cityId) {
    this.selectedCityId = cityId;
}


RegionCitySelectPair.prototype.onRegionSelectChange = function() {
    this.pair.setRegion(this.value);
}
RegionCitySelectPair.prototype.onCitySelectChange = function() {
    this.pair.setCity(this.value);
}

