var dsCountries = new Spry.Data.XMLDataSet('/common/data/distributors.xml', 'distributors/country');
var dsCities = new Spry.Data.NestedXMLDataSet(dsCountries, 'city');
var dsDistributors = new Spry.Data.NestedXMLDataSet(dsCities, 'distributor');
var countrySelect;

Spry.Utils.addLoadListener(function() {
  var observer = {
    onPostUpdate:
      function(notifier, data) {
        Spry.Utils.addEventListener('country_select', 'change', function(){updateCities();}, false);
        Spry.Utils.addEventListener('country_select', 'keyup', function(){updateCities();}, false);
		    countrySelect = Spry.$$('#country_select');

		    var matchingRow = dsCountries.findRowsWithColumnValues({'@name':'Brasil'}, true);
        var index = matchingRow.ds_RowID;
        countrySelect[0].selectedIndex = index;
        dsCountries.setCurrentRow(countrySelect[0].selectedIndex);
      }
   };
   Spry.Data.Region.addObserver('country_select_region', observer);
});

function updateCities(index) {
  if(index===undefined) {
    index = countrySelect[0].selectedIndex;
  }

  if(isNaN(index)) {
    var matchingRow = dsCountries.findRowsWithColumnValues({'@name':index}, true);
    index = matchingRow.ds_RowID;
  }

  countrySelect[0].selectedIndex = index;
  dsCountries.setCurrentRow(countrySelect[0].selectedIndex);
}

//used in interface.js
function hideSelect() {
	if(countrySelect){
		countrySelect.addClassName('nao_exibe');
	}
}
function showSelect() {
	if(countrySelect){
		countrySelect.removeClassName('nao_exibe');
	}
}

