<!DOCTYPE html>
<html lang="%lang;">
<head>
  <title>[*modify::tree]</title>
  <meta name="robots" content="none"%/>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="shortcut icon" href="%images_prefix;favicon_gwd.png">
  <link rel="apple-touch-icon" href="%images_prefix;favicon_gwd.png">
  %include;css
</head>
<body%body_prop;>
%include;home
%include;hed
%let;mid;%sp;class="align-middle"%in;
%let;max_index;%pvar.highest;%in;
%define;one_pvar_line(znz,zfnz,zsnz,zocz,zbdz,ztz,zparamz)
  <trzparamz>
    <td class="align-middle text-center text-nowrap px-3">
      <button type="button" class="btn btn-success btn-sm row_add"
              title="[*add/insert/delete/up/down row]1"
              aria-label="[*add/insert/delete/up/down row aria-label]1">
        <i class="fas fa-plus" aria-hidden="true"></i>
      </button>
      <button type="button" class="btn btn-danger btn-sm row_del"
              title="[*add/insert/delete/up/down row]2"
              aria-label="[*add/insert/delete/up/down row aria-label]2">
        <i class="fas fa-minus" aria-hidden="true"></i>
      </button>
    </td>
    <td class="align-middle text-center text-nowrap pr-3">
      <button type="button" class="btn btn-secondary btn-sm row_move_up"
              title="[*add/insert/delete/up/down row]3"
              aria-label="[*add/insert/delete/up/down row aria-label]3">
        <i class="fas fa-arrow-up" aria-hidden="true"></i>
      </button>
      <button type="button" class="btn btn-secondary btn-sm row_move_down"
              title="[*add/insert/delete/up/down row]4"
              aria-label="[*add/insert/delete/up/down row aria-label]4">
        <i class="fas fa-arrow-down" aria-hidden="true"></i>
      </button>
    </td>
    <td class="align-middle font-weight-bold border-left px-3 line-number"></td>
    <td%mid;><input name="p" class="form-control reset_bd_text" size="30" value="zfnz" aria-label="[*first name/first names]1"></td>
    <td%mid;><input name="n" class="form-control reset_bd_text" size="30" value="zsnz" aria-label="[*surname/surnames]0"></td>
    <td%mid;><input name="oc" type="number" min="0" class="form-control reset_bd_text" value="zocz" aria-label="[*occ]0"></td>
    <td class="bd_text align-middle">zbdz</td>
    <td%mid;><input name="t" class="form-control" size="30" value="ztz" aria-label="[*note/notes]1"></td>
  </tr>
%end;
%define;one_pvar(zz)
  %if;(e.izz!="" or e.pzz!="")
    %let;datespan;
      %if;pvar.zz.exist;
        <div class="d-flex flex-column justify-content-center" style="line-height: 0.9;">
          %if;pvar.zz.has_birth_date;
            <div aria-label="[*birth date]">° %pvar.zz.slash_birth_date;</div>
          %elseif;pvar.zz.has_baptism_date;
            <div aria-label="[*baptism date]"><span class="text-danger">°</span> %pvar.zz.slash_baptism_date;</div>
          %end;
          %if;pvar.zz.has_death_date;
            <div aria-label="[*death date]">† %pvar.zz.slash_death_date;</div>
          %elseif;pvar.zz.has_burial_date;
            <div aria-label="[*burial date]"><span class="text-danger">†</span> %pvar.zz.slash_burial_date;</div>
          %elseif;pvar.zz.has_cremation_date;
            <div aria-label="[*cremation date]"><span class="text-danger">†</span>%pvar.zz.slash_cremation_date;</div>
          %end;
        </div>
      %else;
        <div class="text-center">[unknown person]!!</div>
      %end;
    %in;
    %if;(pvar.zz.exist)
      %apply;one_pvar_line("zz", pvar.zz.first_name, pvar.zz.surname, pvar.zz.occ, datespan, e.tzz, "")
    %else;
      %apply;one_pvar_line("zz", e.pzz, e.nzz, e.oczz, datespan, e.tzz, " class='bg-warning'")
    %end;
  %end;
  %if;(zz<=max_index)
    %apply;one_pvar(zz+1)
  %end;
