Project

General

Profile

1
import {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, DOI, 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

    
22
declare var UIkit: any;
23

    
24
@Component({
25
  selector: 'new-search-page',
26
  templateUrl: 'newSearchPage.component.html'
27
})
28
export class NewSearchPageComponent {
29
  @ViewChild('offcanvas_element') offcanvasElement: ElementRef;
30

    
31
  @Input() piwikSiteId = null;
32
  @Input() hasPrefix: boolean = true;
33
  @Input() pageTitle = "";
34
  @Input() results = [];
35
  @Input() type;
36
  @Input() entityType;
37
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
38
  @Input() fieldIds: string[];
39
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
40
  @Input() selectedFields: AdvancedField[];
41
  @ViewChild(ModalLoading) loading: ModalLoading;
42
  @Input() csvParams: string;
43
  @Input() csvPath: string;
44
  @Input() simpleSearchLink: string = "";
45
  @Input() advancedSearchLink: string = "";
46
  @Input() disableForms: boolean = false;
47
  @Input() loadPaging: boolean = true;
48
  @Input() oldTotalResults: number = 0;
49
  @Input() openaireLink: string;
50
  @Input() customFilter: SearchCustomFilter = null;
51
  @Input() sort: boolean = false;
52
  @Input() searchFormClass: string = "searchForm";
53
  //From simple:
54
  @Input() rangeFilters: RangeFilter[] = [];
55
  @Input() rangeFields: string[][] = [];
56
  @Input() refineFields = [];
57
  @Input() filters = [];
58
  selectedFilters: number = 0;
59
  selectedRangeFilters: number = 0;
60
  private searchFieldsHelper: SearchFields = new SearchFields();
61
  @Input() newQueryButton: boolean = true;
62
  public showUnknownFilters: boolean = false; // when a filter exists in query but has no results, so no filters returned from the query
63
  URLCreatedFilters: Filter[] = [];
64
  URLCreatedRangeFilters: RangeFilter[] = [];
65
  @Input() showRefine: boolean = true;
66
  @Input() tableViewLink: string;
67
  @Input() usedBy: string = "search";
68
  @Input() public zenodoInformation: ZenodoInformationClass = new ZenodoInformationClass();
69
  @Input() showLastIndex: boolean = true;
70
  @Input() showResultCount: boolean = true;
71
  @Input() showMoreFilterValuesInline: boolean = true;
72
  @Input() filterValuesNum: number = 6;
73
  @Input() keywordFields = [];
74
  @Input() simpleView: boolean = true;
75
  @Input() formPlaceholderText = "Type Keywords...";
76
  @Input() resultTypes = null;
77
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
78
  @Input() includeOnlyResultsAndFilter:boolean = false;
79
  @Input() lastIndex: boolean = true;
80

    
81
  piwiksub: any;
82
  public parameterNames: string[] = [];
83
  public parameterValues: string[] = [];
84

    
85
  public csvLimit: number = 0;
86
  public pagingLimit: number = 0;
87
  public resultsPerPage: number = 0;
88
  isPiwikEnabled = false;
89
  properties: EnvProperties;
90
  public pageContents = null;
91
  public divContents = null;
92
  public routerHelper: RouterHelper = new RouterHelper();
93
  public errorCodes: ErrorCodes = new ErrorCodes();
94

    
95
  url = null;
96

    
97
  @Input() entitiesSelection:boolean = true;
98
  @Input() showAdvancedSearchLink:boolean = true;
99
  constructor(private route: ActivatedRoute,
100
              private location: Location,
101
              private _meta: Meta,
102
              private _title: Title,
103
              private _piwikService: PiwikService,
104
              private router: Router,
105
              private seoService: SEOService,
106
              private helper: HelperService) {
107
  }
108

    
109
  ngOnInit() {
110
    this.route.data
111
      .subscribe((data: { envSpecific: EnvProperties }) => {
112
        this.properties = data.envSpecific;
113
        //this.getDivContents();
114
        this.getPageContents();
115
        this.pagingLimit = data.envSpecific.pagingLimit;
116
        this.resultsPerPage = data.envSpecific.resultsPerPage;
117
        this.csvLimit = data.envSpecific.csvLimit;
118
        this.isPiwikEnabled = data.envSpecific.enablePiwikTrack;
119
        if (typeof window !== 'undefined') {
120
          this.updateUrl(data.envSpecific.baseLink + location.pathname);
121
          this.url = data.envSpecific.baseLink + location.pathname
122
        }
123
        if (typeof document !== 'undefined' && this.isPiwikEnabled) {
124
          this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
125
        }
126
      });
127

    
128
    var description = "Openaire, search, repositories, open access, type, content provider, funder, project, " + this.pageTitle;
129

    
130
    this.updateTitle(this.pageTitle);
131
    this.updateDescription(description);
132

    
133
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
134
    this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.router.url, false);
135

    
136

    
137
  }
138

    
139
  private getPageContents() {
140
    this.helper.getPageHelpContents(this.router.url, this.properties, (this.customFilter) ? this.customFilter.valueId : null).subscribe(contents => {
141

    
142
      this.pageContents = contents;
143
    })
144
  }
145

    
146
  private getDivContents() {
147
    this.helper.getDivHelpContents(this.router.url, this.properties, (this.customFilter) ? this.customFilter.valueId : null).subscribe(contents => {
148
      this.divContents = contents;
149
    })
150
  }
151

    
152
  ngOnDestroy() {
153
    if (this.piwiksub) {
154
      this.piwiksub.unsubscribe();
155
    }
156
  }
157

    
158
  updateDescription(description: string) {
159
    this._meta.updateTag({content: description}, "name='description'");
160
    this._meta.updateTag({content: description}, "property='og:description'");
161
  }
162

    
163
  updateTitle(title: string) {
164
    var _prefix = "";
165
    if (this.hasPrefix) {
166
      _prefix = "OpenAIRE | ";
167
    }
168
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
169
    this._title.setTitle(_title);
170
    this._meta.updateTag({content: _title}, "property='og:title'");
171
  }
172

    
173
  updateUrl(url: string) {
174
    this._meta.updateTag({content: url}, "property='og:url'");
175
  }
176

    
177

    
178
  clearFilters() {
179
    for (var i = 0; i < this.filters.length; i++) {
180
      for (var j = 0; j < this.filters[i].countSelectedValues; j++) {
181
        if (this.filters[i].values[j].selected) {
182
          this.filters[i].values[j].selected = false;
183
        }
184
        this.filters[i].countSelectedValues = 0;
185
      }
186
    }
187
    this.selectedFilters = 0;
188
    for(let i = 0; i < this.rangeFilters.length; i++) {
189
      this.rangeFilters[i].selectedFromValue = null;
190
      this.rangeFilters[i].selectedToValue = null;
191
    }
192
    this.selectedRangeFilters = 0;
193
    if (this.quickFilter) {
194
      this.removeValueFromQuickFilter();
195
    }
196
    this.goTo(1);
197
    // this.clearKeywords();
198
  }
199

    
200
  goTo(page: number = 1) {
201
    if(this.offcanvasElement) {
202
      UIkit.offcanvas(this.offcanvasElement.nativeElement).hide();
203
    }
204

    
205
    this.searchUtils.page = page;
206
    this.buildPageURLParameters(this.filters, this.rangeFilters, true);
207
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
208
    /* Code For Piwik*/
209
    if (typeof localStorage !== 'undefined') {
210
      //console.log("In PreviousRouteRecorder : "+this.router.url );
211
      localStorage.setItem('previousRoute', this.router.url);
212
    }
213
    if (this.isPiwikEnabled && (typeof document !== 'undefined')) {
214
      this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
215
    }
216
    /* End Piwik Code */
217
  }
218

    
219
  queryChanged() {
220

    
221
    this.goTo(1);
222
  }
223

    
224

    
225
  sizeChanged($event) {
226
    this.searchUtils.size = $event.value;
227
    this.goTo(1);
228
  }
229

    
230
  sortByChanged($event) {
231
    this.searchUtils.sortBy = $event.value;
232
    this.goTo(1);
233
  }
234

    
235

    
236
  getOperatorParameter(parameter: string): string {
237
    for (let id of this.fieldIds) {
238
      if (this.fieldIdsMap[id]["param"] == parameter) {
239
        return this.fieldIdsMap[id]["operator"];
240
      }
241
    }
242
  }
243

    
244
  /*
245
* Get A sub-array of this.refineFields array, which contains the ids of the selected filters
246
*/
247
  public getSelectedFilters(): string[] {
248
    var selected: string[] = [];
249
    for (var i = 0; i < this.filters.length; i++) {
250
      var filter: Filter = this.filters[i];
251
      if (filter.countSelectedValues > 0) {
252
        selected.push(filter.filterId);
253
      }
254
    }
255
    return selected;
256
  }
257

    
258
  /*
259
    * Get A sub-array of this.refineFields array, which contains the ids of the selected parameters
260
    */
261
  private getSelectedParameters(): string[] {
262
    var selected: string[] = [];
263
    for (var i = 0; i < this.refineFields.length; i++) {
264
      if (this.parameterNames.indexOf(this.refineFields[i]) != -1) {
265
        selected.push(this.refineFields[i]);
266
      }
267
    }
268
    return selected;
269
  }
270

    
271
  /*
272
  * 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 )
273
  */
274
  public getFields(): string[] {
275
    var selected_filters: string[] = this.getSelectedFilters();
276
    if (selected_filters.length == 0) {
277
      selected_filters = this.getSelectedParameters();
278
    }
279
    var fields: string[] = [];
280
    for (var i = 0; i < this.refineFields.length; i++) {
281
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
282

    
283
      //if filter is not marked as hidden OR it is hidden but it is dependent to a field that it IS selected
284
      if (this.searchFieldsHelper.HIDDEN_FIELDS.indexOf(this.refineFields[i]) == -1 || (selected_filters.indexOf(dependentTo) != -1) || (selected_filters.indexOf(this.refineFields[i]) != -1)) {
285
        fields.push(this.refineFields[i]);
286
      }
287
    }
288
    return fields;
289
  }
290

    
291
  /*
292
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
293
  */
294
  public getRefineFieldsQuery(): string {
295

    
296
    var fields: string[] = this.getFields();
297
    var fieldsStr = ""
298
    for (var i = 0; i < fields.length; i++) {
299
      fieldsStr += "&fields=" + fields[i];
300
    }
301
    return "&refine=true" + fieldsStr;
302
  }
303

    
304

    
305
  /*
306
  * Mark as check the new filters that are selected, when you get them from search
307
  */
308
  public checkSelectedFilters(filters: Filter[]) {
309
    this.filters = filters;
310
    for (var i = 0; i < filters.length; i++) {
311
      var filter: Filter = filters[i];
312
      filter.countSelectedValues = 0;
313
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
314
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
315
        for (let filterValue of filter.values) {
316
          if (values.indexOf(StringUtils.quote(filterValue.id)) > -1) {
317
            filterValue.selected = true;
318
            filter.countSelectedValues++;
319
          } else {
320
            filterValue.selected = false;
321

    
322
          }
323
        }
324
      } else if (this.quickFilter && this.quickFilter.filterId == filter.filterId && this.quickFilter.selected) {
325
        for (let filterValue of filter.values) {
326
          if (filterValue.id == this.quickFilter.value) {
327
            filterValue.selected = true;
328
            filter.countSelectedValues++;
329
          } else {
330
            filterValue.selected = false;
331
          }
332
        }
333
      } else {
334
        for (let filterValue of filter.values) {
335
          filterValue.selected = false;
336
        }
337
      }
338
      if (this.quickFilter && filter.filterId == this.quickFilter.filterId) {
339
        this.quickFilter.filter = filter;
340
      }
341
    }
342
    this.filterFilterValues(this.filters);
343
    return filters;
344
  }
