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

    
94
  subscriptions = [];
95
  public parameterNames: string[] = [];
96
  public parameterValues: string[] = [];
97

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

    
112
  @Input() entitiesSelection:boolean = true;
113
  @Input() showSwitchSearchLink:boolean = true;
114

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

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

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

    
139
  ngOnInit() {
140
      this.properties = properties;
141
      //this.getDivContents();
142
      this.getPageContents();
143
      this.pagingLimit = this.properties.pagingLimit;
144
      this.resultsPerPage = this.properties.resultsPerPage;
145
      this.csvLimit = this.properties.csvLimit;
146
      this.isPiwikEnabled = this.properties.enablePiwikTrack;
147
      this.updateUrl(this.properties.domain + this.properties.baseLink + this.router.url);
148
      this.url = this.properties.domain + this.properties.baseLink + this.router.url;
149
      if (typeof document !== 'undefined' && this.isPiwikEnabled && !this.includeOnlyResultsAndFilter && this.piwikSiteId) {
150
        this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe());
151
      }
152
    this.route.queryParams.subscribe(params => {
153
      if (params['page'] && params['page'] != 1) {
154
        HelperFunctions.scrollToId("searchForm");
155
      }
156
      this.customFilterEnabled = params['cf'] && params['cf'] == "true";
157
    });
158
    if (!this.includeOnlyResultsAndFilter) {
159
      if(this.basicMetaDescription.length == 0 ){
160
        if (this.entityType == "result") {
161
          this.basicMetaDescription =  ["Discover" + (this.properties.adminToolsCommunity == 'openaire'?"over 100 million of":"")+" research outcomes ", "categorized by research type, year range, funder, languages, community and content providers."];
162
        } else if (this.entityType == "project") {
163
          this.basicMetaDescription =  ["Discover research projects and correlated research categorized by Funder and active year. ", "Statistics data about produced research outcomes per year available."];
164
        } else if (this.entityType == "organization") {
165
          this.basicMetaDescription =  ["Discover worldwide research organizations from over 100 countries and correlated research. ", "Funding, content providers, research pubblications and research data available."];
166
        }else{
167
          this.basicMetaDescription.push(this.pageTitle)
168
        }
169
      }
170
      this.metaDescription = this.basicMetaDescription.join(" ");
171
      this.updateTitle(this.pageTitle);
172
      this.updateDescription();
173
    }
174

    
175
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
176
    this.seoService.createLinkForCanonicalURL(this.properties.domain + this.properties.baseLink + this.router.url, false);
177
    this.breadcrumbs.push({name: 'home', route: '/'});
178
    if(this.simpleView) {
179
      this.breadcrumbs.push( {name: "Search", route: null});
180
    }else if(!this.simpleView && this.advancedSearchLink) {
181
      this.breadcrumbs.push({name: "Advanced Search", route: null});
182
    }
183
    //console.log(this.filters)
184
    if (typeof document !== 'undefined') {
185
      this.subscriptions.push(this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
186
        if (lastIndexUpdate) {
187
          this.indexUpdateDate = new Date(lastIndexUpdate);
188
        }
189
      }));
190
    }
191
  }
192

    
193
  private getPageContents() {
194
    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 => {
195
      this.pageContents = contents;
196
    }));
197

    
198
  }
199

    
200
  private getDivContents() {
201
      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 => {
202
        this.divContents = contents;
203
      }));
204
  }
205

    
206
  ngOnDestroy() {
207
    this.subscriptions.forEach(subscription => {
208
      if (subscription instanceof Subscriber) {
209
        subscription.unsubscribe();
210
      }
211
    });
212
  }
