/
flexibleSearch.js
executable file
·984 lines (908 loc) · 39.3 KB
/
flexibleSearch.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
/*
* flexibleSearch.js
*
* Copyright (c) Tomohiro Okuwaki / bit part LLC (http://bit-part.net/)
*
* Since : 2010-11-12
* Update : 2015-03-24
* Version: 2.2.0
* Comment: Please use this with Movable Type :)
*
* You have to include "mustache.js" before "flexibleSearch.js".
* Maybe... jQuery 1.7.x later
*
*/
(function ($) {
$.fn.flexibleSearch = function (options) {
var op = $.extend({}, $.fn.flexibleSearch.defaults, options);
var $this = this;
// =======================================================================
// Search Form HTML <start>
//
if (op.searchFormCreation) {
// Advanced Form HTML <start>
var advancedFormTmpl = [];
var advancedFormHTML = "";
if (op.advancedFormObj !== null) {
// input:hidden
if ("hidden" in op.advancedFormObj) {
advancedFormTmpl.push([
'<div class="fs-advanced-hidden" style="display:none;">',
'{{#hidden}}',
'<input type="hidden"',
'{{#id}} id="{{id}}"{{/id}}',
'{{#name}} name="{{name}}"{{/name}}',
'{{#value}} value="{{value}}"{{/value}}>',
'{{/hidden}}',
'</div>'
].join(""));
}
// input:text
if ("text" in op.advancedFormObj) {
advancedFormTmpl.push([
'<div class="fs-advanced-text">',
'{{#text}}',
'{{#label}}',
'<label{{#id}} id="{{id}}-label"{{/id}}{{#name}} for="{{name}}"{{/name}} class="fs-text{{#name}} fs-{{name}}{{/name}}">',
'{{/label}}',
'<input type="text"',
'{{#id}} id="{{id}}"{{/id}}',
'{{#name}} name="{{name}}"{{/name}}',
'{{#value}} value="{{value}}"{{/value}}',
'{{#placeholder}} placeholder="{{placeholder}}"{{/placeholder}}>',
'{{#label}}',
'{{label}}</label>',
'{{/label}}',
'{{/text}}',
'</div>'
].join(""));
}
// input:checkbox
if ("checkbox" in op.advancedFormObj) {
advancedFormTmpl.push([
'<div class="fs-advanced-checkbox">',
'{{#checkbox}}',
'{{#label}}',
'<label{{#id}} id="{{id}}-label"{{/id}}{{#name}} for="{{name}}"{{/name}} class="fs-checkbox{{#name}} fs-{{name}}{{/name}}">',
'{{/label}}',
'<input type="checkbox"',
'{{#id}} id="{{id}}"{{/id}}',
'{{#name}} name="{{name}}"{{/name}}',
'{{#value}} value="{{value}}"{{/value}}',
'{{#checked}} checked="checked"{{/checked}}>',
'{{#label}}',
'{{label}}</label>',
'{{/label}}',
'{{/checkbox}}',
'</div>'
].join(""));
}
// input:radio
if ("radio" in op.advancedFormObj) {
advancedFormTmpl.push([
'<div class="fs-advanced-radio">',
'{{#radio}}',
'{{#label}}',
'<label{{#id}} id="{{id}}-label"{{/id}}{{#name}} for="{{name}}"{{/name}} class="fs-radio{{#name}} fs-{{name}}{{/name}}">',
'{{/label}}',
'<input type="radio"',
'{{#id}} id="{{id}}"{{/id}}',
'{{#name}} name="{{name}}"{{/name}}',
'{{#value}} value="{{value}}"{{/value}}',
'{{#checked}} checked="checked"{{/checked}}>',
'{{#label}}',
'{{label}}</label>',
'{{/label}}',
'{{/radio}}',
'</div>'
].join(""));
}
// Make HTML of hidden, text, checkbox and radio
advancedFormHTML = Mustache.render(advancedFormTmpl.join(""), op.advancedFormObj);
// input:select
if ("select" in op.advancedFormObj) {
var advancedFormSelectObj = {
"selects": op.advancedFormObj.select,
"options": function () {
var optionObj = this.option;
var optionSet = [];
for (var i = 0, l = optionObj.length; i < l; i++) {
var slctd = optionObj[i].selected ? " selected": "";
optionSet.push('<option value="' + optionObj[i].value + '"' + slctd + '>' + optionObj[i].label +'</option>');
}
return optionSet.join("");
}
};
var advancedFormSelectTmpl = [
'<div class="fs-advanced-select">',
'{{#selects}}',
'<select{{#id}} id="{{id}}"{{/id}}{{#name}} name="{{name}}"{{/name}}{{#size}} size="{{size}}"{{/size}}{{#multiple}} multiple{{/multiple}} class="fs-select{{#name}} fs-{{name}}{{/name}}">',
'{{{options}}}',
'</select>',
'{{/selects}}',
'</div>'
].join("");
// Make HTML of select
advancedFormHTML += Mustache.render(advancedFormSelectTmpl, advancedFormSelectObj);
}
}
// Advanced Form HTML </end>
// Search Form <start>
//
// * {{action}} (= op.searchFormAction)
// * {{type}} (= op.searchFormInputType)
// * {{placeholder}} (= op.searchFormInputPlaceholder)
// * {{submitBtnText}} (= op.searchFormSubmitBtnText)
var searchFormObj = {
action: op.searchFormAction,
type: op.searchFormInputType,
placeholder: op.searchFormInputPlaceholder,
submitBtnText: op.searchFormSubmitBtnText
};
var searchFormHTML = "";
if (op.limit !== null && typeof op.limit === 'number') {
op.paginateCount = op.limit;
}
if (op.searchFormHTML !== null) {
searchFormHTML = op.searchFormHTML;
}
else {
var searchFormTmpl = [
'<form action="{{action}}" method="GET">',
'<input type="hidden" name="offset" value="0">',
'<input type="hidden" name="limit" value="' + op.paginateCount + '">',
'<input type="{{type}}" name="search" placeholder="{{placeholder}}" class="fs-text fs-search">',
'<input type="submit" value="{{submitBtnText}}" class="fs-btn fs-submit">',
advancedFormHTML, // Advanced Form
'</form>'
].join("");
// Make search form HTML
searchFormHTML = Mustache.render(searchFormTmpl, searchFormObj);
}
// Search Form </end>
// Insert into DOM
$this[0].innerHTML = searchFormHTML;
}
//
// Search Form HTML </end>
// -----------------------------------------------------------------------
// =======================================================================
// Result Block Template <start>
//
// Search Result Loading Image <start>
var resultLoadingHTML = "";
if (op.loadingImgHTML !== null) {
resultLoadingHTML = op.loadingImgHTML;
}
else if (op.loadingImgPath) {
resultLoadingHTML = '<span class="fs-loading"><img src="' + op.loadingImgPath + '" alt=""></span>';
}
// Search Result Loading Image </end>
// Search Result Message <start>
//
// * {{keywords}}
// * {{count}}
// * {{firstPage}}
// * {{lastPage}}
// * {{currentPage}}
var resultMsgTmpl = "";
if (op.resultMsgTmpl !== null) {
resultMsgTmpl = op.resultMsgTmpl;
}
else {
resultMsgTmpl = [
'<div{{#id}} id="{{id}}"{{/id}}{{#classname}} class="{{classname}}"{{/classname}}>',
'<p>',
'{{#keywords}}「{{keywords}}」が {{/keywords}}',
'{{#count}}{{count}} 件見つかりました。{{/count}}',
'{{^count}}見つかりませんでした。{{/count}}',
'{{#count}}({{lastPage}} ページ中 {{currentPage}} ページ目を表示){{/count}}',
// '({{firstPage}}〜{{lastPage}} ページ中 {{currentPage}} ページ目を表示)',
'</p>',
'</div>'
].join("");
}
// Search Result Message </end>
// Search Result Item <start>
//
// * keys used in your JSON
var resultItemTmpl = "";
if (op.resultItemTmpl !== null) {
resultItemTmpl = op.resultItemTmpl;
}
else {
resultItemTmpl = [
'<div id="' + op.resultBlockId + '-items">',
'<ul>',
'{{#items}}',
'<li>{{&title}}</li>',
'{{/items}}',
'</ul>',
'</div>'
].join("");
}
// Search Result Item </end>
// Paginate <start>
//
// * {{paginateId}}
// * {{¤t}}
// * {{.}}
var paginateTmpl = "";
if (op.paginateTmpl !== null) {
paginateTmpl = op.paginateTmpl;
}
else {
paginateTmpl = [
'<div{{#id}} id="{{id}}"{{/id}}{{#classname}} class="{{classname}}"{{/classname}}>',
'<ul>',
'{{#showTurnPage}}',
'{{#exceptFirst}}',
'<li class="fs-prev"><span><a class="fs-prev-link fs-turn-page-link" href="#" title="{{prevPageText}}">{{prevPageText}}</a></span></li>',
'{{/exceptFirst}}',
'{{/showTurnPage}}',
'{{#page}}',
'{{#checkRange}}',
'<li class="{{current}}"{{#hidePageNumber}} style="display:none;"{{/hidePageNumber}}><span><a class="fs-page-link {{currentLink}}" href="#" title="{{pageNumber}}">{{pageNumber}}</a></span></li>',
'{{/checkRange}}',
'{{/page}}',
'{{#showTurnPage}}',
'{{#exceptLast}}',
'<li class="fs-next"><span><a class="fs-next-link fs-turn-page-link" href="#" title="{{nextPageText}}">{{nextPageText}}</a></span></li>',
'{{/exceptLast}}',
'{{/showTurnPage}}',
'</ul>',
'</div>'
].join("");
}
// Paginate </end>
//
// Result Block Template </end>
// -----------------------------------------------------------------------
// =======================================================================
// Get parameters and serialize parameters <start>
//
// Serialize parameters
$this.find("form").on("submit", function (e) {
e.preventDefault();
var url = $(this).attr("action") || location.href.replace(/\?.*/, "");
var params = $(this).serializeArray();
for (var i = -1, n = params.length; ++i < n;) {
if (params[i].name === "search") {
params[i].value = $.trim(params[i].value.replace(" ", " "));
}
}
params = op.submitAction(params);
var serializeParams = $.param(params);
if (serializeParams) {
url = url + "?" + serializeParams;
}
location.href = url;
return false;
});
var paramStr = decodeURIComponent(location.search.replace(/^\?/, ""));
//
// Get parameters and serialize parameters </end>
// -----------------------------------------------------------------------
// =======================================================================
// Preload search data files <start>
//
if (paramStr === "") {
switch (typeof op.searchDataPathPreload) {
case "string":
$.ajax({
type: "GET",
cache: true,
dataType: "json",
url: op.searchDataPathPreload
});
break;
case "object":
if (op.searchDataPathPreload === null || op.searchDataPathPreload === "") {
break;
}
if (op.searchDataPathPreload.length) {
for (var i = -1, n = op.searchDataPathPreload.length; ++i < n;) {
$.ajax({
type: "GET",
cache: true,
dataType: "json",
url: op.searchDataPathPreload[i]
});
}
}
else {
for (var key in op.searchDataPathPreload) {
$.ajax({
type: "GET",
cache: true,
dataType: "json",
url: op.searchDataPathPreload[key]
});
}
}
break;
}
return false;
}
//
// Preload search data files </end>
// -----------------------------------------------------------------------
// Search Result Loading Image
if (resultLoadingHTML) {
document.getElementById(op.resultBlockId).innerHTML = resultLoadingHTML;
}
// Set values to Search Form
var searchWords = [];
var paramAry = paramStr.split(/&|%26/);
var paramObj = {};
var paramExistArry = [];
var advancedSearchObj = {};
var offset = 0;
var limit = 10;
var sortBy = "";
var sortOrder = "";
var sortType = "";
var jsonPath = "";
var dataId = "";
var api = false;
var excludeParams = ["search", "dataId", "offset", "limit", "sortBy", "sortOrder", "sortType"];
if (op.excludeParams !== null) {
$.merge(excludeParams, op.excludeParams.toLowerCase().split(","));
}
for (var i = -1, n = paramAry.length; ++i < n;) {
var param = paramAry[i].split("=");
var key = param[0];
var value = param[1] || "";
paramObj[key] = value;
// Set "advancedSearchObj" and "searchWords"
switch (key) {
case "search":
value = (value === "+") ? "" : value; // If value is " ", it is "+" on URL.
searchWords = value.split(/\+| |%20/);
break;
case "offset":
offset = value;
break;
case "limit":
limit = value;
if (op.limit !== null && typeof op.limit === 'number') {
limit = op.limit;
}
break;
case "dataId":
dataId = value;
break;
case "sortBy":
sortBy = value.toLowerCase();
break;
case "sortOrder":
sortOrder = value.toLowerCase();
break;
case "sortType":
sortType = value.toLowerCase();
break;
}
// Restore search condition
if (key === "offset" || key === "limit") {
continue;
}
$this.find("[name='" + key + "']").each(function () {
var tagname = this.tagName.toLowerCase();
switch (tagname) {
case "input":
var type = $(this).attr('type');
if (type === "checkbox" && $(this).val() === value) {
$(this).prop("checked", true);
}
else if (type === "radio" && $(this).val() === value) {
$(this).prop("checked", true);
}
else if (type === "text" || type === "search" || type === "hidden") {
if (key === "search") {
$(this).val(value.replace("+"," "));
} else {
$(this).val(value);
}
}
break;
case "select":
$(this).find("option").each(function () {
if ($(this).val() === value) {
$(this).prop("selected", true);
}
else if (value === "" && $(this).val() === " ") {
$(this).prop("selected", true);
}
});
break;
}
});
// Set advancedSearchObj. This object is used in original search.
if (value !== "" ) {
if ($.inArray(key, excludeParams) !== -1) {
continue;
}
if ($.inArray(key, paramExistArry) !== -1) {
advancedSearchObj[key] += "," + value;
}
else {
advancedSearchObj[key] = value;
}
}
paramExistArry.push(key);
} // for
// Set paramKeyCount
var paramKeyCount = 0;
for (var key in advancedSearchObj) {
paramKeyCount++;
}
// =======================================================================
// Set JSON path and using Data API <start>
//
// Set jsonPath
switch (typeof op.searchDataPath) {
case "string":
jsonPath = op.searchDataPath;
break;
case "object":
if (dataId === "") {
window.alert("dataId is required.");
return;
}
else {
if (op.dataApiDataIds !== null && $.inArray(dataId, op.dataApiDataIds.split(",")) !== -1) {
api = true;
if (op.dataApiParams !== null) {
paramStr += (paramStr !== "") ? "&" + $.param(op.dataApiParams): $.param(op.dataApiParams);
}
}
jsonPath = op.searchDataPath[dataId];
}
break;
}
//
// Set JSON path and using Data API </end>
// -----------------------------------------------------------------------
// =======================================================================
// Search <start>
//
if (api) {
jsonPath += "?" + paramStr;
}
$.ajax({
type: "GET",
cache: op.cache,
dataType: "json",
url: jsonPath,
error: function (jqXHR, textStatus, errorThrown) {
op.ajaxError(jqXHR, textStatus, errorThrown);
},
success: function (response) {
var resultJSON = {};
if (api) {
// Data API
resultJSON = response;
}
else {
// Original JSON
// Clone the items
var cloneItems = $.grep(response.items, function () {
return true;
});
// Advanced Search
cloneItems = $.grep(cloneItems, function (item, i) {
return jsonAdvancedSearch (item, advancedSearchObj, paramKeyCount, "like", op.advancedSearchCond);
});
// Search by keywords
cloneItems = $.grep(cloneItems, function (item, i) {
return jsonKeywordsSearch (item, searchWords);
});
// Do custom search
if (op.customSearch !== null && typeof op.customSearch === "function") {
cloneItems = $.grep(cloneItems, function (item, i) {
return op.customSearch(item, paramObj);
});
}
// Set resultJSON
var limitIdx = Number(limit) + Number(offset);
resultJSON.totalResults = cloneItems.length;
// Sort
if (resultJSON.totalResults !== 0 && sortBy !== "" && sortBy in cloneItems[0]) {
if (sortOrder !== "ascend") {
sortOrder = "descend";
}
if (sortType !== "numeric") {
sortType = "string";
}
objectSort(cloneItems, sortBy, sortOrder, sortType);
}
resultJSON.items = $.grep(cloneItems, function (item, i) {
if (i < offset) {
return false;
}
else if (i >= limitIdx) {
return false;
}
else {
return true;
}
});
}
// Paginate
var currentPage = Math.ceil(offset / limit) + 1;
var realMaxPageCount = Math.ceil(resultJSON.totalResults / limit);
var maxPageCount = op.maxPageCount ? op.maxPageCount : 100;
var forwordRange = ((maxPageCount % 2) == 0) ? (maxPageCount / 2) - 1 : Math.floor(maxPageCount / 2);
var backwardRange = ((maxPageCount % 2) == 0) ? maxPageCount / 2 : Math.floor(maxPageCount / 2);
var startPage, lastPage;
if (realMaxPageCount <= maxPageCount) {
startPage = 1;
lastPage = realMaxPageCount;
}
else {
startPage = currentPage - forwordRange;
lastPage = currentPage + backwardRange;
if (startPage < 1) {
startPage = 1;
lastPage = maxPageCount;
}
else {
if (lastPage > realMaxPageCount) {
backwardRange = realMaxPageCount - currentPage;
lastPage = realMaxPageCount;
forwordRange = maxPageCount - backwardRange;
startPage = currentPage - forwordRange;
}
}
}
var pageList = [];
for (var i = 0, n = realMaxPageCount; ++i <= n;) {
pageList.push({pageNumber: i});
}
var paginateJSON = {
id: op.paginateId,
classname: op.paginateClassName,
page: pageList,
hidePageNumber: op.hidePageNumber,
showTurnPage: op.showTurnPage,
prevPageText: op.prevPageText,
nextPageText: op.nextPageText,
isFirst: function(){
return currentPage === 1;
},
isLast: function(){
if (!pageList.length) {
return true;
}
return currentPage === pageList.length;
},
exceptFirst: function(){
return currentPage !== 1;
},
exceptLast: function(){
return pageList.length > 0 && currentPage !== pageList.length;
},
checkRange: function(){
return this.pageNumber >= startPage && this.pageNumber <= lastPage;
},
current: function () {
if (this.pageNumber === currentPage) {
return 'fs-current';
}
else if (this.pageNumber === (currentPage - 1)) {
return "fs-current-prev";
}
else if (this.pageNumber === (currentPage + 1)) {
return "fs-current-next";
}
else {
return "";
}
},
currentLink: function () {
if (this.pageNumber === currentPage) {
return 'fs-current-link';
}
else if (this.pageNumber === (currentPage - 1)) {
return "fs-current-prev-link";
}
else if (this.pageNumber === (currentPage + 1)) {
return "fs-current-next-link";
}
else {
return "";
}
}
};
var paginateHTML = Mustache.render(paginateTmpl, paginateJSON);
// Result message
var resultMsgObj = {
id: op.resultMsgId ? op.resultMsgId : '',
classname: op.resultMsgClassName ? op.resultMsgClassName : '',
keywords: searchWords.join(", "),
keywordArray: searchWords,
count: resultJSON.totalResults,
metaTitle: document.title,
firstPage: function () {
return paginateJSON.page[0].pageNumber;
},
lastPage: function () {
return paginateJSON.page.length;
},
currentPage: currentPage
};
var resultMsgHTML = Mustache.render(resultMsgTmpl, resultMsgObj);
// Set the meta title
var resultMetaTitleTmpl = (op.resultMetaTitleTmpl) ? op.resultMetaTitleTmpl : [
// '{{#keywords}}{{keywords}}{{/keywords}}',
'{{#keywordArray}}{{.}} {{/keywordArray}}',
'{{#count}} {{count}}件{{/count}}',
'{{#count}} {{currentPage}}/{{lastPage}}{{/count}}',
'{{#metaTitle}} | {{metaTitle}}{{/metaTitle}}'
].join("");
var resultMetaTitleHTML = Mustache.render(resultMetaTitleTmpl, resultMsgObj);
document.title = resultMetaTitleHTML;
// Show result
if (op.modifyResultJSON !== null && typeof op.modifyResultJSON === "function") {
resultJSON = op.modifyResultJSON(resultJSON);
}
var resultItemHTML = Mustache.render(resultItemTmpl, resultJSON);
// Callback
if (op.modifyResultMsgHTML !== null && typeof op.modifyResultMsgHTML === "function") {
resultMsgHTML = op.modifyResultMsgHTML(resultMsgHTML);
}
if (op.modifyResultItemHTML !== null && typeof op.modifyResultItemHTML === "function") {
resultItemHTML = op.modifyResultItemHTML(resultItemHTML);
}
if (op.modifyPaginateHTML !== null && typeof op.modifyPaginateHTML === "function") {
paginateHTML = op.modifyPaginateHTML(paginateHTML);
}
// Search Result Block HTML
var resultAllHTML = '';
// Add result message HTML
if (op.resultMsgInsertMethods === null) {
resultAllHTML += resultMsgHTML;
}
// Add result items HTML
resultAllHTML += resultItemHTML;
// Add paginate HTML
if (op.paginateInsertMethods === null) {
resultAllHTML += paginateHTML;
}
// Add all of result HTML to DOM
document.getElementById(op.resultBlockId).innerHTML = resultAllHTML;
// Add result message HTML to DOM
if (op.resultMsgInsertMethods !== null) {
for (var i = 0, l = op.resultMsgInsertMethods.length; i < l; i++) {
$(op.resultMsgInsertMethods[i].selector)[op.resultMsgInsertMethods[i].method](resultMsgHTML);
}
}
// Add paginate HTML to DOM
if (op.paginateInsertMethods !== null) {
for (var i = 0, l = op.paginateInsertMethods.length; i < l; i++) {
$(op.paginateInsertMethods[i].selector)[op.paginateInsertMethods[i].method](paginateHTML);
}
}
// Callback
if (op.resultComplete !== null && typeof op.resultComplete === "function") {
op.resultComplete(resultJSON.totalResults);
}
// Bind pageLink() to paginate link
var paginateSelector = op.paginateId ? "#" + op.paginateId : "." + op.paginateClassName;
$(paginateSelector)
.on("click", "a.fs-page-link", function (e) {
e.preventDefault();
var page = $(this).attr("title");
var offset = (Number(page) - 1) * Number(limit);
offset = "offset=" + offset;
var url = location.href.split("?");
var query = url[1].replace(/offset=[0-9]+/, offset);
location.href = url[0] + "?" + query;
})
.on("click", "a.fs-turn-page-link", function (e) {
e.preventDefault();
if ($(this).hasClass('fs-prev-link')) {
$(e.delegateTarget).find('.fs-current-prev-link').trigger('click');
}
else if ($(this).hasClass('fs-next-link')) {
$(e.delegateTarget).find('.fs-current-next-link').trigger('click');
}
});
} // success
}); // ajax
//
// Search </end>
// -----------------------------------------------------------------------
// =======================================================================
// Functions <start>
//
function jsonAdvancedSearch (obj, advancedSearchObj, paramKeyCount, matchType, cond) {
var matched = 0;
if (matchType === "like") {
for (var key in advancedSearchObj) {
var valueArray = advancedSearchObj[key].split(",");
var valueArrayLength = valueArray.length;
var _matched = 0;
for (var i = -1, n = valueArrayLength; ++i < n;) {
var reg = new RegExp(valueArray[i], "i");
if (typeof obj[key] === "undefined" || typeof obj[key] === "string" && reg.test(obj[key])) {
if (cond === 'AND' || cond === 'and') {
_matched++;
}
else {
matched++;
break;
}
}
// else if (obj[key] && typeof obj[key] === "object" && obj[key].length) {
// for (var i = -1, n = obj[key].length; ++i < n;) {
// if (reg.test(obj[key])) return true;
// }
// }
}
if (cond === 'AND' || cond === 'and') {
if (_matched === valueArrayLength) {
matched++;
}
}
}
return matched === paramKeyCount;
}
else {
for (var key in advancedSearchObj) {
if (obj[key] && typeof obj[key] === "string" && obj[key] !== advancedSearchObj[key]) {
return false;
}
// else if (obj[key] && typeof obj[key] === "object" && obj[key].length) {
// for (var i = -1, n = obj[key].length; ++i < n;) {
// return advancedSearchObj[key] === obj[key][i];
// }
// }
}
}
return matched;
}
function jsonKeywordsSearch (obj, keywordsArray) {
var keywordsCount = keywordsArray.length;
var keywordsMutchCount = 0;
for (var i = -1; ++i < keywordsCount;) {
var reg = new RegExp(keywordsArray[i], "i");
// if (reg.test(obj[key])) keyMatch++;
for (var key in obj) {
if (reg.test(obj[key])) {
keywordsMutchCount++;
break;
}
}
}
return (keywordsCount === keywordsMutchCount);
}
// Sort object.
// @paran {Array} array JSON
// @paran {String} sortBy Sort by this property's value.
// @paran {String} sortOrder ascend or descend.
// @paran {String} sortType numeric or string.
function objectSort (array, sortBy, sortOrder, sortType) {
if (!sortBy && typeof sortBy !== "string") {
return;
}
sortOrder = (sortOrder === 'ascend') ? -1 : 1;
array.sort(function(obj1, obj2){
var v1 = obj1[sortBy];
var v2 = obj2[sortBy];
if (sortType === 'numeric') {
v1 = v1 - 0;
v2 = v2 - 0;
}
else if (sortType === 'string') {
v1 = '' + v1;
v2 = '' + v2;
}
if (v1 < v2) {
return 1 * sortOrder;
}
if (v1 > v2) {
return -1 * sortOrder;
}
return 0;
});
}
//
// Functions </end>
// -----------------------------------------------------------------------
};
$.fn.flexibleSearch.defaults = {
// The limit parameter is overwritten and locked as this value.
limit: null,
// Path
searchDataPath: "/flexibleSearch/search.json",
searchDataPathPreload: null,
// Data API
dataApiDataIds: null,
dataApiParams: null,
// Performance
cache: true, // I recommend "true".
// Search Form
searchFormCreation: true,
searchFormHTML: null,
searchFormAction: "",
searchFormInputType: "search",
searchFormInputPlaceholder: "Search words",
searchFormSubmitBtnText: "Search",
// Advanced Search Form
advancedFormObj: null,
advancedSearchCond: 'OR', // 'AND'
// Result Block
loadingImgPath: "/flexibleSearch/loading.gif",
loadingImgHTML: null,
resultBlockId: "fs-result",
resultItemTmpl: null,
resultMsgId: null,
resultMsgClassName: "fs-result-msg",
resultMsgTmpl: null,
resultMetaTitleTmpl: null,
// You can set an array including plane object which has two properties,
// method property and selector property.
// e.g.
// resultMsgInsertMethods: [
// {
// "selector": "foo",
// "method": "append"
// }
// ],
resultMsgInsertMethods: null,
// Paginate
paginateId: null,
paginateClassName: "fs-paginate",
paginateTmpl: null,
paginateCount: 10,
hidePageNumber: false,
showTurnPage: true,
prevPageText: 'Prev',
nextPageText: 'Next',
maxPageCount: 10,
// You can set an array including plane object which has two properties,
// method property and selector property.
// e.g.
// paginateInsertMethods: [
// {
// "selector": "foo",
// "method": "append"
// }
// ],
paginateInsertMethods: null,
// Submit
submitAction: function (paramArray) {
return paramArray;
},
// Ajax
ajaxError: function (jqXHR, textStatus, errorThrown) {
window.alert(textStatus);
},
// Callbacks
// you can search in your logic.
// e.g.
// customSearch: function(item, paramObj){
// // item : Each item in items
// // paramObj : Plane object of parameters
// // The item is removed when return false
// return true or false;
// },
customSearch: null,
// You can modify the search result JSON.
// e.g.
// modifyResultJSON = function(json){
// json["fullName"] = function(){
// return this.firstName + " " + this.lastName;
// };
// return json;
// },
modifyResultJSON: null,
modifyResultMsgHTML: null,
modifyResultItemHTML: null,
modifyPaginateHTML: null,
resultComplete: null,
excludeParams: null,
dummy: false
};
})(jQuery);