<?
  // Set page title.
  $this->headTitle($this->translate('Advanced Search'));

  // Disable top search box -- this page has a special layout.
  $this->layout()->searchbox = false;

  // Set up breadcrumbs:
  $this->layout()->breadcrumbs = '<li>';
  $lastSearchLink = $this->searchMemory()->getLastSearchLink($this->transEsc('Search'));
  $this->layout()->breadcrumbs .= !empty($lastSearchLink)
    ? $lastSearchLink : $this->transEsc('Search');
  $this->layout()->breadcrumbs .= '</li> <li class="active">' . $this->transEsc('Advanced') . '</li>';

  // Set up saved search details:
  if (isset($this->saved) && is_object($this->saved)) {
    $searchDetails = $this->saved->getParams()->getQuery();
    if ($searchDetails instanceof \VuFindSearch\Query\Query) {
        // Not an advanced query -- ignore it.
        $searchDetails = $groups = false;
    } else {
        $groups = $searchDetails->getQueries();
    }
    $hasDefaultsApplied = $this->saved->getParams()->hasDefaultsApplied();
    $searchFilters = $this->saved->getParams()->getFilterList();
    $hiddenFilters = $this->saved->getParams()->getHiddenFilters();
  } else {
    $hasDefaultsApplied = $searchDetails = $searchFilters = $groups = false;
    $hiddenFilters = $this->searchtabs()->getHiddenFilters($this->searchClassId, true);
  }

  // Step 1: Load the javascript
  $this->headScript()->appendFile(
    isset($this->advancedSearchJsOverride) ? $this->advancedSearchJsOverride : 'advanced_search.js'
  );
  // Step 2: Build the page
  $this->headScript()->appendScript(
    $this->partial(
      isset($this->buildPageOverride) ? $this->buildPageOverride : 'search/advanced/build_page.phtml',
      ['options' => $this->options, 'searchDetails' => $searchDetails]
    )
  );

  // Collect previous search queries
  $setSearchGroups = [];
  $setGroupCount = 0;
  $setQueries = [];
  if (isset($searchDetails) && is_object($searchDetails)) {
    foreach ($searchDetails->getQueries() as $group=>$searchGroup) {
      $setSearchGroups[$group] = $searchGroup->isNegated() ? 'NOT' : $searchGroup->getOperator();
      if ($setGroupCount < $group) {
        $setGroupCount = $group;
      }
      if (!isset($setQueries[$group])) {
        $setQueries[$group] = [];
      }
      foreach ($searchGroup->getQueries() as $search) {
        $setQueries[$group][] = $search;
      }
    }
  }
?>

