Project

General

Profile

1
import {ChangeDetectorRef, Component, ElementRef, Input, Output, ViewChild} from '@angular/core';
2
import {Location} from '@angular/common';
3
import {ActivatedRoute, Router} from '@angular/router';
4
import {Meta, Title} from '@angular/platform-browser';
5

    
6
import {AdvancedField, Filter, Value} from './searchHelperClasses.class';
7
import {SearchCustomFilter, SearchUtilsClass} from './searchUtils.class';
8
import {ModalLoading} from '../../utils/modal/loading.component';
9
import {Dates, Identifier, StringUtils} from '../../utils/string-utils.class';
10
import {ErrorCodes} from '../../utils/properties/errorCodes';
11
import {RouterHelper} from '../../utils/routerHelper.class';
12

    
13
import {PiwikService} from '../../utils/piwik/piwik.service';
14
import {EnvProperties} from '../../utils/properties/env-properties';
15
import {SEOService} from '../../sharedComponents/SEO/SEO.service';
16
import {HelperService} from "../../utils/helper/helper.service";
17
import {SearchFields} from "../../utils/properties/searchFields";
18
import {RefineResultsUtils} from "../../services/servicesUtils/refineResults.class";
19
import {RangeFilter} from "../../utils/rangeFilter/rangeFilterHelperClasses.class";
20
import {ZenodoInformationClass} from "../../deposit/utils/zenodoInformation.class";
21
import {Breadcrumb} from "../../utils/breadcrumbs/breadcrumbs.component";
22
import {HelperFunctions} from "../../utils/HelperFunctions.class";
23
import {properties} from "../../../../environments/environment";
24
import {AlertModal} from "../../utils/modal/alert";
25
import {Subscriber} from "rxjs";
26
import {IndexInfoService} from "../../utils/indexInfo.service";
27

    
28
declare var UIkit: any;
29

    
30
@Component({
31
  selector: 'new-search-page',
32
  templateUrl: 'newSearchPage.component.html'
33
})
34
export class NewSearchPageComponent {
35
  @ViewChild('offcanvas_element') offcanvasElement: ElementRef;
36
  @Input() piwikSiteId = null;
37
  @Input() hasPrefix: boolean = true;
38
  @Input() prefix: string = "OpenAIRE | ";
39
  @Input() pageTitle = "";
40
  pageTitleWithFilters = "";
41
  @Input() results = [];
42
  @Input() type;
43
  @Input() entityType;
44
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
45
  @Input() fieldIds: string[];
46
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
47
  @Input() selectedFields: AdvancedField[];
48
  @ViewChild(ModalLoading) loading: ModalLoading;
49
  @Input() csvParams: string;
50
  @Input() csvPath: string;
51
  @Input() simpleSearchLink: string = "";
52
  @Input() advancedSearchLink: string = "";
53
  @Input() disableForms: boolean = false;
54
  @Input() disableRefineForms: boolean = false;
55
  @Input() loadPaging: boolean = true;
56
  @Input() oldTotalResults: number = 0;
57
  @Input() openaireLink: string;
58
  @Input() customFilter: SearchCustomFilter;
59
  @Input() sort: boolean = true;
60
  @Input() sortedByChanged: string = "";
61
  @Input() resultsPerPageChanged: number;
62
  @Input() searchFormClass: string = "searchForm";
63
  //From simple:
64
  @Input() rangeFilters: RangeFilter[] = [];
65
  @Input() rangeFields: string[][] = [];
66
  @Input() refineFields = [];
67
  @Input() filters:Filter[] = [];
68
  selectedFilters: number = 0;
69
  selectedRangeFilters: number = 0;
70
  private searchFieldsHelper: SearchFields = new SearchFields();
71
  @Input() newQueryButton: boolean = true;
72
  public showUnknownFilters: boolean = false; // when a filter exists in query but has no results, so no filters returned from the query
73
  URLCreatedFilters: Filter[] = [];
74
  URLCreatedRangeFilters: RangeFilter[] = [];
75
  @Input() showRefine: boolean = true;
76
  @Input() tableViewLink: string;
77
  @Input() usedBy: string = "search";
78
  @Input() public zenodoInformation: ZenodoInformationClass = new ZenodoInformationClass();
79
  @Input() showIndexInfo: boolean = true;
80
  @Input() showResultCount: boolean = true;
81
  @Input() showMoreFilterValuesInline: boolean = true;
82
  @Input() filterValuesNum: number = 6;
83
  @Input() keywordFields = [];
84
  @Input() simpleView: boolean = true;
85
  @Input() formPlaceholderText = "Type Keywords...";
86
  @Input() resultTypes:Filter = null;
87
  resultTypeOptions = {"publications":{"id":"publication", "name":"Publications"},"datasets":{"id":"dataset", "name":"Research data"},
88
    "software":{"id":"software", "name":"Software"},"other":{"id":"other", "name":" Other research products"}};
89
  selectedTypesNum = 0;
90
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
91
  @Input() includeOnlyResultsAndFilter:boolean = false;
92
  @Input() showBreadcrumb:boolean = false;
93
  @Input() showDownload: boolean = true;
94
  public dashboard: boolean = properties.isDashboard;
95

    
96
  subscriptions = [];
97
  public parameterNames: string[] = [];
98
  public parameterValues: string[] = [];
99

    
100
  public csvLimit: number = 0;
101
  public pagingLimit: number = 0;
102
  public resultsPerPage: number = 0;
103
  isPiwikEnabled = false;
104
  properties: EnvProperties = properties;
105
  public pageContents = null;
106
  public divContents = null;
107
  public routerHelper: RouterHelper = new RouterHelper();
108
  public errorCodes: ErrorCodes = new ErrorCodes();
109
  breadcrumbs:Breadcrumb[] = [];
110
  url = null;
111
  metaDescription = "";
112
  @Input() basicMetaDescription = [];
113

    
114
  @Input() entitiesSelection:boolean = true;
115
  @Input() showSwitchSearchLink:boolean = true;
116

    
117
  // on 1st load, do not show filters until results query returns.
118
  public hideFilters: boolean = true;
119

    
120
  //Dashboard
121
  filterToggle = false;
122
  customFilterEnabled:boolean =  false;
123
  //stickyform
124
  @Input() stickyForm:boolean = false;
125

    
126
  @ViewChild('removeCustomFilter') removeCustomFilter: AlertModal;
127
  currentValueToRemove;
128
  currentFilterToRemove;
129
  public indexUpdateDate: Date;
130
  constructor(private route: ActivatedRoute,
131
              private location: Location,
132
              private _meta: Meta,
133
              private _title: Title,
134
              private _piwikService: PiwikService,
135
              private router: Router,
136
              private seoService: SEOService,
137
              private helper: HelperService,
138
              private cdr:ChangeDetectorRef, private indexInfoService: IndexInfoService) {
139
  }
140

    
141
  ngOnInit() {
142
      //this.getDivContents();
143
      this.getPageContents();
144
      this.pagingLimit = this.properties.pagingLimit;
145
      this.resultsPerPage = this.properties.resultsPerPage;
146
      this.csvLimit = this.properties.csvLimit;
147
      this.isPiwikEnabled = this.properties.enablePiwikTrack;
148
      this.updateUrl(this.properties.domain + this.properties.baseLink + this.router.url);
149
      this.url = this.properties.domain + this.properties.baseLink + this.router.url;
150
      if (typeof document !== 'undefined' && this.isPiwikEnabled && !this.includeOnlyResultsAndFilter && this.piwikSiteId) {
151
        this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe());
152
      }
153
    this.route.queryParams.subscribe(params => {
154
      if (params['page'] && params['page'] != 1) {
155
        HelperFunctions.scrollToId("searchForm");
156
      }
157
      this.customFilterEnabled = params['cf'] && params['cf'] == "true";
158
      if(this.basicMetaDescription.length == 0 ){
159
        if (this.entityType == "result") {
160
          this.basicMetaDescription =  ["Research outcomes","Discover" + (this.properties.adminToolsCommunity == 'openaire'?" over 100 million of":"")+" research outcomes ", "categorized by research type, year range, funder, languages, community and content providers."];
161
        } else if (this.entityType == "project") {
162
          this.basicMetaDescription =  ["Research projects", "Discover research projects and correlated research categorized by Funder and active year. ", "Statistics data about produced research outcomes per year available."];
163
        } else if (this.entityType == "organization") {
164
          this.basicMetaDescription =  ["Research organization","Discover worldwide research organizations from over 100 countries and correlated research. ", "Funding, content providers, research pubblications and research data available."];
165
        }else{
166
          this.basicMetaDescription.push(this.pageTitle)
167
        }
168
      }
169
      console.log("title " + this.pageTitle, this.basicMetaDescription)
170
      this.updateMeta(this.pageTitle);
171
    });
172
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
173
    this.breadcrumbs.push({name: 'home', route: '/'});
174
    if(this.simpleView) {
175
      this.breadcrumbs.push( {name: "Search", route: null});
176
    }else if(!this.simpleView && this.advancedSearchLink) {
177
      this.breadcrumbs.push({name: "Advanced Search", route: null});
178
    }
179
    //console.log(this.filters)
180
    if (typeof document !== 'undefined') {
181
      this.subscriptions.push(this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
182
        if (lastIndexUpdate) {
183
          this.indexUpdateDate = new Date(lastIndexUpdate);
184
        }
185
      }));