345

    
346
  /*
347
* Mark as check the new range filters that are selected
348
*/
349
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
350
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
351

    
352
    this.rangeFilters = filters;
353
    for (let i = 0; i < filters.length; i++) {
354
      let filter: RangeFilter = filters[i];
355

    
356
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
357
        //console.log(filter.filterId + " "+this.parameterNames.indexOf(filter.filterId) );
358
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
359
        let operators: string [] = (StringUtils.URIDecode(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
360
        if (values.length == operators.length) {
361
          for (let j = 0; j < values.length; j++) {
362
            if (this.fieldIdsMap[filter.originalFilterIdFrom+"-range-"+filter.originalFilterIdTo].filterType == "range") {
363
              let value: string = StringUtils.unquote(values[j]);
364
              let validDates: boolean = true;
365

    
366
              let years: string[] = (value.substring(5)).split(":");
367
              let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
368
              let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
369
              //console.log("checkSelectedRangeFilters: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
370
              if(yearFrom) {
371
                filter.selectedFromValue = yearFrom;
372
              }
373
              if(yearTo) {
374
                filter.selectedToValue = yearTo;
375
              }
376
              if(yearFrom && yearTo) {
377
                filter.selectedFromAndToValues = yearFrom + "-" + yearTo;
378
              } else if(yearFrom) {
379
                filter.selectedFromAndToValues = "From " + yearFrom;
380
              } else if(yearTo) {
381
                filter.selectedFromAndToValues = "Until " + yearTo;
382
              }
383

    
384
              if(!yearFrom && !yearTo) {
385
                validDates = false;
386
              }
387

    
388
              // if (value.length < 14) {
389
              //   validDates = false;
390
              //   console.log("not valid (length<14)");
391
              // } else {
392
              //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
393
              //     validDates = false;
394
              //     console.log("not valid years");
395
              //   } else {
396
              //     filter.selectedFromValue = value.substring(5, 9);
397
              //     filter.selectedToValue = value.substring(10, 14);
398
              //     console.log(filter);
399
              //   }
400
              // }
401
            }
402
          }
403
        }
404
      } else {
405
        filter.selectedFromValue = null;
406
        filter.selectedToValue = null;
407
      }
408
    }
409
    return this.rangeFilters;
410
  }
