
/**
 * When the region changes, get a list of matching countries from the server and
 * update the country selector.
 */
function getCountriesByRegion() {
  var region_id = $('#edit-region').val();
  $('#edit-region').each(function() {
    var region_id = $(this).val();
    var filter_by_brand = location.href.indexOf('admin/search/trip') == -1;
    $.get("/ajax/region/get-countries/" + region_id, {filter_by_brand: filter_by_brand}, updateCountrySelector);
  });
}


function updateCountrySelector(response) {
//  alert(response);
  var countries = eval('(' + response + ')');
  // get the current value:
  var selected_country_nid = $('#edit-country').val();
  // empty the countries selector:
  var country_selector = $('#edit-country').get(0); 
  country_selector.options.length = 0;
  // add new country options:
  var option = document.createElement('option');
  option.value = -2;
  option.text = 'All';
  country_selector.options[country_selector.options.length] = option;
  var country_name;
  var found = false;
  for (var country_nid in countries) {
    option = document.createElement('option');
    option.value = country_nid;
    option.text = countries[country_nid];
    country_selector.options[country_selector.options.length] = option;
    if (selected_country_nid == country_nid) {
      found = true;
    }
  }
  // select 'All' by default:
  country_selector.value = found ? selected_country_nid : -2;
}

// $(getCountriesByRegion);

