

$(document).ready(function () {

  EASY.utils.setInfiniteScrollDefaults();

  $('table.list.admin:first > tbody').infinitescroll({
    navSelector: '.pagination',
    nextSelector: '.pagination .next > a',
    itemSelector: 'table.list.admin:first > tbody > tr, .pagination .next > a',
    previousSelect: '.pagination .previous > a'
  }, function(data, opts) {
    var a = $(data.pop());
    if(a.is('a')) {
      opts.path = [a.attr('href')];
      a.remove();
    } else {
      data.push(a[0]);
      opts.state.isPaused = true;
      $(".infinite-scroll-load-next-page-trigger").parent().hide();
    }
    initEasyInlineEdit();
  });

  $(document).on('click', 'span.project-parent-expander', function() {
    var $this = $(this),
      tr = $this.closest('tr'),
      childRows;
    if ($this.hasClass('open')) {
      var row = tr.next();
      while( parseInt( row.data('level') ) > parseInt(tr.data('level')) ) {
        row.hide();
        row = row.next();
      }
      $this.removeClass('open');
    } else {
      if($this.hasClass('preloaded')) {
        $this.addClass('open');
        var row = tr.next();
        while( parseInt( row.data('level') ) > parseInt(tr.data('level')) ) {
          row.show();
          row = row.next();
        }
        var rows = tr.nextUntil('tr.root');
        var expanders = rows.find('span.project-parent-expander:not(.open)');
        $.each(expanders, function( _, value ) {
          var data = $(value).data();
          if(data) { $('tr.' + data.prefix + 'parentproject_' + data.id).hide(); }
        });
      } else {
        $this.addClass('preloaded');
        $.get(window.location.href  + '?' + $('#admin-projects-filter').serialize(), {
          root_id: $this.data().id
        }, function (resp) {
          var newRows = $(resp).find('table.admin tbody:first').children("tr");
          $this.addClass('open');
          newRows.each(function() {
            initInlineEditForContainer(this);
          });
          newRows.insertAfter(tr);

        });
      }
    }
  });

  $(document).on('click', '.infinite-scroll-load-next-page-trigger', function(e) {
    $('table.list.admin:first > tbody').infinitescroll('retrieve', {});
    $(e.target).remove();
  });

});

function initAdminProjectIndex(searchUrl) {
  $(function() {

    var timeoutId;
    $('#easy_query_q').keyup(function(e) {
      if(timeoutId) clearTimeout(timeoutId);
      timeoutId = setTimeout(projectSearch, 300);
    });

    function projectSearch() {
      var q =  $('#easy_query_q').val();
      if(!q || q.length < 3) return false;
      $.post(searchUrl, $('#query_form, #easy_query_q, #admin-projects-filter').serialize(), function(resp) {
        $('#projects').html(resp);
      });
    }

  });
}
