<table class="table-address-add">
  <tr>
    <td style="text-align: left;">
      <div class="pagination">
        <%= paginate @address_books %>
      </div>
    </td>
  </tr>
</table>

<table class="table-address">
  <tr>
    <th>組織</th>
    <th>名前</th>
    <th>メールアドレス</th>
  </tr>

<% @address_books.each do |address_book| %>
  <tr class="address_items" id="address_item_<%= address_book.id %>">
    <td class="address_organization">
      <%= truncate(address_book.organization, {length: 20}) %><%= hidden_field_tag "address_book_organization_#{address_book.id}",address_book.organization, {class: "address_organization_h"} %>
    </td>
    <td class="address_name">
      <%= truncate(address_book.name, {length: 20}) %><%= hidden_field_tag "address_book_name_#{address_book.id}",address_book.name, {class: "address_name_h"} %>
    </td>
    <td class="address_email">
      <%= truncate(address_book.email,  {length: 30}) %><%= hidden_field_tag "address_book_email_#{address_book.id}",address_book.email, {class: "address_email_h"} %>
    </td>
  </tr>

<% end %>
</table>

<table class="table-address-add">
  <tr>
    <td style="text-align: left;">
      <div class="pagination">
        <%= paginate @address_books %>
      </div>
    </td>
  </tr>
</table>

<script type="text/javascript">
// ページネーション差し替え後も動作するようdocumentレベルでイベント委譲
// 重複登録防止
if (!window._addressBookIndexSubResultClickBound) {
  window._addressBookIndexSubResultClickBound = true;
  document.addEventListener('click', function(e) {
    var resultEl = document.getElementById('result');
    if (!resultEl || !resultEl.contains(e.target)) return;
    var target = e.target.closest('.address_organization, .address_name, .address_email, .address_notes');
    if (target) {
      var recipient_number = document.getElementById("recipient_number").value;
      var name_value = "";
      if (document.getElementById("conditions_organization_flg").checked) {
        name_value = target.parentElement.querySelector(".address_organization_h").value + "　" + target.parentElement.querySelector(".address_name_h").value;
      } else {
        name_value = target.parentElement.querySelector(".address_name_h").value;
      }
      var receiverName = window.parent.document.getElementById("receiver_"+ recipient_number + "_name");
      if (receiverName) {
        receiverName.value = name_value;
        window.parent.document.getElementById("receiver_"+ recipient_number + "_mail_address").value = target.parentElement.querySelector(".address_email_h").value;
      }else{
        window.parent.document.getElementById("requested_matter_"+ recipient_number + "_name").value = name_value;
        window.parent.document.getElementById("requested_matter_"+ recipient_number + "_mail_address").value = target.parentElement.querySelector(".address_email_h").value;
      }
      $.modal.close();
    }
  });
}
</script>
