<div id="querybuilder-container" style="display:none;">
  <div id="builder"></div>
    <div class="btn-group">
    <button id="btn-get-standard-searchform" class="btn btn-warning reset" data-target="basic">Стандартная форма поиска</button>
    <button id="btn-reset" class="btn btn-warning reset" data-target="basic">Очистить</button>
    <button id="btn-set" class="btn btn-success set-json" data-target="basic">Пример</button>
    <button id="btn-search" class="btn btn-warning reset" data-target="basic">Поиск</button>
  <!-- <button id="btn-get" class="btn btn-primary parse-json" data-target="basic">Get rules</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 = 
{
  "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
};
	 var rules_start;
	 if (localStorage.getItem('queryBuilderFormSaved') === true || localStorage.getItem('queryBuilderFormSaved') === 'true') {
       rules_start = JSON.parse(localStorage.getItem('queryBuilderForm'));
     } else {
       rules_start = rules_example;
     }

	$('#builder').queryBuilder({
		filters: [
          <#list searchFields as field>
            <#if field.hasFilters == "true">
              <@multivalueField field=field />
            <#else>
              <@freeField field=field />
            </#if>
          </#list>
           
                 ],
		lang_code: 'ru',
		rules: rules_start
	});

	$('#btn-reset').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();
    });


	//$('#btn-get').on('click', function() {
	//	var result = $('#builder').queryBuilder('getRules');
//
	//	if (!$.isEmptyObject(result)) {
	//		alert(JSON.stringify(result, null, 2));
//		}
//	
//	});

	$('#btn-search').on('click', function() {
		var json_result = $('#builder').queryBuilder('getRules');
		var query_string = format_query_string(json_result,"");
        if (!$.isEmptyObject(query_string)) {
         localStorage.setItem('queryBuilderForm',JSON.stringify(json_result));
         localStorage.setItem('queryBuilderFormSaved',true);


          window.open("${urls.base}/customsearch?querytext=" + query_string,"_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;
	}
</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: {
      <#list searchFilters as filter>
        <#if filter.field == field.field>
          '${filter.id}':'${filter.name}',
        </#if>
      </#list>
		
    },
	operators: ['contains', 'not_contains']
  },
</#macro>