186
    }
187
  }
188

    
189
  private getPageContents() {
190
    this.subscriptions.push(this.helper.getPageHelpContents(this.properties, (this.customFilter && this.customFilter.queryFieldName == "communityId") ? this.customFilter.valueId : this.properties.adminToolsCommunity, this.router.url).subscribe(contents => {
191
      this.pageContents = contents;
192
    }));
193

    
194
  }
195

    
196
  private getDivContents() {
197
      this.subscriptions.push(this.helper.getDivHelpContents(this.properties, (this.customFilter && this.customFilter.queryFieldName == "communityId") ? this.customFilter.valueId : this.properties.adminToolsCommunity, this.router.url).subscribe(contents => {
198
        this.divContents = contents;
199
      }));
200
  }
201

    
202
  ngOnDestroy() {
203
    this.subscriptions.forEach(subscription => {
204
      if (subscription instanceof Subscriber) {
205
        subscription.unsubscribe();
206
      }
207
    });
208
  }
209

    
210
  updateMeta(title:string) {
211
    let filterArray = [];
212
    let filtervalues = [];
213
    let filterURL = "";
214
    if(this.resultTypes && this.resultTypes.countSelectedValues> 0){
215
      filterURL += ((filterURL.length == 0) ? '?' : '&') + this.resultTypes.filterId + "=";
216
      let filterName = this.resultTypes.title+" ";
217
      for(let value of this.resultTypes.values){
218
        if(value.selected) {
219
          filterArray.push(filterName + '"' + value.name + '"');
220
          filtervalues.push(value.name);
221
          filterURL += ((filterName.length == 0) ? ',' : '') + StringUtils.URIEncode('"' + value.id+ '"' );
222
          filterName = "";
223
        }
224
      }
225
    }
226
    for(let filter of this.filters){
227
      if(filter.countSelectedValues> 0){
228
        filterURL += ((filterURL.length == 0) ? '?' : '&') + filter.filterId + "=";
229
        let filterName = filter.title+" ";
230
       for(let value of filter.values){
231
         if(value.selected) {
232
           filterArray.push(filterName + '"' + value.name + '"');
233
           filtervalues.push(value.name);
234
           filterURL += ((filterName.length == 0) ? ',' : '') + StringUtils.URIEncode('"' + value.id + '"' );
235
           filterName = "";
236

    
237
         }
238
        }
239
      }
240
    }
241
    let nonCanonicalizedPage = (filterArray.length > 0 && filterArray.length<3);
242
      this.metaDescription= (nonCanonicalizedPage?( (this.basicMetaDescription[0] + " filtered by: " + filterArray.join(" and ") + ". ") + (this.basicMetaDescription.length > 1 ?this.basicMetaDescription[1]:""))
243
      :((this.basicMetaDescription.length > 2 ?this.basicMetaDescription[1] + this.basicMetaDescription[2]:this.basicMetaDescription[0])));
244
    this._meta.updateTag({content: this.metaDescription}, "name='description'");
245
    this._meta.updateTag({content: this.metaDescription}, "property='og:description'");
246
    this.updateTitle(title, (nonCanonicalizedPage ? filtervalues.join(" | ") + " | ": ""));
247
    this.url = this.properties.domain + this.properties.baseLink + this.router.url.split('?')[0] + (nonCanonicalizedPage ?  filterURL : "");
248
    this.seoService.createLinkForCanonicalURL(this.url, true);
249
  }
250

    
251
  updateTitle(title: string, filters:string) {
252
    let _title = (this.hasPrefix?this.prefix:"") + filters + title;
253
    // _title = ((_title.length > 50) ? _title.substring(0, 50) : _title);
254
    this.pageTitleWithFilters = _title;
255
    this._title.setTitle(_title);
256
    this._meta.updateTag({content: _title}, "property='og:title'");
257
  }
258

    
259
  updateUrl(url: string) {
260
    this._meta.updateTag({content: url}, "property='og:url'");
261
  }
262

    
263

    
264
  clearFilters() {
265
    for (var i = 0; i < this.filters.length; i++) {
266
      for (var j = 0; j < this.filters[i].countSelectedValues; j++) {
267
        if (this.filters[i].values[j].selected) {
268
          this.filters[i].values[j].selected = false;
269
        }
270
        this.filters[i].countSelectedValues = 0;
271
        this.filters[i].radioValue = "";
272
      }
273
    }
274
    this.selectedFilters = 0;
275
    for(let i = 0; i < this.rangeFilters.length; i++) {
276
      this.rangeFilters[i].selectedFromValue = null;
277
      this.rangeFilters[i].selectedToValue = null;
278
    }
279
    this.selectedRangeFilters = 0;
280
    if (this.quickFilter) {
281
      this.removeValueFromQuickFilter();
282
    }
283
    if(this.resultTypes) {
284
      this.resultTypes.values = [];
285
    }
286
    this.goTo(1);
287
    // this.clearKeywords();
288
  }
289

    
290
  goTo(page: number = 1, scroll:boolean = true) {
291
    if(this.offcanvasElement && (typeof document !== 'undefined')) {
292
      UIkit.offcanvas(this.offcanvasElement.nativeElement).hide();
293
    }
294

    
295
    this.searchUtils.page = page;
296
    this.buildPageURLParameters(this.filters, this.rangeFilters, true);
297
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
298
    if(scroll) {
299
      HelperFunctions.scrollToId("searchForm");
300
    }
301
    /* Code For Piwik*/
302
    if (typeof localStorage !== 'undefined') {
303
      //console.log("In PreviousRouteRecorder : "+this.router.url );
304
      localStorage.setItem('previousRoute', this.router.url);
305
    }
306
    if (this.isPiwikEnabled && (typeof document !== 'undefined') && this.piwikSiteId) {
307
      this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe());
308
    }
309
    /* End Piwik Code */
310
  }
311

    
312
  queryChanged($event) {
313
    if($event == "filters_update"){
314
      this.cdr.detectChanges();
315
      return;
316
    }
317
    this.goTo(1, false);
318
  }
319

    
320

    
321
  sizeChanged($event) {
322
    //this.searchUtils.size = $event.value;
323
    this.resultsPerPageChanged = $event;
324

    
325
    this.goTo(1);
326
  }
327

    
328
  sortByChanged($event) {
329
    //this.searchUtils.sortBy = $event.value;
330
    this.sortedByChanged = $event;
331
    this.goTo(1);
332
  }
333

    
334

    
335
  getOperatorParameter(parameter: string): string {
336
    for (let id of this.fieldIds) {
337
      if (this.fieldIdsMap[id]["param"] == parameter) {
338
        return this.fieldIdsMap[id]["operator"];
339
      }
340
    }
341
  }
