forked from davtalab/Ocean_Observation_FacetView
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ocean.jquery.facetview.js
1658 lines (1554 loc) · 78.2 KB
/
ocean.jquery.facetview.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Created by LorraineSposto on 4/10/16.
*/
/*
* jquery.facetview.js
*
* displays faceted browse results by querying a specified elasticsearch index
* can read config locally or can be passed in as variable when executed
* or a config variable can point to a remote config
*
* created by Mark MacGillivray - [email protected]
*
* http://cottagelabs.com
*
* There is an explanation of the options below.
*
*/
var line_chart = null;
var MONTHS = [
null,
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var dd_width = 850;
var dd_height = 300;
// first define the bind with delay function from (saves loading it separately)
// https://github.com/bgrins/bindWithDelay/blob/master/bindWithDelay.js
(function($) {
$.fn.bindWithDelay = function( type, data, fn, timeout, throttle ) {
var wait = null;
var that = this;
if ( $.isFunction( data ) ) {
throttle = timeout;
timeout = fn;
fn = data;
data = undefined;
}
function cb() {
var e = $.extend(true, { }, arguments[0]);
var throttler = function() {
wait = null;
fn.apply(that, [e]);
};
if (!throttle) { clearTimeout(wait); }
if (!throttle || !wait) { wait = setTimeout(throttler, timeout); }
}
return this.bind(type, data, cb);
};
})(jQuery);
// add extension to jQuery with a function to get URL parameters
jQuery.extend({
getUrlVars: function() {
var params = new Object;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for ( var i = 0; i < hashes.length; i++ ) {
hash = hashes[i].split('=');
if ( hash.length > 1 ) {
if ( hash[1].replace(/%22/gi,"")[0] == "[" || hash[1].replace(/%22/gi,"")[0] == "{" ) {
hash[1] = hash[1].replace(/^%22/,"").replace(/%22$/,"");
var newval = JSON.parse(unescape(hash[1].replace(/%22/gi,'"')));
} else {
var newval = unescape(hash[1].replace(/%22/gi,'"'));
}
params[hash[0]] = newval;
}
}
return params;
},
getUrlVar: function(name){
return jQuery.getUrlVars()[name];
}
});
// Deal with indexOf issue in <IE9
// provided by commentary in repo issue - https://github.com/okfn/facetview/issues/18
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
/* EXPLAINING THE FACETVIEW OPTIONS
Facetview options can be set on instantiation. The list below details which options are available.
Options can also be set and retrieved externally via $.fn.facetview.options.
Query values can also be read from the query parameters of the current page, or provided in
the "source" option for initial search.
Also, whilst facetview is executing a query, it will "show" any element with the "notify-loading" class.
So that class can be applied to any element on a page that can be used to signify loading is taking place.
Once facetview has executed a query, the querystring used is available under "options.querystring".
And the result object as retrieved directly from the index is available under "options.rawdata".
searchbox_class
---------------
This should only be set if embedded_search is set to false, and if an alternative search box on the page should
be used as the source of search terms. If so, this should be set to
the class name (including preceding .) of the text input that should be used as the source of the search terms.
It is only a class instead of an ID so that it can be applied to fields that may already have an ID -
it should really identify a unique box on the page for entering search terms for this instance of facetview.
So an ID could actually also be used - just precede with # instead of .
This makes it possible to embed a search box anywhere on a page and have it be used as the source of simple
search parameters for the facetview. Only the last text box with this clas will be used.
embedded_search
---------------
Default to true, in which case full search term functionality is created and displayed on the page.
If this is false, the search term text box and options will be hidden, so that new search terms cannot
be provided by the user.
It is possible to set an alternative search term input box on the page instead, by setting this to false and
also setting a searchbox_class value to identify the basic source of search terms, in which case such a box
must be manually created elsewhere on the page.
searchbox_shade
---------------
The background colour to apply to the search box
sharesave_link
--------------
Default to true, in which case the searchbox - if drawn by facetview - will be appended with a button that
shows the full current search parameters as a URL.
config_file
-----------
Specify as a URL from which to pull a JSON config file specifying these options.
facets
------
A list of facet objects which should be created as filter options on the page.
As per elasticsearch facets settings, plus "display" as a display name for the facet, instead of field name.
If these should be nested, define them with full scope e.g. nestedobj.nestedfield.
extra_facets
------------
An object of named extra facet objects that should be submitted and executed on each query.
These will NOT be used to generate filters on the page, but the result object can be queried
for their content for other purposes.
searchbox_fieldselect
---------------------
A list of objects specifying fields to which search terms should be restricted.
Each object should have a "display" value for displaying as the name of the option,
and a "field" option specifying the field to restrict the search to.
search_sortby
----------------
A list of objects describing sort option dropdowns.
Each object requires a "display" value, and "field" value upon which to sort results.
NOTE sort fields must be unique on the ES index, NOT lists. Otherwise it will fail silently. Choose wisely.
enable_rangeselect
------------------
RANGES NEED SOME WORK AFTER RECENT UPDATE, KEEP DISABLED FOR NOW
Enable or disable the ability to select a range of filter values
include_facets_in_querystring
-----------------------------
Default to false.
Whether or not to include full facet settings in the querystring when it is requested for display.
This makes it easier to get the querystring for other purposes, but does not change the query that is
sent to the index.
result_display
--------------
A display template for search results. It is a list of lists.
Each list specifies a line. Within each list, specify the contents of the line using objects to describe
them. Each content piece should pertain to a particular "field" of the result set, and should specify what
to show "pre" and "post" the given field
display_images
--------------
Default to true, in which case any image found in a given result object will be displayed to the left
in the result object output.
description
-----------
Just an option to provide a human-friendly description of the functionality of the instantiated facetview.
Like "search my shop". Will be displayed on the page.
search_url
----------
The URL at the index to which searches should be submitted in order to retrieve JSON results.
datatype
--------
The datatype that should be used when submitting a search to the index - e.g. JSON for local, JSONP for remote.
initialsearch
-------------
Default to true, in which case a search-all will be submitted to the index on page load.
Set to false to wait for user input before issuing the first search.
fields
------
A list of which fields the index should return in result objects (by default elasticsearch returns them all).
partial_fields
--------------
A definition of which fields to return, as per elasticsearch docs http://www.elasticsearch.org/guide/reference/api/search/fields.html
nested
------
A list of keys for which the content should be considered nested for query and facet purposes.
NOTE this requires that such keys be referenced with their full scope e.g. nestedobj.nestedfield.
Only works on top-level keys so far.
default_url_params
------------------
Any query parameters that the index search URL needs by default.
freetext_submit_delay
---------------------
When search terms are typed in the search box, they are automatically submitted to the index.
This field specifies in milliseconds how long to wait before sending another query - e.g. waiting
for the user to finish typing a word.
q
-
Specify a query value to start with when the page is loaded. Will be submitted as the initial search value
if initialsearch is enabled. Will also be set as the value of the searchbox on page load.
predefined_filters
------------------
Facet / query values to apply to all searches. Give each one a reference key, then in each object define it
as per an elasticsearch query for appending to the bool must.
If these filters should be applied at the nested level, then prefix the name with the relevant nesting prefix.
e.g. if the nested object is called stats, call the filter stats.MYFILTER.
filter
-------
JSON document describing an `elasticsearch filter <http://www.elasticsearch.org/guide/reference/api/search/filter/>`_
paging
------
An object defining the paging settings:
from
----
Which result number to start displaying results from
size
----
How many results to get and display per "page" of results
pager_on_top
------------
Default to false, in which case the pager - e.g. result count and prev / next page buttons - only appear
at the bottom of the search results.
Set to true to show the pager at the top of the search results as well.
pager_slider
------------
If this is set to true, then the paging options will be a left and right arrow at the bottom, with the
count in between, but a bit bigger and more slider-y than the standard one. Works well for displaying
featured content, for example.
sort
----
A list of objects defining how to sort the results, as per elasticsearch sorting.
searchwrap_start
searchwrap_end
----------------
HTML values in which to wrap the full result set, to style them into the page they are being injected into.
resultwrap_start
resultwrap_end
----------------
HTML values in which to wrap each result object
result_box_colours
------------------
A list of background colours that will be randomly assigned to each result object that has the "result_box"
class. To use this, specify the colours in this list and ensure that the "result_display" option uses the
"result_box" class to wrap the result objects.
fadein
------
Define a fade-in delay in milliseconds so that whenever a new list of results is displays, it uses the fade-in effect.
post_search_callback
--------------------
This can define or reference a function that will be executed any time new search results are retrieved and presented on the page.
pushstate
---------
Updates the URL string with the current query when the user changes the search terms
linkify
-------
Makes any URLs in the result contents into clickable links
default_operator
----------------
Sets the default operator in text search strings - elasticsearch uses OR by default, but can also be AND
default_freetext_fuzzify
------------------------
If this exists and is not false, it should be either * or ~. If it is * then * will be prepended and appended
to each string in the freetext search term, and if it is ~ then ~ will be appended to each string in the freetext
search term. If * or ~ or : are already in the freetext search term, it will be assumed the user is already trying
to do a complex search term so no action will be taken. NOTE these changes are not replicated into the freetext
search box - the end user will not know they are happening.
*/
// now the facetview function
(function($){
$.fn.facetview = function(options) {
// a big default value (pulled into options below)
// demonstrates how to specify an output style based on the fields that can be found in the result object
// where a specified field is not found, the pre and post for it are just ignored
var resdisplay = [
[
{
"field": "author.name"
},
{
"pre": "(",
"field": "year",
"post": ")"
}
],
[
{
"pre": "<strong>",
"field": "title",
"alternative_field": "booktitle",
"post": "</strong>"
}
],
[
{
"field": "howpublished"
},
{
"pre": "in <em>",
"field": "journal.name",
"post": "</em>,"
},
{
"pre": "<em>",
"field": "booktitle",
"post": "</em>,"
},
{
"pre": "vol. ",
"field": "volume",
"post": ","
},
{
"pre": "p. ",
"field": "pages"
},
{
"field": "publisher"
}
],
[
{
"field": "link.url"
}
],
[
{
"pre": "<span class='highlightings'>",
"highlight_field": "text",
"post": "</span>"
}
]
];
// specify the defaults
var defaults = {
"config_file": false,
"embedded_search": true,
"searchbox_class": "",
"searchbox_fieldselect": [],
"searchbox_shade": "#ecf4ff",
"search_sortby": [],
"sharesave_link": true,
"description":"",
"facets":[],
"default_url_params":{
'facet.mincount':1,
'wt':'json',
'indent':'true'
},
"solr_paging_params":{
"from":"start",
"size":"rows"
},
"query_parameter":"q",
"extra_facets": {},
"enable_rangeselect": false,
"include_facets_in_querystring": false,
"result_display": resdisplay,
"display_images": true,
"search_url":"",
"datatype":"jsonp",
"initialsearch":true,
"fields": false,
"partial_fields": false,
"nested": [],
"default_url_params":{},
"freetext_submit_delay":"500",
"q":"",
"sort":[],
"predefined_filters":{},
"paging":{
"from":0,
"size":10
},
"pager_on_top": false,
"pager_slider": false,
"searchwrap_start":'<table class="table table-striped table-bordered" id="facetview_results">',
"searchwrap_end":"</table>",
"resultwrap_start":"<tr><td>",
"resultwrap_end":"</td></tr>",
"result_box_colours":[],
"fadein":800,
"post_search_callback": false,
"pushstate": true,
"linkify": true,
"default_operator": "OR",
"default_freetext_fuzzify": false
};
// and add in any overrides from the call
// these options are also overridable by URL parameters
// facetview options are declared as a function so they are available externally
// (see bottom of this file)
var provided_options = $.extend(defaults, options);
var url_options = $.getUrlVars();
$.fn.facetview.options = $.extend(provided_options,url_options);
var options = $.fn.facetview.options;
// ===============================================
// functions to do with filters
// ===============================================
// show the filter values
var showfiltervals = function(event) {
event.preventDefault();
if ( $(this).hasClass('facetview_open') ) {
$(this).children('i').removeClass('icon-minus');
$(this).children('i').addClass('icon-plus');
$(this).removeClass('facetview_open');
$('[id="facetview_' + $(this).attr('rel') +'"]', obj ).children().find('.facetview_filtervalue').hide();
$(this).siblings('.facetview_filteroptions').hide();
} else {
$(this).children('i').removeClass('icon-plus');
$(this).children('i').addClass('icon-minus');
$(this).addClass('facetview_open');
$('[id="facetview_' + $(this).attr('rel') +'"]', obj ).children().find('.facetview_filtervalue').show();
$(this).siblings('.facetview_filteroptions').show();
}
};
// function to switch filters to OR instead of AND
var orfilters = function(event) {
event.preventDefault();
if ( $(this).attr('rel') == 'AND' ) {
$(this).attr('rel','OR');
$(this).css({'color':'#333'});
$('.facetview_filterselected[rel="' + $(this).attr('href') + '"]', obj).addClass('facetview_logic_or');
} else {
$(this).attr('rel','AND');
$(this).css({'color':'#aaa'});
$('.facetview_filterselected[rel="' + $(this).attr('href') + '"]', obj).removeClass('facetview_logic_or');
}
dosearch();
}
// function to perform for sorting of filters
var sortfilters = function(event) {
event.preventDefault();
var sortwhat = $(this).attr('href');
var which = 0;
for ( var i = 0; i < options.facets.length; i++ ) {
var item = options.facets[i];
if ('field' in item) {
if ( item['field'] == sortwhat) {
which = i;
}
}
}
// iterate to next sort type on click. order is term, rterm, count, rcount
if ( $(this).hasClass('facetview_term') ) {
options.facets[which]['order'] = 'reverse_term';
$(this).html('a-z <i class="icon-arrow-up"></i>');
$(this).removeClass('facetview_term').addClass('facetview_rterm');
} else if ( $(this).hasClass('facetview_rterm') ) {
options.facets[which]['order'] = 'count';
$(this).html('count <i class="icon-arrow-down"></i>');
$(this).removeClass('facetview_rterm').addClass('facetview_count');
} else if ( $(this).hasClass('facetview_count') ) {
options.facets[which]['order'] = 'reverse_count';
$(this).html('count <i class="icon-arrow-up"></i>');
$(this).removeClass('facetview_count').addClass('facetview_rcount');
} else if ( $(this).hasClass('facetview_rcount') ) {
options.facets[which]['order'] = 'term';
$(this).html('a-z <i class="icon-arrow-down"></i>');
$(this).removeClass('facetview_rcount').addClass('facetview_term');
}
dosearch();
};
// adjust how many results are shown
var morefacetvals = function(event) {
event.preventDefault();
var morewhat = options.facets[ $(this).attr('rel') ];
if ('size' in morewhat ) {
var currentval = morewhat['size'];
} else {
var currentval = 10;
}
var newmore = prompt('Currently showing ' + currentval + '. How many would you like instead?');
if (newmore) {
options.facets[ $(this).attr('rel') ]['size'] = parseInt(newmore);
$(this).html(newmore);
dosearch();
}
};
// insert a facet range once selected
// TODO: UPDATE
var dofacetrange = function(rel) {
$('#facetview_rangeresults_' + rel, obj).remove();
var range = $('#facetview_rangechoices_' + rel, obj).html();
var newobj = '<div style="display:none;" class="btn-group" id="facetview_rangeresults_' + rel + '"> \
<a class="facetview_filterselected facetview_facetrange facetview_clear \
btn btn-info" rel="' + rel +
'" alt="remove" title="remove"' +
' href="' + $(this).attr("href") + '">' +
range + ' <i class="icon-white icon-remove"></i></a></div>';
$('#facetview_selectedfilters', obj).append(newobj);
$('.facetview_filterselected', obj).unbind('click',clearfilter);
$('.facetview_filterselected', obj).bind('click',clearfilter);
options.paging.from = 0;
dosearch();
};
// clear a facet range
var clearfacetrange = function(event) {
event.preventDefault();
$('#facetview_rangeresults_' + $(this).attr('rel'), obj).remove();
$('#facetview_rangeplaceholder_' + $(this).attr('rel'), obj).remove();
dosearch();
};
// build a facet range selector
var facetrange = function(event) {
// TODO: when a facet range is requested, should hide the facet list from the menu
// should perhaps also remove any selections already made on that facet
event.preventDefault();
var rel = $(this).attr('rel');
var rangeselect = '<div id="facetview_rangeplaceholder_' + rel + '" class="facetview_rangecontainer clearfix"> \
<div class="clearfix"> \
<h3 id="facetview_rangechoices_' + rel + '" style="margin-left:10px; margin-right:10px; float:left; clear:none;" class="clearfix"> \
<span class="facetview_lowrangeval_' + rel + '">...</span> \
<small>to</small> \
<span class="facetview_highrangeval_' + rel + '">...</span></h3> \
<div style="float:right;" class="btn-group">';
rangeselect += '<a class="facetview_facetrange_remove btn" rel="' + rel + '" alt="remove" title="remove" \
href="#"><i class="icon-remove"></i></a> \
</div></div> \
<div class="clearfix" style="margin:20px;" id="facetview_slider_' + rel + '"></div> \
</div>';
$('#facetview_selectedfilters', obj).after(rangeselect);
$('.facetview_facetrange_remove', obj).unbind('click',clearfacetrange);
$('.facetview_facetrange_remove', obj).bind('click',clearfacetrange);
var values = [];
var valsobj = $( '#facetview_' + $(this).attr('href').replace(/\./gi,'_'), obj );
valsobj.find('.facetview_filterchoice', obj).each(function() {
values.push( $(this).attr('href') );
});
values = values.sort();
$( "#facetview_slider_" + rel, obj ).slider({
range: true,
min: 0,
max: values.length-1,
values: [0,values.length-1],
slide: function( event, ui ) {
$('#facetview_rangechoices_' + rel + ' .facetview_lowrangeval_' + rel, obj).html( values[ ui.values[0] ] );
$('#facetview_rangechoices_' + rel + ' .facetview_highrangeval_' + rel, obj).html( values[ ui.values[1] ] );
dofacetrange( rel );
}
});
$('#facetview_rangechoices_' + rel + ' .facetview_lowrangeval_' + rel, obj).html( values[0] );
$('#facetview_rangechoices_' + rel + ' .facetview_highrangeval_' + rel, obj).html( values[ values.length-1] );
};
// pass a list of filters to be displayed
var buildfilters = function() {
if ( options.facets.length > 0 ) {
var filters = options.facets;
var thefilters = '';
for ( var idx = 0; idx < filters.length; idx++ ) {
var _filterTmpl = '<table id="facetview_{{FILTER_NAME}}" class="facetview_filters table table-bordered table-condensed table-striped"> \
<tr><td><a class="facetview_filtershow" title="filter by {{FILTER_DISPLAY}}" rel="{{FILTER_NAME}}" \
style="color:#333; font-weight:bold;" href=""><i class="icon-plus"></i> {{FILTER_DISPLAY}} \
</a> \
<div class="btn-group facetview_filteroptions" style="display:none; margin-top:5px;"> \
<a class="btn btn-small facetview_learnmore" title="click to view search help information" href="#"><b>?</b></a> \
<a class="btn btn-small facetview_morefacetvals" title="filter list size" rel="{{FACET_IDX}}" href="{{FILTER_EXACT}}">{{FILTER_HOWMANY}}</a> \
<a class="btn btn-small facetview_sort {{FILTER_SORTTERM}}" title="filter value order" href="{{FILTER_EXACT}}">{{FILTER_SORTCONTENT}}</a> \
<a class="btn btn-small facetview_or" title="select another option from this filter" rel="AND" href="{{FILTER_EXACT}}" style="color:#aaa;">OR</a> \
';
if ( options.enable_rangeselect ) {
_filterTmpl += '<a class="btn btn-small facetview_facetrange" title="make a range selection on this filter" rel="{{FACET_IDX}}" href="{{FILTER_EXACT}}" style="color:#aaa;">range</a>';
}
_filterTmpl +='</div> \
</td></tr> \
</table>';
_filterTmpl = _filterTmpl.replace(/{{FILTER_NAME}}/g, filters[idx]['field'].replace(/\./gi,'_').replace(/\:/gi,'_')).replace(/{{FILTER_EXACT}}/g, filters[idx]['field']);
thefilters += _filterTmpl;
if ('size' in filters[idx] ) {
thefilters = thefilters.replace(/{{FILTER_HOWMANY}}/gi, filters[idx]['size']);
} else {
thefilters = thefilters.replace(/{{FILTER_HOWMANY}}/gi, 10);
};
if ( 'order' in filters[idx] ) {
if ( filters[idx]['order'] == 'term' ) {
thefilters = thefilters.replace(/{{FILTER_SORTTERM}}/g, 'facetview_term');
thefilters = thefilters.replace(/{{FILTER_SORTCONTENT}}/g, 'a-z <i class="icon-arrow-down"></i>');
} else if ( filters[idx]['order'] == 'reverse_term' ) {
thefilters = thefilters.replace(/{{FILTER_SORTTERM}}/g, 'facetview_rterm');
thefilters = thefilters.replace(/{{FILTER_SORTCONTENT}}/g, 'a-z <i class="icon-arrow-up"></i>');
} else if ( filters[idx]['order'] == 'count' ) {
thefilters = thefilters.replace(/{{FILTER_SORTTERM}}/g, 'facetview_count');
thefilters = thefilters.replace(/{{FILTER_SORTCONTENT}}/g, 'count <i class="icon-arrow-down"></i>');
} else if ( filters[idx]['order'] == 'reverse_count' ) {
thefilters = thefilters.replace(/{{FILTER_SORTTERM}}/g, 'facetview_rcount');
thefilters = thefilters.replace(/{{FILTER_SORTCONTENT}}/g, 'count <i class="icon-arrow-up"></i>');
};
} else {
thefilters = thefilters.replace(/{{FILTER_SORTTERM}}/g, 'facetview_count');
thefilters = thefilters.replace(/{{FILTER_SORTCONTENT}}/g, 'count <i class="icon-arrow-down"></i>');
};
thefilters = thefilters.replace(/{{FACET_IDX}}/gi,idx);
if ('display' in filters[idx]) {
thefilters = thefilters.replace(/{{FILTER_DISPLAY}}/g, filters[idx]['display']);
} else {
thefilters = thefilters.replace(/{{FILTER_DISPLAY}}/g, filters[idx]['field']);
};
};
$('#facetview_filters', obj).html("").append(thefilters);
$('.facetview_morefacetvals', obj).bind('click',morefacetvals);
$('.facetview_facetrange', obj).bind('click',facetrange);
$('.facetview_sort', obj).bind('click',sortfilters);
$('.facetview_or', obj).bind('click',orfilters);
$('.facetview_filtershow', obj).bind('click',showfiltervals);
$('.facetview_learnmore', obj).unbind('click',learnmore);
$('.facetview_learnmore', obj).bind('click',learnmore);
options.description ? $('#facetview_filters', obj).append('<div>' + options.description + '</div>') : "";
};
};
// trigger a search when a filter choice is clicked
// or when a source param is found and passed on page load
var clickfilterchoice = function(event,rel,href) {
if ( event ) {
event.preventDefault();
var rel = $(this).attr("rel");
var href = $(this).attr("href");
}
var relclean = rel.replace(/\./gi,'_').replace(/\:/gi,'_');
// Do nothing if element already exists.
if( $('a.facetview_filterselected[href="'+href+'"][rel="'+rel+'"]').length ){
return null;
}
var newobj = '<a class="facetview_filterselected facetview_clear btn btn-info';
if ( $('.facetview_or[href="' + rel + '"]', obj).attr('rel') == 'OR' ) {
newobj += ' facetview_logic_or';
}
newobj += '" rel="' + rel +
'" alt="remove" title="remove"' +
' href="' + href + '">' +
href + ' <i class="icon-white icon-remove" style="margin-top:1px;"></i></a>';
if ( $('#facetview_group_' + relclean, obj).length ) {
$('#facetview_group_' + relclean, obj).append(newobj);
} else {
var pobj = '<div id="facetview_group_' + relclean + '" class="btn-group">';
pobj += newobj + '</div>';
$('#facetview_selectedfilters', obj).append(pobj);
};
$('.facetview_filterselected', obj).unbind('click',clearfilter);
$('.facetview_filterselected', obj).bind('click',clearfilter);
if ( event ) {
options.paging.from = 0;
dosearch();
};
};
// clear a filter when clear button is pressed, and re-do the search
var clearfilter = function(event) {
event.preventDefault();
if ( $(this).siblings().length == 0 ) {
$(this).parent().remove();
} else {
$(this).remove();
}
dosearch();
};
// ===============================================
// functions to do with building results
// ===============================================
// read the result object and return useful vals
// returns an object that contains things like ["data"] and ["facets"]
var parseresults = function(dataobj) {
var resultobj = new Object();
resultobj["records"] = new Array();
resultobj["start"] = "";
resultobj["found"] = "";
resultobj["facets"] = new Object();
if (options.search_index == "elasticsearch"){
for ( var item = 0; item < dataobj.hits.hits.length; item++ ) {
if ( options.fields ) {
resultobj["records"].push(dataobj.hits.hits[item].fields);
} else if ( options.partial_fields ) {
var keys = [];
for(var key in options.partial_fields){
keys.push(key);
}
resultobj["records"].push(dataobj.hits.hits[item].fields[keys[0]]);
} else {
resultobj["records"].push(dataobj.hits.hits[item]._source);
}
}
resultobj["start"] = "";
resultobj["found"] = dataobj.hits.total;
for (var item in dataobj.facets) {
var facetsobj = new Object();
for (var thing = 0; thing < dataobj.facets[item]["terms"].length; thing++) {
facetsobj[ dataobj.facets[item]["terms"][thing]["term"] ] = dataobj.facets[item]["terms"][thing]["count"];
}
resultobj["facets"][item] = facetsobj;
}
}
else{
resultobj["records"] = dataobj.response.docs;
resultobj["start"] = dataobj.response.start;
resultobj["found"] = dataobj.response.numFound;
if (dataobj.facet_counts) {
for (var item in dataobj.facet_counts.facet_fields) {
var facetsobj = new Object();
var count = 0;
for ( var each in dataobj.facet_counts.facet_fields[item]) {
if ( count % 2 == 0 ) {
facetsobj[ dataobj.facet_counts.facet_fields[item][each] ] = dataobj.facet_counts.facet_fields[item][count + 1];
}
count += 1;
}
resultobj["facets"][item] = facetsobj;
}
}
}
return resultobj;
};
// decrement result set
var decrement = function(event) {
event.preventDefault();
if ( $(this).html() != '..' ) {
options.paging.from = options.paging.from - options.paging.size;
options.paging.from < 0 ? options.paging.from = 0 : "";
dosearch();
}
};
// increment result set
var increment = function(event) {
event.preventDefault();
if ( $(this).html() != '..' ) {
options.paging.from = parseInt($(this).attr('href'));
dosearch();
}
};
// used to get value by dotted notation in result_display
var getvalue = function(obj, dotted_notation) {
if(!dotted_notation) return;
var parts = dotted_notation.split('.');
parts.reverse();
var ref = [parts.pop()];
while (parts.length && !(ref.join(".") in obj)) {
ref.push(parts.pop());
}
var addressed_ob = obj[ref.join(".")];
var left = parts.reverse().join(".");
if (addressed_ob && addressed_ob.constructor.toString().indexOf("Array") == -1) {
if (parts.length)
return getvalue(addressed_ob, left);
else
return addressed_ob;
} else {
if ( addressed_ob !== undefined ) {
var thevalue = [];
for ( var row = 0; row < addressed_ob.length; row++ ) {
thevalue.push(addressed_ob[row]);
}
return thevalue;
} else {
return undefined;
}
}
};
// given a result record, build how it should look on the page
var buildrecord = function(index) {
var record = options.data['records'][index];
var result = options.resultwrap_start;
// add first image where available
if (options.display_images) {
// TODO: this is where we need to take the URL as stored in ID field, translate it to a web URL, and show it.
var recstr = JSON.stringify(record);
var regex = /(http:\/\/\S+?\.(jpg|png|gif|jpeg))/;
var img = regex.exec(recstr);
if (img) {
result += '<img class="thumbnail" style="float:left; width:100px; margin:0 5px 10px 0; max-height:150px;" src="' + img[0] + '" />';
}
}
// add the record based on display template if available
var display = options.result_display;
var lines = '';
for ( var lineitem = 0; lineitem < display.length; lineitem++ ) {
line = "";
for ( var object = 0; object < display[lineitem].length; object++ ) {
var thekey = display[lineitem][object]['field'];
var thevalue = getvalue(record, thekey);
if (thevalue && thevalue.toString().length) {
line += display[lineitem][object]['pre'] ? display[lineitem][object]['pre'] : false;
if ( typeof(thevalue) == 'object' ) {
for ( var val = 0; val < thevalue.length; val++ ) {
line += val != 0 ? ', ' : '';
line += thevalue[val];
}
} else {
line += thevalue;
}
display[lineitem][object]['post']
? line += display[lineitem][object]['post'] : line += ' ';
}
}
if (line) {
lines += line.replace(/^\s/,'').replace(/\s$/,'').replace(/\,$/,'') + "<br />";
}
}
lines ? result += lines : result += JSON.stringify(record,""," ");
result += options.resultwrap_end;
return result;
};
// view a full record when selected
var viewrecord = function(event) {
event.preventDefault();
var record = options.data['records'][$(this).attr('href')];
alert(JSON.stringify(record,""," "));
}
// put the results on the page
var showresults = function(sdata) {
options.rawdata = sdata;
// get the data and parse from the es layout
var data = parseresults(sdata);
options.data = data;
// initialize plot
if (line_chart == null && options.linechart_field != null && options.linechart_field != "") {
line_chart = c3.generate({
bindto: '#line_chart',
data: {
x: 'year',
columns: [
]
}
});
}
// for each filter setup, find the results for it and append them to the relevant filter
for ( var each = 0; each < options.facets.length; each++ ) {
var facet = options.facets[each]['field'];
var facetclean = options.facets[each]['field'].replace(/\./gi,'_').replace(/\:/gi,'_');
var facet_filter = $('[id="facetview_'+facetclean+'"]', obj);
facet_filter.children().find('.facetview_filtervalue').remove();
var records = data["facets"][ facet ];
// compensate for Solr not being able to show facet results in reverse order
if ("order" in options.facets[each] && options.facets[each]["order"].indexOf("reverse") > -1) {
// http://stackoverflow.com/questions/18977881/can-i-loop-through-a-javascript-object-in-reverse-order
function ReverseObject(Obj){
var TempArr = [];
var NewObj = {};
for (var Key in Obj){
TempArr.push(Key);
}
for (var i = TempArr.length-1; i >= 0; i--){
NewObj[TempArr[i]] = Obj[TempArr[i]];
}
return NewObj;
};
records = ReverseObject(records);
}
var years = ['year'];
var year_hits = ['hits'];
var lineChartFacet = false;
var dendrogramFacet = false;
if (facet == options.linechart_field){
lineChartFacet = true;
}
if (facet == options.dendrogram_field){
dendrogramFacet = true;
}
for ( var item in records ) {
var append = '<tr class="facetview_filtervalue" style="display:none;"><td><a class="facetview_filterchoice' +
'" rel="' + facet + '" href="' + item + '">' + item +
' (' + records[item] + ')</a></td></tr>';
facet_filter.append(append);
if (lineChartFacet){
years.push(item);
year_hits.push(records[item]);
}
}
if ( $('.facetview_filtershow[rel="' + facetclean + '"]', obj).hasClass('facetview_open') ) {
facet_filter.children().find('.facetview_filtervalue').show();
}
if(lineChartFacet){
// clean the years and hits
var year_hash = {}
for (var i = 0; i < years.length; i++){
if (years[i] == "year") continue;
var year = years[i].substring(0,4);
if (year in year_hash){
hits = parseInt(years[year]);
hits += parseInt(year_hits[i]);
}
else{
year_hash[year] = year_hits[i];
}
}
years = [];
year_hits = [];
years.push('year');
year_hits.push('hits');
for (var year in year_hash){
years.push(year);
year_hits.push(year_hash[year]);
}
line_chart.load({
columns: [
years,
year_hits
]
});
}
if (dendrogramFacet){
$('#dendrogram').empty();
dendrogram = null;
var facet_selected = $('a.facetview_filterselected[rel="'+facet+'"]');
var root = {};
if (facet_selected.length > 0) {
dd_cluster = d3.layout.cluster().size([dd_height, dd_width - 160]);
dd_diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });
dendrogram = d3.select("#dendrogram").append("svg:svg")
.attr("width", dd_width)
.attr("height", dd_height)
.append("svg:g")
.attr("transform", "translate(80, 0)");
var facet_text = facet_selected[0].text;
//alert(facet_text);
root = {
"name": facet_text,
"children": []
};
//alert(data.records);
var rel_nodes = [];
for ( var i = 0; i < data.records.length; i++ ) {
var drec = data.records[i];
var drec_length = 0;
var drec_facet = eval('drec.'+facet);
if (drec_facet != undefined){
drec_length = drec_facet.length;
}
for (var j = 0; j < drec_length; j++) {
var rel_node = eval('drec.'+facet+'[j]');