411

    
412
  /*
413
  * For Funder filters - if funder selected
414
  */
415
  public filterFilterValues(filters: Filter[]) {
416
    var funders = [];
417
    var funder_prefix = [];
418
    for (var i = 0; i < filters.length; i++) {
419

    
420
      var filter: Filter = filters[i];
421
      //  console.log(filter.filterId);
422
      if (filter.filterId.indexOf("funder") != -1 && this.parameterNames.indexOf(filter.filterId) != -1) {
423
        let funders = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
424
        for (let funder of funders) {
425
          funder_prefix.push(StringUtils.unquote(funder).split("____")[0]);
426
        }
427
        //  console.log(funder_prefix );
428
      } else if (filter.filterId.indexOf("funding") != -1) {
429
        //  console.log(" funding: "+filter.filterId );
430
        var filteredValues = []
431
        for (let filterValue of filter.values) {
432
          var value_prefix = filterValue.id.split("____")[0];
433
          //  console.log("Value prefix: "+value_prefix );
434
          if (funder_prefix.indexOf(value_prefix) != -1) {
435
            //  console.log("here" + value_prefix);
436
            filteredValues.push(filterValue);
437
          }
438

    
439
        }
440
        if (filteredValues.length > 0) {
441
          filter.values = filteredValues;
442
        }
443
      }
444

    
445
    }
446

    
447
    return filters;
448
  }
449

    
450
  public countSelectedFilters(filters: Filter[]): number {
451
    this.selectedFilters = 0;
452
    for (let filter of filters) {
453
      if (filter.countSelectedValues > 0) {
454
        this.selectedFilters += filter.countSelectedValues;
455
      }
456
    }
457
    return this.selectedFilters;
458
  }
459

    
460
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
461
    this.selectedRangeFilters = 0;
462
    for(let filter of rangeFilters) {
463
      if(filter.selectedFromValue || filter.selectedToValue) {
464
        this.selectedRangeFilters++;
465
      }
466
    }
467
    return this.selectedRangeFilters;
468
  }
469

    
470
  private clearKeywords() {
471
    if (this.searchUtils.keyword.length > 0) {
472
      this.searchUtils.keyword = '';
473
    }
474
    this.goTo(1);
475
  }
476

    
477
  public removeFilter(value: Value, filter: Filter) {
478
    filter.countSelectedValues--;
479
    this.selectedFilters--;
480
    if (value.selected == true) {
481
      value.selected = false;
482
    }
483
    if (this.quickFilter && this.quickFilter.filterId == filter.filterId) {
484
      this.removeValueFromQuickFilter();
485
    }
486
    this.goTo(1);
487
  }
488

    
489
  public removeRangeFilter(filter: RangeFilter) {
490
    filter.selectedFromValue = null;
491
    filter.selectedToValue = null;
492
    this.goTo(1);
493
  }
494

    
495
  getSelectedValues(filter): any {
496
    var selected = [];
497
    if (filter.countSelectedValues > 0) {
498
      for (var i = 0; i < filter.values.length; i++) {
499
        if (filter.values[i].selected) {
500
          selected.push(filter.values[i]);
501
        }
502
      }
503
    }
504
    return selected;
505

    
506
  }
507

    
508
  filterChanged($event) {
509
    if (this.quickFilter && this.quickFilter.filter) {
510
      this.removeValueFromQuickFilter();
511
    }
512
    this.goTo(1);
513

    
514
  }
515

    
516
  /**
517
   * if there is a change in the values of the quick filter, this function has to be run, to also update the quickFilter
518
   */
