{% load assets %}
<div class="carrousel-content">
 {% for menuitem in menuitems %}
  <input type="radio" name="carrousel-{{cell.id}}"
     class="carrousel-radio-{{forloop.counter}}"
     id="carrousel-{{cell.id}}-{{forloop.counter}}"
     {% if forloop.first %}checked{% endif %}>
  <div class="slide">
     <div class="carrousel-item"
          style="background-image: url({% asset_url menuitem.page.picture size="1200" crop="center" %})">
      <div class="carrousel-item-content">
       {% for cell in menuitem.page.get_cells %}
         {{cell.text|safe}}
       {% endfor %}
      </div>
     </div>
  </div>
 {% endfor %}
 <a class="carrousel-left" title="Afficher la page précédente du carrousel" href=""></a>
 <div class="carrousel-nav">
 {% for menuitem in menuitems %}
 <label tabindex="0" class="carrousel-label-{{forloop.counter}}" for="carrousel-{{cell.id}}-{{forloop.counter}}"
         title="Afficher la page {{forloop.counter}} du carrousel"></label>
 {% endfor %}
 </div>
 <a class="carrousel-right" title="Afficher la page suivante du carrousel" href=""></a>
</div>
<script>
$(function() {
  function next() {
    if ($('.carrousel-content input:checked ~ input').length) {
      $('.carrousel-content input:checked ~ input').first().click();
    } else {
      $('.carrousel-content input').first().click();
    }
  }
  function previous() {
    if ($('.carrousel-content input ~ input:checked').length) {
      $('.carrousel-content input:checked').prev().prev().click();
    } else {
      $('.carrousel-content input').last().click();
    }
  }
  var timeout_id = setInterval(next, 5000);
  $('.carrousel-content label').on('click', function() {
    clearInterval(timeout_id);
  });
  $('.carrousel-content label').on('keypress', function(ev) {
    if (ev.key == 'Enter' || ev.key == ' ') {
      clearInterval(timeout_id);
      $('#' + $(this).attr('for')).click();
    }
    return false;
  });
  $('a.carrousel-left, a.carrousel-right').on('focus', function() {
    // stop autorefresh when an arrow gets focus, so it can be navigated with
    // a keyboard more easily.
    clearInterval(timeout_id);
    return false;
  });
  $('a.carrousel-left').on('click', function() {
    clearInterval(timeout_id);
    previous();
    return false;
  });
  $('a.carrousel-right').on('click', function() {
    clearInterval(timeout_id);
    next();
    return false;
  });

  var touch_start = null;
  $('.carrousel-item').on('touchstart', function(ev) {
    touch_start = ev.originalEvent.touches[0].pageX;
  });
  $('.carrousel-item').on('touchend', function(ev) {
    var touch_end = ev.originalEvent.changedTouches[0].pageX;
    var diff = touch_start - touch_end;
    touch_start = null;
    clearInterval(timeout_id);
    var width = $('body').width();
    if (diff*2 > width) {
      previous();
    }
    if (diff*2 < -width) {
      next();
    }
  });

});
</script>