213

    
214
  updateDescription() {
215
    // this.metaDescription2 = "";
216
    /*if(this.resultTypes){
217
      let array = [];
218
      for(let type of this.resultTypeOptions){
219
        if(this.resultTypes[type.id]== true){
220
          array.push(type.name);
221
        }
222
      }
223
      if(array.length == 0){
224
        this.metaDescription += "research outcomes ";
225
      }else{
226
        this.metaDescription += array.join(", ") + " ";
227
      }
228
    }else{
229
      this.metaDescription = this.pageTitle + " ";
230
    }*/
231
    let filterArray = [];
232
    for(let filter of this.filters){
233
      if(filter.countSelectedValues> 0){
234
       for(let value of filter.values){
235
         if(value.selected) {
236
           filterArray.push(value.name);
237
         }
238
        }
239
      }
240
    }
241
    for(let field of this.selectedFields){
242
      if((field.type == "entity" || field.type == "refine") && field.valueLabel.length > 0 && filterArray.indexOf(field.valueLabel)==-1){
243
        filterArray.push(field.valueLabel)
244
      }else if(!(field.type == "entity" || field.type == "refine")  && field.value.length > 0 && filterArray.indexOf(field.value)==-1) {
245
        filterArray.push(field.value);
246
      }
247
    }
248
    this.metaDescription= (filterArray.length > 0?( this.basicMetaDescription[0] + " Filtered by: " + filterArray.join(", ") + " ")
249
      :this.basicMetaDescription.join(" "));
250
    this._meta.updateTag({content: this.metaDescription}, "name='description'");
251
    this._meta.updateTag({content: this.metaDescription}, "property='og:description'");
252
  }
253

    
254
  updateTitle(title: string) {
255
    var _prefix = "";
256
    if (this.hasPrefix) {
257
      _prefix = "OpenAIRE | ";
258
    }
259
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
260
    this._title.setTitle(_title);
261
    this._meta.updateTag({content: _title}, "property='og:title'");
262
  }
263

    
264
  updateUrl(url: string) {
265
    this._meta.updateTag({content: url}, "property='og:url'");
266
  }
