forked from elkarte/Elkarte
/
script_elk.js
1419 lines (1241 loc) · 41 KB
/
script_elk.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
/**
* @name ElkArte Forum
* @copyright ElkArte Forum contributors
* @license BSD http://opensource.org/licenses/BSD-3-Clause
*
* @version 1.0 Beta 2
*
* This file contains javascript utility functions specific to ElkArte
*/
/**
* Sets an auto height so small code blocks collapse
* Sets a height for larger code blocks and lets them resize / overflow as normal
*/
function elk_codefix()
{
$('.bbc_code').each(function()
{
$(this).height("auto");
if ($(this).height() > 200)
$(this).css('height', '20em');
});
}
/**
* Turn a regular url button in to an ajax request
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
* @param {string} confirmation_msg_variable var name of the text sting to display in the "are you sure" box
*/
function toggleButtonAJAX(btn, confirmation_msg_variable)
{
$.ajax({
type: 'GET',
url: btn.href + ';xml;api',
context: document.body,
beforeSend: ajax_indicator(true)
})
.done(function(request) {
if (request === '')
return;
var oElement = $(request).find('elk')[0];
// No errors
if (oElement.getElementsByTagName('error').length === 0)
{
var text = oElement.getElementsByTagName('text'),
url = oElement.getElementsByTagName('url'),
confirm_elem = oElement.getElementsByTagName('confirm');
// Update the page so button/link/confirm/etc reflect the new on or off status
if (confirm_elem.length === 1)
var confirm_text = confirm_elem[0].firstChild.nodeValue.removeEntities();
$('.' + btn.className.replace(/(list|link)level\d/g, '').trim()).each(function() {
// @todo: the span should be moved somewhere in themes.js?
if (text.length === 1)
$(this).html('<span>' + text[0].firstChild.nodeValue.removeEntities() + '</span>');
if (url.length === 1)
$(this).attr('href', url[0].firstChild.nodeValue.removeEntities());
// Replaces the confirmation var text with the new one from the response to allow swapping on/off
if (typeof (confirm_text) !== 'undefined')
eval(confirmation_msg_variable + '= \'' + confirm_text.replace(/[\\']/g, '\\$&') + '\'');
});
}
else
{
// Error returned from the called function, show an alert
if (oElement.getElementsByTagName('text').length !== 0)
alert(oElement.getElementsByTagName('text')[0].firstChild.nodeValue.removeEntities());
if (oElement.getElementsByTagName('url').length !== 0)
window.location.href = oElement.getElementsByTagName('url')[0].firstChild.nodeValue;
}
})
.fail(function() {
// ajax failure code
})
.always(function() {
// turn off the indicator
ajax_indicator(false);
});
return false;
}
/**
* Helper function: displays and removes the ajax indicator and
* hides some page elements inside "container_id"
* Used by some (one at the moment) ajax buttons
*
* @todo it may be merged into the function if not used anywhere else
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
* @param {string} container_id css ID of the data container
*/
function toggleHeaderAJAX(btn, container_id)
{
// Show ajax is in progress
ajax_indicator(true);
var body_template = '<div class="board_row centertext">{body}</div>';
$.ajax({
type: 'GET',
url: btn.href + ';xml;api',
context: document.body,
beforeSend: ajax_indicator(true)
})
.done(function(request) {
if (request === '')
return;
var oElement = $(request).find('elk')[0];
// No errors
if (oElement.getElementsByTagName('error').length === 0)
{
var text_elem = oElement.getElementsByTagName('text'),
body_elem = oElement.getElementsByTagName('body');
$('#' + container_id + ' .pagesection').remove();
$('#' + container_id + ' .topic_listing').remove();
$('#' + container_id + ' .topic_sorting').remove();
if (text_elem.length === 1)
$('#' + container_id + ' #unread_header').html(text_elem[0].firstChild.nodeValue.removeEntities());
if (body_elem.length === 1)
$(body_template.replace('{body}', body_elem[0].firstChild.nodeValue.removeEntities())).insertAfter('#unread_header');
}
})
.fail(function() {
// ajax failure code
})
.always(function() {
// turn off the indicator
ajax_indicator(false);
});
}
/**
* Ajaxify the "notify" button in Display
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
*/
function notifyButton(btn)
{
if (typeof (notification_topic_notice) !== 'undefined' && !confirm(notification_topic_notice))
return false;
return toggleButtonAJAX(btn, 'notification_topic_notice');
}
/**
* Ajaxify the "notify" button in MessageIndex
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
*/
function notifyboardButton(btn)
{
if (typeof (notification_board_notice) !== 'undefined' && !confirm(notification_board_notice))
return false;
toggleButtonAJAX(btn, 'notification_board_notice');
return false;
}
/**
* Ajaxify the "unwatch" button in Display
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
*/
function unwatchButton(btn)
{
toggleButtonAJAX(btn);
return false;
}
/**
* Ajaxify the "mark read" button in MessageIndex
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
*/
function markboardreadButton(btn)
{
toggleButtonAJAX(btn);
// Remove all the "new" icons next to the topics subjects
$('.new_posts').remove();
return false;
}
/**
* Ajaxify the "mark all messages as read" button in BoardIndex
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
*/
function markallreadButton(btn)
{
toggleButtonAJAX(btn);
// Remove all the "new" icons next to the topics subjects
$('.new_posts').remove();
// Turn the board icon class to off
$('.board_icon').each(function() {
$(this).removeClass('on_board on2_board').addClass('off_board');
});
$('.board_new_posts').removeClass('board_new_posts');
return false;
}
/**
* Ajaxify the "mark all messages as read" button in Recent
*
* @param {string} btn string representing this, generally the anchor link tag <a class="" href="" onclick="">
*/
function markunreadButton(btn)
{
toggleHeaderAJAX(btn, 'main_content_section');
return false;
}
/**
* This function changes the relative time around the page real-timeish
*/
var relative_time_refresh = 0;
function updateRelativeTime()
{
// In any other case no more than one hour
relative_time_refresh = 3600000;
$('time').each(function() {
var oRelativeTime = new relativeTime($(this).data('timestamp') * 1000, oRttime.referenceTime),
time_text = '';
if (oRelativeTime.seconds())
{
$(this).text(oRttime.now);
relative_time_refresh = Math.min(relative_time_refresh, 10000);
}
else if (oRelativeTime.minutes())
{
time_text = oRelativeTime.deltaTime > 1 ? oRttime.minutes : oRttime.minute;
$(this).text(time_text.replace('%s', oRelativeTime.deltaTime));
relative_time_refresh = Math.min(relative_time_refresh, 60000);
}
else if (oRelativeTime.hours())
{
time_text = oRelativeTime.deltaTime > 1 ? oRttime.hours : oRttime.hour;
$(this).text(time_text.replace('%s', oRelativeTime.deltaTime));
relative_time_refresh = Math.min(relative_time_refresh, 3600000);
}
else if (oRelativeTime.days())
{
time_text = oRelativeTime.deltaTime > 1 ? oRttime.days : oRttime.day;
$(this).text(time_text.replace('%s', oRelativeTime.deltaTime));
relative_time_refresh = Math.min(relative_time_refresh, 3600000);
}
else if (oRelativeTime.weeks())
{
time_text = oRelativeTime.deltaTime > 1 ? oRttime.weeks : oRttime.week;
$(this).text(time_text.replace('%s', oRelativeTime.deltaTime));
relative_time_refresh = Math.min(relative_time_refresh, 3600000);
}
else if (oRelativeTime.months())
{
time_text = oRelativeTime.deltaTime > 1 ? oRttime.months : oRttime.month;
$(this).text(time_text.replace('%s', oRelativeTime.deltaTime));
relative_time_refresh = Math.min(relative_time_refresh, 3600000);
}
else if (oRelativeTime.years())
{
time_text = oRelativeTime.deltaTime > 1 ? oRttime.years : oRttime.year;
$(this).text(time_text.replace('%s', oRelativeTime.deltaTime));
relative_time_refresh = Math.min(relative_time_refresh, 3600000);
}
});
oRttime.referenceTime += relative_time_refresh;
setTimeout('updateRelativeTime()', relative_time_refresh);
}
/**
* Function/object to handle relative times
* sTo is optional, if omitted the relative time is
* calculated from sFrom up to "now"
*
* @param {string} sFrom
* @param {string} sTo
*/
function relativeTime(sFrom, sTo)
{
if (typeof sTo === 'undefined')
{
this.dateTo = new Date();
}
else if (parseInt(sTo) == 'NaN')
{
var sToSplit = sTo.split(/\D/);
this.dateTo = new Date(sToSplit[0], --sToSplit[1], sToSplit[2], sToSplit[3], sToSplit[4]);
}
else
this.dateTo = new Date(sTo);
if (parseInt(sFrom) == 'NaN')
{
var sFromSplit = sFrom.split(/\D/);
this.dateFrom = new Date(sFromSplit[0], --sFromSplit[1], sFromSplit[2], sFromSplit[3], sFromSplit[4]);
}
else
this.dateFrom = new Date(sFrom);
this.time_text = '';
this.past_time = (this.dateTo - this.dateFrom) / 1000;
this.deltaTime = 0;
}
relativeTime.prototype.seconds = function()
{
// Within the first 60 seconds it is just now.
if (this.past_time < 60)
{
this.deltaTime = this.past_time;
return true;
}
return false;
};
relativeTime.prototype.minutes = function()
{
// Within the first hour?
if (this.past_time >= 60 && Math.round(this.past_time / 60) < 60)
{
this.deltaTime = Math.round(this.past_time / 60);
return true;
}
return false;
};
relativeTime.prototype.hours = function()
{
// Some hours but less than a day?
if (Math.round(this.past_time / 60) >= 60 && Math.round(this.past_time / 3600) < 24)
{
this.deltaTime = Math.round(this.past_time / 3600);
return true;
}
return false;
};
relativeTime.prototype.days = function()
{
// Some days ago but less than a week?
if (Math.round(this.past_time / 3600) >= 24 && Math.round(this.past_time / (24 * 3600)) < 7)
{
this.deltaTime = Math.round(this.past_time / (24 * 3600));
return true;
}
return false;
};
relativeTime.prototype.weeks = function()
{
// Weeks ago but less than a month?
if (Math.round(this.past_time / (24 * 3600)) >= 7 && Math.round(this.past_time / (24 * 3600)) < 30)
{
this.deltaTime = Math.round(this.past_time / (24 * 3600) / 7);
return true;
}
return false;
};
relativeTime.prototype.months = function()
{
// Months ago but less than a year?
if (Math.round(this.past_time / (24 * 3600)) >= 30 && Math.round(this.past_time / (30 * 24 * 3600)) < 12)
{
this.deltaTime = Math.round(this.past_time / (30 * 24 * 3600));
return true;
}
return false;
};
relativeTime.prototype.years = function()
{
// Oha, we've passed at least a year?
if (Math.round(this.past_time / (30 * 24 * 3600)) >= 12)
{
this.deltaTime = this.dateTo.getFullYear() - this.dateFrom.getFullYear();
return true;
}
return false;
};
/**
* Used to tag mentioned names when they are entered inline but NOT selected from the dropdown list
* The name must have appeared in the dropdown and be found in that cache list
*
* @param {string} sForm the form that holds the container, only used for plain text QR
* @param {string} sInput the container that atWho is attached
*/
function revalidateMentions(sForm, sInput)
{
var cached_names,
cached_queries,
body,
mentions,
pos = -1,
// Some random punctation marks that may appear next to a name
boundaries_pattern = /[ \.,;!\?'-\\\/="]/i;
for (var i = 0, count = all_elk_mentions.length; i < count; i++)
{
// Make sure this mention object is for this selector, saftey first
if (all_elk_mentions[i].selector === sInput || all_elk_mentions[i].selector === '#' + sInput)
{
// Was this invoked as the editor plugin?
if (all_elk_mentions[i].oOptions.isPlugin)
{
var $editor = $('#' + all_elk_mentions[i].selector).data("sceditor");
cached_names = $editor.opts.mentionOptions.cache.names;
cached_queries = $editor.opts.mentionOptions.cache.queries;
// Clean up the newlines and spacing so we can find the @mentions
body = $editor.getText().replace(/[\u00a0\r\n]/g, ' ');
mentions = $($editor.opts.mentionOptions.cache.mentions);
}
// Or just our plain text quick reply box?
else
{
cached_names = all_elk_mentions[i].oMention.cached_names;
cached_queries = all_elk_mentions[i].oMention.cached_queries;
// Keep everything separated with spaces, not newlines or no breakable
body = document.forms[sForm][sInput].value.replace(/[\u00a0\r\n]/g, ' ');
// The last pulldown box that atWho populated
mentions = $(all_elk_mentions[i].oMention.mentions);
}
// Adding a space at the beginning to facilitate catching of mentions at the 1st char
// and one at the end to simplify catching any last thing in the text
body = ' ' + body + ' ';
// First check if all those in the list are really mentioned
$(mentions).find('input').each(function (idx, elem) {
var name = $(elem).data('name'),
next_char,
prev_char,
index = body.indexOf(name);
// It is undefined coming from a preview
if (typeof(name) !== 'undefined')
{
if (index === -1)
$(elem).remove();
else
{
next_char = body.charAt(index + name.length);
prev_char = body.charAt(index - 1);
if (next_char !== '' && next_char.search(boundaries_pattern) !== 0)
$(elem).remove();
else if (prev_char !== '' && prev_char.search(boundaries_pattern) !== 0)
$(elem).remove();
}
}
});
for (var k = 0, ccount = cached_queries.length; k < ccount; k++)
{
var names = cached_names[cached_queries[k]];
for (var l = 0, ncount = names.length; l < ncount; l++)
{
if(checkWordOccurrence(body, names[l].name)) {
// alert(names[l].name);
pos = body.indexOf(' @' + names[l].name);
// If there is something like "{space}@username" AND the following char is a space or a punctation mark
if (pos !== -1 && body.charAt(pos + 2 + names[l].name.length + 1).search(boundaries_pattern) === 0)
mentions.append($('<input type="hidden" name="uid[]" />').val(names[l].id));
}
}
}
}
}
}
/**
* Check whether the word exists in a given paragraph
*
* @param paragraph to check
* @param word to match
*/
function checkWordOccurrence(paragraph, word){
return new RegExp( '\\b' + word + '\\b', 'i').test(paragraph);
}
/**
* This is called from the editor plugin or display.template to set where to
* find the cache values for use in revalidateMentions
*
* @param {string} selector id of element that atWho is attached to
* @param {object} oOptions only set when called from the plugin, contains those options
*/
var all_elk_mentions = [];
function add_elk_mention(selector, oOptions)
{
// Global does not exist, hummm
if (all_elk_mentions.hasOwnProperty(selector))
return;
// No options means its attached to the plain text box
if (typeof oOptions === 'undefined')
oOptions = {};
oOptions.selector = selector;
// Add it to the stack
all_elk_mentions[all_elk_mentions.length] = {
selector: selector,
oOptions: oOptions
};
}
/**
* Drag and drop to reorder ID's via UI Sortable
*
* @param {object} $
*/
(function($) {
'use strict';
$.fn.elkSortable = function(oInstanceSettings) {
$.fn.elkSortable.oDefaultsSettings = {
opacity: 0.7,
cursor: 'move',
axis: 'y',
scroll: true,
containment: 'parent',
delay: 150,
href: '', // If an error occurs redirect here
tolerance: 'intersect', // mode to use for testing whether the item is hovering over another item.
setorder: 'serialize', // how to return the data, really only supports serialize and inorder
placeholder: '', // css class used to style the landing zone
preprocess: '', // This function is called at the start of the update event (when the item is dropped) must in in global space
tag: '#table_grid_sortable', // ID(s) of the container to work with, single or comma separated
connect: '', // Use to group all related containers with a common CSS class
sa: '', // Subaction that the xmlcontroller should know about
title: '', // Title of the error box
error: '', // What to say when we don't know what happened, like connection error
token: '' // Security token if needed
};
// Account for any user options
var oSettings = $.extend({}, $.fn.elkSortable.oDefaultsSettings, oInstanceSettings || {});
// Divs to hold our responses
var ajax_infobar = document.createElement('div'),
ajax_errorbox = document.createElement('div');
// Prepare the infobar and errorbox divs to confirm valid responses or show an error
$(ajax_infobar).css({'position': 'fixed', 'top': '0', 'left': '0', 'width': '100%'});
$("body").append(ajax_infobar);
$(ajax_infobar).slideUp();
$(ajax_errorbox).css({'display': 'none'});
$("body").append(ajax_errorbox).attr('id', 'errorContainer');
// Find all oSettings.tag and attach the UI sortable action
$(oSettings.tag).sortable({
opacity: oSettings.opacity,
cursor: oSettings.cursor,
axis: oSettings.axis,
containment: oSettings.containment,
connectWith: oSettings.connect,
placeholder: oSettings.placeholder,
tolerance: oSettings.tolerance,
delay: oSettings.delay,
scroll: oSettings.scroll,
helper: function(e, ui) {
// Fist create a helper container
var $originals = ui.children(),
$helper = ui.clone(),
$clone;
// Replace the helper elements with spans, normally this is a <td> -> <span>
// Done to make this container agnostic.
$helper.children().each(function() {
$(this).replaceWith(function(){
return $("<span />", {html: $(this).html()});
});
});
// Set the width of each helper cell span to be the width of the original cells
$helper.children().each(function(index) {
// Set helper cell sizes to match the original sizes
return $(this).width($originals.eq(index).width()).css('display', 'inline-block');
});
// Next to overcome an issue where page scrolling does now work, we add the new agnostic helper
// element to the body, and hide it
$('body').append('<div id="clone" class="' + oSettings.placeholder + '">' + $helper.html()+ '</div>');
$clone = $('#clone');
$clone.hide();
// Append the clone element to the actual container we are working in and show it
setTimeout(function() {
$clone.appendTo(ui.parent());
$clone.show();
}, 1);
// The above append process allows page scrolls to work while dragging the clone element
return $clone;
},
update: function(e, ui) {
// Called when an element is dropped in a new location
var postdata = '',
moved = ui.item.attr('id'),
order = [],
receiver = ui.item.parent().attr('id');
// Calling a pre processing function?
if (oSettings.preprocess !== '')
window[oSettings.preprocess]();
// How to post the sorted data
if (oSettings.setorder === 'inorder')
{
// This will get the order in 1-n as shown on the screen
$(oSettings.tag).find('li').each(function() {
var aid = $(this).attr('id').split('_');
order.push({name: aid[0] + '[]', value: aid[1]});
});
postdata = $.param(order);
}
// Get all id's in all the sortable containers
else
{
$(oSettings.tag).each(function() {
// Serialize will be 1-n of each nesting / connector
if (postdata === "")
postdata += $(this).sortable(oSettings.setorder);
else
postdata += "&" + $(this).sortable(oSettings.setorder);
});
}
// Add in our security tags and additional options
postdata += '&' + elk_session_var + '=' + elk_session_id;
postdata += '&order=reorder';
postdata += '&moved=' + moved;
postdata += '&received=' + receiver;
if (oSettings.token !== '')
postdata += '&' + oSettings.token.token_var + '=' + oSettings.token.token_id;
// And with the post data prepared, lets make the ajax request
$.ajax({
type: "POST",
url: elk_scripturl + "?action=xmlhttp;sa=" + oSettings.sa + ";xml",
dataType: "xml",
data: postdata
})
.fail(function(jqXHR, textStatus, errorThrown) {
$(ajax_infobar).attr('class', 'errorbox');
$(ajax_infobar).html(textStatus).slideDown('fast');
setTimeout(function() {
$(ajax_infobar).slideUp();
}, 3500);
// Reset the interface?
if (oSettings.href !== '')
setTimeout(function() {
window.location.href = elk_scripturl + oSettings.href;
}, 1000);
})
.done(function(data, textStatus, jqXHR) {
if ($(data).find("error").length !== 0)
{
// Errors get a modal dialog box and redirect on close
$('#errorContainer').append('<p id="errorContent"></p>');
$('#errorContent').html($(data).find("error").text());
$('#errorContent').dialog({
autoOpen: true,
title: oSettings.title,
modal: true,
close: function(event, ui) {
// Redirecting due to the error, thats a good idea
if (oSettings.href !== '')
window.location.href = elk_scripturl + oSettings.href;
}
});
}
else if ($(data).find("elk").length !== 0)
{
// Valid responses get the unobtrusive slider
$(ajax_infobar).attr('class', 'infobox');
$(ajax_infobar).html($(data).find('elk > orders > order').text()).slideDown('fast');
setTimeout(function() {
$(ajax_infobar).slideUp();
}, 3500);
}
else
{
// Something "other" happened ...
$('#errorContainer').append('<p id="errorContent"></p>');
$('#errorContent').html(oSettings.error + ' : ' + textStatus);
$('#errorContent').dialog({autoOpen: true, title: oSettings.title, modal: true});
}
})
.always(function(data, textStatus, jqXHR) {
if (textStatus === 'success' && $(data).find("elk > tokens > token").length !== 0)
{
// Reset the token
oSettings.token.token_id = $(data).find("tokens").find('[type="token"]').text();
oSettings.token.token_var = $(data).find("tokens").find('[type="token_var"]').text();
}
});
}
});
};
})(jQuery);
/**
* Helper function used in the preprocess call for drag/drop boards
* Sets the id of all 'li' elements to cat#,board#,childof# for use in the
* $_POST back to the xmlcontroller
*/
function setBoardIds() {
// For each category of board
$("[id^=category_]").each(function() {
var cat = $(this).attr('id').split('category_'),
uls = $(this).find("ul");
// First up add drop zones so we can drag and drop to each level
if (uls.length === 1)
{
// A single empty ul in a category, this can happen when a cat is dragged empty
if ($(uls).find("li").length === 0)
$(uls).append('<li id="cbp_' + cat + ',-1,-1"></li>');
// Otherwise the li's need a child ul so we have a "child-of" drop zone
else
$(uls).find("li:not(:has(ul))").append('<ul class="nolist"></ul>');
}
// All others normally
else
$(uls).find("li:not(:has(ul))").append('<ul class="nolist"></ul>');
// Next make find all the ul's in this category that have children, update the
// id's with information that indicates the 1-n and parent/child info
$(this).find('ul:parent').each(function(i, ul) {
// Get the (li) parent of this ul
var parentList = $(this).parent('li').attr('id'),
pli = 0;
// No parent, then its a base node 0, else its a child-of this node
if (typeof (parentList) !== "undefined")
{
pli = parentList.split(",");
pli = pli[1];
}
// Now for each li in this ul
$(this).find('li').each(function(i, el) {
var currentList = $(el).attr('id');
var myid = currentList.split(",");
// Remove the old id, insert the newly computed cat,brd,childof
$(el).removeAttr("id");
myid = "cbp_" + cat[1] + "," + myid[1] + "," + pli;
$(el).attr('id', myid);
});
});
});
}
/**
* Expands the ... of the page indexes
*
* @todo not exactly a plugin and still very bound to the theme structure
*
*/
;(function($) {
$.fn.expand_pages = function() {
var $container,
lastPositions = [];
// Hovering over an ... we expand it as much as we can
function hover_expand($element)
{
var $expanded_pages_li = $element,
baseurl = eval($element.data('baseurl')),
perpage = $element.data('perpage'),
firstpage = $element.data('firstpage'),
lastpage = $element.data('lastpage'),
$exp_pages = $('<li id="expanded_pages" />'),
pages = 0,
container_width = $element.outerWidth() * 2,
width_elements = 3,
$scroll_left = null,
$scroll_right = null;
var aModel = $element.closest('.linavPages').prev().find('a').clone();
if (typeof(lastPositions[firstpage]) === 'undefined')
lastPositions[firstpage] = 0;
$container = $('<ul id="expanded_pages_container">');
for (var i = firstpage; i < lastpage; i += perpage)
{
pages++;
var bElem = aModel.clone();
bElem.attr('href', baseurl.replace('%1$d', i)).text(i / perpage + 1);
$exp_pages.append(bElem);
}
if (pages > width_elements)
{
$container.append($('<li />').append(aModel.clone()
.attr('id', 'pages_scroll_left')
.attr('href', '#').text('<').click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
}).hover(
function() {
$exp_pages.animate({
'margin-left': 0
}, 200 * pages);
},
function() {
$exp_pages.stop();
lastPositions[firstpage] = $exp_pages.css('margin-left');
}
)));
}
$container.append($exp_pages);
$element.parent().superfish({
delay : 300,
speed: 175,
speedOut: 50,
onHide: function () {
$container.remove();
}
});
$element.append($container);
if (pages > width_elements)
{
$container.append($('<li />').append(aModel.clone()
.attr('id', 'pages_scroll_right')
.attr('href', '#').text('>').click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
}).hover(
function() {
var $pages = $exp_pages.find('a'),
move = 0;
for (var i = 0, count = $exp_pages.find('a').length; i < count; i++)
move += $($pages[i]).outerWidth();
move = (move + $container.find('#pages_scroll_left').outerWidth()) - ($container.outerWidth() - $container.find('#pages_scroll_right').outerWidth());
$exp_pages.animate({
'margin-left': -move
}, 200 * pages);
},
function() {
$exp_pages.stop();
lastPositions[firstpage] = $exp_pages.css('margin-left');
}
)));
}
// @todo this seems broken
$exp_pages.find('a').each(function() {
if (width_elements > -1)
container_width += $element.outerWidth();
if (width_elements <= 0 || pages >= width_elements)
{
$container.css({
'margin-left': -container_width / 2
}).width(container_width);
}
if (width_elements < 0)
return false;
width_elements--;
}).click(function (ev) {
$expanded_pages_li.attr('onclick', '').off('click');
});
$exp_pages.css({
'height': $element.outerHeight(),
'padding-left': $container.find('#pages_scroll_left').outerWidth(),
'margin-left': lastPositions[firstpage]
});
}
// Used when the user clicks on the ... to expand instead of just a hover expand
function expand_pages($element)
{
var $baseAppend = $($element.closest('.linavPages')),
boxModel = $baseAppend.prev().clone(),
aModel = boxModel.find('a').clone(),
expandModel = $element.clone(),
perPage = $element.data('perpage'),
firstPage = $element.data('firstpage'),
lastPage = $element.data('lastpage'),
rawBaseurl = $element.data('baseurl'),
baseurl = eval($element.data('baseurl')),
first;
var i = 0,
oldLastPage = 0,
perPageLimit = 10;
// Prevent too many pages to be loaded at once.
if ((lastPage - firstPage) / perPage > perPageLimit)
{
oldLastPage = lastPage;
lastPage = firstPage + perPageLimit * perPage;
}
// Calculate the new pages.
for (i = lastPage; i > firstPage; i -= perPage)
{
var bElem = aModel.clone(),
boxModelClone = boxModel.clone();
bElem.attr('href', baseurl.replace('%1$d', i - perPage)).text(i / perPage);
boxModelClone.find('a').each(function() {
$(this).replaceWith(bElem[0]);
});
$baseAppend.after(boxModelClone);
// This is needed just to remember where to attach the new expand
if (typeof first === 'undefined')
first = boxModelClone;
}
$baseAppend.remove();
if (oldLastPage > 0)
{
// This is to remove any hover_expand
expandModel.find('#expanded_pages_container').each(function() {
$(this).remove();
});
expandModel.click(function(e) {
var $zhis = $(this);
e.preventDefault();
expand_pages($zhis);
$zhis.off('mouseenter focus');
})
.on('mouseenter focus', function() {
hover_expand($(this));
})
.data('perpage', perPage)
.data('firstpage', lastPage)
.data('lastpage', oldLastPage)
.data('baseurl', rawBaseurl);
first.after(expandModel);
}
}
this.attr('tabindex', 0).click(function(e) {
var $zhis = $(this);
e.preventDefault();
expand_pages($zhis);
$zhis.off('mouseenter focus');
})
.on('mouseenter focus', function() {
hover_expand($(this));