342

    
343
  /*
344
* Get A sub-array of this.refineFields array, which contains the ids of the selected filters
345
*/
346
  public getSelectedFilters(): string[] {
347
    var selected: string[] = [];
348
    var filters= this.URLCreatedFilters;
349
    for (var i = 0; i < filters.length; i++) {
350
      var filter: Filter = filters[i];
351
      if (filter.countSelectedValues > 0) {
352
        selected.push(filter.filterId);
353
      }
354
    }
355
    return selected;
356
  }
357

    
358
  /*
359
    * Get A sub-array of this.refineFields array, which contains the ids of the selected parameters
360
    */
361
  private getSelectedParameters(): string[] {
362
    var selected: string[] = [];
363
    for (var i = 0; i < this.refineFields.length; i++) {
364
      if (this.parameterNames.indexOf(this.refineFields[i]) != -1) {
365
        selected.push(this.refineFields[i]);
366
      }
367
    }
368
    return selected;
369
  }
370

    
371
  /*
372
  * Get A sub-array of this.refineFields array, which hides hidden fields (e.g Funding level 0,1,2,..), and contains those that depend on another fields (e.g  Funding level 0 if Funder is selected )
373
  */
374
  public getFields(): string[] {
375
    var selected_filters: string[] = this.getSelectedFilters();
376
    if (selected_filters.length == 0) {
377
      selected_filters = this.getSelectedParameters();
378
    }
379
    var fields: string[] = [];
380
    for (var i = 0; i < this.refineFields.length; i++) {
381
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
382

    
383
      //if filter is not marked as hidden OR it is hidden but it is dependent to a field that it IS selected
384
      if (this.searchFieldsHelper.HIDDEN_FIELDS.indexOf(this.refineFields[i]) == -1 || (selected_filters.indexOf(dependentTo) != -1) || (selected_filters.indexOf(this.refineFields[i]) != -1)) {
385
        fields.push(this.refineFields[i]);
386
      }
387
    }
388
    return fields;
389
  }
390

    
391
  /*
392
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
393
  */
394
  public getRefineFieldsQuery(): string {
395

    
396
    var fields: string[] = this.getFields();
397
    var fieldsStr = ""
398
    for (var i = 0; i < fields.length; i++) {
399
      fieldsStr += "&fields=" + fields[i];
400
    }
401
    return "&refine=true" + fieldsStr;
402
  }
403

    
404

    
405
  /*
406
  * Mark as check the new filters that are selected, when you get them from search
407
  */
408
  public checkSelectedFilters(filters: Filter[]) {
409
    this.filters = filters;
410
    if(this.customFilter && !this.customFilter.isHiddenFilter) {
411
      this.customFilter.selected = null;
412
    }
413
    for (var i = 0; i < filters.length; i++) {
414
      var filter: Filter = filters[i];
415
      filter.countSelectedValues = 0;
416
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
417
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
418
        for (let filterValue of filter.values) {
419
          if (values.indexOf(StringUtils.quote(filterValue.id)) > -1) {
420
            filterValue.selected = true;
421
            filter.countSelectedValues++;
422
          } else {
423
            filterValue.selected = false;
424

    
425
          }
426
        }
427
        if(this.customFilter){
428
          this.customFilter.selected = this.customFilter.queryFieldName == filter.filterId && values.indexOf(StringUtils.quote(this.customFilter.valueId)) != -1;
429
        }
430
      } else if (this.quickFilter && this.quickFilter.filterId == filter.filterId && this.quickFilter.selected) {
431
        for (let filterValue of filter.values) {
432
          if (filterValue.id == this.quickFilter.value) {
433
            filterValue.selected = true;
434
            filter.countSelectedValues++;
435
          } else {
436
            filterValue.selected = false;
437
          }
438
        }
439
      } else {
440
        for (let filterValue of filter.values) {
441
          filterValue.selected = false;
442
        }
443
      }
444
      if (this.quickFilter && filter.filterId == this.quickFilter.filterId) {
445
        this.quickFilter.filter = filter;
446
      }
447
    }
448
    if (this.parameterNames.indexOf("cf") != -1 && this.parameterValues[this.parameterNames.indexOf("cf")] == "true") {
449
      this.customFilter.selected = true;
450
    }else if(this.customFilter && this.customFilter.selected == null){
451
      this.customFilter.selected = false;
452
    }
453
    this.filterFilterValues(this.filters);
454
    if(!this.includeOnlyResultsAndFilter) {
455
      this.updateMeta(this.pageTitle);
456
    }
457
    return filters;
458
  }
459

    
460
  /*
461
* Mark as check the new range filters that are selected
462
*/
463
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
464
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
465

    
466
    this.rangeFilters = filters;
467
    for (let i = 0; i < filters.length; i++) {
468
      let filter: RangeFilter = filters[i];
469

    
470
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
471
        //console.log(filter.filterId + " "+this.parameterNames.indexOf(filter.filterId) );
472
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
473
        let operators: string [] = (StringUtils.URIDecode(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
474
        if (values.length == operators.length) {
475
          for (let j = 0; j < values.length; j++) {
476
            if (this.fieldIdsMap[filter.originalFilterIdFrom+"-range-"+filter.originalFilterIdTo].filterType == "range") {
477
              let value: string = StringUtils.unquote(values[j]);
478
              let validDates: boolean = true;
479

    
480
              let years: string[] = (value.substring(5)).split(":");
481
              let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
482
              let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
483
              //console.log("checkSelectedRangeFilters: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
484
              if(yearFrom) {
485
                filter.selectedFromValue = yearFrom;
486
              }
487
              if(yearTo) {
488
                filter.selectedToValue = yearTo;
489
              }
490
              if(yearFrom && yearTo) {
491
                filter.selectedFromAndToValues = yearFrom + "-" + yearTo;
492
              } else if(yearFrom) {
493
                filter.selectedFromAndToValues = "From " + yearFrom;
494
              } else if(yearTo) {
495
                filter.selectedFromAndToValues = "Until " + yearTo;
496
              }
497

    
498
              if(!yearFrom && !yearTo) {
499
                validDates = false;
500
              }
501

    
502
              // if (value.length < 14) {
503
              //   validDates = false;
504
              //   console.log("not valid (length<14)");
505
              // } else {
506
              //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
507
              //     validDates = false;
508
              //     console.log("not valid years");
509
              //   } else {
510
              //     filter.selectedFromValue = value.substring(5, 9);
511
              //     filter.selectedToValue = value.substring(10, 14);
512
              //     console.log(filter);
513
              //   }
514
              // }
515
            }
516
          }
517
        }
518
      } else {
519
        filter.selectedFromValue = null;
520
        filter.selectedToValue = null;
521
      }
522
    }
523
    return this.rangeFilters;
524
  }
525

    
526
  get existingFiltersWithValues() {
527
    if(this.filters.length == 0) {
528
      return 0;
529
    }
530
    return this.filters.some(filter => (filter.values && filter.values.length > 0));
531
  }
532

    
533
  /*
534
  * For Funder filters - if funder selected
535
  */
536
  public filterFilterValues(filters: Filter[]) {
537
    var funders = [];
538
    var funder_prefix = [];
539
    for (var i = 0; i < filters.length; i++) {
540

    
541
      var filter: Filter = filters[i];
542
      //  console.log(filter.filterId);
543
      if (filter.filterId.indexOf("funder") != -1 && this.parameterNames.indexOf(filter.filterId) != -1) {
544
        let funders = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
545
        for (let funder of funders) {
546
          funder_prefix.push(StringUtils.unquote(funder).split("____")[0]);
547
        }
548
        //  console.log(funder_prefix );
549
      } else if (filter.filterId.indexOf("funding") != -1) {
550
        //  console.log(" funding: "+filter.filterId );
551
        var filteredValues = []
552
        for (let filterValue of filter.values) {
553
          var value_prefix = filterValue.id.split("____")[0];
554
          //  console.log("Value prefix: "+value_prefix );
555
          if (funder_prefix.indexOf(value_prefix) != -1) {
556
            //  console.log("here" + value_prefix);
557
            filteredValues.push(filterValue);
558
          }
559

    
560
        }
561
        if (filteredValues.length > 0) {
562
          filter.values = filteredValues;
563
        }
564
      }
565

    
566
    }
567

    
568
    return filters;
569
  }