%end;
%define;one_pvar_json(zz)
  %if;(e.izz!="" or e.pzz!="")
    %if;pvar.zz.exist;
      %if;(zz!=1),%end;
      {"i":"%pvar.zz.index;","p":"%pvar.zz.first_name;","n":"%pvar.zz.surname;"%if;(pvar.zz.occ!=0),"oc":"%pvar.zz.occ;"%end;%if;(e.tzz!=""),"t":"%e.tzz;"%end;,"self":"%pvar.zz;"}%nn;
    %end;
  %end;
  %if;(zz<=max_index)
    %apply;one_pvar_json(zz+1)
  %end;
%end;
%define;my_hidden(xx)
  %if;(e.xx!="")<input type="hidden" name="xx" value="%e.xx;">%end;
%end;
<div class="container-xl">
<form id="upd">
  <div class="h2 m-3">[*add/clear/show/edit the graph]3 RM/RLM</div>
  <div class="d-flex">
  <div class="alert alert-warning mx-auto d-none">[*RLM unknowns persons]</div>
  </div>
  %hidden;
  <input type="hidden" name="m" value='RLM'>
  %apply;my_hidden("spouse")
  %apply;my_hidden("image")
  %apply;my_hidden("bd")
  %apply;my_hidden("new")
  <div class="table-responsive">
  <table class="table table-hover table-sm w-auto">
    <thead>
      <tr>
        <th scope="col" class="border-top-0"></th>
        <th scope="col" class="border-top-0"></th>
        <th scope="col" class="align-middle font-weight-bold border-left px-3">#</th>
        <th scope="col" class="align-middle pl-2">[*first name/first names]0</th>
        <th scope="col" class="align-middle pl-2">[*surname/surnames]0</th>
        <th scope="col" class="align-middle" style="width:90px">[*occ]1</th>
        <th scope="col" class="align-middle">
          <div class="d-flex flex-column justify-content-center" style="line-height:0.9">
            <div>[*birth]</div>
            <div>[*death]</div>
          </div>
        </th>
        <th scope="col" class="align-middle pl-2">[*text]</th>
      </tr>
    </thead>
    <tbody>
      %apply;one_pvar_line("", "", "", "", "", "", " id='template_line' style='display:none;'")
      %if;(e.i0!="" and e.p0!="")
        %apply;one_pvar(0)
      %else;
        %apply;one_pvar(1)
      %end;
    </tbody>
    <tfoot>
      <td colspan="8" class="text-center p-2">
        <button type="button" class="btn btn-success row_add mr-4"
                title="[*add/insert/delete/up/down row]0">
          <i class="fas fa-plus mr-2" aria-hidden="true"></i>%nn;
          [*add/insert/delete/up/down row aria-label]0
        </button>
        <button type="button" class="btn btn-outline-info mr-2" id="refreshForm"
                title="[*RLM update data/save data/show graph]0" disabled>
           <span class="mr-2">
             <i class="fas fa-check toggle-icon"></i>
             <i class="fas fa-rotate toggle-icon d-none"></i>
           </span>[*validate/delete]0
        </button>
        <script id="rlm-data" type="application/json">%[%apply;one_pvar_json(1)%]</script>
        <button type="button" class="btn btn-info mr-4" id="saveRLM"
                title="[*RLM update data/save data/show graph]1" disabled>
          <span class="mr-2">
            <i class="fas fa-download toggle-icon"></i>
            <i class="fas fa-check toggle-icon d-none"></i>
          </span>[*save]
        </button>
        <button type="button" class="btn btn-primary mr-4" id="showGraph"
                title="[*RLM update data/save data/show graph]2 (RLM)" disabled>
          <i class="fas fa-eye mr-2"></i>[*add/clear/show/edit the graph]2
        </button>
        <button type="button" class="btn btn-warning" id="showMatrix"
          title="[*relationship table]1 (RM)" onclick="showOverlay()" disabled>
          <i class="fas fa-table-cells mr-2"></i>[*relationship table]0
        </button>
      </td>
    </tfoot>
  </table>
  </div>
  </form>
%if;(not cancel_links)
  %include;trl
  %include;copyr