519
  removeValueFromQuickFilter() {
520
    if (this.quickFilter.filter.countSelectedValues == 0) {
521
      this.quickFilter.selected = false;
522
    } else {
523
      let isQuickEnabled = false;
524
      for (let filterValue of this.quickFilter.filter.values) {
525
        isQuickEnabled = (filterValue.name == this.quickFilter.value)
526
      }
527
      this.quickFilter.selected = (isQuickEnabled && this.quickFilter.filter.countSelectedValues == 1);
528
    }
529
  }
530

    
531
  // for loading
532
  public openLoading() {
533
    this.loading.open();
534
  }
535

    
536
  public closeLoading() {
537
    this.loading.close();
538
  }
539

    
540
  /**
541
   * Build advanced search Filters based on the URL parameters
542
   * @param params
543
   */
544
  createAdvancedSearchSelectedFiltersFromNewURLParameters(params) {
545
    for (let i = 0; i < Object.keys(params).length; i++) {
546
      if(params["f"+i] && params["fv"+i]   ) {
547
        let fieldId = params["f" + i].split(",")[0];
548
        let operator = (params["f" + i].split(",").length  >1 )?params["f" + i].split(",")[1]:"and";
549
        let fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
550

    
551
        if (!this.fieldIdsMap[fieldId]) {
552
          console.error("Field: " + fieldId + " not found in fieldIds map");
553
          continue;
554
        }
555
        let value: string = StringUtils.URIDecode(params["fv"+i]);
556
        if (this.fieldIdsMap[fieldId].type == "date") {
557
            let validDates: boolean = true;
558
            let dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operator);
559
            if (value.indexOf("range") != -1) {
560
              dateField.dateValue.type = "range";
561
              if (value.length < 26) {
562
                validDates = false;
563
              } else {
564
                if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
565
                  validDates = false;
566
                } else {
567
                  dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
568
                  dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
569
                }
570
              }
571
              //  "rangeYYYY-MM-DD:YYYY-MM-DD"
572
            } else {
573
              dateField.dateValue.setDatesByType(value);
574
            }
575
            if (validDates) {
576
              this.selectedFields.push(dateField);
577
            }
578

    
579
          } else {
580
            this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type,value, operator));
581
          }
582

    
583
        }
584
      }
585
  }
586
  /**
587
   * Build advanced search Filters based on the URL parameters
588
   * @param params
589
   */
590
  createAdvancedSearchSelectedFiltersFromURLParameters(params) {
591
    this.createAdvancedSearchSelectedFiltersFromNewURLParameters(params);
592
    for (var i = 0; i < this.fieldIds.length; i++) {
593
      var fieldId = this.fieldIds[i];
594
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
595
      if (!this.fieldIdsMap[fieldId]) {
596
        console.error("Field: " + fieldId + " not found in fieldIds map");
597
        continue;
598
      }
599

    
600
      var operatorId = this.getOperatorParameter(fieldparam);
601
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
602
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
603
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
604
        if (values.length == operators.length) {
605
          for (var j = 0; j < values.length; j++) {
606
            if (this.fieldIdsMap[fieldId].type == "date") {
607
              var value: string = StringUtils.unquote(values[j]);
608
              var validDates: boolean = true;
609
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
610
              if (value.indexOf("range") != -1) {
611
                dateField.dateValue.type = "range";
612
                if (value.length < 26) {
613
                  validDates = false;
614
                } else {
615
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
616
                    validDates = false;
617
                  } else {
618
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
619
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
620
                  }
621
                }
622
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
623
              } else {
624
                dateField.dateValue.setDatesByType(value);
625
              }
626
              if (validDates) {
627
                this.selectedFields.push(dateField);
628
              }
629

    
630
            } else {
631
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
632
            }
633
          }
634
        }
635
      }
636
    }
637
    if (params['keyword'] && params['keyword'].length > 0) {
638
      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"));
639
    }
640
    if (this.selectedFields.length == 0) {
641
      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"));
642
    }
643
  }
644

    
645
  /**
646
   * Create Search API query based on the selected fields of the advanced form
647
   */
648
  getSearchAPIQueryForAdvancedSearhFields() {
649

    
650
    var params = "";
651
    var countParams = 0;
652
    for (var i = 0; i < this.selectedFields.length; i++) {
653
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
654
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
655
        if (this.selectedFields[i].type == "date") {
656
          if (this.selectedFields[i].dateValue.type != "any") {
657
            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)) + " "
658
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
659
          }
660
        } else {
661
          if (this.selectedFields[i].id == "q") {
662
            console.log(this.selectedFields[i].value)
663
            var op = "";
664
            var doisParams = "";
665
            if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
666
              var DOIs: Identifier[] = Identifier.getIdentifiersFromString(this.selectedFields[i].value);
667
              for (let identifier of DOIs) {
668
                console.log(identifier)
669
                // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
670
                //and (authorid exact \"0000-0001-7291-3210 \" )"
671
                if(identifier.class == "ORCID"){
672
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
673
                }else{
674
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
675
                }
676
              }
677
            }
678
            if (doisParams.length > 0) {
679
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId ,countParams,true, true) + " or " + doisParams;
680
            } else {
681
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId,countParams,true);
682
            }
683
            //TODO deposit case
684
            console.log(this.usedBy)
685
            console.log(this.keywordFields)
686

    
687
            if(this.usedBy == "deposit") {
688

    
689
              if(this.keywordFields.length > 0) {
690
                params += " or ("
691
              }
692
              for(let j=0; j< this.keywordFields.length ; j++) {
693
                if(j > 0) {
694
                  params += " or "
695
                }
696
                params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.keywordFields[j].name, " or ", countParams,false);
697
                // let field = this.keywordFields[i];
698
                //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
699
                // params += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
700
              }
701
              if(this.keywordFields.length > 0) {
702
                params += " ) "
703
              }
704
            }
705

    
706
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
707
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
708
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
709
            params+=this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams, false);
710
          }else{
711
              params += (countParams == 0 ? "" : this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
712

    
713
          }
714
        }
715
        countParams++;
716
      }
717
    }
718

    
719
    if (this.customFilter) {
720
      params += (countParams == 0 ? "" : " and ") + this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId));