570

    
571
  public countSelectedFilters(filters: Filter[]): number {
572
    this.selectedFilters = 0;
573
    for (let filter of filters) {
574
      if (filter.countSelectedValues > 0) {
575
        this.selectedFilters += filter.countSelectedValues;
576
      }
577
    }
578
    return this.selectedFilters;
579
  }
580

    
581
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
582
    this.selectedRangeFilters = 0;
583
    for(let filter of rangeFilters) {
584
      if(filter.selectedFromValue || filter.selectedToValue) {
585
        this.selectedRangeFilters++;
586
      }
587
    }
588
    return this.selectedRangeFilters;
589
  }
590

    
591
  private clearKeywords() {
592
    if (this.searchUtils.keyword.length > 0) {
593
      this.searchUtils.keyword = '';
594
    }
595
    this.goTo(1);
596
  }
597

    
598
  public removeFilter(value: Value, filter: Filter, forceRemove:boolean = false) {
599
    this.currentValueToRemove = value;
600
    this.currentFilterToRemove = filter;
601
    if(!forceRemove && this.customFilter && this.customFilter.queryFieldName ==filter.filterId && this.customFilter.valueId == value.id && this.customFilter.promptToAddFilter ){
602
      this.openRemoveCustomFilterModal();
603
      return;
604
    }
605
    filter.countSelectedValues--;
606
    this.selectedFilters--;
607
    if (value.selected == true) {
608
      value.selected = false;
609
    }
610
    if(filter.filterType == "radio"){
611
      filter.radioValue = "";
612
    }
613
    if (this.quickFilter && this.quickFilter.filterId == filter.filterId) {
614
      this.removeValueFromQuickFilter();
615
    }
616
    this.goTo(1);
617
  }
618
  public openRemoveCustomFilterModal() {
619
    this.removeCustomFilter.alertTitle = 'Remove filter';
620
    this.removeCustomFilter.message = 'You are about to see results that are not related to '+ this.customFilter.valueName + '. Do you want to proceed?';
621
    this.removeCustomFilter.okButtonText = 'Yes';
622
    this.removeCustomFilter.cancelButtonText = 'No';
623
    this.removeCustomFilter.open();
624
  }
625

    
626
  closeCustomFilterModal() {
627
    this.customFilterEnabled = false;
628
    this.removeFilter(this.currentValueToRemove, this.currentFilterToRemove, true);
629
  }
630

    
631
  public removeRangeFilter(filter: RangeFilter) {
632
    filter.selectedFromValue = null;
633
    filter.selectedToValue = null;
634
    this.goTo(1);
635
  }
636

    
637
  getSelectedValues(filter): any {
638
    var selected = [];
639
    if (filter.countSelectedValues > 0) {
640
      for (var i = 0; i < filter.values.length; i++) {
641
        if (filter.values[i].selected) {
642
          selected.push(filter.values[i]);
643
        }
644
      }
645
    }
646
    return selected;
647

    
648
  }
649

    
650
  filterChanged($event) {
651
    if (this.quickFilter && this.quickFilter.filter) {
652
      this.removeValueFromQuickFilter();
653
    }
654
    this.goTo(1);
655

    
656
  }
657

    
658
  /**
659
   * if there is a change in the values of the quick filter, this function has to be run, to also update the quickFilter
660
   */
661
  removeValueFromQuickFilter() {
662
    if (this.quickFilter.filter.countSelectedValues == 0) {
663
      this.quickFilter.selected = false;
664
    } else {
665
      let isQuickEnabled = false;
666
      for (let filterValue of this.quickFilter.filter.values) {
667
        isQuickEnabled = (filterValue.name == this.quickFilter.value)
668
      }
669
      this.quickFilter.selected = (isQuickEnabled && this.quickFilter.filter.countSelectedValues == 1);
670
    }
671
  }
672

    
673
  /**
674
   * Set selected the value of the custom filter.
675
   */
676
  addCustomFilter() {
677
    this.customFilter.selected = true;
678
    this.customFilterEnabled = true;
679
    if(this.refineFields.indexOf(this.customFilter.queryFieldName) != -1  ){
680
      let found = false;
681
      for (let filter of this.filters) {
682
        if (this.customFilter.queryFieldName == filter.filterId) {
683
          for (let value of filter.values) {
684
            if (value.id == this.customFilter.valueId) {
685
              value.selected = true;
686
              filter.countSelectedValues++;
687
              found = true;
688
              break;
689
            }
690
          }
691
          //add filter when field exist in refine but not in the refine values
692
          if(!found){
693
            filter.countSelectedValues ++ ;
694
            filter.values.push({selected : true, name: this.customFilter.valueName, id: this.customFilter.valueId, number:0});
695
          }
696
          break;
697
        }
698
      }
699
    }
700
    this.filterChanged(null);
701

    
702
  }
703
  // for loading
704
  public openLoading() {
705
    this.loading.open();
706
  }
707

    
708
  public closeLoading() {
709
    this.loading.close();
710
  }
711

    
712
  /**
713
   * Build advanced search Filters based on the URL parameters
714
   * @param params
715
   */
716
  createAdvancedSearchSelectedFiltersFromNewURLParameters(params) {
717
    for (let i = 0; i < Object.keys(params).length; i++) {
718
      if(params["f"+i] && params["fv"+i]   ) {
719
        let fieldId = params["f" + i].split(",")[0];
720
        let operator = (params["f" + i].split(",").length  >1 )?params["f" + i].split(",")[1]:"and";
721
        let fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
722

    
723
        if (!this.fieldIdsMap[fieldId]) {
724
          console.error("Field: " + fieldId + " not found in fieldIds map");
725
          continue;
726
        }
727
        let value: string = StringUtils.URIDecode(params["fv"+i]);
728
        if (this.fieldIdsMap[fieldId].type == "date") {
729
            let validDates: boolean = true;
730
            let dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operator);
731
            if (value.indexOf("range") != -1) {
732
              dateField.dateValue.type = "range";
733
              if (value.length < 26) {
734
                validDates = false;
735
              } else {
736
                if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
737
                  validDates = false;
738
                } else {
739
                  dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
740
                  dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
741
                }
742
              }
743
              //  "rangeYYYY-MM-DD:YYYY-MM-DD"
744
            } else {
745
              dateField.dateValue.setDatesByType(value);
746
            }
747
            if (validDates) {
748
              this.selectedFields.push(dateField);
749
            }
750

    
751
          } else {
752
            this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type,value, operator));
753
          }
754

    
755
        }
756
      }
757
  }
758
  /**
759
   * Build advanced search Filters based on the URL parameters
760
   * @param params
761
   */
762
  createAdvancedSearchSelectedFiltersFromURLParameters(params) {
763
    this.createAdvancedSearchSelectedFiltersFromNewURLParameters(params);
764
    for (var i = 0; i < this.fieldIds.length; i++) {
765
      var fieldId = this.fieldIds[i];
766
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
767
      if (!this.fieldIdsMap[fieldId]) {
768
        console.error("Field: " + fieldId + " not found in fieldIds map");
769
        continue;
770
      }
771

    
772
      var operatorId = this.getOperatorParameter(fieldparam);
773
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
774
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
775
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
776
        if (values.length == operators.length) {
777
          for (var j = 0; j < values.length; j++) {
778
            if (this.fieldIdsMap[fieldId].type == "date") {
779
              var value: string = StringUtils.unquote(values[j]);
780
              var validDates: boolean = true;
781
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
782
              if (value.indexOf("range") != -1) {
783
                dateField.dateValue.type = "range";
784
                if (value.length < 26) {
785
                  validDates = false;
786
                } else {
787
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
788
                    validDates = false;
789
                  } else {
790
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
791
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
792
                  }
793
                }
794
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
795
              } else {
796
                dateField.dateValue.setDatesByType(value);
797
              }
798
              if (validDates) {
799
                this.selectedFields.push(dateField);
800
              }
801

    
802
            } else {
803
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
804
            }
805
          }
806
        }
807
      }
808
    }
809
    if (params['keyword'] && params['keyword'].length > 0) {
810
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, params['keyword'], "and"));
811
    }
