$(function(){
  function all_checked() {
    return $('.js-select:checked').length == $('.js-select').length;
  }

  function count_select_boxes () {
    return $('.js-select:checked').length;
  }
  function checked() {
    var checked = $('.js-select:checked');
    var i;
    var l = [];
    for (i=0; i < checked.length; i++) {
      l.push(checked[i].value);
    }
    return l.join(',');
  }
  function update() {
    var count = count_select_boxes();
    var all = all_checked();
    var everything = $('input[name=selection]').val() == 'everything' && all;

    // console.log(count);
    // console.log(all);
    // console.log(everything);

    $('.actions').toggle(count != 0);
    if (everything) {
      $('.js-selected').text($('.js-total').text());
    } else {
      $('.js-selected').text(count);
    }
    $('.js-select-all').prop('checked', all);
    if (everything) {
      $('input[name=selection]').val('everything');
    } else {
      $('input[name=selection]').val(checked());
    }
    $('.js-delete-selection').toggle(everything);
    $('.js-select-everything').toggle(all && ! everything);
    // console.log($('input[name=selection]').val());
  }
  $('.js-delete-selection').on('click', function (event) {
    $('.js-select').prop('checked', false);
    $('input[name=selection]').val(checked());
    update();
    event.stopPropagation();
  });
  $('.js-select-everything').on('click', function (event) {
    $('input[name=selection]').val('everything');
    update();
    event.stopPropagation();
  });

  $('.js-select').on('change', update)
  $('.js-select').on('click', function (event) { event.stopPropagation(); });
  $('.js-select-all').on('change', function (event) {
    $('.js-select').prop('checked', $(event.target).prop('checked'))
    update();
  })

})
