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

  selectBroadcast(_this, checkbox);
});

$(document).on("click", "[data-behavior=select_broadcast] input[type='checkbox']", function(e) {
  e.stopPropagation();

  var _this = this;
  var checkbox = $(this);

  selectBroadcast(_this, checkbox);
});

function selectBroadcast(clicked_element, checkbox) {
  if (clicked_element.hasChildNodes()) {
    if(checkbox.prop("checked")) {
      checkbox.prop('checked', false);
    } else {
      checkbox.prop('checked', true);
    }
  }

  var checked = checkbox.prop("checked");
  var project_id = JSON.parse($('#multi_view_broadcasts').parent().attr('data-project-id'));
  var broadcast_ids = JSON.parse($('#multi_view_broadcasts').parent().attr('data-broadcast-ids'));
  var selected_broadcast_id = checkbox.val();

  if (checked && !broadcast_ids.includes(selected_broadcast_id)) {
    broadcast_ids.push(selected_broadcast_id);
  } else if(!checked && broadcast_ids.includes(selected_broadcast_id)) {
    broadcast_ids.splice( $.inArray(selected_broadcast_id, broadcast_ids), 1 );
  }

  $('#multi_view_broadcasts').parent().attr('data-broadcast-ids', JSON.stringify(broadcast_ids));

  if (broadcast_ids.length >= 2) {
    multi_view_ids = $.param({multi_view_ids: broadcast_ids});
    broadcast_url = "/en/projects/" + project_id + "/broadcasts/" + broadcast_ids[0] + "?" + multi_view_ids

    $("#multi_view_broadcasts").attr("href", broadcast_url);
    $("#multi_view_broadcasts").attr("target", "_blank");
    $("#multi_view_broadcasts").removeClass('disabled');
  } else if (broadcast_ids.length < 2) {
    $("#multi_view_broadcasts").attr("href", "javascript:void(0);");
    $("#multi_view_broadcasts").addClass('disabled');
  }
}