812
    if (this.selectedFields.length == 0) {
813
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, "", "and"));
814
    }
815
  }
816

    
817
  /**
818
   * Create Search API query based on the selected fields of the advanced form
819
   */
820
  getSearchAPIQueryForAdvancedSearhFields() {
821

    
822
    var params = "";
823
    var countParams = 0;
824
    for (var i = 0; i < this.selectedFields.length; i++) {
825
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
826
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
827
        if (this.selectedFields[i].type == "date") {
828
          if (this.selectedFields[i].dateValue.type != "any") {
829
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.from)) + " "
830
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
831
          }
832
        } else {
833
          if (this.selectedFields[i].id == "q") {
834
            // console.log(this.selectedFields[i].value)
835
/*            var op = "";
836
            var doisParams = "";
837
            if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
838
              var DOIs: Identifier[] = Identifier.getIdentifiersFromString(this.selectedFields[i].value);
839
              for (let identifier of DOIs) {
840
                // console.log(identifier)
841
                // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
842
                //and (authorid exact \"0000-0001-7291-3210 \" )"
843
                if(identifier.class == "ORCID"){
844
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
845
                }else{
846
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
847
                }
848
              }
849
            }
850
            if (doisParams.length > 0) {
851
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId ,countParams,true, true) + " or " + doisParams;
852
            } else {
853
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId,countParams,true);
854
            }*/
855
            params += NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
856
            //TODO deposit case
857
            // console.log(this.usedBy)
858
            // console.log(this.keywordFields)
859

    
860
            if(this.usedBy == "deposit") {
861

    
862
              if(this.keywordFields.length > 0) {
863
                params += " or ("
864
              }
865
              for(let j=0; j< this.keywordFields.length ; j++) {
866
                if(j > 0) {
867
                  params += " or "
868
                }
869
                params += NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.keywordFields[j].name, " or ", countParams,false);
870
                // let field = this.keywordFields[i];
871
                //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
872
                // params += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
873
              }
874
              if(this.keywordFields.length > 0) {
875
                params += " ) "
876
              }
877
            }
878

    
879
          } else if(this.selectedFields[i].type == "identifier") {
880
            params += NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
881
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
882
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
883
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
884
            params+=NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams, false);
885
          }else{
886
              params += (countParams == 0 ? "" : " " + this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
887

    
888
          }
889
        }
890
        countParams++;
891
      }
892
    }
893

    
894
    // console.log("ParameterS:")
895
    // console.log(params)
896
    return params;
897
  }
898
  public static createKeywordQuery(entityType:string, value:string, id, operatorId, countParams=0){
899
    let params = "";
900
    let doisParams = "";
901
    var DOIs: Identifier[] = Identifier.getIdentifiersFromString(value);
902
    if ((entityType == 'publication' || entityType == 'dataset' || entityType == 'software' || entityType == 'other' || entityType == "result")) {
903
      for (let identifier of DOIs) {
904
        // console.log(identifier)
905
        // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
906
        //and (authorid exact \"0000-0001-7291-3210 \" )"
907
        if(identifier.class == "ORCID"){
908
          doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + StringUtils.URIEncode(identifier.id) + '")';
909
          // doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + StringUtils.URIEncode(identifier.id) + '" and (authoridtype exact "orcid"))';
910
        }else{
911
          doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  StringUtils.URIEncode(identifier.id) + '")';
912
          // doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
913
        }
914
      }
915
    }
916
    if (doisParams.length > 0) {
917
      params += "(" + this.createQuotedKeywordQuery(value, id, operatorId ,countParams,true, true) + " or " + doisParams+")";
918
    } else {
919
      //if it is PIDs but no doisquery produced, forced to use quotes as the query will fail due to special characters
920
      params += this.createQuotedKeywordQuery(value, id, operatorId,countParams,true,
921
        (DOIs.length > 0 && doisParams.length == 0) );
922
    }
923
    return params;
924

    
925
  }
