Event.observe(window, 'load', function() {
  try{
    number_new_topics;
  }catch(e){
    return;
  }

  var related_topics_list = $$('#related-topics ul');

  for(var i = 0; i < number_new_topics; i++){
    var item = 'publication_new_topics_' + i;
    new Ajax.Autocompleter(item, item + '_auto_complete', '/research_knowledge/topics/search', {frequency: 0.1, minChars: 2});
    if(i == number_new_topics - 1){
      Event.observe(item, 'focus', add_topic_field);
    }
  }
});

function add_topic_field(event){
  if(number_new_topics >= 10){
    return
  }
  new Insertion.After($(Event.element(event).parentNode), '<li><label for="publication_new_topics_' + number_new_topics + '">New topic:</label> <input type="text" name="publication[new_topics][]" id="publication_new_topics_' + number_new_topics + '" />');
  new Insertion.After('publication_new_topics_' + (number_new_topics - 1) + '_auto_complete', '<div class="auto_complete" id="publication_new_topics_' + number_new_topics + '_auto_complete"></div>');
  new Ajax.Autocompleter('publication_new_topics_' + number_new_topics, 'publication_new_topics_' + number_new_topics + '_auto_complete', '/research_knowledge/topics/search', {frequency: 0.1, minChars: 2});
  Event.observe('publication_new_topics_' + number_new_topics, 'focus', add_topic_field);
  Event.stopObserving(Event.element(event), 'focus', add_topic_field);
  number_new_topics++;
}