721
    }
722
    console.log("ParameterS:")
723
    console.log(params)
724
    return params;
725
  }
726

    
727
  createQuotedKeywordQuery(fieldValue, fieldId, fieldOperator, countParams:number, isSearchAll:boolean, forceQuotted:boolean=false){
728
    let params = "";
729
    let quotedParts = (fieldValue)?fieldValue.match(/(["'])(.*?)*?\1/g):[];
730
    params+= (countParams == 0 ? "" : fieldOperator) + " (";
731
    if(forceQuotted){
732
      return this.getQuotedQueryPart(fieldId, '"'+ fieldValue+'"',isSearchAll);
733
    }
734
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == fieldValue ){
735
      params+=this.getQuotedQueryPart(fieldId, fieldValue,isSearchAll);
736
    }else if( quotedParts && quotedParts.length > 0){
737
      for(let i=0; i< quotedParts.length; i++){
738
        params+=(i>0)?" and ":"";
739
        params+=this.getQuotedQueryPart(fieldId, quotedParts[i],isSearchAll);
740
      }
741
      let startPoint = 0;
742
      let endPoint = 0;
743
      for(let i=0; i< quotedParts.length; i++){
744
        let index = fieldValue.indexOf(quotedParts[i]);
745
        endPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+1]):fieldValue.length;
746
        // console.log(fieldValue.indexOf(quotedParts[i+1]) +" - "+fieldValue.length);
747
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
748
        if(index==startPoint){
749
          startPoint +=quotedParts[i].length;
750
        }else if(startPoint < index){
751
          endPoint = index;
752
        }
753
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
754
        if(decodeURIComponent(fieldValue.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
755
          params += " and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint, endPoint), isSearchAll);
756
        }
757
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
758
        // startPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+i]):fieldValue.length;//(startPoint<index  )?(index + quotedParts[i].length):fieldValue.length;
759
        startPoint = ((i+1<quotedParts.length)?(fieldValue.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
760
      }
761
      if(startPoint !=fieldValue.length && decodeURIComponent(fieldValue.substring(startPoint,fieldValue.length)).split(" ").join("").length > 0){
762
        params+=" and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint,fieldValue.length),isSearchAll);
763
      }
764
    }else{
765
      params+=this.getNoQuotedQueryPart(fieldId, fieldValue,isSearchAll);
766
    }
767
    params += " )";
768
    return params;
769
  }
770

    
771
  private getQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
772
      return (isSearchAll?"__all":fieldId)+" exact "+StringUtils.URIEncode(value);
773
  }
774
  private getNoQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
775
    if(isSearchAll){
776
      return  value ;
777
    }else{
778
      return fieldId+"="+ StringUtils.URIEncode(value);
779
    }
780
  }
781

    
782
  /**
783
   * Create Search API query based on the filters of refine fields
784
   * @param URLparams
785
   * @param firstLoad
786
   */
787
  getSearchAPIQueryForRefineFields(URLparams, firstLoad: boolean) {
788

    
789
    var allFqs = "";
790
    console.log(this.refineFields)
791
    for (var i = 0; i < this.refineFields.length; i++) {
792
      var filterId = this.refineFields[i];
793

    
794
      if (URLparams[filterId] != undefined) {
795
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterId]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
796
        var countvalues = 0;
797
        var fq = "";
798
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
799
        // console.info(filterId, filterOp);
800
        for (let value of values) {
801
          countvalues++;
802
          var paramId = this.fieldIdsMap[filterId].param;
803
          // parameters+='&' + paramId+ '='+ value;//+"&" + this.fieldIdsMap[paramId].operator + "="+((countvalues == 1)?"and":"or");
804
          fq += (fq.length > 0 ? " " + filterOp + " " : "") + filterId + " exact " + (value);
805
        }
806
        if (countvalues > 0) {
807
          fq = "&fq=" + StringUtils.URIEncode(fq);
808
        }
809
        allFqs += fq;
810
      }
811
    }
812
    if (this.customFilter) {
813
      allFqs += "&fq=" + StringUtils.URIEncode(this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId)));
814
    }
815

    
816
    if (this.quickFilter && this.entityType == "result") {
817
      if((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)   || URLparams["qf"] == "true"
818
        || ((URLparams[this.quickFilter.filterId] != undefined && StringUtils.URIDecode(URLparams[this.quickFilter.filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1).indexOf(StringUtils.quote(this.quickFilter.value)) != -1))) {
819
        this.quickFilter.selected = true;
820
      } else {
821
        this.quickFilter.selected = false;
822
      }
823
      if ((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)
824
      ||( URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == "true")) {
825
        allFqs += "&fq=resultbestaccessright exact " + StringUtils.quote(this.quickFilter.value);
826
      }
827
    }
828

    
829
    if (this.entityType == "result") {
830
      if (URLparams["type"]) {
831
        for (let type of URLparams["type"].split(",")) {
832
          allFqs += "&type=" + type;
833
        }
834
      }else{
835
        allFqs += "&type=publications&type=datasets&type=software&type=other";
836
      }
837
    } else if (this.entityType == "publication") {
838
      allFqs += "&type=publications";
839
    } else if (this.entityType == "dataset") {
840
      allFqs += "&type=datasets";
841
    } else if (this.entityType == "software") {
842
      allFqs += "&type=software";
843
    } else if (this.entityType == "other") {
844
      allFqs += "&type=other";
845
    } else if(this.entityType == "project") {
846
      allFqs += "&type=projects";
847
    } else if(this.entityType == "organization") {
848
      allFqs += "&type=organizations";
849
    } else if(this.entityType == "dataprovider") {
850
      allFqs += "&type=datasources";
851
    }
852
    console.log("AllFqs (check type): "+allFqs);
853
    console.log("type: "+this.entityType);
854
    // var keyword = URLparams['keyword'];
855
    // var doiQuery = "";
856
    // var keywordQuery = "";
857
    // if((keyword && keyword.length > 0)){
858
    //   if((this.type == 'publications' ||this.type == 'research data' || this.type == 'software' || this.type == 'other research products')){
859
    //     var DOIs:string[] = DOI.getDOIsFromString(keyword);
860
    //     var doisParams = "";
861
    //
862
    //     for(var i =0 ;i < DOIs.length; i++){
863
    //       doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
864
    //     }
865
    //     if(doisParams.length > 0){
866
    //       doiQuery += "&"+doisParams;
867
    //     }else {
868
    //       keywordQuery += "&q="+StringUtils.URIEncode(keyword);
869
    //     }
870
    //   }else{
871
    //     if(this.usedBy == "deposit") {
872
    //       if(this.keywordFields.length > 0) {
873
    //         keywordQuery = "&fq=";
874
    //       }
875
    //
876
    //       for(let i=0; i< this.keywordFields.length ; i++) {
877
    //         if(i > 0) {
878
    //           keywordQuery += " or ";
879
    //         }
880
    //         let field = this.keywordFields[i];
881
    //         //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
882
    //         keywordQuery += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
883
    //       }
884
    //     } else {
885
    //       keywordQuery += "&q=" + StringUtils.URIEncode(keyword);
886
    //     }
887
    //
888
    //   }
889
    // }
890
    //TODO add DOI?
891
     return allFqs;
892

    
893
  }