%end;
</div>
%include;overlay
%include;js
%query_time;
<script>
function updateLineNumbers() {
  var lineNumber = 1;
  $('tbody tr:visible:not(.last_row)').each(function() {
    $(this).find('.line-number').text(lineNumber++);
  });
}
function updateArrowVisibility() {
  $('.row_move_up, .row_move_down').css('visibility', 'visible');
  $('tbody tr:visible:first .row_move_up').css('visibility', 'hidden');
  $('tbody tr:last .row_move_down').css('visibility', 'hidden');
  updateLineNumbers();
}
function toggleIcons(buttonId) {
  $(buttonId + ' .toggle-icon').toggleClass('d-none');
}
$(document).on( "click", ".row_add", function() {
  var newRow = $("#template_line").clone().removeAttr("id").removeAttr("style");
  if($(this).closest('tfoot').length) {
    $('tbody').append(newRow.get(0));
  } else {
    $(this).closest("tr").before(newRow.get(0));
  }
  newRow.find('input:first').focus();
  updateArrowVisibility();
});
$(document).on( "click", ".row_del", function() {
  $(this).closest('tr').remove();
  updateArrowVisibility();
});
$(document).on("click", ".row_move_up", function() {
  var row = $(this).closest("tr");
  if(row.index() > 1) {
    row.insertBefore(row.prev());
    updateArrowVisibility();
  }
});
$(document).on("click", ".row_move_down", function() {
  var row = $(this).closest("tr");
  var lastBodyRow = $('tbody tr:visible:last');
  if(!row.is(lastBodyRow)) {
    row.insertAfter(row.next());
    updateArrowVisibility();
  }
});
$(document).on( "change", ".reset_bd_text", function() {
  $(this).closest( "tr" ).children( ".bd_text").html( "" );
});
$('#saveRLM').on('click', function() {
  const jsonText = $('#rlm-data').html().trim();
  try {
    const jsonData = JSON.parse(jsonText);
    localStorage.setItem('inds', JSON.stringify(jsonData));
    toggleIcons('#saveRLM');
    setTimeout(() => toggleIcons('#saveRLM'), 2000);
  } catch (e) {
    console.error("Invalid JSON data in #rlm-data", e);
  }
});
function buildUrl(mode = 'RLM') {
  var dataIndex = 1;
  var params = new URLSearchParams();
  params.set('m', mode);
  if (mode === 'TP') params.set('v', 'updRLM');
  var currentParams = new URLSearchParams(window.location.search);
  var b = currentParams.get('b');
  if (b) params.set('b', b);
  $('tbody tr:visible').each(function() {
    var $row = $(this);
    var firstName = $row.find("input[name='p']").val().trim();
    var lastName = $row.find("input[name='n']").val().trim();
    if (firstName !== "" || lastName !== "") {
      if (firstName !== "") params.set('p' + dataIndex, firstName);
      if (lastName !== "") params.set('n' + dataIndex, lastName);
      var oc = $row.find("input[name='oc']").val();
      if (oc !== "" && oc !== "0") {
        params.set('oc' + dataIndex, oc);
      }
      if (mode === 'RLM') {
        var text = $row.find("input[name='t']").val().trim();
        if (text !== "") {
          params.set('t' + dataIndex, text);
        }
      }
      dataIndex++;
    }
  });
  return '?' + params.toString();
}
$('#refreshForm').on('click', function() {
  window.location.href = buildUrl('TP');
});
$('#showGraph').on('click', function() {
  window.location.href = buildUrl('RLM');
});
$('#showMatrix').on('click', function() {
  window.location.href = buildUrl('RM');
});
function checkFormValidity() {
  const warningRows = $('tbody tr.bg-warning, tbody tr .bg-warning').length;
  const validRows = $('tbody tr:visible').length - warningRows;
  const noErrors = warningRows === 0;
  if (noErrors && validRows >= 2) {
    $('#saveRLM, #showGraph, #showMatrix').prop('disabled', false);
  } else {
    $('.alert-warning').removeClass('d-none');
  }
}
$(document).ready(function() {
  updateArrowVisibility();
  checkFormValidity();
  setTimeout(() => {
    const $firstWarning = $('tbody tr.bg-warning:first input[name="p"]');
    if ($firstWarning.length > 0) {
      const input = $firstWarning[0];
      $firstWarning.focus();
      if (input.setSelectionRange) {
        input.setSelectionRange(input.value.length, input.value.length);
      }
    } else {
      $('#saveRLM').focus();
    }
  }, 300);
  const enableRefresh = () => {
    if ($('#refreshForm').prop('disabled')) {
      $('#refreshForm').prop('disabled', false);
      setTimeout(checkFormValidity, 100);
      toggleIcons('#refreshForm');
    }
  };
  $(document)
    .on('input change', 'tbody input', enableRefresh)
    .on('click', '.row_add, .row_del, .row_move_up, .row_move_down', enableRefresh)
    .on('keydown', function(e) {
      if (e.key === 'Enter' && !$('#refreshForm').prop('disabled')) {
        e.preventDefault();
        $('#refreshForm').click();
      }
    });
});
</script>
</body>
</html>
