// Makes releasables selectable and taggable.

$(document).on("click", "[data-behavior=all-selectable]", function() {
  var checkbox = $(this).children("input:checkbox");
  var checked = checkbox.prop("checked");

  if (checked) {
    checkbox.prop("checked", false);
  } else {
    checkbox.prop("checked", true);
  }

  var checkedNewValue = checkbox.prop("checked");

  if(checkedNewValue) {
    $("[data-behavior=select]").children('input:checkbox').each(function() {
      if (!this.checked) {
        $(this).parent().trigger('click')
      }
    });
  } else {
    $("[data-behavior=select]").children('input:checkbox').each(function() {
      if (this.checked) {
        $(this).parent().trigger('click')
      }
    });
  }
});

$(document).on("click", "[data-behavior=select]", function() {
  var checkbox = $(this).children("input:checkbox");
  var checked = checkbox.prop("checked");

  var releasable_ids = JSON.parse($('#tag_all').parent().attr('data-releasable-ids'));
  var selected_releasable_id = $(this).children('input').val();

  if (checked) {
    checkbox.prop("checked", false);
  } else {
    checkbox.prop("checked", true);
  }

  var checkedNewValue = checkbox.prop("checked");

  if (checkedNewValue && !releasable_ids.includes(selected_releasable_id)) {
    releasable_ids.push(selected_releasable_id);
  } else if(!checkedNewValue && releasable_ids.includes(selected_releasable_id)) {
    releasable_ids.splice( $.inArray(selected_releasable_id, releasable_ids), 1 );
  }

  if (releasable_ids.length >= 1) {
    $("#tag_all").prop('disabled', false);
  } else if (releasable_ids.length < 1) {
    $("#tag_all").prop('disabled', true);
  }

  $('#tag_all').parent().attr('data-releasable-ids', JSON.stringify(releasable_ids));
});

$(document).on("click", "#tag_all", function(event) {
  event.preventDefault();
  var releasable_ids = JSON.parse($(this).parent().attr('data-releasable-ids'));

  if (releasable_ids.length >= 1) {
    var input_ids = $('<input>').attr({ type: 'hidden', name: 'releasable_ids', value: JSON.stringify(releasable_ids) });
    var input_name = $('<input>').attr({ type: 'hidden', name: 'releasable_name', value: $("tbody").attr("id") });

    $(this).parent().append(input_ids);
    $(this).parent().append(input_name);

    Rails.fire($(this).parent()[0], 'submit');
  }
});

$(document).on("click", "[data-behavior=select] input:checkbox", function() {
  $(this).parent().trigger('click');
});

$(document).on("click", "[data-behavior=all-selectable] input:checkbox", function() {
  $(this).parent().trigger('click');
});