<div id="querybuilder-container" style="display:none;">
<div id="CounterSearchWrapper"> 
 <div id="builder">
<div id="SearchTitle">${i18n().extended_search_label}</div>
</div>
    <div class="btn-group-bottom">
	  <div id="settingsButtons">
		<div id="OuterWrapperButtons">
		  <div id="wrapperButtons">
	        <button id="btn-set" class="btn btn-success set-json" data-target="basic">${i18n().extended_search_example}</button>
	        <button id="btn-reset-button" class="btn btn-warning reset" data-target="basic">${i18n().extended_search_clean}</button>
            <!-- <button id="btn-get" class="btn btn-primary parse-json" data-target="basic">Get rules</button> -->
              <div id="SelectResults">
                 <label style="display:inline;" for="hitsPerPage">${i18n().extended_search_results_on_page}</label>
	             <@selectHitsPerPage/>
	         </div>
          </div>		
       </div>
		 <button id="btn-search-expand" class="btn btn-warning reset" data-target="basic">${i18n().extended_search_execute_search}</button>	
		</div>
	</div>
</div>
		<div id="backgroundForm">
		 	<button id="btn-get-standard-searchform" class="btn btn-warning reset" data-target="basic">${i18n().open_standard_search_form}</button>
		</div>
</div>
<script src="themes/iph/js/query-builder.standalone.min.js"></script>
<script src="themes/iph/js/query-builder.ru.js"></script>
<script>
	var rules_example = 
	<#if searchFields?has_content>
	{
	  "condition": "AND",
	  "rules": [
	    {
	      "id": "titles",
	      "field": "titles",
	      "type": "string",
	      "input": "text",
	      "operator": "not_contains",
	      "value": "постмодернизм"
	    },
	    {
	      "condition": "OR",
	      "rules": [
	        {
	          "id": "keywords",
	          "field": "keywords",
	          "type": "string",
	          "input": "text",
	          "operator": "contains",
	          "value": "постмодернизм"
	        },
	        {
	          "id": "bibliography",
	          "field": "bibliography",
	          "type": "string",
	          "input": "text",
	          "operator": "contains",
	          "value": "постмодернизм"
	        }
	      ]
	    }
	  ],
	  "valid": true
	};
	<#else>
	     {
	  "condition": "AND",
	  "rules": [
	    {
	      "id": "ALLTEXT",
	      "field": "everywhere",
	      "type": "string",
	      "input": "text",
	      "operator": "contains",
	      "value": "publication"
	    }
	  ],
	  "valid": true
	};
	</#if>
	 var rules_start;
	 <#if queryBuilderRules??>
	   rules_start = ${queryBuilderRules};
	 <#else>
	   if (localStorage.getItem('queryBuilderFormSaved') === true || localStorage.getItem('queryBuilderFormSaved') === 'true') {
         rules_start = JSON.parse(localStorage.getItem('queryBuilderForm'));
       } else {
         rules_start = rules_example;
       }
	 </#if>


	$('#builder').queryBuilder({
		filters: [
		  <#if searchFields?has_content>
	          <#list searchFields as field>
	            <#if field.hasFilters == "true">
	              <@multivalueField field=field />
	            <#else>
	              <@freeField field=field />
	            </#if>
	          </#list>
	      <#else>
	          {
			    id: 'ALLTEXT',
				label: 'Everywhere',
				type: 'string',
				operators: ['contains', 'not_contains']
			  },
          </#if>
           
                 ],
		lang_code: 'ru',
		rules: rules_start
	});

	$('#btn-reset-button').on('click', function() {
		$('#builder').queryBuilder('reset');
	});

	$('#btn-set').on('click', function() {
		$('#builder').queryBuilder('setRules', rules_example);
	});
    
    $('#btn-get-standard-searchform').on('click', function() {
      $('#querybuilder-container').hide();    
      $('#simple-search-container').show();
      localStorage.setItem('extendedSearchOpen',false);
    });


	$('#btn-search-expand').on('click', function() {
		var json_result = $('#builder').queryBuilder('getRules');
		var query_string = format_query_string(json_result,"");
        var hits = $("#hitsPerPageSelect :selected");
        if (!$.isEmptyObject(query_string)) {
         <#if !queryBuilderRules??>
           localStorage.setItem('queryBuilderForm',JSON.stringify(json_result));
           localStorage.setItem('queryBuilderFormSaved',true);
         </#if>
         var queryURL = "${urls.base}/customsearch?querytext=" + query_string;
         if (hits !== null){
           queryURL = queryURL.concat("&hitsPerPage=",hits.text());
         }
         window.open(queryURL,"_self")
        }
		//if (!$.isEmptyObject(json_result)) {
		//	alert(JSON.stringify(json_result, null, 2));
		//	alert(query_string);
		//}
	});

	function format_query_string(json_query, string_query){
	  if ('condition' in json_query && 'rules' in json_query ){
        if (json_query.rules.length > 1 ) {
          string_query +=" ( ";
          var i;
          for (i = 0; i < json_query.rules.length; i++) {
            string_query = format_query_string(json_query.rules[i], string_query);
            if (i + 1 < json_query.rules.length){
              string_query += " " + json_query.condition + " ";
            }
          } 
          string_query +=" ) ";
        } else {
          string_query = format_query_string(json_query.rules[0], string_query);
        }
	  }	else if ( 'field' in json_query && 'value' in json_query ){
        if ('operator' in json_query && json_query.operator.startsWith("not_")){
          string_query +=  "NOT ";
        }
        string_query += json_query.field + ":" + json_query.value.toString().replace(/[']+/g,'').replace(/#/g,'%23') ;
      }
	  return string_query;
	}
	
	function excludeDocByURI(uri){
  		var allRules = $('#builder').queryBuilder('getRules');
  		var excludeRuleString = '{ "id": "URI", "field": "URI", "type": "string", "input": "text", "operator": "not_contains", "value": "" }';
  		var excludeRule = JSON.parse(excludeRuleString);
  		excludeRule.value = uri;
  		if (allRules !== null){
  			if (allRules.condition === "AND"){
  				allRules.rules.push(excludeRule);
  			} else {
  			var outerRulesString = '{ "condition": "AND", "rules": [] }';
  			var outerRules = JSON.parse(outerRulesString);
  			outerRules.rules.push(allRules);
  			outerRules.rules.push(excludeRule);
  			allRules = outerRules;
  			}
			$('#builder').queryBuilder('setRules', allRules);
  		}
	}
</script>
<#macro freeField field >
  {
    id: '${field.field}',
	label: '${field.name}',
	type: 'string',
	operators: ['contains', 'not_contains']
  },
</#macro>

<#macro multivalueField field >
  {
	id: '${field.field}',
	label: '${field.name}',
	type: 'string',
	input: 'select',
	values: {

		 <#if searchFields??>
      <#list searchFilters as filter>
        <#if filter.field == field.field>
          '&quot;${filter.id}&quot;':'${filter.name}',
        </#if>
      </#list>
	      <#else>
	          {
			    id: 'ALLTEXT',
				label: 'Everywhere',
				type: 'string',
				operators: ['contains', 'not_contains']
			  },
          </#if>
    },
	operators: ['contains', 'not_contains']
  },
</#macro>

<#macro selectHitsPerPage>
  <#if !hitsPerPage?? >
    <#assign hitsPerPage = 20 >
  </#if>
  <#assign hitsValues= [20,40,60,80,100]>
  <select name="hitsPerPage" id="hitsPerPageSelect">
    <option value="${hitsPerPage}" selected="selected">${hitsPerPage}</option>
	<#list hitsValues as hppValue>
	  <#if hppValue != hitsPerPage>
	    <option value="${hppValue}">${hppValue}</option>  
	  </#if>
	</#list>
	
  </select>
</#macro>
