<?php
  $account = $this->auth()->getManager(); 
  $coverDetails = $this->record($this->driver)->getCoverDetails('result-list', 'medium', $this->recordLink()->getUrl($this->driver));
  $cover = $coverDetails['html'];
  $thumbnail = false;
  $thumbnailAlignment = $this->record($this->driver)->getThumbnailAlignment('result');
  $eBook = in_array("eBook",$this->driver->getFormats()) ? true  : false; 
  $accessRestrictions =  $this->driver->getAccessRestrictions();
  $itemNote = "check in eBook platform after login";
  if ($cover):
    ob_start(); ?>

  <?php    // Create links to place a hold or recall an item 
	$offlineMode = $this->ils()->getOfflineMode();
    try {
        $holdings = $this->driver->getRealTimeHoldings();
    } catch (\VuFind\Exception\ILS $e) {
        $holdings = ['holdings' => []];
        $offlineMode = 'ils-offline';
    }
    $availableLinks = [] ;
    $checkedOutLinks = [] ;
    if (strcmp($offlineMode,'ils-offline') != 0)  {

        foreach ($holdings['holdings'] as $holding)  {
            foreach ($holding['items'] as $row)   {
		if (strcmp($row['status'],'status_in_acquisition') != 0 && strcmp($row['status'],'status_internal_administration') != 0 )   {
 	               if (strtolower($row['reserve']) == 'x')   continue;
	                if (! isset($row['barcode']) || $row['barcode'] == "") continue;
	                if (! isset($row['link']) || $row['link'] == '')        continue;
		}
		if ($eBook) {
			if (isset($row['item_notes']))  {
				$itemNote = $row['item_notes']; 
			}
		}
                $check = isset($row['check']) && $row['check'];
		if (strcmp($row['status'], "status_internal_administration") != 0 && strcmp($row['status'],'status_internal_administration') != 0 )  {
                        $link = ' class="';
                        if ($check) $link .= 'checkRequest ';
                        $link .= 'placehold" ' ;
                        if (!empty($row['linkLightbox'])) $link .= 'data-lightbox ';
                        $link .= "href=\""  .$this->recordLink()->getRequestUrl($row['link']) ."\">";
                        if ($check) {
                                $link .= $this->transEsc("Check Hold") ;
                          } else {
                                if (strcmp($row['status'], "Available") == 0)  {
                                        $link .= $this->transEsc("Place a Hold") ;
                                        $availableLinks[] = $link ;
                                  } else {
                                        $link .= $this->transEsc("Recall This") ;
                                        $checkedOutLinks[] = $link ;
                                }
                        }
		}
           }
	}
    }
  ?>


    <div class="media-<?=$thumbnailAlignment ?> <?=$this->escapeHtmlAttr($coverDetails['size'])?>">
      <?=$cover ?>
    </div>
    <?php $thumbnail = ob_get_contents(); ?>
  <?php ob_end_clean(); ?>
