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

  selectContractTemplate(_this, checkbox);
});

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

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

  selectContractTemplate(_this, checkbox);
});

function selectContractTemplate(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($('#group_qr_code').attr('data-project-id'));
  var contract_template_ids = JSON.parse($('#group_qr_code').attr('data-contract-template-ids'));
  var selected_contract_template_id = checkbox.val();

  if (checked && !contract_template_ids.includes(selected_contract_template_id)) {
    contract_template_ids.push(selected_contract_template_id);
  } else if(!checked && contract_template_ids.includes(selected_contract_template_id)) {
    contract_template_ids.splice( $.inArray(selected_contract_template_id, contract_template_ids), 1 );
  }
  
  $('#group_qr_code').attr('data-contract-template-ids', JSON.stringify(contract_template_ids));

  if (contract_template_ids.length >= 2) {
    multi_sign_ids = $.param({multi_sign_ids: contract_template_ids});
    contract_template_url = "/en/contract_templates/" + contract_template_ids[0] + "/qr_codes?" + multi_sign_ids

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