$(function() {
  if ($('.textcell.services').length == 0) return;

  var authentic_url = null;
  $(COMBO_KNOWN_SERVICES).each(function(index, service) {
    if (service.service_id == 'authentic') {
      authentic_url = service.backoffice_menu_url.split('manage/menu.json')[0];
    }
  });
  $.ajax({url: authentic_url + 'services.json',
	  xhrFields: { withCredentials: true },
	  async: true,
	  dataType: 'jsonp',
	  crossDomain: true,
	  success: function(data) {
	    var service_links = $('<ul id="service-links">');
	    $(data).each(function(index, service) {
	      var li = null;
	      if (service.authentication_level_is_enough) {
	        li = $('<li><a href="#">' + service.label + '</a></li>').appendTo(service_links);
		$(li).find('a').attr('href', service.url);
	      } else {
	        li = $('<li><span><span class="service-label">' + service.label + '</span> <span class="auth-level">(' +
			service.authentication_levels.join(', ') + ')</span></span></li>').appendTo(service_links);
	      }
	    });
	    service_links.appendTo('.textcell.services > div');
	  },
	  error: function(error) { console.log('bouh', error); }
	 }
  );

  $.ajax({url: authentic_url + 'user_info/',
	  xhrFields: { withCredentials: true },
	  async: true,
	  dataType: 'jsonp',
	  crossDomain: true,
	  success: function(data) {
		$('<h2>' + data.pratic_collectivity + '</h2>').appendTo('.textcell.collectivity');
		if (data.pratic_is_admin || data.django_user_is_superuser) {
		  $('<ul><li><a href="' + authentic_url + 'manage/">Gestion Pr@tic</a></li></ul>').insertAfter('.textcell.collectivity h2');
		}
	  },
	  error: function(error) { console.log('bouh', error); }
	 }
  );
});
