<actions>

<meta>
  <description lang="de">Schnittstelle für Bibliotheca+ (OPEN)</description>
  <description lang="en">Interface for Bibliotheca+ (OPEN)</description>
  <variable name="urlaccount">
    <description lang="de">Vollständige URL der Seite für den Kontozugriff 
(beginnt mit "http" und endet meistens mit "Konto" oder "Konto.aspx")</description>
    <description lang="en">URL to access a library account</description>
  </variable>
  <variable name="urlsearch">
    <description lang="de">Vollständige URL der Seite für die erweiterte Suche 
(beginnt mit "http" und endet meistens mit "Erweiterte-Suche" oder "Erweiterte-Suche.aspx")</description>
    <description lang="en">URL for the advanced search in the library OPAC</description>
  </variable>
</meta>

<action id="connect"></action>
<action id="internal-login">
  <page url="{$urlaccount}">
    <template><form>{
      let $names := //input/@name[contains(., "login")]
      return
      loginForm := form(., {"__EVENTTARGET": ($names[ends-with(., "cmdLogin")])[1], 
                            ($names[ends-with(., "txtUsername")])[1]: $username, 
                            ($names[ends-with(., "txtPassword")])[1]: $password,
                            "": {"kind": "submit"}  })
    }</form></template>
  </page>
</action>
<!--

}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}-->

<action id="update-all">
  <s>pendingLoginError := (), all-copyIds := (), last-extendable-check := ()</s>
  <call action="internal-login"/>
  <page url="{$loginForm}"><template><html>{
    for $message in //span[ends-with(@id, "lblMessage")][ancestor::div[ends-with(@id, "Login_UP") or contains(@class, "dnnFormValidationSummary")]] 
    return $pendingLoginError := normalize-space($message)
  }</html></template></page>
  <page url="{$urlaccount}" templateFile="list"/>
</action>