926
  private static createQuotedKeywordQuery(fieldValue, fieldId, fieldOperator, countParams:number, isSearchAll:boolean, forceQuotted:boolean=false){
927
    let params = "";
928
    let countQuote = (fieldValue.match(/'/g) || []).length;
929
    let countDoubleQuote = (fieldValue.match(/"/g) || []).length;
930
    let quotedParts = [];
931
    if(countQuote % 2 == 0 && countDoubleQuote % 2 ==0){
932
      quotedParts = (fieldValue)?fieldValue.match(/(["'])(.*?)*?\1/g):[];
933
    }
934
    params+= (countParams == 0 ? "" : fieldOperator);
935
    params+=   " (";
936
    if(forceQuotted){
937
      return (countParams == 0 ? "" : " "+fieldOperator+" ") + this.getQuotedQueryPart(fieldId, '"'+ fieldValue+'"',isSearchAll);
938
    }
939
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == fieldValue ){
940
      params+=this.getQuotedQueryPart(fieldId, fieldValue,isSearchAll);
941
    }else if( quotedParts && quotedParts.length > 0){
942
      for(let i=0; i< quotedParts.length; i++){
943
        params+=(i>0)?" and ":"";
944
        params+=this.getQuotedQueryPart(fieldId, quotedParts[i],isSearchAll);
945
      }
946
      let startPoint = 0;
947
      let endPoint = 0;
948
      for(let i=0; i< quotedParts.length; i++){
949
        let index = fieldValue.indexOf(quotedParts[i]);
950
        endPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+1]):fieldValue.length;
951
        // console.log(fieldValue.indexOf(quotedParts[i+1]) +" - "+fieldValue.length);
952
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
953
        if(index==startPoint){
954
          startPoint +=quotedParts[i].length;
955
        }else if(startPoint < index){
956
          endPoint = index;
957
        }
958
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
959
        if(decodeURIComponent(fieldValue.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
960
          params += " and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint, endPoint), isSearchAll);
961
        }
962
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
963
        // startPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+i]):fieldValue.length;//(startPoint<index  )?(index + quotedParts[i].length):fieldValue.length;
964
        startPoint = ((i+1<quotedParts.length)?(fieldValue.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
965
      }
966
      if(startPoint !=fieldValue.length && decodeURIComponent(fieldValue.substring(startPoint,fieldValue.length)).split(" ").join("").length > 0){
967
        params+=" and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint,fieldValue.length),isSearchAll);
968
      }
969
    }else{
970
      params+=this.getNoQuotedQueryPart(fieldId, fieldValue,isSearchAll);
971
    }
972
    params += ")";
973
    return params;
974
  }
975

    
976
  private static getQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
977
      return (isSearchAll?"__all":fieldId)+" exact "+StringUtils.URIEncode(value);
978
  }
979
  private static getNoQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
980
    //split the keywords of the vlaue and query seperately for each keyword using quotes to allow characters like .@
981
    let valueKeywords= value.split(" ");
982
    let query = "";
983
    let i=0;
984
    for(let keyword of valueKeywords ){
985
      if(keyword.length > 0){
986
        query+= (i!=0?" and ":"")+(isSearchAll?"(":fieldId+"=")+"\""+StringUtils.URIEncode(this.checkForReservedWords(keyword)) +"\""+ (isSearchAll?")":"");
987
        i++;
988
      }
989
    }
990
    return query
991
  }
992
  private static checkForReservedWords(keyword:string){
993
    let reservedWords = ["AND", "OR", "NOT"];
994
    if(reservedWords.indexOf(keyword)!=-1){
995
      return keyword.toLowerCase();
996
    }
997
    return keyword;
998
  }
999
  /**
1000
   * Create Search API query based on the filters of refine fields
1001
   * @param URLparams
1002
   * @param firstLoad
1003
   */
1004
  getSearchAPIQueryForRefineFields(URLparams, firstLoad: boolean) {
1005

    
1006
    var allFqs = "";
1007
    // console.log(this.refineFields)
1008
    for (var i = 0; i < this.refineFields.length; i++) {
1009
      var filterId = this.refineFields[i];
1010

    
1011
      if (URLparams[filterId] != undefined) {
1012
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterId]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1013
        var countvalues = 0;
1014
        var fq = "";
1015
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
1016
        // console.info(filterId, filterOp);
1017
        for (let value of values) {
1018
          countvalues++;
1019
          var paramId = this.fieldIdsMap[filterId].param;
1020
          // parameters+='&' + paramId+ '='+ value;//+"&" + this.fieldIdsMap[paramId].operator + "="+((countvalues == 1)?"and":"or");
1021
          fq += (fq.length > 0 ? " " + filterOp + " " : "") + filterId + " exact " + (value);
1022
        }
1023
        if (countvalues > 0) {
1024
          fq = "&fq=" + StringUtils.URIEncode(fq);
1025
        }
1026
        allFqs += fq;
1027
      }
1028
    }
1029
    this.customFilterEnabled = URLparams["cf"] == "true";
1030
    if(this.customFilter && (this.customFilter.isHiddenFilter || this.customFilterEnabled)){
1031
      allFqs += "&fq=" + StringUtils.URIEncode(this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId)));
1032
    }
1033

    
1034
    if (this.quickFilter && this.entityType == "result") {
1035
      if((URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)   || URLparams["qf"] == "true"
1036
        || ((URLparams[this.quickFilter.filterId] != undefined && StringUtils.URIDecode(URLparams[this.quickFilter.filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1).indexOf(StringUtils.quote(this.quickFilter.value)) != -1))) {
1037
        this.quickFilter.selected = true;
1038
      } else {
1039
        this.quickFilter.selected = false;
1040
      }
1041
      if( this.quickFilter.selected && URLparams[this.quickFilter.filterId] == undefined){
1042
      // if ((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)
1043
      // ||( URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == "true")) {
1044
        allFqs += "&fq=resultbestaccessright exact " + StringUtils.quote(this.quickFilter.value);
1045
      }
1046
    }
1047

    
1048
    if (this.entityType == "result") {
1049
      if (URLparams["type"]) {
1050
        let types = URLparams["type"];
1051
        types = Array.isArray(types) ? types.join(',').split(","):types.split(",");
1052
        types.map( function (t) {
1053
          return StringUtils.unquote(StringUtils.URIDecode(t));
1054
        } );
1055

    
1056
        if(types.indexOf("publications")!=-1 && types.indexOf("datasets")!=-1 && types.indexOf("software")!=-1 && types.indexOf("other")!=-1 ){
1057
          allFqs += "&type=results";
1058
        }else{
1059
          for (let type of types) {
1060
            allFqs += "&type=" + StringUtils.unquote(StringUtils.URIDecode(type));
1061
          }
1062
        }
1063
      }else{
1064
        allFqs += "&type=results";
1065
      }
1066
    } else if (this.entityType == "publication") {
1067
      allFqs += "&type=publications";
1068
    } else if (this.entityType == "dataset") {
1069
      allFqs += "&type=datasets";
1070
    } else if (this.entityType == "software") {
1071
      allFqs += "&type=software";
1072
    } else if (this.entityType == "other") {
1073
      allFqs += "&type=other";
1074
    } else if(this.entityType == "project") {
1075
      allFqs += "&type=projects";
1076
    } else if(this.entityType == "organization") {
1077
      allFqs += "&type=organizations";
1078
    } else if(this.entityType == "dataprovider") {
1079
      allFqs += "&type=datasources";
1080
    }
1081
    // console.log("AllFqs (check type): "+allFqs);
1082
    // console.log("type: "+this.entityType);
1083
    // var keyword = URLparams['keyword'];
1084
    // var doiQuery = "";
1085
    // var keywordQuery = "";
1086
    // if((keyword && keyword.length > 0)){
1087
    //   if((this.type == 'publications' ||this.type == 'research data' || this.type == 'software' || this.type == 'other research products')){
1088
    //     var DOIs:string[] = DOI.getDOIsFromString(keyword);
1089
    //     var doisParams = "";
1090
    //
1091
    //     for(var i =0 ;i < DOIs.length; i++){
1092
    //       doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
1093
    //     }
1094
    //     if(doisParams.length > 0){
1095
    //       doiQuery += "&"+doisParams;
1096
    //     }else {
1097
    //       keywordQuery += "&q="+StringUtils.URIEncode(keyword);
1098
    //     }
1099
    //   }else{
1100
    //     if(this.usedBy == "deposit") {
1101
    //       if(this.keywordFields.length > 0) {
1102
    //         keywordQuery = "&fq=";
1103
    //       }
1104
    //
1105
    //       for(let i=0; i< this.keywordFields.length ; i++) {
1106
    //         if(i > 0) {
1107
    //           keywordQuery += " or ";
1108
    //         }
1109
    //         let field = this.keywordFields[i];
1110
    //         //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
1111
    //         keywordQuery += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
1112
    //       }
1113
    //     } else {
1114
    //       keywordQuery += "&q=" + StringUtils.URIEncode(keyword);
1115
    //     }
1116
    //
1117
    //   }
1118
    // }
1119
    //TODO add DOI?
1120
     return allFqs;
1121

    
1122
  }
1123

    
1124
  /**
1125
   * Create Search API query based on the filters of refine fields
1126
   * @param URLparams
1127
   */
1128
  getSearchAPIQueryForRangeFields(URLparams) {
1129
    let allFqs = "";
1130
    for (let i = 0; i < this.rangeFields.length; i++) {
1131
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1132
      let filterParam = this.searchFieldsHelper.getFieldParam(filterId, this.entityType);
1133

    
1134
      if (URLparams[filterParam] != undefined) {
1135
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterParam]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1136
        var countvalues = 0;
1137
        var fq = "";
1138
        var fqFrom = "";
1139
        var fqTo = "";
1140
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
1141

    
1142
        for (let value of values) {
1143
          if (this.fieldIdsMap[filterId].filterType == "range") {
1144

    
1145
            let selectedFromValue;
1146
            let selectedToValue;
1147

    
1148
            let years: string[] = (value.substring(5)).split(":");
1149
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1150
            //(Number.isInteger(parseInt(years[0], 10)) ? years[0] : null);
1151
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1152
            //console.log("getSearchAPIQueryForRangeFields: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1153
            if(yearFrom) {
1154
              selectedFromValue = yearFrom;
1155
            }
1156
            if(yearTo) {
1157
              selectedToValue = yearTo;
1158
            }
1159
            if(yearFrom || yearTo) {
1160

    
1161
            // if (value.length <= 14) {
1162
            //   if(Dates.isValidYear(value.substring(5, 9))) {
1163
            //     selectedFromValue = value.substring(5, 9);
1164
            //   }
1165
            //   if(Dates.isValidYear(value.substring(10, 14))) {
1166
            //     selectedToValue = value.substring(10, 14);
1167
            //   }
1168

    
1169
              /*if(this.rangeFields[i][0] == this.rangeFields[i][1]) {
1170
                //console.log(selectedFromValue + " - "+selectedToValue);
1171
                if (selectedFromValue && selectedToValue) {
1172
                  let equalityOp = this.fieldIdsMap[filterId].equalityOperator;
1173
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
1174
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1175
                } else if (selectedFromValue) {
1176
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
1177
                  if(equalityOp == " = ") {
1178
                    equalityOp = " >= ";
1179
                  }
1180
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + "\"";
1181
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1182
                } else if (selectedToValue) {
1183
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
1184
                  if(equalityOp == " = ") {
1185
                    equalityOp = " <= ";
1186
                  }
1187
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedToValue + "\"";
1188
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1189
                }
1190
              } else {
1191
                let equalityOpFrom = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
1192
                let equalityOpTo = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
1193

    
1194
                if (selectedFromValue) {
1195
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1196
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1197
                }
1198
                if (selectedToValue) {
1199
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][1] + equalityOpTo + "\"" + selectedToValue + "\"";
1200
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1201
                }
1202
                if(selectedFromValue || selectedToValue) {
1203
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1204
                }
1205
              }*/
1206
              fq = NewSearchPageComponent.createRangeFilterQuery(this.rangeFields[i], selectedFromValue, selectedToValue, this.fieldIdsMap[filterId].equalityOperator, this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator, this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator, filterOp );
1207
            }
1208
          }
1209
        }
1210
        allFqs += fq +fqFrom + fqTo;
1211
      }
1212
    }
1213

    
1214
    return allFqs;
1215

    
1216
  }
1217
  // createRangeFilterQuery(this.rangeFields[i], selectedFromValue, selectedToValue, this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator, this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator; filterOp )
1218
public static createRangeFilterQuery(rangeField,selectedFromValue, selectedToValue, equalityOp, equalityOpFrom, equalityOpTo, filterOp ){
1219
    let fq="";
1220
  if(rangeField[0] == rangeField[1]) {
1221
    //console.log(selectedFromValue + " - "+selectedToValue);
1222
    if (selectedFromValue && selectedToValue) {
1223
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
1224
      fq = "&fq=" + StringUtils.URIEncode(fq);
1225
    } else if (selectedFromValue) {
1226
      if(equalityOpFrom == " = ") {
1227
        equalityOpFrom = " >= ";
1228
      }
1229
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1230
      fq = "&fq=" + StringUtils.URIEncode(fq);
1231
    } else if (selectedToValue) {
1232
      if(equalityOpTo == " = ") {
1233
        equalityOpTo = " <= ";
1234
      }
1235
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpTo + "\"" + selectedToValue + "\"";
1236
      fq = "&fq=" + StringUtils.URIEncode(fq);
1237
    }
1238
  } else {
1239

    
1240
    if (selectedFromValue) {
1241
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1242
      // fq = "&fq=" + StringUtils.URIEncode(fq);
1243
    }
1244
    if (selectedToValue) {
1245
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[1] + equalityOpTo + "\"" + selectedToValue + "\"";
1246
      // fq = "&fq=" + StringUtils.URIEncode(fq);
1247
    }
1248
    if(selectedFromValue || selectedToValue) {
1249
      fq = "&fq=" + StringUtils.URIEncode(fq);
1250
    }
1251

    
1252
  }
1253
  return fq;
1254
}
1255
  /**
1256
   * Sets parameterNames and parameterValues arrays
1257
   * used in paging, advanced search link, Goto()
1258
   * @param filters either query filters or filters defined by the URL parameters
1259
   * @param rangeFilters defined by the URL parameters
1260
   * @param includePage
1261
   */
1262
  buildPageURLParameters(filters:Filter[], rangeFilters: RangeFilter[], includePage: boolean) {
1263
    this.parameterNames.splice(0, this.parameterNames.length);
1264
    this.parameterValues.splice(0, this.parameterValues.length);
1265
    for (var i = 0; i < this.selectedFields.length; i++) {
1266
      //default operator is and
1267
      this.parameterNames.push("f"+i);
1268
      this.parameterValues.push(this.selectedFields[i].id + (this.selectedFields[i].operatorId!='and'?(","+this.selectedFields[i].operatorId):''));
1269
      this.parameterNames.push("fv"+i);
1270
      if (this.selectedFields[i].type == "date") {
1271

    
1272
        if (this.selectedFields[i].dateValue.type == "range") {
1273
          this.parameterValues.push(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to)));
1274
        } else {
1275
          this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].dateValue.type));
1276
        }
