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

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

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

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

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

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

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

    
140
  ngOnInit() {
141
      // this.properties = properties;
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
      this.updateMeta(this.pageTitle);
170
    });
171
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
172
    this.breadcrumbs.push({name: 'home', route: '/'});
173
    if(this.simpleView) {
174
      this.breadcrumbs.push( {name: "Search", route: null});
175
    }else if(!this.simpleView && this.advancedSearchLink) {
176
      this.breadcrumbs.push({name: "Advanced Search", route: null});
177
    }
178
    //console.log(this.filters)
179
    if (typeof document !== 'undefined') {
180
      this.subscriptions.push(this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
181
        if (lastIndexUpdate) {
182
          this.indexUpdateDate = new Date(lastIndexUpdate);
183
        }
184
      }));
185
    }
186
  }
187

    
188
  private getPageContents() {
189
    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 => {
190
      this.pageContents = contents;
191
    }));
192

    
193
  }
194

    
195
  private getDivContents() {
196
      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 => {
197
        this.divContents = contents;
198
      }));
199
  }
200

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

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

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

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

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

    
266

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

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

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

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

    
323

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

    
328
    this.goTo(1);
329
  }
330

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

    
337

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

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

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

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

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

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

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

    
407

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

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

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

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

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

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

    
501
              if(!yearFrom && !yearTo) {
502
                validDates = false;
503
              }
504

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

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

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

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

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

    
569
    }
570

    
571
    return filters;
572
  }
573

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

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

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

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

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

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

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

    
651
  }
652

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

    
659
  }
660

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

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

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

    
711
  public closeLoading() {
712
    this.loading.close();
713
  }
714

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

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

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

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

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

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

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

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

    
863
            if(this.usedBy == "deposit") {
864

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

    
882
          } else if(this.selectedFields[i].type == "identifier") {
883
            params += NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
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="' + StringUtils.URIEncode(identifier.id) + '")';
912
          // doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + StringUtils.URIEncode(identifier.id) + '" and (authoridtype exact "orcid"))';
913
        }else{
914
          doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  StringUtils.URIEncode(identifier.id) + '")';
915
          // doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
916
        }
917
      }
918
    }
919
    if (doisParams.length > 0) {
920
      params += "(" + this.createQuotedKeywordQuery(value, id, operatorId ,countParams,true, true) + " or " + doisParams+")";
921
    } else {
922
      //if it is PIDs but no doisquery produced, forced to use quotes as the query will fail due to special characters
923
      params += this.createQuotedKeywordQuery(value, id, operatorId,countParams,true,
924
        (DOIs.length > 0 && doisParams.length == 0) );
925
    }
926
    return params;
927

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

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

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

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

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

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

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

    
1125
  }
1126

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

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

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

    
1148
            let selectedFromValue;
1149
            let selectedToValue;
1150

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

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

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

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

    
1217
    return allFqs;
1218

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

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

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

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

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

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

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

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

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

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

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

    
1438
      }
1439

    
1440
    }
1441

    
1442
    this.URLCreatedFilters = filters;
1443
  }
1444

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

    
1464

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

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

    
1511
  }
1512

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

    
1531
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1532
    //this.checkSelectedRangeFilters(this.rangeFilters);
1533

    
1534
    this.checkSelectedFilters(this.filters);
1535
    this.countSelectedFilters(this.filters);
1536
    this.updateMeta(this.pageTitle)
1537
    return this.filters;
1538
  }
1539

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

    
1546
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1547
    this.checkSelectedRangeFilters(this.rangeFilters);
1548
    this.countSelectedRangeFilters(this.rangeFilters);
1549
    return this.rangeFilters;
1550
  }
1551

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

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