$(function () {
   var elements_with_frequent_values = $('*[data-frequent-values]'); 
   function set_click(elt, dest, code, description) {
        elt.click(function () {
          $(dest).val(code);
          $('#label_'+$(dest).attr('id')).val(description);
          if ($(dest).data('update')) {
            $(dest).data('update')(code);
          }
        });
   }
   elements_with_frequent_values.each(function (i, elt) {
      var e = $(elt).data('frequent-values'); 
      var intro = $("<span> <em>Codes récemment utilisés: </em> </span>");
      var after = $(elt);
      after.after(intro); 
      after = intro;
      for (var i = 0; i < e.length; i++) { 
        var y=e[i];
        var a=$('<a href="#">' + y[0] + '</a>'); 
        set_click(a, elt, y[1], y[0]);
        if (i>0) {
            var comma = $('<span>, </span>')
            after.after(comma);
            after = comma;
        }
        after.after(a);
        after = a;
      }
   });
});