<?php endif; ?>
<input type="hidden" value="<?=$this->escapeHtmlAttr($this->driver->getUniqueID())?>" class="hiddenId" />
<input type="hidden" value="<?=$this->escapeHtmlAttr($this->driver->getSourceIdentifier())?>" class="hiddenSource" />
<div class="media">
  <?php if ($thumbnail && $thumbnailAlignment == 'left'): ?>
    <?=$thumbnail ?>
  <?php endif ?>
  <div class="media-body">
    <div class="result-body">

        <div class="title-container">
            <a href="<?=$this->recordLink()->getUrl($this->driver)?>" class="title getFull" data-view="<?=$this->params->getOptions()->getListViewOption() ?>">
            <?=$this->record($this->driver)->getTitleHtml()?>
	    <?php $subTitle = $this->driver->getTitleSection(); ?>
            <?php if (!empty($subTitle)): ?>
		<br> <?=$subTitle?>
            <?php endif; ?>
	    </a>
        </div>

        <div class="author">
            <?php $summAuthors = $this->driver->getPrimaryAuthorsWithHighlighting(); if (!empty($summAuthors)): ?>
                <?=$this->transEsc('by')?>
                <?php $authorCount = count($summAuthors); foreach ($summAuthors as $i => $summAuthor): ?>
                    <a href="<?=$this->record($this->driver)->getLink('author', $this->highlight($summAuthor, null, true, false))?>"><?=$this->highlight($summAuthor)?></a><?=$i + 1 < $authorCount ? ';' : ''?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <table width="99%">
            <tr>
                <th width="35%"></th>
                <td width="20%"></td>
                <td width="15%"></td>
                <td width="*"></td>
            </tr>
            <tbody class="result-table">
            <tr>
                <th><?=$this->transEsc("Format")?></th>
                <th><?=$this->transEsc("Stock")?></th>
                <th><?=$this->transEsc('Call Number')?></th>
                <th><?=$this->transEsc("Availability")?></th>
            </tr>
            <tr>
		<?php // $format = $this->driver->getFormats(); print_r($format) ; ?> 
		<?php $eBook = in_array("eBook",$this->driver->getFormats()) ? true  : false ?>
                <td><?=$this->record($this->driver)->getFormatList() ?></td>
                <td> <img src="/vufind/themes/bibb/images/BIBB_library_small.png"> </td>

                <td>
                    <?php $summCallNo = $this->driver->getCallNumber(); if (!empty($summCallNo)): ?>
                        <?=$this->escapeHtml($summCallNo)?>
                    <?php endif; ?>
                </td>

                <td>
                    <?php if (!$eBook && !$openUrlActive && empty($urls) && $this->driver->supportsAjaxStatus() ): ?>
                        <span class="status ajax-availability hidden">
                       		<span class="label label-default"><?=$this->transEsc('Loading')?>...</span>
                        </span>
		    <?endif ; ?>
		    <?php if ($eBook) : ?>
			<?=$this->transEsc($itemNote)?>
                    <?php endif; ?>
                </td>
            </tr>
	  </tbody>
        </table>

      <div class="published">
        <?php if($this->driver->isCollection()): ?>
          <?=implode('<br>', array_map(array($this, 'escapeHtml'), $this->driver->getSummary())); ?>
        <?php else: ?>

          <?php $journalTitle = $this->driver->getContainerTitle(); $summDate = $this->driver->getPublicationDates(); ?>
          <?php if (!empty($journalTitle)): ?>
            <?=!empty($summAuthor) ? '<br />' : ''?>
            <?=$this->transEsc('Published in')?>
            <?php $containerSource = $this->driver->getSourceIdentifier(); ?>
            <?php $containerID = $this->driver->getContainerRecordID(); ?>
            <?php /* TODO: handle highlighting more elegantly here: */?>
            <a href="<?=($containerID ? $this->recordLink()->getUrl("$containerSource|$containerID") : $this->record($this->driver)->getLink('journaltitle', str_replace(array('{{{{START_HILITE}}}}', '{{{{END_HILITE}}}}'), '', $journalTitle)))?>"><?=$this->highlight($journalTitle) ?></a>
            <?=!empty($summDate) ? ' (' . $this->escapeHtml($summDate[0]) . ')' : ''?>
          <?php elseif (!empty($summDate)): ?>
            <?=!empty($summAuthor) ? '<br />' : ''?>
            <?=$this->transEsc('Published') . ' ' . $this->escapeHtml($summDate[0])?>
          <?php endif; ?>
          <?php $summInCollection = $this->driver->getContainingCollections(); if (!empty($summInCollection)): ?>
            <?php foreach ($summInCollection as $collId => $collText): ?>
              <div>
                <b><?=$this->transEsc("in_collection_label")?></b>
                <a class="collectionLinkText" href="<?=$this->url('collection', array('id' => $collId))?>?recordID=<?=urlencode($this->driver->getUniqueID())?>">
                  <?=$this->escapeHtml($collText)?>
                </a>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        <?php endif; ?>
      </div>

      <?php if(!$this->driver->isCollection()): ?>
        <?php if ($snippet = $this->driver->getHighlightedSnippet()): ?>
          <?php if (!empty($snippet['caption'])): ?>
            <strong><?=$this->transEsc($snippet['caption']) ?>:</strong> ';
          <?php endif; ?>
          <?php if (!empty($snippet['snippet'])): ?>
            <span class="quotestart">&#8220;</span>...<?=$this->highlight($snippet['snippet']) ?>...<span class="quoteend">&#8221;</span><br/>
          <?php endif; ?>
        <?php endif; ?>
      <?php endif; ?>

      <?
      /* Display information on duplicate records if available */
      if ($dedupData = $this->driver->getDedupData()): ?>
        <div class="dedupInformation">
        <?
          $i = 0;
          foreach ($dedupData as $source => $current) {
            if (++$i == 1) {
              ?><span class="currentSource"><a href="<?=$this->recordLink()->getUrl($this->driver)?>"><?=$this->transEsc("source_$source", array(), $source)?></a></span><?
            } else {
              if ($i == 2) {
                ?> <span class="otherSources">(<?=$this->transEsc('Other Sources')?>: <?
              } else {
                ?>, <?
              }
              ?><a href="<?=$this->recordLink()->getUrl($current['id'])?>"><?=$this->transEsc("source_$source", array(), $source)?></a><?
            }
          }
          if ($i > 1) {
            ?>)</span><?
          }?>
        </div>
      <?php endif; ?>

      <?php /* We need to find out if we're supposed to display an OpenURL link ($openUrlActive),
            but even if we don't plan to display the link, we still want to get the $openUrl
            value for use in generating a COinS (Z3988) tag -- see bottom of file.
          */
        $openUrl = $this->openUrl($this->driver, 'results');
        $openUrlActive = $openUrl->isActive();
        // Account for replace_other_urls setting
        $urls = $this->record($this->driver)->getLinkDetails($openUrlActive);

        if ($openUrlActive || !empty($urls)): ?>
        <?php if ($openUrlActive): ?>
          <br/>
          <?=$openUrl->renderTemplate()?>
        <?php endif; ?>
        <?php if (!is_array($urls)) $urls = array();
		if(!$this->driver->isCollection()):
			foreach ($urls as $current): ?>
				<?php if (strncmp("https://bibb-dspace.bibb.de/jspui/handle/BIBB", $current['url'], strlen("https://bibb-dspace.bibb.de/jspui/handle/BIBB")) == 0)    continue; ?>

        	          	<?php if (strncmp($current['url'],"http://dispatch.opac.d-nb.de/", strlen("http://dispatch.opac.d-nb.de/")) == 0) : ?>
         				<?php $title = $this->driver->getMainTitle();  
        	   		   	   if (strpos($title,':') !== false) { 
							$title = trim(strstr($title,":", true));
					   } ?>	
         				<?php $current['url'] = "https://zdb-katalog.de/list.xhtml?t=" .urlencode("\"" .$title ."\"")  ."&key=tit" ; ?>
         				<?php $current['desc'] = "\"" .$title ."\" in der ZDB"; ?>
        		  	<?php endif; ?>

				<?php if (($start = strpos($this->proxyUrl($current['url']), "(")) !== false) : ?> 
				     <a href="<?=$this->escapeHtmlAttr(trim(substr($this->proxyUrl($current['url']),0, $start-1)))?>" class="fulltext" target="new"><i class="fa fa-external-link" aria-hidden="true"></i> <?=($current['url'] == $current['desc']) ? $this->transEsc(trim(substr($this->proxyUrl($current['url']),$start+1,strlen($this->proxyUrl($current['url']))-($start+2)))) : $this->escapeHtml($current['desc'])?></a><br/>
				<?php endif; ?>   

				<?php $LoginRequired = false ; ?>
					<?php if (((strpos($current['url'],"search.ebscohost.com/login.aspx") !== false) || (strpos($current['url'], "econtent.hogrefe.com")) !== false || strpos($current['url'],"research.ebsco.com/")) !== false || strlen($accessRestrictions[0]) > 0) : ?>
        				<?php $LoginRequired = true ;  ?>
    				<?php endif; ?>

    				<?php if (($LoginRequired == true) && ! $account->isLoggedIn()) : ?>
            				<?=$this->escapeHtml($current['desc'])?> &nbsp; &nbsp;
     				   <?php else: ?>
            				<a href="<?=$this->escapeHtmlAttr(trim($this->proxyUrl($current['url'])))?>" target="_blank"><?=$this->escapeHtml($current['desc'])?></a> &nbsp; &nbsp;
    				<?php endif; ?>
			<?php endforeach; ?>
		<?php endif; ?>
      <?php endif; ?>

      <div class="result-previews">
        <?=$this->record($this->driver)->getPreviews()?>
      </div>
    </div>

      <div class="add-result">
          <div class="favorites">
              <?php if ($this->userlist()->getMode() !== 'disabled'): ?>
                  <?php /* Add to favorites */ ?>
                  <a href="<?=$this->recordLink()->getActionUrl($this->driver, 'Save')?>" data-lightbox class="save-record result-link-label" data-id="<?=$this->escapeHtmlAttr($this->driver->getUniqueId()) ?>"><?=$this->transEsc('Add to favorites')?></a>
                  <i class="result-link-icon fa fa-fw fa-star" aria-hidden="true"></i><br/>
                  <?php /* Saved lists */ ?>
                  <div class="savedLists">
                      <strong><?=$this->transEsc("Saved in")?>:</strong>
                  </div>
              <?php endif; ?>
          </div>

          <div class="result-links hidden-print">
              <?php /* Display qrcode if appropriate: */ ?>
              <?php if ($QRCode = $this->record($this->driver)->getQRCode("results")): ?>
                  <?
                  // Add JS Variables for QrCode
                  $this->jsTranslations()->addStrings(array('qrcode_hide' => 'qrcode_hide', 'qrcode_show' => 'qrcode_show'));
                  ?>
                  <span class="hidden-xs">
          <a href="<?=$this->escapeHtmlAttr($QRCode);?>" class="qrcodeLink"><?=$this->transEsc('qrcode_show')?></a><i class="fa fa-fw fa-qrcode" aria-hidden="true"></i>
          <div class="qrcode hidden">
            <script type="text/template" class="qrCodeImgTag">
              <img alt="<?=$this->transEsc('QR Code')?>" src="<?=$this->escapeHtmlAttr($QRCode);?>"/>
            </script>
          </div><br/>
        </span>
              <?php endif; ?>

              <?php if ($this->cart()->isActiveInSearch() && $this->params->getOptions()->supportsCart() && $this->cart()->isActive()): ?>
                  <?=$this->render('record/cart-buttons.phtml', ['id' => $this->driver->getUniqueId(), 'source' => $this->driver->getSourceIdentifier()]); ?><br/>
              <?php endif; ?>



              <?php /* Hierarchy tree link */ ?>
              <?php $trees = $this->driver->tryMethod('getHierarchyTrees'); if (!empty($trees)): ?>
                  <?php foreach ($trees as $hierarchyID => $hierarchyTitle): ?>
                      <div class="hierarchyTreeLink">
                          <input type="hidden" value="<?=$this->escapeHtmlAttr($hierarchyID)?>" class="hiddenHierarchyId" />

                          <a class="hierarchyTreeLinkText result-link-label" data-lightbox href="<?=$this->recordLink()->getTabUrl($this->driver, 'HierarchyTree')?>?hierarchy=<?=urlencode($hierarchyID)?>#tabnav" title="<?=$this->transEsc('hierarchy_tree')?>" data-lightbox-href="<?=$this->recordLink()->getTabUrl($this->driver, 'AjaxTab')?>?hierarchy=<?=urlencode($hierarchyID)?>" data-lightbox-post="tab=hierarchytree">
                              <?=$this->transEsc('hierarchy_view_context')?><?php if (count($trees) > 1): ?>: <?=$this->escapeHtml($hierarchyTitle)?><?php endif; ?>
                          </a>
                          <i class="result-link-icon fa fa-fw fa-sitemap" aria-hidden="true"></i>
                      </div>
                  <?php endforeach; ?>
              <?php endif; ?>


  <?php //Display Links to place a hold or to recall an item ?>
  <?php if (!$eBook) : ?>
  	<?php if (!empty($availableLinks)) : ?>
    		</br>
    		<a <?=$availableLinks[0] ?> </a><i class="fa fa-book fa-lg" style="color:#44801e;"></i>
  	<?endif; ?>
  	<?php if (empty($availableLinks) && !empty($checkedOutLinks)) : ?>
    		</br>
    		<a <?=$checkedOutLinks[0] ?> </a><i class="fa fa-book fa-lg" style="color:#44801e;"></i>
  	<?endif; ?>
  <?php endif ; ?>

              <?=$this->driver->supportsCoinsOpenUrl()?'<span class="Z3988" title="'.$this->escapeHtmlAttr($this->driver->getCoinsOpenUrl()).'"></span>':''?>
          </div>
      </div>
  </div>
  <?php if ($thumbnail && $thumbnailAlignment == 'right'): ?>
    <?=$thumbnail ?>
  <?php endif ?>
</div>
