forked from phpbb/phpbb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.js
More file actions
1912 lines (1649 loc) · 50.3 KB
/
core.js
File metadata and controls
1912 lines (1649 loc) · 50.3 KB
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
/* global bbfontstyle */
var phpbb = {};
phpbb.alertTime = 100;
(function($) { // Avoid conflicts with other libraries
'use strict';
// define a couple constants for keydown functions.
var keymap = {
TAB: 9,
ENTER: 13,
ESC: 27,
ARROW_UP: 38,
ARROW_DOWN: 40
};
var $dark = $('#darkenwrapper');
var $loadingIndicator;
var phpbbAlertTimer = null;
phpbb.isTouch = (window && typeof window.ontouchstart !== 'undefined');
// Add ajax pre-filter to prevent cross-domain script execution
$.ajaxPrefilter(function(s) {
if (s.crossDomain) {
s.contents.script = false;
}
});
/**
* Display a loading screen
*
* @returns {object} Returns loadingIndicator.
*/
phpbb.loadingIndicator = function() {
if (!$loadingIndicator) {
$loadingIndicator = $('#loading_indicator');
}
if (!$loadingIndicator.is(':visible')) {
$loadingIndicator.fadeIn(phpbb.alertTime);
// Wait 60 seconds and display an error if nothing has been returned by then.
phpbb.clearLoadingTimeout();
phpbbAlertTimer = setTimeout(function() {
phpbb.showTimeoutMessage();
}, 60000);
}
return $loadingIndicator;
};
/**
* Show timeout message
*/
phpbb.showTimeoutMessage = function () {
var $alert = $('#phpbb_alert');
if ($loadingIndicator.is(':visible')) {
phpbb.alert($alert.attr('data-l-err'), $alert.attr('data-l-timeout-processing-req'));
}
};
/**
* Clear loading alert timeout
*/
phpbb.clearLoadingTimeout = function() {
if (phpbbAlertTimer !== null) {
clearTimeout(phpbbAlertTimer);
phpbbAlertTimer = null;
}
};
/**
* Close popup alert after a specified delay
*
* @param {int} delay Delay in ms until darkenwrapper's click event is triggered
*/
phpbb.closeDarkenWrapper = function(delay) {
phpbbAlertTimer = setTimeout(function() {
$('#darkenwrapper').trigger('click');
}, delay);
};
/**
* Display a simple alert similar to JSs native alert().
*
* You can only call one alert or confirm box at any one time.
*
* @param {string} title Title of the message, eg "Information" (HTML).
* @param {string} msg Message to display (HTML).
*
* @returns {object} Returns the div created.
*/
phpbb.alert = function(title, msg) {
var $alert = $('#phpbb_alert');
$alert.find('.alert_title').html(title);
$alert.find('.alert_text').html(msg);
$(document).on('keydown.phpbb.alert', function(e) {
if (e.keyCode === keymap.ENTER || e.keyCode === keymap.ESC) {
phpbb.alert.close($alert, true);
e.preventDefault();
e.stopPropagation();
}
});
phpbb.alert.open($alert);
return $alert;
};
/**
* Handler for opening an alert box.
*
* @param {jQuery} $alert jQuery object.
*/
phpbb.alert.open = function($alert) {
if (!$dark.is(':visible')) {
$dark.fadeIn(phpbb.alertTime);
}
if ($loadingIndicator && $loadingIndicator.is(':visible')) {
$loadingIndicator.fadeOut(phpbb.alertTime, function() {
$dark.append($alert);
$alert.fadeIn(phpbb.alertTime);
});
} else if ($dark.is(':visible')) {
$dark.append($alert);
$alert.fadeIn(phpbb.alertTime);
} else {
$dark.append($alert);
$alert.show();
$dark.fadeIn(phpbb.alertTime);
}
$alert.on('click', function(e) {
e.stopPropagation();
});
$dark.one('click', function(e) {
phpbb.alert.close($alert, true);
e.preventDefault();
e.stopPropagation();
});
$alert.find('.alert_close').one('click', function(e) {
phpbb.alert.close($alert, true);
e.preventDefault();
});
};
/**
* Handler for closing an alert box.
*
* @param {jQuery} $alert jQuery object.
* @param {bool} fadedark Whether to remove dark background.
*/
phpbb.alert.close = function($alert, fadedark) {
var $fade = (fadedark) ? $dark : $alert;
$fade.fadeOut(phpbb.alertTime, function() {
$alert.hide();
});
$alert.find('.alert_close').off('click');
$(document).off('keydown.phpbb.alert');
};
/**
* Display a simple yes / no box to the user.
*
* You can only call one alert or confirm box at any one time.
*
* @param {string} msg Message to display (HTML).
* @param {function} callback Callback. Bool param, whether the user pressed
* yes or no (or whatever their language is).
* @param {bool} fadedark Remove the dark background when done? Defaults
* to yes.
*
* @returns {object} Returns the div created.
*/
phpbb.confirm = function(msg, callback, fadedark) {
var $confirmDiv = $('#phpbb_confirm');
$confirmDiv.find('.alert_text').html(msg);
fadedark = typeof fadedark !== 'undefined' ? fadedark : true;
$(document).on('keydown.phpbb.alert', function(e) {
if (e.keyCode === keymap.ENTER || e.keyCode === keymap.ESC) {
var name = (e.keyCode === keymap.ENTER) ? 'confirm' : 'cancel';
$('input[name="' + name + '"]').trigger('click');
e.preventDefault();
e.stopPropagation();
}
});
$confirmDiv.find('input[type="button"]').one('click.phpbb.confirmbox', function(e) {
var confirmed = this.name === 'confirm';
callback(confirmed);
$confirmDiv.find('input[type="button"]').off('click.phpbb.confirmbox');
phpbb.alert.close($confirmDiv, fadedark || !confirmed);
e.preventDefault();
e.stopPropagation();
});
phpbb.alert.open($confirmDiv);
return $confirmDiv;
};
/**
* Turn a querystring into an array.
*
* @argument {string} string The querystring to parse.
* @returns {object} The object created.
*/
phpbb.parseQuerystring = function(string) {
var params = {}, i, split;
string = string.split('&');
for (i = 0; i < string.length; i++) {
split = string[i].split('=');
params[split[0]] = decodeURIComponent(split[1]);
}
return params;
};
/**
* Makes a link use AJAX instead of loading an entire page.
*
* This function will work for links (both standard links and links which
* invoke confirm_box) and forms. It will be called automatically for links
* and forms with the data-ajax attribute set, and will call the necessary
* callback.
*
* For more info, view the following page on the phpBB wiki:
* http://wiki.phpbb.com/JavaScript_Function.phpbb.ajaxify
*
* @param {object} options Options.
*/
phpbb.ajaxify = function(options) {
var $elements = $(options.selector),
refresh = options.refresh,
callback = options.callback,
overlay = (typeof options.overlay !== 'undefined') ? options.overlay : true,
isForm = $elements.is('form'),
isText = $elements.is('input[type="text"], textarea'),
eventName;
if (isForm) {
eventName = 'submit';
} else if (isText) {
eventName = 'keyup';
} else {
eventName = 'click';
}
$elements.on(eventName, function(event) {
var action, method, data, submit, that = this, $this = $(this);
if ($this.find('input[type="submit"][data-clicked]').attr('data-ajax') === 'false') {
return;
}
/**
* Handler for AJAX errors
*/
function errorHandler(jqXHR, textStatus, errorThrown) {
if (typeof console !== 'undefined' && console.log) {
console.log('AJAX error. status: ' + textStatus + ', message: ' + errorThrown);
}
phpbb.clearLoadingTimeout();
var responseText, errorText = false;
try {
responseText = JSON.parse(jqXHR.responseText);
responseText = responseText.message;
} catch (e) {}
if (typeof responseText === 'string' && responseText.length > 0) {
errorText = responseText;
} else if (typeof errorThrown === 'string' && errorThrown.length > 0) {
errorText = errorThrown;
} else {
errorText = $dark.attr('data-ajax-error-text-' + textStatus);
if (typeof errorText !== 'string' || !errorText.length) {
errorText = $dark.attr('data-ajax-error-text');
}
}
phpbb.alert($dark.attr('data-ajax-error-title'), errorText);
}
/**
* This is a private function used to handle the callbacks, refreshes
* and alert. It calls the callback, refreshes the page if necessary, and
* displays an alert to the user and removes it after an amount of time.
*
* It cannot be called from outside this function, and is purely here to
* avoid repetition of code.
*
* @param {object} res The object sent back by the server.
*/
function returnHandler(res) {
var alert;
phpbb.clearLoadingTimeout();
// Is a confirmation required?
if (typeof res.S_CONFIRM_ACTION === 'undefined') {
// If a confirmation is not required, display an alert and call the
// callbacks.
if (typeof res.MESSAGE_TITLE !== 'undefined') {
alert = phpbb.alert(res.MESSAGE_TITLE, res.MESSAGE_TEXT);
} else {
$dark.fadeOut(phpbb.alertTime);
if ($loadingIndicator) {
$loadingIndicator.fadeOut(phpbb.alertTime);
}
}
if (typeof phpbb.ajaxCallbacks[callback] === 'function') {
phpbb.ajaxCallbacks[callback].call(that, res);
}
// If the server says to refresh the page, check whether the page should
// be refreshed and refresh page after specified time if required.
if (res.REFRESH_DATA) {
if (typeof refresh === 'function') {
refresh = refresh(res.REFRESH_DATA.url);
} else if (typeof refresh !== 'boolean') {
refresh = false;
}
phpbbAlertTimer = setTimeout(function() {
if (refresh) {
window.location = res.REFRESH_DATA.url;
}
// Hide the alert even if we refresh the page, in case the user
// presses the back button.
$dark.fadeOut(phpbb.alertTime, function() {
if (typeof alert !== 'undefined') {
alert.hide();
}
});
}, res.REFRESH_DATA.time * 1000); // Server specifies time in seconds
}
} else {
// If confirmation is required, display a dialog to the user.
phpbb.confirm(res.MESSAGE_BODY, function(del) {
if (!del) {
return;
}
phpbb.loadingIndicator();
data = $('<form>' + res.S_HIDDEN_FIELDS + '</form>').serialize();
$.ajax({
url: res.S_CONFIRM_ACTION,
type: 'POST',
data: data + '&confirm=' + res.YES_VALUE + '&' + $('form', '#phpbb_confirm').serialize(),
success: returnHandler,
error: errorHandler
});
}, false);
}
}
// If the element is a form, POST must be used and some extra data must
// be taken from the form.
var runFilter = (typeof options.filter === 'function');
data = {};
if (isForm) {
action = $this.attr('action').replace('&', '&');
data = $this.serializeArray();
method = $this.attr('method') || 'GET';
if ($this.find('input[type="submit"][data-clicked]')) {
submit = $this.find('input[type="submit"][data-clicked]');
data.push({
name: submit.attr('name'),
value: submit.val()
});
}
} else if (isText) {
var name = $this.attr('data-name') || this.name;
action = $this.attr('data-url').replace('&', '&');
data[name] = this.value;
method = 'POST';
} else {
action = this.href;
data = null;
method = 'GET';
}
var sendRequest = function() {
var dataOverlay = $this.attr('data-overlay');
if (overlay && (typeof dataOverlay === 'undefined' || dataOverlay === 'true')) {
phpbb.loadingIndicator();
}
var request = $.ajax({
url: action,
type: method,
data: data,
success: returnHandler,
error: errorHandler,
cache: false
});
request.always(function() {
if ($loadingIndicator && $loadingIndicator.is(':visible')) {
$loadingIndicator.fadeOut(phpbb.alertTime);
}
});
};
// If filter function returns false, cancel the AJAX functionality,
// and return true (meaning that the HTTP request will be sent normally).
if (runFilter && !options.filter.call(this, data, event, sendRequest)) {
return;
}
sendRequest();
event.preventDefault();
});
if (isForm) {
$elements.find('input:submit').click(function () {
var $this = $(this);
// Remove data-clicked attribute from any submit button of form
$this.parents('form:first').find('input:submit[data-clicked]').removeAttr('data-clicked');
$this.attr('data-clicked', 'true');
});
}
return this;
};
phpbb.search = {
cache: {
data: []
},
tpl: [],
container: []
};
/**
* Get cached search data.
*
* @param {string} id Search ID.
* @returns {bool|object} Cached data object. Returns false if no data exists.
*/
phpbb.search.cache.get = function(id) {
if (this.data[id]) {
return this.data[id];
}
return false;
};
/**
* Set search cache data value.
*
* @param {string} id Search ID.
* @param {string} key Data key.
* @param {string} value Data value.
*/
phpbb.search.cache.set = function(id, key, value) {
if (!this.data[id]) {
this.data[id] = { results: [] };
}
this.data[id][key] = value;
};
/**
* Cache search result.
*
* @param {string} id Search ID.
* @param {string} keyword Keyword.
* @param {Array} results Search results.
*/
phpbb.search.cache.setResults = function(id, keyword, results) {
this.data[id].results[keyword] = results;
};
/**
* Trim spaces from keyword and lower its case.
*
* @param {string} keyword Search keyword to clean.
* @returns {string} Cleaned string.
*/
phpbb.search.cleanKeyword = function(keyword) {
return $.trim(keyword).toLowerCase();
};
/**
* Get clean version of search keyword. If textarea supports several keywords
* (one per line), it fetches the current keyword based on the caret position.
*
* @param {jQuery} $input Search input|textarea.
* @param {string} keyword Input|textarea value.
* @param {bool} multiline Whether textarea supports multiple search keywords.
*
* @returns string Clean string.
*/
phpbb.search.getKeyword = function($input, keyword, multiline) {
if (multiline) {
var line = phpbb.search.getKeywordLine($input);
keyword = keyword.split('\n').splice(line, 1);
}
return phpbb.search.cleanKeyword(keyword);
};
/**
* Get the textarea line number on which the keyword resides - for textareas
* that support multiple keywords (one per line).
*
* @param {jQuery} $textarea Search textarea.
* @returns {int} The line number.
*/
phpbb.search.getKeywordLine = function ($textarea) {
var selectionStart = $textarea.get(0).selectionStart;
return $textarea.val().substr(0, selectionStart).split('\n').length - 1;
};
/**
* Set the value on the input|textarea. If textarea supports multiple
* keywords, only the active keyword is replaced.
*
* @param {jQuery} $input Search input|textarea.
* @param {string} value Value to set.
* @param {bool} multiline Whether textarea supports multiple search keywords.
*/
phpbb.search.setValue = function($input, value, multiline) {
if (multiline) {
var line = phpbb.search.getKeywordLine($input),
lines = $input.val().split('\n');
lines[line] = value;
value = lines.join('\n');
}
$input.val(value);
};
/**
* Sets the onclick event to set the value on the input|textarea to the
* selected search result.
*
* @param {jQuery} $input Search input|textarea.
* @param {object} value Result object.
* @param {jQuery} $row Result element.
* @param {jQuery} $container jQuery object for the search container.
*/
phpbb.search.setValueOnClick = function($input, value, $row, $container) {
$row.click(function() {
phpbb.search.setValue($input, value.result, $input.attr('data-multiline'));
phpbb.search.closeResults($input, $container);
});
};
/**
* Runs before the AJAX search request is sent and determines whether
* there is a need to contact the server. If there are cached results
* already, those are displayed instead. Executes the AJAX request function
* itself due to the need to use a timeout to limit the number of requests.
*
* @param {Array} data Data to be sent to the server.
* @param {object} event Onkeyup event object.
* @param {function} sendRequest Function to execute AJAX request.
*
* @returns {boolean} Returns false.
*/
phpbb.search.filter = function(data, event, sendRequest) {
var $this = $(this),
dataName = ($this.attr('data-name') !== undefined) ? $this.attr('data-name') : $this.attr('name'),
minLength = parseInt($this.attr('data-min-length'), 10),
searchID = $this.attr('data-results'),
keyword = phpbb.search.getKeyword($this, data[dataName], $this.attr('data-multiline')),
cache = phpbb.search.cache.get(searchID),
key = event.keyCode || event.which,
proceed = true;
data[dataName] = keyword;
// No need to search if enter was pressed
// for selecting a value from the results.
if (key === keymap.ENTER) {
return false;
}
if (cache.timeout) {
clearTimeout(cache.timeout);
}
var timeout = setTimeout(function() {
// Check min length and existence of cache.
if (minLength > keyword.length) {
proceed = false;
} else if (cache.lastSearch) {
// Has the keyword actually changed?
if (cache.lastSearch === keyword) {
proceed = false;
} else {
// Do we already have results for this?
if (cache.results[keyword]) {
var response = {
keyword: keyword,
results: cache.results[keyword]
};
phpbb.search.handleResponse(response, $this, true);
proceed = false;
}
// If the previous search didn't yield results and the string only had characters added to it,
// then we won't bother sending a request.
if (keyword.indexOf(cache.lastSearch) === 0 && cache.results[cache.lastSearch].length === 0) {
phpbb.search.cache.set(searchID, 'lastSearch', keyword);
phpbb.search.cache.setResults(searchID, keyword, []);
proceed = false;
}
}
}
if (proceed) {
sendRequest.call(this);
}
}, 350);
phpbb.search.cache.set(searchID, 'timeout', timeout);
return false;
};
/**
* Handle search result response.
*
* @param {object} res Data received from server.
* @param {jQuery} $input Search input|textarea.
* @param {bool} fromCache Whether the results are from the cache.
* @param {function} callback Optional callback to run when assigning each search result.
*/
phpbb.search.handleResponse = function(res, $input, fromCache, callback) {
if (typeof res !== 'object') {
return;
}
var searchID = $input.attr('data-results'),
$container = $(searchID);
if (this.cache.get(searchID).callback) {
callback = this.cache.get(searchID).callback;
} else if (typeof callback === 'function') {
this.cache.set(searchID, 'callback', callback);
}
if (!fromCache) {
this.cache.setResults(searchID, res.keyword, res.results);
}
this.cache.set(searchID, 'lastSearch', res.keyword);
this.showResults(res.results, $input, $container, callback);
};
/**
* Show search results.
*
* @param {Array} results Search results.
* @param {jQuery} $input Search input|textarea.
* @param {jQuery} $container Search results container element.
* @param {function} callback Optional callback to run when assigning each search result.
*/
phpbb.search.showResults = function(results, $input, $container, callback) {
var $resultContainer = $('.search-results', $container);
this.clearResults($resultContainer);
if (!results.length) {
$container.hide();
return;
}
var searchID = $container.attr('id'),
tpl,
row;
if (!this.tpl[searchID]) {
tpl = $('.search-result-tpl', $container);
this.tpl[searchID] = tpl.clone().removeClass('search-result-tpl');
tpl.remove();
}
tpl = this.tpl[searchID];
$.each(results, function(i, item) {
row = tpl.clone();
row.find('.search-result').html(item.display);
if (typeof callback === 'function') {
callback.call(this, $input, item, row, $container);
}
row.appendTo($resultContainer).show();
});
$container.show();
phpbb.search.navigateResults($input, $container, $resultContainer);
};
/**
* Clear search results.
*
* @param {jQuery} $container Search results container.
*/
phpbb.search.clearResults = function($container) {
$container.children(':not(.search-result-tpl)').remove();
};
/**
* Close search results.
*
* @param {jQuery} $input Search input|textarea.
* @param {jQuery} $container Search results container.
*/
phpbb.search.closeResults = function($input, $container) {
$input.off('.phpbb.search');
$container.hide();
};
/**
* Navigate search results.
*
* @param {jQuery} $input Search input|textarea.
* @param {jQuery} $container Search results container.
* @param {jQuery} $resultContainer Search results list container.
*/
phpbb.search.navigateResults = function($input, $container, $resultContainer) {
// Add a namespace to the event (.phpbb.search),
// so it can be unbound specifically later on.
// Rebind it, to ensure the event is 'dynamic'.
$input.off('.phpbb.search');
$input.on('keydown.phpbb.search', function(event) {
var key = event.keyCode || event.which,
$active = $resultContainer.children('.active');
switch (key) {
// Close the results
case keymap.ESC:
phpbb.search.closeResults($input, $container);
break;
// Set the value for the selected result
case keymap.ENTER:
if ($active.length) {
var value = $active.find('.search-result > span').text();
phpbb.search.setValue($input, value, $input.attr('data-multiline'));
}
phpbb.search.closeResults($input, $container);
// Do not submit the form
event.preventDefault();
break;
// Navigate the results
case keymap.ARROW_DOWN:
case keymap.ARROW_UP:
var up = key === keymap.ARROW_UP,
$children = $resultContainer.children();
if (!$active.length) {
if (up) {
$children.last().addClass('active');
} else {
$children.first().addClass('active');
}
} else if ($children.length > 1) {
if (up) {
if ($active.is(':first-child')) {
$children.last().addClass('active');
} else {
$active.prev().addClass('active');
}
} else {
if ($active.is(':last-child')) {
$children.first().addClass('active');
} else {
$active.next().addClass('active');
}
}
$active.removeClass('active');
}
// Do not change cursor position in the input element
event.preventDefault();
break;
}
});
};
$('#phpbb').click(function() {
var $this = $(this);
if (!$this.is('.live-search') && !$this.parents().is('.live-search')) {
phpbb.search.closeResults($('input, textarea'), $('.live-search'));
}
});
phpbb.history = {};
/**
* Check whether a method in the native history object is supported.
*
* @param {string} fn Method name.
* @returns {bool} Returns true if the method is supported.
*/
phpbb.history.isSupported = function(fn) {
return !(typeof history === 'undefined' || typeof history[fn] === 'undefined');
};
/**
* Wrapper for the pushState and replaceState methods of the
* native history object.
*
* @param {string} mode Mode. Either push or replace.
* @param {string} url New URL.
* @param {string} [title] Optional page title.
* @param {object} [obj] Optional state object.
*/
phpbb.history.alterUrl = function(mode, url, title, obj) {
var fn = mode + 'State';
if (!url || !phpbb.history.isSupported(fn)) {
return;
}
if (!title) {
title = document.title;
}
if (!obj) {
obj = null;
}
history[fn](obj, title, url);
};
/**
* Wrapper for the native history.replaceState method.
*
* @param {string} url New URL.
* @param {string} [title] Optional page title.
* @param {object} [obj] Optional state object.
*/
phpbb.history.replaceUrl = function(url, title, obj) {
phpbb.history.alterUrl('replace', url, title, obj);
};
/**
* Wrapper for the native history.pushState method.
*
* @param {string} url New URL.
* @param {string} [title] Optional page title.
* @param {object} [obj] Optional state object.
*/
phpbb.history.pushUrl = function(url, title, obj) {
phpbb.history.alterUrl('push', url, title, obj);
};
/**
* Hide the optgroups that are not the selected timezone
*
* @param {bool} keepSelection Shall we keep the value selected, or shall the
* user be forced to repick one.
*/
phpbb.timezoneSwitchDate = function(keepSelection) {
var $timezoneCopy = $('#timezone_copy');
var $timezone = $('#timezone');
var $tzDate = $('#tz_date');
var $tzSelectDateSuggest = $('#tz_select_date_suggest');
if ($timezoneCopy.length === 0) {
// We make a backup of the original dropdown, so we can remove optgroups
// instead of setting display to none, because IE and chrome will not
// hide options inside of optgroups and selects via css
$timezone.clone()
.attr('id', 'timezone_copy')
.css('display', 'none')
.attr('name', 'tz_copy')
.insertAfter('#timezone');
} else {
// Copy the content of our backup, so we can remove all unneeded options
$timezone.html($timezoneCopy.html());
}
if ($tzDate.val() !== '') {
$timezone.children('optgroup').remove(':not([data-tz-value="' + $tzDate.val() + '"])');
}
if ($tzDate.val() === $tzSelectDateSuggest.attr('data-suggested-tz')) {
$tzSelectDateSuggest.css('display', 'none');
} else {
$tzSelectDateSuggest.css('display', 'inline');
}
var $tzOptions = $timezone.children('optgroup[data-tz-value="' + $tzDate.val() + '"]').children('option');
if ($tzOptions.length === 1) {
// If there is only one timezone for the selected date, we just select that automatically.
$tzOptions.prop('selected', true);
keepSelection = true;
}
if (typeof keepSelection !== 'undefined' && !keepSelection) {
var $timezoneOptions = $timezone.find('optgroup option');
if ($timezoneOptions.filter(':selected').length <= 0) {
$timezoneOptions.filter(':first').prop('selected', true);
}
}
};
/**
* Display the date/time select
*/
phpbb.timezoneEnableDateSelection = function() {
$('#tz_select_date').css('display', 'block');
};
/**
* Preselect a date/time or suggest one, if it is not picked.
*
* @param {bool} forceSelector Shall we select the suggestion?
*/
phpbb.timezonePreselectSelect = function(forceSelector) {
// The offset returned here is in minutes and negated.
var offset = (new Date()).getTimezoneOffset();
var sign = '-';
if (offset < 0) {
sign = '+';
offset = -offset;
}
var minutes = offset % 60;
var hours = (offset - minutes) / 60;
if (hours === 0) {
hours = '00';
sign = '+';
} else if (hours < 10) {
hours = '0' + hours.toString();
} else {
hours = hours.toString();
}
if (minutes < 10) {
minutes = '0' + minutes.toString();
} else {
minutes = minutes.toString();
}
var prefix = 'UTC' + sign + hours + ':' + minutes;
var prefixLength = prefix.length;
var selectorOptions = $('option', '#tz_date');
var i;
var $tzSelectDateSuggest = $('#tz_select_date_suggest');
for (i = 0; i < selectorOptions.length; ++i) {
var option = selectorOptions[i];
if (option.value.substring(0, prefixLength) === prefix) {
if ($('#tz_date').val() !== option.value && !forceSelector) {
// We do not select the option for the user, but notify him,
// that we would suggest a different setting.
phpbb.timezoneSwitchDate(true);
$tzSelectDateSuggest.css('display', 'inline');
} else {
option.selected = true;
phpbb.timezoneSwitchDate(!forceSelector);
$tzSelectDateSuggest.css('display', 'none');
}
var suggestion = $tzSelectDateSuggest.attr('data-l-suggestion');
$tzSelectDateSuggest.attr('title', suggestion.replace('%s', option.innerHTML));
$tzSelectDateSuggest.attr('value', suggestion.replace('%s', option.innerHTML.substring(0, 9)));
$tzSelectDateSuggest.attr('data-suggested-tz', option.innerHTML);
// Found the suggestion, there cannot be more, so return from here.
return;
}
}
};
phpbb.ajaxCallbacks = {};
/**
* Adds an AJAX callback to be used by phpbb.ajaxify.
*