{% load gnm %}

{% get_goto_cell page request as goto_cell %}

{{cell.text|safe}}

<div id="goto-way"></div>

<div class="cell"
     id="goto-dest"
     data-ajax-cell-url="/ajax/cell/{{ goto_cell.page.id }}/{{ goto_cell.get_reference }}/"
     ><div></div>
</div>

<h2>Vos solutions</h2>

<div class="geolocating">
  <div class="running">Géolocalisation en cours</div>
  <div class="failed" style="display: none">
    <p>Votre position n’a pu être géolocalisée.</p>
    <p class="perms" style="display: none">
      Il peut être utile de vérifier que le mode avion n’est pas activé et que
      l’accès à votre position est autorisé.
    </p>
    <button>Réessayer</button>
  </div>
</div>

<script>
$(function() {
  combo_load_cell($('#goto-dest'));
});

// https://www.toodego.com/ajax/cell/322/data_configjsoncell-289/?lat2=45.7607097863131220&lng2=4.8362889729420431&date=2018-09-09_16-00&lat1=45.7506&lng1=4.8433&to=Station Place de la République

function getOnlyMoovDateString(){
  var now = new Date();
  var soon = new Date(now.getTime() + 60000);
  function pad(n) {return n<10 ? '0'+n : n}
  return soon.getFullYear() + '-' + pad(soon.getMonth()+1) +'-' + pad(soon.getDate()) + '_'
                + pad(soon.getHours()) + '-' + pad(soon.getMinutes());
}

function maybe_go()
{
  var lat1 = $('body').data('user-lat');
  var lng1 = $('body').data('user-lng');
  var lat2 = $('.action-goto').data('lat');
  var lng2 = $('.action-goto').data('lng');
  if (! (lat1 && lng1 && lat2 && lng2)) return;
  $('.cell.goto').each(function() {
    var url = $(this).data('ajax-cell-url');
    $(this).data('ajax-cell-url', url + '?lat1=' + lat1 + '&lng1=' + lng1 +
            '&lat2=' + lat2 + '&lng2=' + lng2 +
            '&date=' + getOnlyMoovDateString() +
            '&to=' + encodeURI($('#goto-destination .tile-title h2').text()) +
            '&');
    combo_load_cell($(this));
  });
}

$(document).on('combo:cell-loaded', function(ev, elem) {
  if ($(elem).attr('id') == 'goto-dest') maybe_go();
});

var t0;

function gnm_geolocate(timeout, maximumAge)
{
  var date = new Date();
  t0 = date.getTime()

  navigator.geolocation.getCurrentPosition(
    function(pos) { /* success */
      $('.geolocating').hide();
      $('body').data('user-lat', pos.coords.latitude);
      $('body').data('user-lng', pos.coords.longitude);
      maybe_go();
    },
    function(err) { /* error */
      $('.geolocating .running').hide();
      date = new Date();
      var t1 = date.getTime();
      if (t1 - t0 < 3000) {
        $('.geolocating .perms').show();
      }
      $('.geolocating .failed').show();
    },
    {enableHighAccuracy: false, timeout: timeout, maximumAge: maximumAge}
  );
}

gnm_geolocate(30*1000, 5 * 60 * 1000);  // initial request

$('.geolocating button').on('click', function() {
  $('.geolocating .failed').hide();
  $('.geolocating .perms').hide();
  $('.geolocating .running').show();
  gnm_geolocate(120*1000, 15 * 60 * 1000);  // longer timeouts
});

</script>