1277

    
1278
      } else {
1279
        // console.log(this.selectedFields[i].value +" " + StringUtils.URIEncode(this.selectedFields[i].value))
1280
        this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].value));
1281
      }
1282
    }
1283
    if (includePage) {
1284
      this.parameterNames.push("page");
1285
      this.parameterValues.push("" + this.searchUtils.page);
1286
    }
1287

    
1288
    //if (this.searchUtils.size != this.resultsPerPage) {
1289
    if (this.resultsPerPageChanged) {
1290
      this.parameterNames.push("size");
1291
      //this.parameterValues.push("" + this.searchUtils.size);
1292
      this.parameterValues.push("" + this.resultsPerPageChanged);
1293
    }
1294

    
1295
    //if (this.sort && this.searchUtils.sortBy) {
1296
    if (this.sort && this.sortByChanged) {
1297
      this.parameterNames.push("sortBy");
1298
      //this.parameterValues.push(this.searchUtils.sortBy);
1299
      this.parameterValues.push(this.sortedByChanged);
1300
    }
1301
    for (let filter of filters) {
1302
      var filterLimits = "";
1303
      if (filter.countSelectedValues > 0) {
1304
        for (let value of filter.values) {
1305
          if (value.selected == true) {
1306
            filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + StringUtils.URIEncode(value.id) + '"';
1307
          }
1308
        }
1309
        if (filterLimits.length > 0) {
1310
          this.parameterNames.push(filter.filterId);
1311
          this.parameterValues.push(filterLimits);
1312
        }
1313
      }
1314
    }
1315
    for (let filter of rangeFilters) {
1316
      var filterLimits = "";
1317
      let yearFrom: string = (Dates.isValidYear(filter.selectedFromValue) ? filter.selectedFromValue : null);
1318
      let yearTo: string = (Dates.isValidYear(filter.selectedToValue) ? filter.selectedToValue : null);
1319
      if(yearFrom || yearTo) {
1320
        this.parameterNames.push(filter.filterId);
1321
        this.parameterValues.push("range" + (yearFrom ? yearFrom : "") + ":" + (yearTo ? yearTo : ""));
1322
      }
1323
      // if (filter.countSelectedValues > 0) {
1324
      //   for (let value of filter.values) {
1325
      //     if (value.selected == true) {
1326
      //       filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1327
      //     }
1328
      //   }
1329
      //   if (filterLimits.length > 0) {
1330
      //     this.parameterNames.push(filter.filterId);
1331
      //     this.parameterValues.push(filterLimits);
1332
      //   }
1333
      // }
1334
    }
1335
    if (this.searchUtils.keyword.length > 0) {
1336
      this.parameterNames.push("keyword");
1337
      this.parameterValues.push(this.searchUtils.keyword);
1338
    }
1339

    
1340
    if (this.resultTypes && (this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
1341
      let values = [];
1342
      for(let value of this.resultTypes.values){
1343
        if(value.selected) {
1344
          values.push(value.id);
1345
        }
1346
      }
1347
      this.selectedTypesNum = 0;
1348
      if (values.length > 0 && values.length != 4) {
1349
        this.parameterNames.push("type");
1350
        this.parameterValues.push(values.join(","));
1351
        this.selectedTypesNum = values.length;
1352
      }
1353
      if(this.quickFilter) {
1354
        this.parameterNames.push("qf");
1355
        this.parameterValues.push("" + this.quickFilter.selected);
1356
      }
1357
    }
1358
    if(this.customFilterEnabled){
1359
      this.parameterNames.push("cf");
1360
      this.parameterValues.push("true");
1361
    }
1362
    // if (this.searchUtils.size != this.resultsPerPage) {
1363
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'size=' + this.searchUtils.size;
1364
    //   this.parameterNames.push("size");
1365
    //   this.parameterValues.push("" + this.searchUtils.size);
1366
    // }
1367
    // if (this.sort && this.searchUtils.sortBy) {
1368
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'sortBy=' + this.searchUtils.sortBy;
1369
    //   this.parameterNames.push("sortBy");
1370
    //   this.parameterValues.push(this.searchUtils.sortBy);
1371
    // }
1372
    // console.log(this.parameterNames)
1373
    // console.log(this.parameterValues)
1374
  }
1375

    
1376
  /**
1377
   * create filters based on URL params
1378
   * @param URLparams
1379
   */