894

    
895
  /**
896
   * Create Search API query based on the filters of refine fields
897
   * @param URLparams
898
   */
899
  getSearchAPIQueryForRangeFields(URLparams) {
900
    let allFqs = "";
901
    for (let i = 0; i < this.rangeFields.length; i++) {
902
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
903
      let filterParam = this.searchFieldsHelper.getFieldParam(filterId, this.entityType);
904

    
905
      if (URLparams[filterParam] != undefined) {
906
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterParam]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
907
        var countvalues = 0;
908
        var fq = "";
909
        var fqFrom = "";
910
        var fqTo = "";
911
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
912

    
913
        for (let value of values) {
914
          if (this.fieldIdsMap[filterId].filterType == "range") {
915

    
916
            let selectedFromValue;
917
            let selectedToValue;
918

    
919
            let years: string[] = (value.substring(5)).split(":");
920
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
921
            //(Number.isInteger(parseInt(years[0], 10)) ? years[0] : null);
922
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
923
            //console.log("getSearchAPIQueryForRangeFields: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
924
            if(yearFrom) {
925
              selectedFromValue = yearFrom;
926
            }
927
            if(yearTo) {
928
              selectedToValue = yearTo;
929
            }
930
            if(yearFrom || yearTo) {
931

    
932
            // if (value.length <= 14) {
933
            //   if(Dates.isValidYear(value.substring(5, 9))) {
934
            //     selectedFromValue = value.substring(5, 9);
935
            //   }
936
            //   if(Dates.isValidYear(value.substring(10, 14))) {
937
            //     selectedToValue = value.substring(10, 14);
938
            //   }
939

    
940
              if(this.rangeFields[i][0] == this.rangeFields[i][1]) {
941
                //console.log(selectedFromValue + " - "+selectedToValue);
942
                if (selectedFromValue && selectedToValue) {
943
                  let equalityOp = this.fieldIdsMap[filterId].equalityOperator;
944
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
945
                  fq = "&fq=" + StringUtils.URIEncode(fq);
946
                } else if (selectedFromValue) {
947
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
948
                  if(equalityOp == " = ") {
949
                    equalityOp = " >= ";
950
                  }
951
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + "\"";
952
                  fq = "&fq=" + StringUtils.URIEncode(fq);
953
                } else if (selectedToValue) {
954
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
955
                  if(equalityOp == " = ") {
956
                    equalityOp = " <= ";
957
                  }
958
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedToValue + "\"";
959
                  fq = "&fq=" + StringUtils.URIEncode(fq);
960
                }
961
              } else {
962
                let equalityOpFrom = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
963
                let equalityOpTo = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
964

    
965
                if (selectedFromValue) {
966
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
967
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
968
                }
969
                if (selectedToValue) {
970
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][1] + equalityOpTo + "\"" + selectedToValue + "\"";
971
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
972
                }
973
                if(selectedFromValue || selectedToValue) {
974
                  fq = "&fq=" + StringUtils.URIEncode(fq);
975
                }
976
              }
977
            }
978
          }
979
        }
980
        allFqs += fq +fqFrom + fqTo;
981
      }
982
    }
983

    
984
    return allFqs;
985

    
986
  }
987

    
988
  /**
989
   * Sets parameterNames and parameterValues arrays
990
   * used in paging, advanced search link, Goto()
991
   * @param filters either query filters or filters defined by the URL parameters
992
   * @param rangeFilters defined by the URL parameters
993
   * @param includePage
994
   */
995
  buildPageURLParameters(filters:Filter[], rangeFilters: RangeFilter[], includePage: boolean) {
996
    this.parameterNames.splice(0, this.parameterNames.length);
997
    this.parameterValues.splice(0, this.parameterValues.length);
998
    for (var i = 0; i < this.selectedFields.length; i++) {
999
      //default operator is and
1000
      this.parameterNames.push("f"+i);
1001
      this.parameterValues.push(this.selectedFields[i].id + (this.selectedFields[i].operatorId!='and'?(","+this.selectedFields[i].operatorId):''));
1002
      this.parameterNames.push("fv"+i);
1003
      if (this.selectedFields[i].type == "date") {
1004

    
1005
        if (this.selectedFields[i].dateValue.type == "range") {
1006
          this.parameterValues.push(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to)));
1007
        } else {
1008
          this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].dateValue.type));
1009
        }
1010

    
1011
      } else {
1012
        console.log(this.selectedFields[i].value +" " + StringUtils.URIEncode(this.selectedFields[i].value))
1013
        this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].value));
1014
      }
1015
    }
1016
    if (includePage && this.searchUtils.page != 1) {
1017
      this.parameterNames.push("page");
1018
      this.parameterValues.push("" + this.searchUtils.page);
1019
    }