<action id="update-single"> <!--todo: parallize? -->
  <if test="exists($book._copyId)">
    <s>$info := $last-extendable-check[?CopyId = $book._copyId]</s>
    <if test="empty($info)">
      <json url="{$extendableCheck}">
        <header>Accept: application/json, text/javascript, */*; q=0.01</header>
        <header>Content-Type: application/json;charset=utf-8</header>
        <header>X-Requested-With: XMLHttpRequest</header>
        <post>{{'portalId':'{$portalId}', 'userName': '{$userRndId}', 'copyId': '{$book._copyId}', 'copyIds': '{if ($book._copyId = $all-copyIds) then join($all-copyIds, ",") else $book._copyId}', 'culture':'{$culture}', 'localResourceFile':'{$localResourceFile}'}}</post>
        <!-- answer looks like: {"d":{"__type":"OCLC.OPEN.PL.DNN.PatronAccountModule.PatronAccountService+ExtendableResponse","IsExtendable":false,"StatusMessages":"(Verlängerungsintervall ist auf 0 Tage eingestellt) Bitte wenden Sie sich an die Bibliothek."}}-->
      </json>
      <s>
      let $d := $json?d return 
      if ($json?d instance of array()) then (
        $last-extendable-check := $d?*,
        $info := $last-extendable-check[?CopyId = $book._copyId]
      ) else $info := $d
      </s>
    </if>
    <s>
    if ($info.IsExtendable) then (book.status := $info.ExtendText[.]!concat("Info: ", .), book.statusId := "curious")
    else (book.status := $info.StatusMessages, book.statusId := "critical")
    </s>
  </if>
<!-- on the webpage:
            var copyId = $(this).find('input[name$="CopyId"]').attr('value');
            var culture = regC.find('input[name$="Culture"]').attr('value');
            var regChk = $('.checkboxRegion:has(input[name$="CopyIdChx"][value="' + copyId + '"])')
            var chk = regChk.find('input[name$="chkSelect"]');
            $.ajax({ type: "POST", url: "/DesktopModules/OCLC.OPEN.PL.DNN.PatronAccountModule/PatronAccountService.asmx/IsCatalogueCopyExtendable", contentType: "application/json;charset=utf-8", dataType: "json",
                data: "{'portalId':'1', 'userName':'----username---', 'copyId':'" + copyId + "', 'culture':'" + culture + "', 'localResourceFile':'/DesktopModules/OCLC.OPEN.PL.DNN.PatronAccountModule/App_LocalResources/NormalView'}",
-->
</action>



<action id="renew-list">
  <s>if (exists($renew-button)) then 
      form := form-combine($user-form, ($renew-books  ! {(.)._renewid: "on"}, $renew-button) ) 
    else 
      vl:raise-internal("Verlängerungsbutton nicht gefunden. Vielleicht ist die Karte abgelaufen.")
  </s>
  <page url="{$form}" templateFile="renew"/> <!-- this returns all of update-all list again-->
  <page url="{$confirm-form}"/> <!-- this returns all of update-all list again-->
  <call action="update-all"/>
</action>

<action id="cancel-list"> <!-- this is murks -->
  <if test="exists($cancel-books[(.).statusId eq 'ordered'])">
    <s>form := form-combine($user-form, ($cancel-books[(.).statusId eq 'ordered'] ! {(.)._cancelid: "on"}, $cancel-ordered-button) ) </s>
    <page url="{$form}" templateFile="list"/> <!-- this returns all of update-all list again, but we only need the user-form (other stuff is irrelevant?)-->
  </if>
  <if test="exists($cancel-books[(.).statusId eq 'provided'])">
    <s>form := form-combine($user-form, ($cancel-books[(.).statusId eq 'provided'] ! {(.)._cancelid: "on"}, $cancel-provided-button) ) </s>
    <page url="{$form}"  templateFile="list"/> <!-- this returns all of update-all list again-->
    <!--    <call action="update-all"/> does not do anything??-->
  </if>
</action>



<action id="gotopage">
  <loop test="$current-page > $target-page">
    <s>$current-page := $current-page - 1</s>
    <page url="{$prev-page}" templateFile="searchListHeaderOnly"/>
  </loop>

  <loop test="$current-page < $target-page and $target-page <= $last-visited-page">
    <s>$current-page := $current-page + 1</s>
    <page url="{$next-page}" templateFile="searchListHeaderOnly"/>
  </loop>
  
  <loop test="$current-page < $target-page">
    <s>$current-page := $current-page + 1, $last-visited-page := $current-page</s>
    <page url="{$next-page}" templateFile="searchList"/>
  </loop>  
</action>

<action id="search-connect">
  <s>loggedIn := false()</s>
  <page url="{$urlsearch}"/>
  <pattern><form>{
    search-form := form(., (.//input[@name[contains(., "BtnSearch") and not(contains(., "SearchSlot"))]])[1]  ), 
    search-fields := .//select[contains(@name, "SearchField")]/@name,
    search-values := .//input[contains(@name, "SearchValue")]/@name,
    search-year-values := .//input[contains(@name, "Year")]/@name,
    let $selects := //select
    let $names := {"libraryBranch": "BranchValue", "mediaType": "MediaGroupValue"}
    return (    
    select-map := map:merge(for $key in map:keys($names) return {$key:$selects[ends-with(@name, $names($key))]}),
    search-params := (  "title", "author", "free", "keywords", "year", "isbn", 
      map:keys($select-map)!{"name": ., "options": $select-map(.)//option}
    )
    )
  }</form></pattern>
</action>

<action id="search">
    
    <s>   current-page := 1, last-visited-page := 1, next-page := (),
          search-keys := {"title": "Title", "author": "Author", "free": "Free", "keywords": "Keyword", "isbn": "ISBNandISSN"},
          search-reverse-keys := {"Publisher": "publisher", "ProductionYear": "year", "Author": "author", "IsbnTitle": "isbn", "1stIsbnTitle": "isbn", "Free": "free"},
          startSearch := form-combine($search-form, {|
            $search-year-values ! { .: $book.year },
            for $key in map:keys($book) 
             where $book($key) and $search-keys($key) 
             count $i 
             where $i le count($search-fields)
             return {$search-fields[$i] : $search-keys($key), $search-values[$i]:  $book($key)},
            for $key in jn:keys($book)
             where $book($key) and $select-map($key)
             return {$select-map($key)/@name: $book($key)}
          |})
    </s>
    <page url="{$startSearch}" templateFile="searchList"/>
</action>

<action id="search-next-page">
  <s>$target-page := $last-visited-page + 1</s>
  <call action="gotopage"/>
</action>

<action id="internal-gotobookpage">
  <s>target-page := $book._page</s>
  <call action="gotopage"/>
  <s>combined-detail-form := if (starts-with($book._detailId, "http")) then $book._detailId else form-combine($form, {'__EVENTTARGET': $book._detailId})</s>
  <page url="{$combined-detail-form}" templateFile="searchDetails"/>
  <page url="{$book._volumeFirst}" templateFile="searchDetails"/>
</action>

<action id="search-details">
  <!--<s>temp := if (not(exists($next-page))) then () 
             else if (contains($book._detailsBackScroll, "scrollAction=")) then $book._detailsBackScroll
             else $book._detailsBackScroll || "?scrollAction=1"
  </s>
  <page url="{$temp}"/>-->
  <call action="internal-gotobookpage"/>
</action>

<action id="order-single"> 
  <if test="not(get('loggedIn', false()))">
    <s>urlaccount := $loginlink</s> <!-- need to use login form from search page, tp  -->
    <call action="internal-login"/>
    <page url="{$loginForm}" templateFile="searchListHeaderOnly"/>
<!--    <s>temp := if (matches($loginlink, "returnurl=")) then uri-decode(extract($loginlink, "returnurl=(.*)", 1)) else $loginForm</s>-->
    <page url="{$loginForm}" templateFile="searchListHeaderOnly"/>
    <s>loggedIn := true()</s>
  </if>
  <s>need-reserve-request-target := (get("holding",())[1]("_orderTarget"), $book._orderTarget)[.]</s>
  <call action="internal-gotobookpage"/>
  <s>need-reserve-request-target := ()</s>
  <page urL="{$reserve-request}"><template>
    <t:switch prioritized="true">
      <form><t:element t:condition='matches(@name||@id, "btnSave|btnConfirm", "i")'>{$input}</t:element>{$form := form(., $input)}</form>
      <div t:condition='matches(@id, "dnnSkinMessage|DivWaring")'>{vl:raise(.)}</div>
    </t:switch>
  </template></page>
 <page urL="{$form}"/>
</action> 



<action id="catalogue">
  <variable name="url" value="{$urlaccount}"/>
</action>
</actions>