267

    
268

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

    
295
  goTo(page: number = 1, scroll:boolean = true) {
296
    if(this.offcanvasElement && (typeof document !== 'undefined')) {
297
      UIkit.offcanvas(this.offcanvasElement.nativeElement).hide();
298
    }
299

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

    
317
  queryChanged($event) {
318
    if($event == "filters_update"){
319
      this.cdr.detectChanges();
320
      return;
321
    }
322
    this.goTo(1, false);
323
  }
324

    
325

    
326
  sizeChanged($event) {
327
    //this.searchUtils.size = $event.value;
328
    this.resultsPerPageChanged = $event;
329

    
330
    this.goTo(1);
331
  }
332

    
333
  sortByChanged($event) {
334
    //this.searchUtils.sortBy = $event.value;
335
    this.sortedByChanged = $event;
336
    this.goTo(1);
337
  }
338

    
339

    
340
  getOperatorParameter(parameter: string): string {
341
    for (let id of this.fieldIds) {
342
      if (this.fieldIdsMap[id]["param"] == parameter) {
343
        return this.fieldIdsMap[id]["operator"];
344
      }
345
    }
346
  }
347

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

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

    
376
  /*
377
  * 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 )
378
  */
379
  public getFields(): string[] {
380
    var selected_filters: string[] = this.getSelectedFilters();
381
    if (selected_filters.length == 0) {
382
      selected_filters = this.getSelectedParameters();
383
    }
384
    var fields: string[] = [];
385
    for (var i = 0; i < this.refineFields.length; i++) {
386
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
387

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

    
396
  /*
397
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
398
  */
399
  public getRefineFieldsQuery(): string {
400

    
401
    var fields: string[] = this.getFields();
402
    var fieldsStr = ""
403
    for (var i = 0; i < fields.length; i++) {
404
      fieldsStr += "&fields=" + fields[i];
405
    }
406
    return "&refine=true" + fieldsStr;
407
  }
408

    
409

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

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

    
465
  /*
466
* Mark as check the new range filters that are selected
467
*/
468
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
469
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
470

    
471
    this.rangeFilters = filters;
472
    for (let i = 0; i < filters.length; i++) {
473
      let filter: RangeFilter = filters[i];
474

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

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

    
503
              if(!yearFrom && !yearTo) {
504
                validDates = false;
505
              }
506

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

    
531
  get existingFiltersWithValues() {
532
    if(this.filters.length == 0) {
533
      return 0;
534
    }
535
    return this.filters.some(filter => (filter.values && filter.values.length > 0));
536
  }
537

    
538
  /*
539
  * For Funder filters - if funder selected
540
  */
541
  public filterFilterValues(filters: Filter[]) {
542
    var funders = [];
543
    var funder_prefix = [];
544
    for (var i = 0; i < filters.length; i++) {
545

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

    
565
        }
566
        if (filteredValues.length > 0) {
567
          filter.values = filteredValues;
568
        }
569
      }
570

    
571
    }
572

    
573
    return filters;
574
  }
575

    
576
  public countSelectedFilters(filters: Filter[]): number {
577
    this.selectedFilters = 0;
578
    for (let filter of filters) {
579
      if (filter.countSelectedValues > 0) {
580
        this.selectedFilters += filter.countSelectedValues;
581
      }
582
    }
583
    return this.selectedFilters;
584
  }
585

    
586
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
587
    this.selectedRangeFilters = 0;
588
    for(let filter of rangeFilters) {
589
      if(filter.selectedFromValue || filter.selectedToValue) {
590
        this.selectedRangeFilters++;
591
      }
592
    }
593
    return this.selectedRangeFilters;
594
  }
595

    
596
  private clearKeywords() {
597
    if (this.searchUtils.keyword.length > 0) {
598
      this.searchUtils.keyword = '';
599
    }
600
    this.goTo(1);
601
  }
602

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

    
631
  closeCustomFilterModal() {
632
    this.customFilterEnabled = false;
633
    this.removeFilter(this.currentValueToRemove, this.currentFilterToRemove, true);
634
  }
635

    
636
  public removeRangeFilter(filter: RangeFilter) {
637
    filter.selectedFromValue = null;
638
    filter.selectedToValue = null;
639
    this.goTo(1);
640
  }
641

    
642
  getSelectedValues(filter): any {
643
    var selected = [];
644
    if (filter.countSelectedValues > 0) {
645
      for (var i = 0; i < filter.values.length; i++) {
646
        if (filter.values[i].selected) {
647
          selected.push(filter.values[i]);
648
        }
649
      }
650
    }
651
    return selected;
652

    
653
  }
654

    
655
  filterChanged($event) {
656
    if (this.quickFilter && this.quickFilter.filter) {
657
      this.removeValueFromQuickFilter();
658
    }
659
    this.goTo(1);
660

    
661
  }
662

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

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

    
707
  }
708
  // for loading
709
  public openLoading() {
710
    this.loading.open();
711
  }
712

    
713
  public closeLoading() {
714
    this.loading.close();
715
  }
716

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

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

    
756
          } else {
757
            this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type,value, operator));
758
          }
759

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

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

    
807
            } else {
808
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
809
            }
810
          }
811
        }
812
      }
813
    }
814
    if (params['keyword'] && params['keyword'].length > 0) {
815
      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"));
816
    }
817
    if (this.selectedFields.length == 0) {
818
      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"));
819
    }
820
  }
821

    
822
  /**
823
   * Create Search API query based on the selected fields of the advanced form
824
   */
825
  getSearchAPIQueryForAdvancedSearhFields() {
826

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

    
865
            if(this.usedBy == "deposit") {
866

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

    
884
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
885
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
886
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
887
            params+=NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams, false);
888
          }else{
889
              params += (countParams == 0 ? "" : " " + this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
890

    
891
          }
892
        }
893
        countParams++;
894
      }
895
    }
896

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

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

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

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

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

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

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

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

    
1123
  }
1124

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

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

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

    
1146
            let selectedFromValue;
1147
            let selectedToValue;
1148

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

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

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

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

    
1215
    return allFqs;
1216

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

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

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

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

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

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

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

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

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

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

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

    
1436
      }
1437

    
1438
    }
1439

    
1440
    this.URLCreatedFilters = filters;
1441
  }
1442

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

    
1462

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

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

    
1509
  }
1510

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

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

    
1532
    this.checkSelectedFilters(this.filters);
1533
    this.countSelectedFilters(this.filters);
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/47)