1020

    
1021
    if (this.searchUtils.size != this.resultsPerPage) {
1022
      this.parameterNames.push("size");
1023
      this.parameterValues.push("" + this.searchUtils.size);
1024
    }
1025

    
1026
    if (this.sort && this.searchUtils.sortBy) {
1027
      this.parameterNames.push("sortBy");
1028
      this.parameterValues.push(this.searchUtils.sortBy);
1029
    }
1030
    for (let filter of filters) {
1031
      var filterLimits = "";
1032
      if (filter.countSelectedValues > 0) {
1033
        for (let value of filter.values) {
1034
          if (value.selected == true) {
1035
            filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1036
          }
1037
        }
1038
        if (filterLimits.length > 0) {
1039
          this.parameterNames.push(filter.filterId);
1040
          this.parameterValues.push(filterLimits);
1041
        }
1042
      }
1043
    }
1044
    for (let filter of rangeFilters) {
1045
      var filterLimits = "";
1046
      let yearFrom: string = (Dates.isValidYear(filter.selectedFromValue) ? filter.selectedFromValue : null);
1047
      let yearTo: string = (Dates.isValidYear(filter.selectedToValue) ? filter.selectedToValue : null);
1048
      if(yearFrom || yearTo) {
1049
        this.parameterNames.push(filter.filterId);
1050
        this.parameterValues.push("range" + (yearFrom ? yearFrom : "") + ":" + (yearTo ? yearTo : ""));
1051
      }
1052
      // if (filter.countSelectedValues > 0) {
1053
      //   for (let value of filter.values) {
1054
      //     if (value.selected == true) {
1055
      //       filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1056
      //     }
1057
      //   }
1058
      //   if (filterLimits.length > 0) {
1059
      //     this.parameterNames.push(filter.filterId);
1060
      //     this.parameterValues.push(filterLimits);
1061
      //   }
1062
      // }
1063
    }
1064
    if (this.searchUtils.keyword.length > 0) {
1065
      this.parameterNames.push("keyword");
1066
      this.parameterValues.push(this.searchUtils.keyword);
1067
    }
1068

    
1069
    if (this.resultTypes && this.entityType == "result") {
1070
      let values = [];
1071
      if (this.resultTypes.publication) {
1072
        values.push("publications");
1073
      }
1074
      if (this.resultTypes.dataset) {
1075
        values.push("datasets");
1076
      }
1077
      if (this.resultTypes.software) {
1078
        values.push("software");
1079
      }
1080
      if (this.resultTypes.other) {
1081
        values.push("other");
1082
      }
1083
      if (values.length > 0) {
1084
        this.parameterNames.push("type");
1085
        this.parameterValues.push(values.join(","));
1086
      }
1087
      if(this.quickFilter) {
1088
        this.parameterNames.push("qf");
1089
        this.parameterValues.push("" + this.quickFilter.selected);
1090
      }
1091
    }
1092

    
1093
    // if (this.searchUtils.size != this.resultsPerPage) {
1094
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'size=' + this.searchUtils.size;
1095
    //   this.parameterNames.push("size");
1096
    //   this.parameterValues.push("" + this.searchUtils.size);
1097
    // }
1098
    // if (this.sort && this.searchUtils.sortBy) {
1099
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'sortBy=' + this.searchUtils.sortBy;
1100
    //   this.parameterNames.push("sortBy");
1101
    //   this.parameterValues.push(this.searchUtils.sortBy);
1102
    // }
1103
    // console.log(this.parameterNames)
1104
    // console.log(this.parameterValues)
1105
  }
1106

    
1107
  /**
1108
   * create filters based on URL params
1109
   * @param URLparams
1110
   */
