[% USE raw %]
[% USE Koha %]
[% USE Branches %]
[% USE KohaDates %]
[% USE Price %]
[% USE ItemTypes %]
[% USE AuthorisedValues %]
[% PROCESS 'i18n.inc' %]
[% PROCESS 'html_helpers.inc' %]
[% SET reserve_input_type = 'radio' %]
[% IF ( Koha.Preference('DisplayMultiItemHolds') ) %]
 [% SET reserve_input_type = 'checkbox' %]
[% END %]
[% INCLUDE 'doc-head-open.inc' %]
<title
    >[% FILTER collapse %]
 [% t("Placing a hold") | html %]
 &rsaquo; [% PROCESS 'library_name_title' %]
 [% END %]</title
>
[% INCLUDE 'doc-head-close.inc' %]
[% BLOCK cssinclude %]
[% END %]
</head>

[% INCLUDE 'bodytag.inc' bodyid='opac-holds' %]
[% INCLUDE 'masthead.inc' %]

<main class="main">
 [% WRAPPER breadcrumbs %]
 [% WRAPPER breadcrumb_item bc_active= 1 %]
 <span>Reservando</span>
 [% END %]
 [% END #/ WRAPPER breadcrumbs %]

 <div class="container-fluid">
 <div id="holds" class="maincontent">
 <h1>Reservando</h1>
 [% IF ( message ) %]
 <div id="holdmessages" class="alert alert-warning">
 <h2>Lo sentimos, usted no puede hacer reservas.</h2>
 <ul>
 [% IF ( GNA ) %]
 <li id="gna">
 De acuerdo con nuestros registros, no disponemos de información de contacto actualizada. Por favor, póngase en contacto con la biblioteca. <a href="/cgi-bin/koha/opac-memberentry.pl">[% IF ( Koha.Preference('OPACPatronDetails') ) %]<span>Actualizar su información de contacto</span>[% ELSE %]<span>Ir a su información de contacto</span>[% END %]</a>
 [% IF ( Koha.Preference('OPACPatronDetails') ) %]<em>(Tenga en cuenta: puede haber un retraso en el restablecimiento de su cuenta si envía sus datos en línea.)</em>[% END %]
 </li>
 [% END %]

 [% IF ( lost ) %]
 <li id="lost">
 Su carné de biblioteca ha sido marcado como perdido o robado.<br />
 <em>Si esto es un error, por favor lleve su carné al puesto de circulación a su biblioteca local y el error será corregido.</em>
 </li>
 [% END %]

 [% IF ( debarred ) %]
 [% INCLUDE "patron-restrictions.inc" %]
 [% END %]

 [% IF ( too_much_oweing ) %]
 <li id="too_much_oweing"> Usted tiene multas pendiente de pago. Por un monto de: [% too_much_oweing | $Price %]. </li>
 [% END %]

 [% IF ( too_many_reserves ) %]
 <li id="too_many_reserves"> Lo sentimos, usted no puede hacer más de [% too_many_reserves | html %] reservas. </li>
 [% END %]

 [% IF ( bad_biblionumber ) %]
 <li id="bad_biblionumber"> ERROR: No hay registro correspondiente al ID del registro [% bad_biblionumber | html %]. </li>
 [% END %]

 [% IF ( no_items_selected ) %]
 <li id="no_items_selected"> Debe seleccionar al menos un ejemplar. </li>
 [% END %]

 [% IF ( no_branch_selected ) %]
 <li id="no_branch_selected"> Debe seleccionar una biblioteca para hacer el retiro. </li>
 [% END %]

 [% IF ( no_biblionumber ) %]
 <li id="no_biblionumber"> ERROR: No se ha especificado ID de registro. </li>
 [% END %]

 [% IF ( bad_data ) %]
 <li id="bad_data"> ERROR: Error interno: solicitud de reserva incompleta. </li>
 [% END %]

 [% IF ( expired_patron ) %]
 <li id="expired_patron"> Su carné de biblioteca ha expirado. Por favor, póngase en contacto con su bibliotecario si desea renovar su carné. </li>
 [% END %]

 [% IF ( no_pickup_locations ) %]
 <li id="no_pickup_locations"> Ninguna de las bibliotecas está disponible para la ubicación de recogida. </li>
 [% END %]
 </ul>
 </div>
 <!-- /.message -->
 [% ELSE # /IF message %]

 [% IF ( none_available && multi_hold ) %]
 <div id="none_available" class="alert"> Lo sentimos, no es posible reservar ninguno de estos títulos. </div>
 [% END %]
 [% END # / IF message %]

 [% UNLESS ( message ) %]
 [% UNLESS ( none_available ) %]
 <h2>Confirmar reservas para:[% INCLUDE 'patron-title.inc' patron = logged_in_user %] ([% logged_in_user.cardnumber | html %])</h2>
 [% END # / UNLESS none_available %]

 [% IF ( new_reserves_allowed ) %]
 <div id="new_reserves_allowed" class="alert"> <strong>Lo sentimos,</strong> usted puede solamente realizar [% new_reserves_allowed | html %] reservas más. Por favor, desactive las casillas de verificación de los ejemplares que no desea colocar en reserva. </div>
 [% END %]

 <form action="/cgi-bin/koha/opac-reserve.pl" method="post" id="hold-request-form">
 [% INCLUDE 'csrf-token.inc' %]
 <legend class="sr-only">Reservas</legend>
 <input type="hidden" name="op" value="cud-place_reserve" />
 [% IF ( Koha.Preference('DisplayAddHoldGroups') && ( multi_hold || Koha.Preference('DisplayMultiItemHolds') ) ) %]
 <div id="hold_group">
 <fieldset class="rows">
 <ul>
 <li>
 <label for="add_to_hold_group_control">Tratar como un grupo de reservas (el próximo ítem disponible completa todas las reservas):</label>
 <input type="checkbox" id="add_to_hold_group_control" name="add_to_hold_group" value="add_to_hold_group" />
 </li>
 </ul>
 </fieldset>
 </div>
 [% END %]
 <!-- These values are set dynamically by js -->
 <input type="hidden" name="biblionumbers" id="biblionumbers" />
 <input type="hidden" name="selecteditems" id="selections" />
 <div id="bigloop">
 [% FOREACH bibitemloo IN bibitemloop %]
 <div class="holdrow">
 [% IF bibitemloo.forced_hold_level %]
 <div class="alert alert-info forced_hold_level">
 [% IF bibitemloo.forced_hold_level == 'item' %]
 <span>Usted tiene al menos una reserva a nivel de ítem para este título. Todas las reservas subsiguientes deben ser a nivel de ítem.</span>
 [% ELSE %]
 <span>Usted tiene al menos una reserva a nivel registro para este título. Todas las reservas subsiguientes deben ser a nivel registro.</span>
 [% END %]
 </div>
 [% END %]

 [% IF ( bibitemloo.reserve_charge ) %]
 <div class="alert" id="reserve_fee">
 [% IF Koha.Preference('HoldFeeMode') == 'any_time_is_collected' %]
 <span>Se le cobrará un costo de reserva de [% bibitemloo.reserve_charge | $Price %] cuando recoja este ítem</span>
 [% ELSE %]
 <span>Se le cobrará un costo de reserva de [% bibitemloo.reserve_charge | $Price %] por hacer esta reserva</span>
 [% END %]
 </div>
 [% END %]

 <p>
 [% IF ( bibitemloo.holdable ) %]
 <input class="reserve_mode" name="reserve_mode" type="hidden" value="single" />
 <input class="single_bib" name="single_bib" type="hidden" value="[% bibitemloo.biblionumber | html %]" />
 <span class="confirmjs_hold" title="[% bibitemloo.biblionumber | html %]" style="padding:.3em"></span>
 <span class="confirm_nonjs">
 <input
                                                type="radio"
                                                class="confirmbox checkitem [% bibitemloo.biblionumber | html %]"
                                                name="[% bibitemloo.biblionumber | html %]"
                                                checked="checked"
                                                id="single_[% bibitemloo.biblionumber | html %]"
                                                value="any"
                                            />
 <label class="confirm_label" for="single_[% bibitemloo.biblionumber | html %]">Reservar </label>
 </span>
 [% END # / bibitemloo.holdable %] [% INCLUDE 'biblio-title.inc' biblio=bibitemloo link=> 1 %] [% IF ( bibitemloo.author ) %], por [% bibitemloo.author | html %][% END %] </p>

 [% UNLESS ( bibitemloo.holdable ) %]
 [% IF ( bibitemloo.ageRestricted ) %]
 <div class="alert alert-warning">Lo sentimos, usted es demasiado joven para reservar este ítem.</div>
 [% END %]
 [% IF ( bibitemloo.already_reserved ) %]
 <div class="alert alert-warning">Usted ya ha solicitado este título.</div>
 [% ELSIF ( bibitemloo.recall ) %]
 <div class="alert alert-warning">Usted ya ha hecho un reclamo para este título.</div>
 [% ELSE %]
 [% IF bibitemloo.alreadypossession %]
 <div class="alert alert-warning">Este título no se puede solicitar debido a que ya se encuentra en su posesión.</div>
 [% ELSIF bibitemloo.tooManyReserves %]
 <div class="alert alert-warning">Este título no se puede solicitar debido a que Ud. ha alcanzado el máximo de reservas.</div>
 [% ELSIF bibitemloo.tooManyHoldsForThisRecord %]
 <div class="alert alert-warning">Este título no se puede solicitar debido a que Ud. ha superado el máximo de reservas por registro.</div>
 [% ELSIF bibitemloo.tooManyReservesToday %]
 <div class="alert alert-warning">Este título no se puede solicitar debido a que Ud. ha alcanzado el límite diario de reservas.</div>
 [% ELSIF bibitemloo.itemAlreadyOnHold %]
 <div class="alert alert-warning">Este título no se puede solicitar debido a que ya tiene una reserva para este ítem.</div>
 [% ELSE %]
 [% UNLESS ( bibitemloo.bib_available ) %]
 <div class="alert">No hay ejemplares que puedan reservarse.</div>
 [% ELSE %]
 <div class="alert">Este título no se puede solicitar.</div>
 [% END %]
 [% END # / UNLESS bibitemloo.already_patron_possession %]
 [% END # / IF bibitemloo.already_reserved %]
 [% END # / UNLESS bibitemloo.holdable %]

 [% IF ( bibitemloo.holdable ) %]
 <fieldset class="rows">
 <ul>
 <!-- HOLDABLE -->
 [% UNLESS ( item_level_itypes ) %]
 <li class="itype">
 <span class="label">Tipo de ítem: </span>
 [% IF ( bibitemloo.imageurl ) %]<img class="itemtype-image" src="[% bibitemloo.imageurl | html %]" alt="" />[% END %]
 <span class="itypetext">[% bibitemloo.translated_description | html %]</span>
 </li>
 [% END %]

 [% SET OPACShowHoldQueueDetails = Koha.Preference('OPACShowHoldQueueDetails') %]
 [% IF OPACShowHoldQueueDetails == 'holds_priority' || OPACShowHoldQueueDetails == 'priority' %]
 <li class="priority">
 <span class="label">Su prioridad: </span>
 [% bibitemloo.rank | html %]
 </li>
 [% END %]

 [% IF OPACShowHoldQueueDetails == 'holds_priority' || OPACShowHoldQueueDetails == 'holds' %]
 <li class="holds-count">
 <span class="label">Número de reservas: </span>
 [% bibitemloo.reservecount | html %]
 </li>
 [% END %]

 [% UNLESS ( singleBranchMode ) %]
 [% IF ( bibitemloo.holdable && Koha.Preference('OPACAllowUserToChooseBranch')) %]
 <li class="branch">
 <label for="branch_[% bibitemloo.biblionumber | html %]">Lugar de retiro:</label>
 [% UNLESS ( bibitemloo.holdable ) %]
 <select name="branch" id="branch_[% bibitemloo.biblionumber | html %]" disabled="disabled">
 [% PROCESS options_for_libraries libraries => Branches.pickup_locations({ search_params => { biblio => bibitemloo.biblionumber, patron => logged_in_user }, selected => branch }) %]
 </select>
 [% ELSE %]
 [% SET at_least_one_library_not_available_for_pickup = 0 %]
 <select name="branch" id="branch_[% bibitemloo.biblionumber | html %]">
 [% FOREACH library IN Branches.pickup_locations({ search_params => { biblio => bibitemloo.biblionumber, patron => logged_in_user }, selected => branch }) %]
 [% SET pickup_available_at = bibitemloo.not_available_at.grep('^' _ library.branchcode _ '$').size ? 0 : 1 %]
 [% IF library.selected AND pickup_available_at %]
 <option value="[% library.branchcode | html %]" selected="selected">[% library.branchname | html %]</option>
 [% ELSIF pickup_available_at %]
 <option value="[% library.branchcode | html %]">[% library.branchname | html %]</option>
 [% ELSE %]
 [% SET at_least_one_library_not_available_for_pickup = 1 %]
 <option disabled="disabled" title="Al menos un ítem está disponible en esta biblioteca" value="[% library.branchcode | html %]">[% library.branchname | html %]</option>
 [% END %]
 [% END %]
 </select>
 [% IF at_least_one_library_not_available_for_pickup %]
 <div class="at_least_one_library_not_available_note">
 Nota: La política de la biblioteca no permite reservar/hacer retiro de un ítem disponible localmente. Por favor, vaya a la biblioteca para solicitar estos ítems </div>
 [% END %]
 [% END # / UNLESS bibitemloo.holdable %]
 </li>
 [% END # / IF bibitemloo.holdable && Koha.Preference('OPACAllowUserToChooseBranch') %]
 [% END # / UNLESS singleBranchMode %]
 </ul>

 <a class="toggle-hold-options" id="toggle-hold-options-[% bibitemloo.biblionumber | html %]" style="display:none;" href="#">Mostrar más opciones</a>

 <div id="hold-options-[% bibitemloo.biblionumber | html %]" class="hold-options">
 <ul>
 [% IF ( reserve_in_future ) %]
 <li>
 <label for="from[% bibitemloo.biblionumber | html %]">La reserva comienza el día:</label>
 <input
                                                            type="text"
                                                            name="reserve_date_[% bibitemloo.biblionumber | html %]"
                                                            id="from[% bibitemloo.biblionumber | html %]"
                                                            data-start_for="to[% bibitemloo.biblionumber | html %]"
                                                            data-flatpickr-futureinclusive="true"
                                                            size="10"
                                                            class="flatpickr holddatefrom"
                                                            value="[% KohaDates.datetime_from_string | $KohaDates dateformat => 'iso' %]"
                                                        />
 <span class="date-format from" data-biblionumber="[% bibitemloo.biblionumber | html %]">[% INCLUDE 'date-format.inc' %]</span>
 <div class="required_label" style="display:none;">Requerido</div>
 </li>
 [% END %]

 <li>
 <label for="to[% bibitemloo.biblionumber | html %]">Reserva no necesaria después de:</label>
 <input
                                                        type="text"
                                                        name="expiration_date_[% bibitemloo.biblionumber | html %]"
                                                        id="to[% bibitemloo.biblionumber | html %]"
                                                        size="10"
                                                        data-flatpickr-future="true"
                                                        class="flatpickr futuredate"
                                                    />
 <span class="date-format to" data-biblionumber="[% bibitemloo.biblionumber | html %]">[% INCLUDE 'date-format.inc' %]</span>
 <div class="required_label" style="display:none;">Requerido</div>
 </li>

 [% IF Koha.Preference('AllowHoldItemTypeSelection') %]
 <li>
 <label for="itemtype">Solicitud de tipo de ítem específico:</label>
 <select name="itemtype" id="itemtype">
 <option value="">Cualquier tipo de ítem</option>
 [% FOREACH i IN bibitemloo.allowed_item_types %]
 <option value="[% i | html %]">[% ItemTypes.GetDescription( i ) | html %]</option>
 [%- END %]
 </select>
 </li>
 [% END %]

 [% UNLESS bibitemloo.forced_hold_level && ( bibitemloo.forced_hold_level == 'item' || bibitemloo.forced_hold_level == 'record' ) %]
 [% IF Koha.Preference('EnableItemGroupHolds') && bibitemloo.object.item_groups.count %]
 <li>
 <label for="itemtype">Solicitar grupo de ítems específico:</label>
 <select name="item_group_id_[% bibitemloo.biblionumber | html %]" id="item_group_id_[% bibitemloo.biblionumber | html %]">
 <option value="">Cualquier grupo de ítems</option>
 [% FOREACH g IN bibitemloo.object.item_groups.search({}, { order_by => ['display_order'] }) %]
 [% IF g.items.count %]
 <option value="[% g.id | html %]">[% g.description | html %]</option>
 [% END %]
 [% END %]
 </select>
 </li>
 [% END %]
 [% END %]

 [% IF ( OpacHoldNotes ) %]
 <li>
 <div class="notesrow" id="notesrow_[% bibitemloo.biblionumber | html %]">
 <label for="holdnotes_[% bibitemloo.biblionumber | html %]">Notas de la reserva:</label>
 <textarea id="holdnotes_[% bibitemloo.biblionumber | html %]" rows="2" cols="30" name="notes_[% bibitemloo.biblionumber | html %]">[% bibitemloo.holdnotes | html %]</textarea>
 </div>
 </li>
 [% END # / IF OpacHoldNotes %]

 [% IF bibitemloo.itemholdable %]
 <!-- ITEM HOLDS -->
 <li class="lradio place_on_type" style="display:none;">
 [% UNLESS bibitemloo.forced_hold_level == 'item' || bibitemloo.forced_hold_level == 'item_group' || bibitemloo.force_hold %]
 <label class="radio inline" for="reqany_[% bibitemloo.biblionumber | html %]">Siguiente ítem disponible</label>
 <input type="radio" name="reqtype_[% bibitemloo.biblionumber | html %]" id="reqany_[% bibitemloo.biblionumber | html %]" class="selectany" value="Any" checked="checked" />
 [% END %]
 <label class="radio inline" for="reqspecific_[% bibitemloo.biblionumber | html %]">Un ítem específico</label>
 <input type="radio" name="reqtype_[% bibitemloo.biblionumber | html %]" id="reqspecific_[% bibitemloo.biblionumber | html %]" class="selectspecific" value="Specific" />
 </li>
 [% END # / IF bibitemloo.itemholdable %]
 </ul>

 [% IF bibitemloo.itemholdable %]
 <div id="copiesrow_[% bibitemloo.biblionumber | html %]" class="copiesrow">
 <table class="table table-bordered table-striped itemstable">
 <caption>Seleccione un ejemplar específico:</caption>
 <thead>
 <tr>
 <th>Copia número</th>
 [% IF ( item_level_itypes ) %]
 <th>Tipo de ítem</th>
 [% END %]
 <th>Código de barras</th>
 [% UNLESS ( singleBranchMode ) %]
 <th>Biblioteca de origen</th>
 <th>Última ubicación</th>
 [% END %]
 [% IF ( itemdata_ccode ) %]
 <th>Colección</th>
 [% END %]
 <th>Signatura topográfica</th>
 [% IF ( itemdata_enumchron ) %]
 <th>Info Vol</th>
 [% END %]
 <th>Notas</th>
 <th>Información</th>
 </tr>
 </thead>
 <tbody>
 [% SET unholdable_items = 0 %]
 [% FOREACH itemLoo IN bibitemloo.itemLoop %]
 [% SET row_class = "holdable" %]
 [% SET row_style = "" %]
 [% IF ( itemLoo.available ) %]
 [% IF ( itemLoo.checkout ) %]
 [% row_class = "holdable onloan" %]
 [% ELSE %]
 [% row_class = "holdable" %]
 [% END %]
 [% ELSE %]
 [% SET unholdable_items = 1 %]
 [% row_style = "display:none" %]
 [% IF ( itemLoo.checkout ) %]
 [% row_class = "unholdable onloan" %]
 [% ELSE %]
 [% row_class = "unholdable" %]
 [% END %]
 [% END %]
 <tr class="[% row_class | html %]" style="[% row_style | html %]">
 [% IF ( itemLoo.available ) %]
 <td class="copynumber" data-order="[% itemLoo.copynumber | html %]">
 <input
                                                                                type="[% reserve_input_type | html %]"
                                                                                class="checkitem checkitem_[% bibitemloo.biblionumber | html %]"
                                                                                name="checkitem_[% bibitemloo.biblionumber | html %]"
                                                                                value="[% itemLoo.itemnumber | html %]"
                                                                            />
 [% IF ( itemLoo.copynumber ) %]
 [% itemLoo.copynumber | html %]
 [% END %]
 </td>
 [%# copynumber %]
 [% ELSE %]
 <td class="copynumber">
 <input aria-label="No se puede reservar" class="checkitem" disabled="disabled" name="checkitem" style="display:none;" type="radio" value="[% itemLoo.itemnumber | html %]" />
 <i aria-hidden="true" class="fa fa-times danger" title="No se puede reservar"></i>
 [% IF ( itemLoo.copynumber ) %]
 [% itemLoo.copynumber | html %]
 [% END %]
 </td>
 [%# copynumber %]
 [% END %]

 [% IF ( item_level_itypes ) %]
 <td class="itype">
 [% UNLESS ( Koha.Preference('OpacNoItemTypeImages') ) %]
 [% IF ( itemLoo.imageurl ) %]
 <img class="itemtype-image" src="[% itemLoo.imageurl | html %]" alt="" />
 [% END %]
 [% END %]
 <span class="itypetext">[% itemLoo.translated_description | html %]</span>
 </td>
 [% END %]

 <td class="barcode">[% itemLoo.barcode | html %]</td>
 [% UNLESS ( singleBranchMode ) %]
 <td class="homebranch">[% Branches.GetName( itemLoo.homebranch) | html %]</td>
 <td class="holdingbranch">[% Branches.GetName( itemLoo.holdingbranch ) | html %]</td>
 [% END %]
 [% IF ( itemdata_ccode ) %]
 <td class="ccode">
 [% IF ( itemLoo.ccode ) %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => itemLoo.ccode, opac => 1 ) | html %][% END %]</td
                                                                        >
 [% END %]
 <td class="call_no">[% itemLoo.itemcallnumber | html %]</td>
 [% IF ( itemdata_enumchron ) %]
 <td class="vol_info">[% itemLoo.enumchron | html %]</td>
 [% END %]
 <td class="itemnotes"> [% itemLoo.itemnotes | html %] </td>
 <td class="information">
 [% IF ( itemLoo.checkout.date_due) %]
 <span class="checkedout">Vencimiento [% itemLoo.checkout.date_due| $KohaDates as_due_date => 1 %]</span>
 [% ELSIF ( itemLoo.transfertwhen ) %]
 <span class="intransit"
                                                                                >En tránsito de [% Branches.GetName( itemLoo.transfertfrom ) | html %] a [% Branches.GetName( itemLoo.transfertto ) | html %] desde [% itemLoo.transfertwhen | $KohaDates %]</span
                                                                            >
 [% END %]

 [% IF ( itemLoo.itemlost == 1 || itemLoo.itemlost == 2 ) %]
 [%# FIXME Why only for 1 or 2? Shouldn't we test for withdrawn as well? %]
 <span class="lost">No disponible (perdido o faltante)</span>
 [% END %]

 [% IF ( itemLoo.notforloan ) %]
 <span class="notforloan"
                                                                                >No para préstamo ([% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => itemLoo.notforloan ) %])</span
                                                                            >
 [% END %]

 [% IF ( itemLoo.first_hold ) %]
 <span class="waiting">
 [% IF ( itemLoo.waitingdate ) %]
 <span>Esperando al usuario en [% Branches.GetName( itemLoo.ExpectedAtLibrary ) | html %] desde [% itemLoo.waitingdate | $KohaDates %]</span>
 [% ELSIF ( itemLoo.reservedate ) %]
 <span>Reservado para el usuario, esperado en [% Branches.GetName( itemLoo.ExpectedAtLibrary ) | html %] desde [% itemLoo.reservedate | $KohaDates %]</span>
 [% ELSE %]
 <span>Reservado para un usuario, esperado en [% Branches.GetName( itemLoo.ExpectedAtLibrary ) | html %]</span>
 [% END %]
 </span>
 [% ELSE %]
 <span class="notonhold">No está reservado</span>
 [% END # / IF ( itemLoo.first_hold ) %]
 </td>
 </tr>
 [% END # / FOREACH itemLoo IN bibitemloo.itemLoop %]
 </tbody>
 </table>
 <!-- / #copiesrow_[% bibitemloo.biblionumber | html %] -->
 [% IF unholdable_items %]
 <button id="show_unholdable" class="btn btn-primary toggle_unholdable unholdable">Mostrar items no reservables</button>
 <button id="hide_unholdable" class="btn btn-primary toggle_unholdable unholdable" style="display:none;">Ocultar items no reservables</button>
 [% END %]
 </div>
 [% END # / IF ( bibitemloo.itemholdable ) %]
 </div>
 <!-- / #hold-options-[% bibitemloo.biblionumber | html %] -->
 </fieldset>
 [% END # / IF ( bibitemloo.holdable ) %]
 </div>
 <!-- / .holdrow -->
 [% END # / FOREACH bibitemloo IN bibitemloop %] </div
                    ><!-- #bigloop -->

 [% UNLESS ( none_available ) %]
 <input class="btn btn-primary placehold" type="submit" value="Confirmar reserva" />
 [% END %]
 </form>
 [% END # / UNLESS message %]
 </div>
 <!-- / #holds -->
 </div>
 <!-- / .container -->
</main>
<!-- / .main -->
[% INCLUDE 'opac-bottom.inc' %]
[% BLOCK jsinclude %]
 [% INCLUDE 'calendar.inc' %]
 [% INCLUDE 'datatables.inc' %]
 <script>
        $(document).ready(function() {

            $(".toggle_unholdable").click(function(e){
                e.preventDefault();
                $(this).parent('div').find(".unholdable").toggle();
            });

            $("#hold-request-form").preventDoubleFormSubmit();
            var copiesRowId = null;
            var wasSpecific = false;
            var lastCopiesRowId = null;

            $(".toggle-hold-options").show();
            $(".hold-options").hide();
            var OPACMandatoryHoldDates = "[% Koha.Preference('OPACMandatoryHoldDates') | html %]";
            if( OPACMandatoryHoldDates == "start" || OPACMandatoryHoldDates == "both" ) {
                $(".holddatefrom").val("").prop( 'required', true ).siblings(".required_label").addClass('required').show();
            }
            if( OPACMandatoryHoldDates == "end"   || OPACMandatoryHoldDates == "both" ) {
                $(".futuredate").prop( 'required', true ).siblings(".required_label").addClass('required').show();
            }

            $(".checkitem").parent().click(function(e){
                if(e.target.tagName.toLowerCase() == 'td'){
                    $(this).find("input.checkitem").each( function() {
                        $(this).attr('checked', 'checked');
                    });
                }
            });

            // click on a first td check the confirmjs checkbox
            $("td.hold").click(function(e){
              if(e.target.tagName.toLowerCase() == 'td'){
                $(this).find("input.confirmjs").each( function() {
                   $(this).attr('checked', !$(this).attr('checked'));
                   $(this).change();
                });
              }
            });

            $(".toggle-hold-options").on("click",function(e){
                e.preventDefault();
                toggleLink = $(this);
                var optionsID = this.id.replace("toggle-hold-options-","");
                $("#hold-options-"+optionsID).toggle(0, function() {
                    toggleLink.text($(this).is(':visible') ? _("Ocultar opciones") : _("Mostrar más opciones"));
                });
            });
            if( $(".holddatefrom").prop('required') || $(".futuredate").prop('required') ) $(".toggle-hold-options").click();

            // Hides all 'specific copy' table rows on load.
            $(".copiesrow").hide();

            [% FOREACH bibitemloo IN bibitemloop %]
              [% IF bibitemloo.force_hold %]
                if( $("#to[% bibitemloo.biblionumber | html %]").parent(":hidden").length )
                    $("#toggle-hold-options-[% bibitemloo.biblionumber | html %]").click();
                $("#reqspecific_[% bibitemloo.biblionumber | html %]").click();
                $("#copiesrow_[% bibitemloo.biblionumber | html %]").show();
              [% END %]
            [% END %]

            // Replace non-JS single-selection with multi-selection capability.
            $(".reserve_mode").val("multi");
            $(".confirm_nonjs").remove();
            $(".confirmjs_hold").each(function(){
                var bib = $(this).attr("title");
                var html = "<label><input type =\"checkbox\" class=\"confirmjs\" checked=\"checked\"";
                html += "value=\"" + bib + "\" id=\"" + bib + "\" /> " + _("Hacer una reserva de") + " </label> ";
                $(this).html(html);
            });
            $(".confirmjs_nohold").each(function(){
                var bib = $(this).attr("title");
                var html = "<label><input type =\"checkbox\" class=\"confirmjs\" disabled=\"disabled\"";
                html += "value=\"" + bib + "\" id=\"" + bib + "\" />" + _("Hacer una reserva de: ") + "</label>";
                $(this).html(html);
            });

            // expand or collapse the copiesrow tr
            function toggle_copiesrow(biblioNum) {
                var checkbox = $("input:checkbox[value='"+biblioNum+"']");
                newCopiesRowId = "#copiesrow_" + biblioNum;
                var select_specific = $("#reqspecific_"+biblioNum).is(":checked");
                // If the checkbox is checked AND we want a specific item, we display the items block
                if ( $(checkbox).is(":checked") && select_specific ) {
                    if ( $(`#item_group_id_${biblioNum}`).length ) {
                        $(`#item_group_id_${biblioNum}`).val("").attr('disabled', 'disabled');
                    }
                    $(newCopiesRowId).show();
                } else {
                    if ( $(`#item_group_id_${biblioNum}`).length ) {
                        $(`#item_group_id_${biblioNum}`).removeAttr('disabled');
                    }
                    $(newCopiesRowId).hide();
                }
            };

            $("#place_on_hdr").show();

            $(".place_on_type").show();
            // onload, selectany is checked
            $(".selectany").attr("checked", "checked");


            // On confirmsjs change
            $(".confirmjs").change(function(){
                var id = suffixOf($(this).attr("id"), "_");
                // If I m checked, I enable radio buttons
                if ( $(this).is(":checked") ) {
                    $("#reqspecific_" + id).attr("disabled", false);
                    $("#reqany_" + id).attr("disabled", false);
                }
                // Else its are disabled
                else {
                    $("#reqspecific_" + id).attr("disabled", "disabled");
                    $("#reqany_" + id).attr("disabled", "disabled");
                }
                // expand or collapse the items block
                toggle_copiesrow(id);
            });

            // When 'specific copy' or 'first available' radio button is clicked
            $(".selectspecific, .selectany").click(function() {
                var id = suffixOf($(this).attr("id"), "_");
                toggle_copiesrow(id);
            });

            // Show or hide holds notes
            $(".shownotes").click(function(){
                biblioNum = suffixOf($(this).attr("id"), "_");
                $("#notesrow_"+biblioNum).toggle();
            });

            // When 'Place Hold' button is clicked
            $(".placehold").click(function(){
                var biblionumbers = "";
                var selections = "";

                [% IF new_reserves_allowed %]
                    if ($(".confirmjs:checked").size() > [% new_reserves_allowed | html %] ) {
                        alert(MSG_MAX_HOLDS_EXCEEDED);
                        return false;
                    }
                [% END %]

                if ($(".confirmjs:checked").size() == 0) {
                    alert( _("Ningún ítem seleccionado") );
                    return false;
                }

                // Find the items with the 'Hold' box checked
                var badBib = null;
                $(".confirmjs:checked").each(function() {
                    var biblioNum = $(this).val();
                    biblionumbers += biblioNum + "/";
                    let select_bib = biblioNum;
                    let select_pickup;
                    let select_items = [];

                    // If required hold note is empty, make it visible
                    if( $("#holdnotes_"+biblioNum).attr( 'required' ) && $("#holdnotes_"+biblioNum).val() == '' ) {
                        if( !$("#hold-options-"+biblioNum).is(':visible')) {
                            $("#toggle-hold-options-"+biblioNum).click();
                        }
                    }

                    if( $(".holddatefrom").prop('required') && $("#from"+ biblioNum).val() == '' ) {
                        alert( _("La fecha de inicio de la reserva debe ser completada.") );
                        badBib = biblioNum;
                        if( $("#from"+biblioNum).parent(":hidden").length ) $("#toggle-hold-options-"+biblioNum).trigger('click');
                        $("#from"+biblioNum).siblings('.flatpickr_wrapper').find('.flatpickr-input').trigger('focus');
                        return false;
                    } else if( $(".futuredate").prop('required') && $("#to"+ biblioNum).val() == '' ) {
                        alert( _("La fecha de expiración de la reserva debe ser completada.") );
                        badBib = biblioNum;
                        if( $("#to"+biblioNum).parent(":hidden").length ) $("#toggle-hold-options-"+biblioNum).trigger('click');
                        $("#to"+biblioNum).siblings('.flatpickr_wrapper').find('.flatpickr-input').trigger('focus');
                        return false;
                    }

                    // If the 'specific copy' radio button is checked
                    if ($("#reqspecific_" + biblioNum + ":checked").size() > 0) {
                        // Find the selected copy
                        var items = $(".checkitem_" + biblioNum + ":checked");
                        if ($(items).size() == 0) {
                            alert( _("Esperando una selección de un ítem específico.") );
                            badBib = biblioNum;
                            return false;
                        } else {
                            items.each( function(index,el){
                                select_items.push( $(el).val() );
                            });
                        }
                    }

                    // Add the pickup location
                    var branchSel = $("#branch_" + biblioNum);
                    if (branchSel.size() > 0) {
                        select_pickup = $(branchSel).val();
                    }
                    if ( select_items.length > 0 ){
                        select_items.forEach( function(item_value,index){
                            selections += select_bib + "/" + item_value + "/" + select_pickup + "/";
                        });
                    }
                    else {
                        selections += select_bib + "/" + "/" + select_pickup + "/";
                    }
                    return true;
                });

                if (badBib) { // alert has been raised already
                    return false;
                }

                $("#selections").val(selections);
                $("#biblionumbers").val(biblionumbers);

                return true;
            });
            $(".itemstable").each(function(){
                $(this).DataTable({
                    dom: "t",
                    initComplete: function() {
                        this.find("input:radio").first().prop("checked", true );
                    },
                    paging: false
                });
            });
        });
    </script>
[% END %]
