Drupal.behaviors.cckManageFields = function(context) {
  attachUpdateSelects(context);
};

function attachUpdateSelects(context) {
  var carModels = Drupal.settings.carMakerModels;

  // Store the default text of widget selects.
  $('#node-form .oja-edit-field-inzeraty-model-nid-nid', context).each(function() {
    this.initialValue = this.options[0].text;
  });
  
  
  // modely aut podla vyrobcu
  $('#node-form .oja-edit-field-inzeraty-vyrobca-nid-nid', context).each(function() {
    this.targetSelect = $('.oja-edit-field-inzeraty-model-nid-nid', $(this).parents('fieldset').eq(0));

    $(this).change(function() {
      var selectedCarMaker = this.options[this.selectedIndex].value;
      var options = (selectedCarMaker in carModels) ? carModels[selectedCarMaker] : [ ];
      this.targetSelect.contentPopulateOptions(options);
    });

    // Trigger change on initial pageload to get the right widget options
    // when field type comes pre-selected (on failed validation).
    $(this).trigger('change');
  });
}
  
jQuery.fn.contentPopulateOptions = function(options, selected) {
  return this.each(function() {
    var disabled = false;
    if (options.length == 0) {
      options = [this.initialValue];
      disabled = true;
    }

    // If possible, keep the same widget selected when changing field type.
    // This is based on textual value, since the internal value might be
    // different (optionwidgets_buttons vs. nodereference_buttons).
    var previousSelectedText = this.options[this.selectedIndex].text;

    var html = '';
    jQuery.each(options, function(value, text) {
      // Figure out which value should be selected. The 'selected' param
      // takes precedence.
      var is_selected = ((typeof(selected) !== 'undefined' && value == selected) || (typeof(selected) == 'undefined' && text == previousSelectedText));
      html += '<option value="' + value + '"' + (is_selected ? ' selected="selected"' : '') +'>' + text + '</option>';
    });

    $(this)
      .html(html)
      .attr('disabled', disabled ? 'disabled' : '');
  });
}