1111
  getRefineFiltersFromURL(URLparams) {
1112
    let fields = new SearchFields();
1113
    let filters: Filter[] = [];
1114
    for (let i = 0; i < this.refineFields.length; i++) {
1115
      let filterId = this.refineFields[i];
1116
      if (URLparams[filterId] != undefined) {
1117
        let filter = new Filter();
1118
        filter.title = fields.getFieldName(filterId, this.entityType);
1119
        filter.filterId = filterId;
1120
        filter.originalFilterId = filterId;
1121
        filter.values = [];
1122
        let values = StringUtils.URIDecode(URLparams[filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1123
        for (let value of values) {
1124

    
1125
          let v: Value = new Value();
1126
          v.name = RefineResultsUtils.keepPartAfterCharacters(StringUtils.unquote(value), "||");
1127
          v.id = StringUtils.unquote(value);
1128
          v.selected = true;
1129
          filter.values.push(v);
1130
          // console.log(v)
1131
          filter.countSelectedValues++;
1132
        }
1133
        filters.push(filter)
1134
      }
1135
    }
1136

    
1137
    if (this.quickFilter) {
1138
      if (this.entityType == "result" && (URLparams[this.quickFilter.filterId] == undefined) && (URLparams["qf"] == undefined || URLparams["qf"] == "true")) {
1139
        let filter = new Filter();
1140
        filter.title = fields.getFieldName(this.quickFilter.filterId, this.entityType);
1141
        filter.filterId = this.quickFilter.filterId;
1142
        filter.originalFilterId = this.quickFilter.filterId;
1143
        filter.values = [];
1144
        let v: Value = new Value();
1145
        v.name = this.quickFilter.value;
1146
        v.id = this.quickFilter.value;
1147
        v.selected = true;
1148
        filter.values.push(v);
1149
        filter.countSelectedValues = 1;
1150
        filters.push(filter)
1151
      }
1152
    }
1153
    if (this.entityType == "result") {
1154
      this.resultTypes = null;
1155
      this.resultTypes = {
1156

    
1157
      };
1158

    
1159
      if (URLparams["type"]) {
1160

    
1161
        this.resultTypes['publication'] = (URLparams["type"].split(",").indexOf("publications") != -1);
1162
        this.resultTypes['dataset'] = (URLparams["type"].split(",").indexOf("datasets") != -1);
1163
        this.resultTypes['software'] = (URLparams["type"].split(",").indexOf("software") != -1);
1164
        this.resultTypes['other'] = (URLparams["type"].split(",").indexOf("other") != -1);
1165

    
1166
      } else {
1167
        this.resultTypes['publication'] = true;
1168
        this.resultTypes['dataset'] = true;
1169
        this.resultTypes['software'] = true;
1170
        this.resultTypes['other'] = true;
1171
      }
1172

    
1173
    }
1174

    
1175
    this.URLCreatedFilters = filters;
1176
  }
1177

    
1178
  /**
1179
   * create range filters based on URL params
1180
   * @param URLparams
1181
   */
1182
  getRangeFiltersFromURL(URLparams) {
1183
    let fields = new SearchFields();
1184
    let filters: RangeFilter[] = [];
1185
    for (let i = 0; i < this.rangeFields.length; i++) {
1186
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1187
      let filterParam = fields.getFieldParam(filterId, this.entityType);
1188
      //console.log("rangeFilter (from url): filterId - filterParam");
1189
      //console.log(filterId + " - "+ filterParam);
1190
      if (URLparams[filterParam] != undefined) {
1191
        let filter = new RangeFilter();
1192
        filter.title = fields.getFieldName(filterId, this.entityType);
1193
        filter.filterId = filterParam;
1194
        filter.originalFilterIdFrom = this.rangeFields[i][0];
1195
        filter.originalFilterIdTo = this.rangeFields[i][1];
1196

    
1197

    
1198
        let values = (decodeURIComponent(URLparams[filterParam])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1199
        for (let j = 0; j < values.length; j++) {
1200
          if (this.fieldIdsMap[filterId].filterType == "range") {
1201
            let value: string = StringUtils.unquote(values[j]);
1202
            let validDates: boolean = true;
1203
            // if (value.length < 14) {
1204
            //   validDates = false;
1205
            // } else {
1206
            //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
1207
            //     validDates = false;
1208
            //   } else {
1209
            //     filter.selectedFromValue = value.substring(5, 9);
1210
            //     filter.selectedToValue = value.substring(10, 14);
1211
            //   }
1212
            // }
1213
            let years: string[] = (value.substring(5)).split(":");
1214
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1215
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1216
            //console.log("getRangeFiltersFromURL: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1217
            if(yearFrom) {
1218
              filter.selectedFromValue = yearFrom;
1219
              //filter.selectedFromAndToValues = yearFrom;
1220
            }
1221
            /*if(yearFrom && yearTo) {
1222
              filter.selectedFromAndToValues += "-";
1223
            }*/
1224
            if(yearTo) {
1225
              filter.selectedToValue = yearTo;
1226
              //filter.selectedFromAndToValues += yearTo;
1227
            }
1228
            //console.log("filter.selectedFromAndToValues: "+filter.selectedFromAndToValues);
1229
            if(!yearFrom && !yearTo) {
1230
              validDates = false;
1231
            }
1232

    
1233
          }
1234
        }
1235
        //console.log(filters);
1236
        filters.push(filter)
1237
      }
1238
    }
1239
    // console.log("Empty Filters");
1240
    // console.log(filters);
1241
    this.URLCreatedRangeFilters = filters;
1242
    // return filters;
1243

    
1244
  }
1245

    
1246
  /**
1247
   * Checks if query has no results, display Filters from URL parameters
1248
   * Mark checked  the selected filters
1249
   * Count the checked
1250
   * @param filters
1251
   */
1252
  public prepareFiltersToShow(filters: Filter[]): Filter[] {
1253
    //console.log("prepareFiltersToShow");
1254
    if (this.URLCreatedFilters.length > 0 && this.searchUtils.totalResults == 0) {
1255
      this.showUnknownFilters = true;
1256
      this.filters = this.URLCreatedFilters;
1257
    } else if (this.searchUtils.totalResults != 0) {
1258
      this.showUnknownFilters = false;
1259
      this.filters = filters;
1260
    }
1261
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1262
    //this.checkSelectedRangeFilters(this.rangeFilters);
1263

    
1264
    this.checkSelectedFilters(this.filters);
1265
    this.countSelectedFilters(this.filters);
1266
    return this.filters;
1267
  }
1268

    
1269
  /**
1270
   * Mark checked  the selected range filters
1271
   */
1272
  public prepareRangeFiltersToShow() {
1273
    this.rangeFilters = RangeFilter.parse(this.rangeFields, this.entityType); // OK
1274

    
1275
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1276
    this.checkSelectedRangeFilters(this.rangeFilters);
1277
    this.countSelectedRangeFilters(this.rangeFilters);
1278
    return this.rangeFilters;
1279
  }
1280

    
1281
  /**
1282
   * Used to set the variables and search page, and prepare it before the getResults query
1283
   * @param fieldIds
1284
   * @param selectedFields
1285
   * @param refineFields
1286
   * @param rangeFields
1287
   * @param fieldIdsMap
1288
   * @param customFilter
1289
   * @param params
1290
   * @param entityType
1291
   * @param quickFilter
1292
   */
1293
  prepareSearchPage(fieldIds, selectedFields, refineFields, rangeFields, fieldIdsMap, customFilter, params, entityType, quickFilter=null){
1294
    console.log(this.refineFields);
1295
    this.entityType = entityType;
1296
    this.fieldIds = fieldIds;
1297
    this.selectedFields = selectedFields;
1298
    this.refineFields = refineFields;
1299
    this.rangeFields = rangeFields;
1300
    this.fieldIdsMap = fieldIdsMap;
1301
    this.customFilter = customFilter;
1302
    this.quickFilter = quickFilter;
1303
    this.getRangeFiltersFromURL(params);
1304
    this.getRefineFiltersFromURL(params);
1305
    this.createAdvancedSearchSelectedFiltersFromURLParameters(params);
1306
  }
1307
}
(20-20/55)