<?xml version="1.0" encoding="UTF-8"?>
<actions>

<meta>
  <description>Schnittstelle für die Webseite des aDIS-Systems.</description>
  <variable name="fullurl"><description>Vollständige Internet-Adresse der Bibliothek 
(mit https:// und meistens mit aDISWeb/app)</description></variable>
  <variable name="server" default=""><description>Alternative zur vollständigen Adresse: reiner Servername, (z.B.: ssl.muenchen.de) </description></variable>
  <variable name="startparams" default=""><description>Alternative zur vollständigen Adresse: Parameter in der URL nach aDISWeb/app für Server, auf denen mehrere Bibliothekssysteme laufen</description></variable>
</meta>


<action id="connect">
  <s>
    declare function local:htmlOnLink($html, $target){
      form($html/ancestor::form[1], "selected=ZTEXT       "||$target) 
        otherwise vl:raise-internal("Link zur Seite " || $target || " nicht gefunden")
    };
    declare function local:aDISLink($link, $fallback-target){
      let $href := $link/@href 
      return
      if (starts-with($href, "javascript:") or $href = "#") then 
        let $code := extract($href, "javascript:top\.htmlOnLink\(['""](.*)['""]\)", 1)[.] 
                     otherwise $fallback-target
        return local:htmlOnLink($link, $code)
      else
       $href
    };
         
    $sessions-reconnects := 3,
    $fullurl := get("fullurl", ()) otherwise concat("https://", get("server"), "/aDISWeb/app", get('startparams'))
  </s>
</action>

<action id="internal-login"> 
  <s>error-login := ()</s>
  <if test="get('idpSystem')">
    <s>i := 1</s>
    <!-- follow links till we reach the login page -->
    <loop test="$i < 10">
        <page url="{$loginFormPost}"/>
        <pattern><t:switch prioritized="true">
          <p class="form-error">{$error-login := ., i := 1000}</p><!-- blb karlsruhe -->
          <div class="error"><i class="fas"></i>{$error-login := ., i := 1000}</div>
          <p class="output-message output--error">{$error-login := ., i := 1000}</p><!--HS Offenburg-->

          <!-- seems we already are on the correct page, send request again (not tested with any library) -->
          <div id="konto-services"/>
          <td>Keine Ausleihen<t:s>i:=1000</t:s></td>
          <a t:condition="contains(., 'Ausleihe') and @href[contains(., '&amp;sp=SZ') or . = '#']"><t:s>i:=1000</t:s></a>
       
          <!-- we were logged out ? -->
          <a>Mein Konto<t:s>loginFormPost := local:aDISLink(., "*SBK")</t:s></a>
    
          <!-- redirection -->
          <form t:condition=".//@name = ('_eventId_proceed', 'SAMLResponse', 'RelayState') ">
            { $loginFormPost := form(., ( 
                (.//input[@name="j_username"])[1]/{"j_username": $username, "j_password": $password},   
                (.//*[@name="_eventId_proceed"])[1] 
              ))  }
          </form>
          <div class="aDISMaske"><select id="AUSGAB_1"/>{$i:=1000}<!--ordering in BLB K--></div>
          <div class="aDISMaske">{vl:raise-internal("Online-Katalog-Webseite wurde nicht erkannt.")}</div>
          <meta http-equiv="refresh">{$loginFormPost}</meta>    
          <a t:condition="contains(@href, '?')">{$loginFormPost}</a>
          <form>{$loginFormPost := form(.)}</form>
          <a>{$loginFormPost}</a>
        </t:switch></pattern>
        <s>$i := $i + 1</s>
    </loop>
    
  
  </if>  


  <page test="not(get('idpSystem'))" url="{$loginFormPost}"/>
  <s>$loginFormPost := ()</s>
  
  <if test="empty($error-login)">
    <pattern href="afterLogin"/>
  </if>
  <if test="exists($loginFormPost)"><page url="{$loginFormPost}"/></if>
</action>

<action id="internal-update-login">
  <s>connect-target := "account", connectPage := ()</s>
  <try>
    <page url="{$fullurl}" templateFile="connected"/>
    <page url="{$connectPage}" templateFile="connected"/>
    <catch errors="http:503"><s>vl:raise("Der Bibliothekskatalog ist momentan temporär nicht erreichbar. Vermutlich werden Wartungsarbeiten durchgeführt (insbesondere bei den VÖBB)")</s></catch>
  </try>
    
  <loop test="exists($loginForm)">
    <s>lf := $loginForm, loginForm := (), loginFormPost := ()</s>
    <page url="{$lf}">
      <template><t:switch prioritized="true">
        <input name="L#AUSW">{
          let $form := (ancestor::form)[1]
          return
          loginFormPost := form($form, ({"L#AUSW": $username, "LPASSW": $password}, $form//input[@type="submit" and contains(@name, "LOGIN")]) )
        }</input>
        <input name="$Textfield">{ loginFormPost := 
          let $form := (ancestor::form, //form)[1] (:Aalen has invalid html where the form is not an ancestor of the input:)
          let $buttons := $form//input[@type="submit" and matches(@value, "Anmeld|Login")]  
                          otherwise //input[@type="submit" and matches(@value, "Anmeld|Login")]
                          otherwise vl:raise-internal("Anmeldebutton nicht gefunden")
          return form($form, ({"$Textfield": $username, "$Textfield$0": $password}, $buttons[1])) } </input> 
        <input name="j_username">{ loginFormPost := let $form := (ancestor::form, //form)[1] return form($form, ({"j_username": $username, "j_password": $password}, ($form//*[@name="_eventId_proceed"])[1])),
                idpSystem := true() }</input> 
        <form><div class="message">Sind Sie Angehörige/r unserer Hochschule?
          <t:s> 
          if (trace($type,"TYPE") > 0) then loginForm := form(ancestor::form[1], (.//input[@type="submit" or @type="button"])[$type])
          else vl:raise-internal("Diese Bibliothek unterscheidet zwischen internen und externen Benutzern. In den Videlibri-Kontoeinstellungen muss dafür der richtige Benutzertyp ausgewählt werden.")
          </t:s>
        </div></form>
        <form><div class="message">vl:raise(.)</div></form>
        <form t:condition=" .//@name = ('_eventId_proceed', 'SAMLResponse', 'RelayState') ">
        { $loginFormPost := form(., (.//*[@name="_eventId_proceed"])[1]), $idpSystem := true() }
        </form>
        <h1>Ihre Sitzung wurde beendet.<t:s>error-login:=.</t:s></h1>
        <h1><strong>Mein Konto</strong>{error-login:="Ihre Sitzung wurde beendet. (3)"}</h1>
      </t:switch></template>
    </page>
  </loop>
  <call action="internal-login"/>
  <if test="$sessions-reconnects > 0 and normalize-space($error-login)!starts-with(., 'Ihre Sitzung wurde beendet')">
    <s>$sessions-reconnects := $sessions-reconnects - 1</s>
    <call action="internal-update-login"/>
  </if>
  <else><s>
  if (exists($error-login)) then vl:raise-login($error-login) 
  else $first-login := true()
  </s></else>
</action>

 
<action id="update-all">
  <call action="internal-update-login"/>
  
  <pattern href="accountOverview"/>

  <s>nextSplitTable := false(), $splitIndex := 1, $splitCount := 0, mode:="lend"</s>
  <if test="exists($kontoPage)">
    <page url="{$kontoPage}" templateFile="list"/>
    <loop test="$nextSplitTable">
      <page url="{$nextSplitTable}" templateFile="list"/>
      <s>$splitIndex := $splitIndex + 1, $nextSplitTable := ()</s>
      <if test="$splitIndex <= $splitCount">
        <page url="{$goBackPage}" templateFile="accountOverview"/>
        <page url="{$kontoPage}" templateFile="nextSplitTable"/>
      </if>
    </loop>
    <page url="{$goBackPage}" templateFile="accountOverview"/>
  </if>
  
  <if test="exists($orderedMagazinePage)">
    <s>mode:="orderedMagazine"</s>
    <page url="{$orderedMagazinePage}" templateFile="list"/>
    <page url="{$goBackPage}" templateFile="accountOverview"/>
  </if>
  
  <if test="exists($providedPage)">
    <s>mode:="provided"</s>
    <page url="{$providedPage}" templateFile="list"/>
    <page url="{$goBackPage}" templateFile="accountOverview"/>
  </if>

  <if test="exists($orderedPage)">
    <s>mode:="ordered"</s>
    <page url="{$orderedPage}" templateFile="list"/>
    <page url="{$goBackPage}" templateFile="accountOverview"/>
  </if>
  
  <if test="exists($requestedPage)">
    <s>mode:="requested"</s>
    <page url="{$requestedPage}" templateFile="list"/>
    <page url="{$goBackPage}" templateFile="accountOverview"/>
  </if>

</action>

<action id="renew-list">
  <s>mode:="lend"</s>
  <if test="not($splitCount)">
    <page url="{$kontoPage}" templateFile="list"/>
    <variable name="book-list">string-join(for $book in $renew-books return $book.extendData, "&amp;")</variable> 
    <page url="{$extendFormPost}"> <post value="{$book-list}"/> </page>    
  </if>
  <if test="$splitCount">
    <s>$renew-splits := distinct-values($renew-books ! (.)._splitIndex)</s>
    <loop var="splitIndex" list="$renew-splits">
      <page url="{$kontoPage}" templateFile="list"/>
      <page url="{$nextSplitTable}" templateFile="list"/>
      <variable name="book-list">string-join(for $book in $renew-books[(.)._splitIndex = $splitIndex] return $book.extendData, "&amp;")</variable> 
      <page url="{$extendFormPost}" templateFile="renewed"> <post value="{$book-list}"/> </page>    
      <page url="{$goBackPage}" templateFile="accountOverview"/>
    </loop>
  </if>
  <call action="update-all"/>
</action>



<action id="cancel-list">
  <loop var="mode" list="distinct-values($cancel-books ! (.)._mode)">
    <s>
    page := switch ($mode)
      case 'ordered' return $orderedPage
      case 'requested' return $requestedPage
      case 'orderedMagazine' return $orderedMagazinePage
      case 'provided' return $providedPage
      default return concat("unknown page ", $mode, "NEU AKTUALISIEREN")
    </s>
    <page url="{$page}"/>  
    <pattern><form>{
      cancelFormPost := form(., (.//input[@type = "submit" and contains(@value, "arkierte") and contains(@value, "schen")])[1]),
      cancelFormPost.post := replace($cancelFormPost.post, "[a-zA-Z0-9]+=on&", "")
    }</form></pattern>

  
    <variable name="book-list">string-join(for $book in $cancel-books[(.)._mode = $mode] return  $book.cancelData, "&amp;")</variable> 
    
    <page url="{$cancelFormPost}" templateFile="renewed">
      <post value="{$book-list}"/>
    </page>
    
    <page url="{$goBackPage}" templateFile="accountOverview"/>
  </loop>
  
  <call action="update-all"/>
</action>








 
<action id="gotoindex">
  <loop test="$firstIndex > $targetIndex">
    <page url="{$form.url}" templateFile="searchBasicForm">
      <post value="{$form.post}{$toolbarPostBackward}"/>
    </page>
  </loop>

  <loop test="$lastIndex &lt; $targetIndex and $targetIndex &lt;= $search-result-count-internal">
    <page url="{$form.url}" templateFile="search">
      <post value="{$form.post}{$toolbarPostForward}"/>
    </page>
    <pattern href="searchBasicForm"/>
  </loop>
  
</action>

<action id="search-connect">
  <call action="connect"/>
  <s>connect-target := "search", connectPage := ()</s>  
  <page url="{$fullurl}" templateFile="connected"/> 
  <!-- some libraries log in directly, some redirect -->
  <page url="{$connectPage}" templateFile="connected"/>
  
  <page url="{$searchPage}" templateFile="searchInputForm"/>
</action>

<action id="search">
  <if test="empty($searchPage)">
    <!-- go back to search form -->
    <call action="search-connect"/>
  </if> 
  
  <s>
  searchPage := (),
  lastSearchedIndex := lastSearchedIndexWithNavigation := 0,
  search-result-count := (),
  search-next-page-available := (), 
  gotDetails_GoBackPage := (),
  firstIndex := 1, lastIndex := 0,
  startSearch := form(//form, ({|
    { $search-basic-input-year: $book.year },
      for $key in jn:keys($book) where $book($key) and $search-basic-options($key) count $i
       return  {$search-basic-selects[$i]: $search-basic-options($key), $search-basic-inputs[$i]: $book($key)},
      for $key in jn:keys($book) where $book($key) and $search-filter-map($key) 
       return {$search-filter-map($key): $book($key)}
  |}, $search-start-button) )

  </s>

  <page url="{$startSearch}" templateFile="search"/>

  <page test="exists($gotDetails_GoBackPage)" url="{$gotDetails_GoBackPage}" templateFile="search"/>
  
  <if test="not($search-result-count = 0)">
    <pattern href="searchBasicForm"/>
  </if>
</action>

<action id="search-next-page">
  <variable>targetIndex := $lastSearchedIndex + 1, $goback := get('goback', ())</variable>
  <choose>
    <when test="$goback and $firstIndex &lt;= $targetIndex and $targetIndex &lt;= $lastIndex">
      <page url="{$goback}" templateFile="search"/>
      <pattern href="searchBasicForm"/>
    </when>
    <otherwise>
      <call action="gotoindex"/>
    </otherwise>
  </choose>
</action>


<action id="search-details">
  <variable name="targetIndex">$book._index * 1</variable> <call action="gotoindex"/>

  <s>form := request-combine($form, "selected=" || $book._searchId)</s>
  <page url="{$form}" templateFile="searchDetails"/>
  
  <page url="{$goback}" templateFile="searchBasicForm" test="not($search-result-count = '1')"/>
  
</action>




<action id="order-single">
  <variable name="targetIndex">$book._index * 1</variable> <call action="gotoindex"/>

  <s>form := request-combine($form, "selected=" || $book._searchId)</s>
  <call action="internal-order-single"/>
</action>

<action id="internal-order-single">
  <page url="{$form}"/>
  <pattern><form>{form:=form(., (.//input[@type = "submit" and contains(@value, "Bestell")])[1])}</form></pattern>
  
  <s>subBookOnly := false(), error := (), internal-loggedin := true()</s>
  <page url="{$form}" templateFile="orderConfirmation"/>    
  <if test="$subBookOnly"> 
    <page url="{$subBookOnly}"/>
    <pattern>
      <form>
        <t:switch-prioritized>
          <input title="Zurück zur vorherigen Seite">{backButtonName := uri-encode(@name)}</input>
          <input t:condition="contains(@title, 'zur vorherigen Seite')">{backButtonName := uri-encode(@name)}</input>
        </t:switch-prioritized> 
        {goBackPage := form(., x"{$backButtonName}.x=0&{$backButtonName}.y=0")}
        <div id="R06"><div class="aDISListe"><table>
          <tr><th>Band</th><td>{vl:choose("internal-order-volume", "Welcher Band soll bestellt werden?", a/substring(normalize-space(.), 1, 75), a/@href)}</td></tr> 
        </table></div></div>
      </form>
    </pattern>
  </if>
  
  <if test="not(get('internal-loggedin', false())) and not($subBookOnly) and not(exists($error))">
    <call action="internal-login"/>
    <if test="exists($error-login)">
      <s>error := $error-login</s>
      <pattern><form>{$goBackPage := form(., //input[@value="Abbrechen"])}</form></pattern> <!-- this only will lead back to the login page. but if there is a trefferliste-link like on voebb, internal-get-go-back-step will find its way -->
    </if>
    <else>
      <variable name="internal-loggedin">true()</variable>
      <variable name="form">$loginFormPost</variable>
      <pattern href="orderConfirmation"/>
      <if test="exists($error)"> <!-- it thinks the login confirmation is an error todo: is this still needed?-->
       <s>error:=()</s>
       <page url="{$form}" templateFile="orderConfirmation"/>
      </if>
    </else>
  </if>
  

  <if test="$error">
    <call action="internal-get-go-back-step"/>
    <page url="{$goBackPage}" templateFile="searchBasicForm"/>
    <s>vl:raise($error)</s>
  </if>

</action>

<action id="internal-get-go-back-step">
  <page url="{$goBackPage}"/>
  <pattern href="goBackToSearchList"/>
</action>

 
<action id="internal-order-volume">
  <if test="$choose-result instance of xs:decimal">
    <page url="{$goBackPage}" templateFile="searchBasicForm"/>
  </if>
  <if test="$choose-result instance of xs:string">
    <s>form := $choose-result</s>
    <call action="internal-order-single"/>
  </if>
</action>


<action id="internal-order-confirmed">
  <if test="$choose-result instance of xs:decimal">
    <call action="internal-get-go-back-step"/>
    <page url="{$goBackPage}" templateFile="searchBasicForm"/>
  </if>

  <if test="$choose-result instance of xs:string">
    <variable name="form">
    {
      "url": $form.url,
      "method": $form.method,
      "post": replace($form.post, "_DESTINATIONFILLER_", $choose-result)
    }
    </variable>  
    
    <s>oldmessage:=(), final-form := ()</s>
    <page url="{$form}" templateFile="orderConfirmed"/>
    <page url="{$form}" templateFile="orderConfirmed"/>
    <if test="empty($final-form)"><pattern href="orderFailed"/></if>
    <page url="{$final-form}"/>

    <pattern href="goBackToSearchList"/>
    <page url="{$goBackPage}" templateFile="searchBasicForm"/>

    <s>if (empty($error)) then book.statusId := "ordered"
       else vl:raise($error)
    </s>
  </if>
</action>

<action id="catalogue">
  <call action="connect"/>
  <variable name="url" value="{$fullurl}"/>
</action>



</actions>