<?=$this->flashmessages()?>
<div role="search">
  <form name="searchForm" id="advSearchForm" method="get" action="<?=$this->url($this->options->getSearchAction())?>">
    <? foreach ($hiddenFilters as $key => $filter): ?>
      <? foreach ($filter as $value): ?>
        <input type="hidden" name="hiddenFilters[]" value="<?=$this->escapeHtmlAttr($key) . ':' . $this->escapeHtmlAttr($value)?>" />
      <? endforeach; ?>
    <? endforeach; ?>
    <div class="<?=$this->layoutClass('mainbody')?>">
      <? $lastSort = $this->searchMemory()->getLastSort($this->searchClassId); ?>
      <? if (!empty($lastSort)): ?>
        <input type="hidden" name="sort" value="<?=$this->escapeHtmlAttr($lastSort)?>" />
      <? endif; ?>
      <div class="clearfix">
        <h2 class="pull-left flip"><?=$this->transEsc('Advanced Search')?></h2>
        <div id="groupJoin" class="form-inline pull-right flip">
          <label for="groupJoinOptions"><?=$this->transEsc("search_match")?>:</label>
          <select id="groupJoinOptions" name="join" class="form-control">
            <option value="AND"<? if($searchDetails && $searchDetails->getOperator()=='ALL'):?> selected<?endif?>><?= $this->transEsc('group_AND') ?></option>
            <option value="OR"<? if($searchDetails && $searchDetails->getOperator()=='OR'):?> selected<?endif?>><?= $this->transEsc('group_OR') ?></option>
          </select>
        </div>
      </div>
        <div class="advanced-and-buttons">
      <span id="groupPlaceHolder" class="hidden">
        <i class="fa fa-plus-circle" aria-hidden="true"></i>
        <a href="#" onClick="addGroup();return false"><?= $this->transEsc('add_search_group') ?></a>
      </span>
      <? /* fallback to a fixed set of search groups/fields if JavaScript is turned off */ ?>
      <div class="no-js">
        <? if(!empty($this->formOverride)): ?>
          <?=$this->formOverride ?>
        <? else: ?>
          <? for($group=0 ; $group<3 || $group<=$setGroupCount ; $group++): ?>
            <? if($group == 0): ?>
              <div id="new_group_template">
            <? endif; ?>
            <div id="group<?=$group ?>" class="adv-group">
              <div class="adv-group-terms">
                <label class="adv-group-label"><?=$this->transEsc("adv_search_label")?>:</label>
                <? for($search=0 ; $search<3 || (isset($setQueries[$group]) && $search<count($setQueries[$group])) ; $search++): ?>
                  <? if($group == 0 && $search == 0): ?>
                    <div id="new_search_template">
                  <? endif; ?>
                  <div id="search<?=$group.'_'.$search ?>" class="adv-search">
                    <input name="lookfor<?=$group ?>[]" id="search_lookfor<?=$group.'_'.$search ?>" class="adv-term-input form-control" type="text"<?if(isset($setQueries[$group][$search])):?> value="<?=$this->escapeHtml($setQueries[$group][$search]->getString())?>"<?endif;?>>
                    <select class="adv-term-type form-control" name="type<?=$group ?>[]">
                      <? foreach ($this->options->getAdvancedHandlers() as $searchVal => $searchDesc): ?>
                        <option value="<?=$this->escapeHtml($searchVal)?>"<?if(isset($setQueries[$group][$search]) && $searchVal == $setQueries[$group][$search]->getHandler()):?> selected<?endif;?>><?=$this->transEsc($searchDesc)?></option>
                      <? endforeach; ?>
                    </select>
                    <a href="#" class="adv-term-remove hidden"></a>
                  </div>
                  <? if($group == 0 && $search == 0): ?>
                      </div>
                    <span class="float-left">
                      <i class="fa fa-plus-circle search_place_holder hidden" aria-hidden="true"></i>
                      <a href="#" class="add_search_link hidden"><?=$this->transEsc("add_search")?></a>
                    </span>
                  <? endif; ?>
                <? endfor; ?>
              </div>
              <div class="adv-group-match">
                <label class="search_bool"><?=$this->transEsc("search_match")?>:&nbsp;</label>
                <select name="bool<?=$group ?>[]" id="search_bool<?=$group ?>" class="form-control">
                  <option value="AND"<? if(isset($setSearchGroups[$group]) && 'AND' == $setSearchGroups[$group]):?> selected<?endif;?>><?=$this->transEsc("search_AND")?></option>
                  <option value="OR"<? if(isset($setSearchGroups[$group]) && 'OR' == $setSearchGroups[$group]):?> selected<?endif;?>><?=$this->transEsc("search_OR")?></option>
                  <option value="NOT"<? if(isset($setSearchGroups[$group]) && 'NOT' == $setSearchGroups[$group]):?> selected<?endif;?>><?=$this->transEsc("search_NOT")?></option>
                </select>
              </div>
              <a href="#" class="adv-group-close hidden"><i class="fa fa-close"></i> <?=$this->transEsc("del_search")?></a>
            </div>
            <? if($group == 0): ?>
              </div>
            <? endif; ?>
          <? endfor; ?>
        <? endif; ?>
      </div>
      <div class="adv-submit">
        <input class="clear-btn btn btn-default" type="button" value="<?= $this->transEsc('Clear')?>">
	<span style="padding-left: 17em; vertical-align:baseline;"> </span>
                    <input type="checkbox" <?=$isSelected ? 'checked="checked"' : '' ?>name='filter' value='(format:"Electronic resource" OR  medium:"Electronic resource")'  /> <?=$this->transEsc('Filter_electronic_resource')?>
        <input class="btn btn-primary" type="submit" value="<?= $this->transEsc('Find')?>">
      </div>
        </div>
      <? if (isset($this->extraAdvancedControls)): ?>
        <div class="clearfix">
          <?=$this->extraAdvancedControls ?>
        </div>
        <div class="adv-submit">
          <input class="clear-btn btn btn-default" type="button" value="<?= $this->transEsc('Clear')?>">
          <input class="btn btn-primary" type="submit" value="<?= $this->transEsc('Find')?>">
        </div>
      <? endif; ?>
    </div>

    <div class="<?=$this->layoutClass('sidebar')?>">
      <? if ($hasDefaultsApplied): ?>
        <input type="hidden" name="dfApplied" value="1" />
      <? endif ?>
      <? if (!empty($searchFilters)): ?>
        <h4><?=$this->transEsc("adv_search_filters")?></h4>
        <div class="facet-group">
          <label class="checkbox">
            <input type="checkbox" checked="checked" class="checkbox-select-all"/>
            <?=$this->transEsc("adv_search_select_all")?>
          </label>
        </div>
        <? foreach ($searchFilters as $field => $data): ?>
          <div class="facet-group">
            <div class="title"><?=$this->transEsc($field)?></div>
            <? foreach ($data as $value): ?>
              <label class="facet checkbox"><input class="checkbox-select-item" type="checkbox" checked="checked" name="filter[]" value='<?=$this->escapeHtmlAttr($value['field'])?>:"<?=$this->escapeHtmlAttr($value['value'])?>"' /> <?=$this->escapeHtml($value['displayText'])?></label>
            <? endforeach; ?>
          </div>
        <? endforeach; ?>
      <? endif; ?>
      <h4><?=$this->transEsc("Help")?></h4>
      <div class="facet-group">
        <a class="facet help-link" data-lightbox href="<?=$this->url('help-home')?>?topic=advsearch&amp;_=<?=time() ?>"><?=$this->transEsc("Help with Advanced Search")?></a>
        <a class="facet help-link" data-lightbox href="<?=$this->url('help-home')?>?topic=search&amp;_=<?=time() ?>"><?=$this->transEsc("Search Tips")?></a>
      </div>
    </div>
  </form>
</div>