1380
  getRefineFiltersFromURL(URLparams) {
1381
    let fields = new SearchFields();
1382
    let filters: Filter[] = [];
1383
    for (let i = 0; i < this.refineFields.length; i++) {
1384
      let filterId = this.refineFields[i];
1385
      if (URLparams[filterId] != undefined) {
1386
        let filter = new Filter();
1387
        filter.title = fields.getFieldName(filterId, this.entityType);
1388
        filter.filterId = filterId;
1389
        filter.originalFilterId = filterId;
1390
        filter.values = [];
1391
        let values = StringUtils.URIDecode(URLparams[filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1392
        for (let value of values) {
1393

    
1394
          let v: Value = new Value();
1395
          v.name = RefineResultsUtils.keepPartAfterCharacters(StringUtils.unquote(value), "||");
1396
          v.name = (v.name.indexOf("::")!=-1)?v.name.substring(v.name.indexOf("::")+2).split("::").join("|"):v.name; // for funding streams
1397
          v.id = StringUtils.unquote(value);
1398
          v.selected = true;
1399
          filter.values.push(v);
1400
          // console.log(v)
1401
          filter.countSelectedValues++;
1402
        }
1403
        filters.push(filter)
1404
      }
1405
    }
1406

    
1407
    if (this.quickFilter) {
1408
      if (this.entityType == "result" && (URLparams[this.quickFilter.filterId] == undefined) && (URLparams["qf"] == undefined || URLparams["qf"] == "true")) {
1409
        let filter = new Filter();
1410
        filter.title = fields.getFieldName(this.quickFilter.filterId, this.entityType);
1411
        filter.filterId = this.quickFilter.filterId;
1412
        filter.originalFilterId = this.quickFilter.filterId;
1413
        filter.values = [];
1414
        let v: Value = new Value();
1415
        v.name = this.quickFilter.value;
1416
        v.id = this.quickFilter.value;
1417
        v.selected = true;
1418
        filter.values.push(v);
1419
        filter.countSelectedValues = 1;
1420
        filters.push(filter)
1421
      }
1422
    }
1423
    if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
1424
      this.resultTypes = {values:[],filterId:"type", countSelectedValues: 0, filterType: 'checkbox', originalFilterId: "", valueIsExact: true, title: "Result Types",filterOperator:"or"};
1425
      if (URLparams["type"]) {
1426
        let types = URLparams["type"];
1427
        types = Array.isArray(types) ? types.join(',').split(","):types.split(",");
1428
        for(let type of types){
1429
          if(["publications", "datasets","software", "other"].indexOf(StringUtils.unquote(type))!=-1 && this.resultTypeOptions[StringUtils.unquote(type)]){
1430
            this.resultTypes.values.push({name: this.resultTypeOptions[StringUtils.unquote(type)].name , id:StringUtils.unquote(type),selected:true, number:0});
1431
            this.resultTypes.countSelectedValues++;
1432
            }
1433
          }
1434

    
1435
      }
1436

    
1437
    }
1438

    
1439
    this.URLCreatedFilters = filters;
1440
  }
1441

    
1442
  /**
1443
   * create range filters based on URL params
1444
   * @param URLparams
1445
   */
1446
  getRangeFiltersFromURL(URLparams) {
1447
    let fields = new SearchFields();
1448
    let filters: RangeFilter[] = [];
1449
    for (let i = 0; i < this.rangeFields.length; i++) {
1450
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1451
      let filterParam = fields.getFieldParam(filterId, this.entityType);
1452
      //console.log("rangeFilter (from url): filterId - filterParam");
1453
      //console.log(filterId + " - "+ filterParam);
1454
      if (URLparams[filterParam] != undefined) {
1455
        let filter = new RangeFilter();
1456
        filter.title = fields.getFieldName(filterId, this.entityType);
1457
        filter.filterId = filterParam;
1458
        filter.originalFilterIdFrom = this.rangeFields[i][0];
1459
        filter.originalFilterIdTo = this.rangeFields[i][1];
1460

    
1461

    
1462
        let values = (decodeURIComponent(URLparams[filterParam])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1463
        for (let j = 0; j < values.length; j++) {
1464
          if (this.fieldIdsMap[filterId].filterType == "range") {
1465
            let value: string = StringUtils.unquote(values[j]);
1466
            let validDates: boolean = true;
1467
            // if (value.length < 14) {
1468
            //   validDates = false;
1469
            // } else {
1470
            //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
1471
            //     validDates = false;
1472
            //   } else {
1473
            //     filter.selectedFromValue = value.substring(5, 9);
1474
            //     filter.selectedToValue = value.substring(10, 14);
1475
            //   }
1476
            // }
1477
            let years: string[] = (value.substring(5)).split(":");
1478
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1479
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1480
            //console.log("getRangeFiltersFromURL: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1481
            if(yearFrom) {
1482
              filter.selectedFromValue = yearFrom;
1483
              //filter.selectedFromAndToValues = yearFrom;
1484
            }
1485
            /*if(yearFrom && yearTo) {
1486
              filter.selectedFromAndToValues += "-";
1487
            }*/
1488
            if(yearTo) {
1489
              filter.selectedToValue = yearTo;
1490
              //filter.selectedFromAndToValues += yearTo;
1491
            }
1492
            //console.log("filter.selectedFromAndToValues: "+filter.selectedFromAndToValues);
1493
            if(!yearFrom && !yearTo) {
1494
              validDates = false;
1495
            }
1496

    
1497
          }
1498
        }
1499
        //console.log(filters);
1500
        filters.push(filter)
1501
      }
1502
    }
1503
    // console.log("Empty Filters");
1504
    // console.log(filters);
1505
    this.URLCreatedRangeFilters = filters;
1506
    // return filters;
1507

    
1508
  }
1509

    
1510
  /**
1511
   * Checks if query has no results, display Filters from URL parameters
1512
   * Mark checked  the selected filters
1513
   * Count the checked
1514
   * @param filters
1515
   */
1516
  public prepareFiltersToShow(filters: Filter[], totalResults): Filter[] {
1517
    if (this.URLCreatedFilters.length > 0 && totalResults == 0) {
1518
      this.showUnknownFilters = true;
1519
      this.filters = this.URLCreatedFilters;
1520
    } else if (totalResults != 0) {
1521
      this.showUnknownFilters = false;
1522
      this.filters = filters;
1523
    }else if((this.URLCreatedFilters.length == 0 && totalResults == 0)){
1524
      this.showUnknownFilters = true;
1525
      this.filters = filters;
1526
    }
1527

    
1528
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1529
    //this.checkSelectedRangeFilters(this.rangeFilters);
1530

    
1531
    this.checkSelectedFilters(this.filters);
1532
    this.countSelectedFilters(this.filters);
1533
    this.updateMeta(this.pageTitle)
1534
    return this.filters;
1535
  }
1536

    
1537
  /**
1538
   * Mark checked  the selected range filters
1539
   */
1540
  public prepareRangeFiltersToShow() {
1541
    this.rangeFilters = RangeFilter.parse(this.rangeFields, this.entityType); // OK
1542

    
1543
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1544
    this.checkSelectedRangeFilters(this.rangeFilters);
1545
    this.countSelectedRangeFilters(this.rangeFilters);
1546
    return this.rangeFilters;
1547
  }
1548

    
1549
  /**
1550
   * Used to set the variables and search page, and prepare it before the getResults query
1551
   * @param fieldIds
1552
   * @param selectedFields
1553
   * @param refineFields
1554
   * @param rangeFields
1555
   * @param fieldIdsMap
1556
   * @param customFilter
1557
   * @param params
1558
   * @param entityType
1559
   * @param quickFilter
1560
   */
1561
  prepareSearchPage(fieldIds, selectedFields, refineFields, rangeFields, fieldIdsMap, customFilter, params, entityType, quickFilter=null){
1562
    // console.log(this.refineFields);
1563
    this.entityType = entityType;
1564
    this.fieldIds = fieldIds;
1565
    this.selectedFields = selectedFields;
1566
    this.refineFields = refineFields;
1567
    this.rangeFields = rangeFields;
1568
    this.fieldIdsMap = fieldIdsMap;
1569
    this.customFilter = customFilter;
1570
    this.quickFilter = quickFilter;
1571
    this.getRangeFiltersFromURL(params);
1572
    this.getRefineFiltersFromURL(params);
1573
    this.createAdvancedSearchSelectedFiltersFromURLParameters(params);
1574
  }
1575

    
1576
  removeResultType(type){
1577
    for(let value of this.resultTypes.values){
1578
      if(type == value.id && value.selected){
1579
        value.selected = false;
1580
        this.goTo(1);
1581
        break;
1582
      }
1583
    }
1584
  }
1585
}
(14-14/44)