var DynSelect = new Class({

  initialize: function(data, selects) {
    this.data = data;
    this.selects = selects.map(function(s) {
      return $(s);
    });
    this.selects.each(function(el, index) {
      el.addEvent('change', this.handleChange.bind(this, index));
    }, this);
  },

  handleChange: function(index) {
    var i, j;
    for (i = index + 1, j = this.selects.length; i < j; i++) {
      this.selects[i].empty();
      this.selects[i].adopt(new Element('option', { value: '' }).set('text', '---'));
    }
    var d = this.data, v;
    for (i = 0, j = index; i <= j; i++) {
      v = this.selects[i].get('value');
      if (v == '') return;
      d = d[v];
    }
    if (d) {
      for (var k in d) {
        this.selects[index + 1].adopt(new Element('option', { value: k }).set('text', k));
      }
    }
  },

  getValues: function() {
    return this.selects.map(function(s) {
      return s.get('value');
    });
  },

  setValues: function(values) {
    this.selects.each(function(sel, index) {
      $A(sel.options).filter(function(opt) {
        return opt.value == values[index];
      }).each(function(opt) {
        opt.selected = true;
      });
      this.handleChange(index);
    }, this);
  }

});
