{% load combo %}
{{json|json_script:"json-favorites"}}
<script>
$(function() {
  var raw_favorites = JSON.parse(document.getElementById('json-favorites').textContent);
  var favorites = Object();
  if (raw_favorites && raw_favorites.data) {
    for (favorite in raw_favorites.data) {
      favorites[raw_favorites.data[favorite].content.link] = raw_favorites.data[favorite].id;
    }
  }
  var url = "{{ site_base }}{% url 'combo-public-ajax-page-cell' page_pk=cell.page.id cell_reference=cell.get_reference %}";
  $('#content .cell').each(function(idx, link) {
    var $link = $(link);
    var link_cell_url = $link.data('ajax-cell-url');
    var $favorite = $('<button class="favorite"></button>');
    if (favorites[link_cell_url]) {
      $link.data('favorite-id', favorites[link_cell_url]);
      $link.addClass('favori');
    }
    $favorite.appendTo($link.find('.big-image-link').parent());
    $favorite.on('click', function() {
      var current_favorite = $link.hasClass('favori');
      if (current_favorite) {
        $.post(url, 'action=delete&id=' + $link.data('favorite-id'));
        if ($('#columns.display-favoris').length) {
          $link.hide();
        }
      } else {
        $.post(url, 'action=create&link=' + link_cell_url,
          function(data) {
            $link.data('favorite-id', data.id);
          }
        );
      }
      $(this).parents('.cell').toggleClass('favori');
    });
  });
});
</script>
