]> git.mxchange.org Git - friendica.git/blob - view/js/main.js
mv URL path uexport -> userexport
[friendica.git] / view / js / main.js
1 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPLv3-or-later
2
3 // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
4 if (!Element.prototype.matches) {
5         Element.prototype.matches =
6                 Element.prototype.matchesSelector ||
7                 Element.prototype.mozMatchesSelector ||
8                 Element.prototype.msMatchesSelector ||
9                 Element.prototype.oMatchesSelector ||
10                 Element.prototype.webkitMatchesSelector ||
11                 function(s) {
12                         var matches = (this.document || this.ownerDocument).querySelectorAll(s),
13                                 i = matches.length;
14                         while (--i >= 0 && matches.item(i) !== this) {}
15                         return i > -1;
16                 };
17 }
18
19 function resizeIframe(obj) {
20         _resizeIframe(obj, 0);
21 }
22
23 function _resizeIframe(obj, desth) {
24         var h = obj.style.height;
25         var ch = obj.contentWindow.document.body.scrollHeight;
26
27         if (h == (ch + 'px')) {
28                 return;
29         }
30         if (desth == ch && ch > 0) {
31                 obj.style.height  = ch + 'px';
32         }
33         setTimeout(_resizeIframe, 100, obj, ch);
34 }
35
36 function openClose(theID) {
37         var el = document.getElementById(theID);
38         if (el) {
39                 if (window.getComputedStyle(el).display === "none") {
40                         openMenu(theID);
41                 } else {
42                         closeMenu(theID);
43                 }
44         }
45 }
46
47 function openMenu(theID) {
48         var el = document.getElementById(theID);
49         if (el) {
50                 if (!el.dataset.display) {
51                         el.dataset.display = 'block';
52                 }
53                 el.style.display = el.dataset.display;
54         }
55 }
56
57 function closeMenu(theID) {
58         var el = document.getElementById(theID);
59         if (el) {
60                 el.dataset.display = window.getComputedStyle(el).display;
61                 el.style.display = "none";
62         }
63 }
64
65 function decodeHtml(html) {
66         var txt = document.createElement("textarea");
67
68         txt.innerHTML = html;
69         return txt.value;
70 }
71
72 var src = null;
73 var prev = null;
74 var livetime = null;
75 var force_update = false;
76 var update_item = 0;
77 var stopped = false;
78 var totStopped = false;
79 var timer = null;
80 var pr = 0;
81 var liking = 0;
82 var in_progress = false;
83 var langSelect = false;
84 var commentBusy = false;
85 var last_popup_menu = null;
86 var last_popup_button = null;
87 var lockLoadContent = false;
88
89 $(function() {
90         $.ajaxSetup({cache: false});
91
92         /* setup comment textarea buttons */
93         /* comment textarea buttons needs some "data-*" attributes to work:
94          *              data-role="insert-formatting" : to mark the element as a formatting button
95          *              data-bbcode="<string>" : name of the bbcode element to insert. insertFormatting() will insert it as "[name][/name]"
96          *              data-id="<string>" : id of the comment, used to find other comment-related element, like the textarea
97          * */
98         $('body').on('click','[data-role="insert-formatting"]', function(e) {
99                 e.preventDefault();
100                 var o = $(this);
101                 var bbcode = o.data('bbcode');
102                 var id = o.data('id');
103                 if (bbcode == "img") {
104                         Dialog.doImageBrowser("comment", id);
105                         return;
106                 }
107
108                 if (bbcode == "imgprv") {
109                         bbcode = "img";
110                 }
111
112                 insertFormatting(bbcode, id);
113         });
114
115         /* event from comment textarea button popups */
116         /* insert returned bbcode at cursor position or replace selected text */
117         $("body").on("fbrowser.image.comment", function(e, filename, bbcode, id) {
118                 $.colorbox.close();
119                 var textarea = document.getElementById("comment-edit-text-" +id);
120                 var start = textarea.selectionStart;
121                 var end = textarea.selectionEnd;
122                 textarea.value = textarea.value.substring(0, start) + bbcode + textarea.value.substring(end, textarea.value.length);
123                 $(textarea).trigger('change');
124         });
125
126         /* setup onoff widgets */
127         $(".onoff input").each(function() {
128                 val = $(this).val();
129                 id = $(this).attr("id");
130                 $("#"+id+"_onoff ." + (val == 0 ? "on":"off")).addClass("hidden");
131         });
132
133         $(".onoff > a").click(function(event) {
134                 event.preventDefault();
135                 var input = $(this).siblings("input");
136                 var val = 1-input.val();
137                 var id = input.attr("id");
138                 $("#"+id+"_onoff ." + (val == 0 ? "on":"off")).addClass("hidden");
139                 $("#"+id+"_onoff ." + (val == 1 ? "on":"off")).removeClass("hidden");
140                 input.val(val);
141         });
142
143         /* popup menus */
144         function close_last_popup_menu() {
145                 if (last_popup_menu) {
146                         last_popup_menu.hide();
147                         last_popup_menu.off('click', function(e) {e.stopPropagation()});
148                         last_popup_button.removeClass("selected");
149                         last_popup_menu = null;
150                         last_popup_button = null;
151                 }
152         }
153         $('a[rel^="#"]').click(function(e) {
154                 e.preventDefault();
155                 var parent = $(this).parent();
156                 var isSelected = (last_popup_button && parent.attr('id') == last_popup_button.attr('id'));
157                 close_last_popup_menu();
158                 if (isSelected) {
159                         return false;
160                 }
161                 menu = $($(this).attr('rel'));
162                 e.preventDefault();
163                 e.stopPropagation();
164                 if (menu.attr('popup') == "false") {
165                         return false;
166                 }
167                 parent.toggleClass("selected");
168                 menu.toggle();
169                 if (menu.css("display") == "none") {
170                         last_popup_menu = null;
171                         last_popup_button = null;
172                 } else {
173                         last_popup_menu = menu;
174                         last_popup_menu.on('click', function(e) {e.stopPropagation()});
175                         last_popup_button = parent;
176                         $('#nav-notifications-menu').perfectScrollbar('update');
177                 }
178                 return false;
179         });
180         $('html').click(function() {
181                 close_last_popup_menu();
182         });
183
184         // fancyboxes
185         $("a.popupbox").colorbox({
186                 'inline' : true,
187                 'transition' : 'elastic',
188                 'maxWidth' : '100%'
189         });
190         $("a.ajax-popupbox").colorbox({
191                 'transition' : 'elastic',
192                 'maxWidth' : '100%'
193         });
194
195         /* notifications template */
196         var notifications_tpl= unescape($("#nav-notifications-template[rel=template]").html());
197         var notifications_all = unescape($('<div>').append($("#nav-notifications-see-all").clone()).html()); //outerHtml hack
198         var notifications_mark = unescape($('<div>').append($("#nav-notifications-mark-all").clone()).html()); //outerHtml hack
199         var notifications_empty = unescape($("#nav-notifications-menu").html());
200
201         /* enable perfect-scrollbars for different elements */
202         $('#nav-notifications-menu, aside').perfectScrollbar();
203
204         /* nav update event  */
205         $('nav').bind('nav-update', function(e, data) {
206                 var invalid = data.invalid || 0;
207                 if (invalid == 1) {
208                         window.location.href=window.location.href
209                 }
210
211                 ['net', 'home', 'intro', 'mail', 'events', 'birthdays', 'notify'].forEach(function(type) {
212                         var number = data[type];
213                         if (number == 0) {
214                                 number = '';
215                                 $('#' + type + '-update').removeClass('show');
216                         } else {
217                                 $('#' + type + '-update').addClass('show');
218                         }
219                         $('#' + type + '-update').text(number);
220                 });
221
222                 var intro = data['intro'];
223                 if (intro == 0) {
224                         intro = ''; $('#intro-update-li').removeClass('show')
225                 } else {
226                         $('#intro-update-li').addClass('show')
227                 }
228
229                 $('#intro-update-li').html(intro);
230
231                 var mail = data['mail'];
232                 if (mail == 0) {
233                         mail = ''; $('#mail-update-li').removeClass('show')
234                 } else {
235                         $('#mail-update-li').addClass('show')
236                 }
237
238                 $('#mail-update-li').html(mail);
239
240                 $(".sidebar-group-li .notify").removeClass("show");
241                 $(data.groups).each(function(key, group) {
242                         var gid = group.id;
243                         var gcount = group.count;
244                         $(".group-"+gid+" .notify").addClass("show").text(gcount);
245                 });
246
247                 $(".forum-widget-entry .notify").removeClass("show");
248                 $(data.forums).each(function(key, forum) {
249                         var fid = forum.id;
250                         var fcount = forum.count;
251                         $(".forum-"+fid+" .notify").addClass("show").text(fcount);
252                 });
253
254                 if (data.notifications.length == 0) {
255                         $("#nav-notifications-menu").html(notifications_empty);
256                 } else {
257                         var nnm = $("#nav-notifications-menu");
258                         nnm.html(notifications_all + notifications_mark);
259
260                         var lastItemStorageKey = "notification-lastitem:" + localUser;
261                         var notification_lastitem = parseInt(localStorage.getItem(lastItemStorageKey));
262                         var notification_id = 0;
263
264                         // Insert notifs into the notifications-menu
265                         $(data.notifications).each(function(key, notif) {
266                                 var text = notif.message.format('<span class="contactname">' + notif.name + '</span>');
267                                 var contact = ('<a href="' + notif.url + '"><span class="contactname">' + notif.name + '</span></a>');
268                                 var seenclass = (notif.seen == 1) ? "notify-seen" : "notify-unseen";
269                                 var html = notifications_tpl.format(
270                                         notif.href,                     // {0}  // link to the source
271                                         notif.photo,                    // {1}  // photo of the contact
272                                         text,                           // {2}  // preformatted text (autor + text)
273                                         notif.date,                     // {3}  // date of notification (time ago)
274                                         seenclass,                      // {4}  // visited status of the notification
275                                         new Date(notif.timestamp*1000), // {5}  // date of notification
276                                         notif.url,                      // {6}  // profile url of the contact
277                                         notif.message.format(contact),  // {7}  // preformatted html (text including author profile url)
278                                         ''                              // {8}  // Deprecated
279                                 );
280                                 nnm.append(html);
281                         });
282
283                         // Desktop Notifications
284                         $(data.notifications.reverse()).each(function(key, e) {
285                                 notification_id = parseInt(e.timestamp);
286                                 if (notification_lastitem !== null && notification_id > notification_lastitem && Number(e.seen) === 0) {
287                                         if (getNotificationPermission() === "granted") {
288                                                 var notification = new Notification(document.title, {
289                                                                                   body: decodeHtml(e.message.replace('&rarr; ', '').format(e.name)),
290                                                                                   icon: e.photo,
291                                                                                 });
292                                                 notification['url'] = e.href;
293                                                 notification.addEventListener("click", function(ev) {
294                                                         window.location = ev.target.url;
295                                                 });
296                                         }
297                                 }
298
299                         });
300                         notification_lastitem = notification_id;
301                         localStorage.setItem(lastItemStorageKey, notification_lastitem)
302
303                         $("img[data-src]", nnm).each(function(i, el) {
304                                 // Add src attribute for images with a data-src attribute
305                                 // However, don't bother if the data-src attribute is empty, because
306                                 // an empty "src" tag for an image will cause some browsers
307                                 // to prefetch the root page of the Friendica hub, which will
308                                 // unnecessarily load an entire profile/ or network/ page
309                                 if ($(el).data("src") != '') {
310                                         $(el).attr('src', $(el).data("src"));
311                                 }
312                         });
313                 }
314
315                 var notif = data['notify'];
316                 if (notif > 0) {
317                         $("#nav-notifications-linkmenu").addClass("on");
318                 } else {
319                         $("#nav-notifications-linkmenu").removeClass("on");
320                 }
321
322                 $(data.sysmsgs.notice).each(function(key, message) {
323                         $.jGrowl(message, {sticky: true, theme: 'notice'});
324                 });
325                 $(data.sysmsgs.info).each(function(key, message) {
326                         $.jGrowl(message, {sticky: false, theme: 'info', life: 5000});
327                 });
328
329                 // Update the js scrollbars
330                 $('#nav-notifications-menu').perfectScrollbar('update');
331         });
332
333         // Asynchronous calls are deferred until the very end of the page load to ease on slower connections
334         window.addEventListener("load", function(){
335                 NavUpdate();
336                 if (typeof acl !== 'undefined') {
337                         acl.get(0, 100);
338                 }
339         });
340
341         // Allow folks to stop the ajax page updates with the pause/break key
342         $(document).keydown(function(event) {
343                 if (event.keyCode == '8') {
344                         var target = event.target || event.srcElement;
345                         if (!/input|textarea/i.test(target.nodeName)) {
346                                 return false;
347                         }
348                 }
349
350                 if (event.keyCode == '19' || (event.ctrlKey && event.which == '32')) {
351                         event.preventDefault();
352                         if (stopped == false) {
353                                 stopped = true;
354                                 if (event.ctrlKey) {
355                                         totStopped = true;
356                                 }
357                                 $('#pause').html('<img src="images/pause.gif" alt="pause" style="border: 1px solid black;" />');
358                         } else {
359                                 unpause();
360                         }
361                 } else if (!totStopped) {
362                         unpause();
363                 }
364         });
365
366         // Scroll to the next/previous thread when pressing J and K
367         $(document).keydown(function (event) {
368                 var threads = $('.thread_level_1');
369                 if ((event.keyCode === 74 || event.keyCode === 75) && !$(event.target).is('textarea, input')) {
370                         var scrollTop = $(window).scrollTop();
371                         if (event.keyCode === 75) {
372                                 threads = $(threads.get().reverse());
373                         }
374                         threads.each(function(key, item) {
375                                 var comparison;
376                                 var top = $(item).offset().top - 100;
377                                 if (event.keyCode === 74) {
378                                         comparison = top > scrollTop + 1;
379                                 } else if (event.keyCode === 75) {
380                                         comparison = top < scrollTop - 1;
381                                 }
382                                 if (comparison) {
383                                         $('html, body').animate({scrollTop: top}, 200);
384                                         return false;
385                                 }
386                         });
387                 }
388         });
389
390         // Set an event listener for infinite scroll
391         if (typeof infinite_scroll !== 'undefined') {
392                 $(window).scroll(function(e) {
393                         if ($(document).height() != $(window).height()) {
394                                 // First method that is expected to work - but has problems with Chrome
395                                 if ($(window).scrollTop() > ($(document).height() - $(window).height() * 1.5))
396                                         loadScrollContent();
397                         } else {
398                                 // This method works with Chrome - but seems to be much slower in Firefox
399                                 if ($(window).scrollTop() > (($("section").height() + $("header").height() + $("footer").height()) - $(window).height() * 1.5)) {
400                                         loadScrollContent();
401                                 }
402                         }
403                 });
404         }
405 });
406
407 function NavUpdate() {
408         if (!stopped) {
409                 var pingCmd = 'ping?format=json' + ((localUser != 0) ? '&f=&uid=' + localUser : '');
410                 $.get(pingCmd, function(data) {
411                         if (data.result) {
412                                 // send nav-update event
413                                 $('nav').trigger('nav-update', data.result);
414
415                                 // start live update
416                                 ['network', 'profile', 'community', 'notes', 'display', 'contact'].forEach(function (src) {
417                                         if ($('#live-' + src).length) {
418                                                 liveUpdate(src);
419                                         }
420                                 });
421                                 if ($('#live-photos').length) {
422                                         if (liking) {
423                                                 liking = 0;
424                                                 window.location.href = window.location.href;
425                                         }
426                                 }
427                         }
428                 });
429         }
430         timer = setTimeout(NavUpdate, updateInterval);
431 }
432
433 function updateConvItems(data) {
434         // add a new thread
435         $('.toplevel_item',data).each(function() {
436                 var ident = $(this).attr('id');
437
438                 // Add new top-level item.
439                 if ($('#' + ident).length == 0 && profile_page == 1) {
440                         $('#' + prev).after($(this));
441
442                 // Replace already existing thread.
443                 } else {
444                         // Find out if the hidden comments are open, so we can keep it that way
445                         // if a new comment has been posted
446                         var id = $('.hide-comments-total', this).attr('id');
447                         if (typeof id != 'undefined') {
448                                 id = id.split('-')[3];
449                                 var commentsOpen = $("#collapsed-comments-" + id).is(":visible");
450                         }
451
452                         $('#' + ident).replaceWith($(this));
453
454                         if (typeof id != 'undefined') {
455                                 if (commentsOpen) {
456                                         showHideComments(id);
457                                 }
458                         }
459                 }
460                 prev = ident;
461         });
462
463         $('.like-rotator').hide();
464         if (commentBusy) {
465                 commentBusy = false;
466                 $('body').css('cursor', 'auto');
467         }
468         /* autocomplete @nicknames */
469         $(".comment-edit-form  textarea").editor_autocomplete(baseurl + '/search/acl');
470         /* autocomplete bbcode */
471         $(".comment-edit-form  textarea").bbco_autocomplete('bbcode');
472 }
473
474 function liveUpdate(src) {
475         if ((src == null) || stopped || !profile_uid) {
476                 $('.like-rotator').hide(); return;
477         }
478
479         if (($('.comment-edit-text-full').length) || in_progress) {
480                 if (livetime) {
481                         clearTimeout(livetime);
482                 }
483                 livetime = setTimeout(function() {liveUpdate(src)}, 5000);
484                 return;
485         }
486
487         if (livetime != null) {
488                 livetime = null;
489         }
490         prev = 'live-' + src;
491
492         in_progress = true;
493
494         if ($(document).scrollTop() == 0) {
495                 force_update = true;
496         }
497
498         var orgHeight = $("section").height();
499
500         var udargs = ((netargs.length) ? '/' + netargs : '');
501         var update_url = 'update_' + src + udargs + '&p=' + profile_uid + '&page=' + profile_page + '&force=' + ((force_update) ? 1 : 0) + '&item=' + update_item;
502
503         $.get(update_url,function(data) {
504                 in_progress = false;
505                 force_update = false;
506                 update_item = 0;
507
508                 $('.wall-item-body', data).imagesLoaded(function() {
509                         updateConvItems(data);
510
511                         document.dispatchEvent(new Event('postprocess_liveupdate'));
512
513                         // Update the scroll position.
514                         $(window).scrollTop($(window).scrollTop() + $("section").height() - orgHeight);
515                 });
516         });
517 }
518
519 function imgbright(node) {
520         $(node).removeClass("drophide").addClass("drop");
521 }
522
523 function imgdull(node) {
524         $(node).removeClass("drop").addClass("drophide");
525 }
526
527 // Since our ajax calls are asynchronous, we will give a few
528 // seconds for the first ajax call (setting like/dislike), then
529 // run the updater to pick up any changes and display on the page.
530 // The updater will turn any rotators off when it's done.
531 // This function will have returned long before any of these
532 // events have completed and therefore there won't be any
533 // visible feedback that anything changed without all this
534 // trickery. This still could cause confusion if the "like" ajax call
535 // is delayed and NavUpdate runs before it completes.
536
537 function dolike(ident,verb) {
538         unpause();
539         $('#like-rotator-' + ident.toString()).show();
540         $.get('like/' + ident.toString() + '?verb=' + verb, NavUpdate);
541         liking = 1;
542         force_update = true;
543         update_item = ident.toString();
544 }
545
546 function dosubthread(ident) {
547         unpause();
548         $('#like-rotator-' + ident.toString()).show();
549         $.get('subthread/' + ident.toString(), NavUpdate);
550         liking = 1;
551 }
552
553 function dostar(ident) {
554         ident = ident.toString();
555         $('#like-rotator-' + ident).show();
556         $.get('starred/' + ident, function(data) {
557                 if (data.match(/1/)) {
558                         $('#starred-' + ident).addClass('starred');
559                         $('#starred-' + ident).removeClass('unstarred');
560                         $('#star-' + ident).addClass('hidden');
561                         $('#unstar-' + ident).removeClass('hidden');
562                 } else {
563                         $('#starred-' + ident).addClass('unstarred');
564                         $('#starred-' + ident).removeClass('starred');
565                         $('#star-' + ident).removeClass('hidden');
566                         $('#unstar-' + ident).addClass('hidden');
567                 }
568                 $('#like-rotator-' + ident).hide();
569         });
570 }
571
572 function doignore(ident) {
573         ident = ident.toString();
574         $('#like-rotator-' + ident).show();
575         $.get('ignored/' + ident, function(data) {
576                 if (data.match(/1/)) {
577                         $('#ignored-' + ident).addClass('ignored');
578                         $('#ignored-' + ident).removeClass('unignored');
579                         $('#ignore-' + ident).addClass('hidden');
580                         $('#unignore-' + ident).removeClass('hidden');
581                 } else {
582                         $('#ignored-' + ident).addClass('unignored');
583                         $('#ignored-' + ident).removeClass('ignored');
584                         $('#ignore-' + ident).removeClass('hidden');
585                         $('#unignore-' + ident).addClass('hidden');
586                 }
587                 $('#like-rotator-' + ident).hide();
588         });
589 }
590
591 function getPosition(e) {
592         var cursor = {x:0, y:0};
593
594         if (e.pageX || e.pageY) {
595                 cursor.x = e.pageX;
596                 cursor.y = e.pageY;
597         } else {
598                 if (e.clientX || e.clientY) {
599                         cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
600                         cursor.y = e.clientY + (document.documentElement.scrollTop  || document.body.scrollTop)  - document.documentElement.clientTop;
601                 } else if (e.x || e.y) {
602                         cursor.x = e.x;
603                         cursor.y = e.y;
604                 }
605         }
606         return cursor;
607 }
608
609 var lockvisible = false;
610
611 function lockview(event,id) {
612         event = event || window.event;
613         cursor = getPosition(event);
614         if (lockvisible) {
615                 lockviewhide();
616         } else {
617                 lockvisible = true;
618                 $.get('lockview/' + id, function(data) {
619                         $('#panel').html(data);
620                         $('#panel').css({'left': cursor.x + 5 , 'top': cursor.y + 5});
621                         $('#panel').show();
622                 });
623         }
624 }
625
626 function lockviewhide() {
627         lockvisible = false;
628         $('#panel').hide();
629 }
630
631 function post_comment(id) {
632         unpause();
633         commentBusy = true;
634         $('body').css('cursor', 'wait');
635         $.post(
636                 "item",
637                 $("#comment-edit-form-" + id).serialize(),
638                 function(data) {
639                         if (data.success) {
640                                 $("#comment-edit-wrapper-" + id).hide();
641                                 $("#comment-edit-text-" + id).val('');
642                                 var tarea = document.getElementById("comment-edit-text-" + id);
643                                 if (tarea) {
644                                         commentClose(tarea,id);
645                                 }
646                                 if (timer) {
647                                         clearTimeout(timer);
648                                 }
649                                 timer = setTimeout(NavUpdate,10);
650                                 force_update = true;
651                                 update_item = id;
652                         }
653                         if (data.reload) {
654                                 window.location.href=data.reload;
655                         }
656                 },
657                 "json"
658         );
659         return false;
660 }
661
662 function preview_comment(id) {
663         $("#comment-edit-preview-" + id).show();
664         $.post(
665                 "item",
666                 $("#comment-edit-form-" + id).serialize() + '&preview=1',
667                 function(data) {
668                         if (data.preview) {
669                                 $("#comment-edit-preview-" + id).html(data.preview);
670                                 $("#comment-edit-preview-" + id + " a").click(function() {return false;});
671                         }
672                 },
673                 "json"
674         );
675         return true;
676 }
677
678 function showHideComments(id) {
679         if ($('#collapsed-comments-' + id).is(':visible')) {
680                 $('#collapsed-comments-' + id).slideUp();
681                 $('#hide-comments-' + id).hide();
682                 $('#hide-comments-total-' + id).show();
683         } else {
684                 $('#collapsed-comments-' + id).slideDown();
685                 $('#hide-comments-' + id).show();
686                 $('#hide-comments-total-' + id).hide();
687         }
688 }
689
690 function preview_post() {
691         $("#jot-preview").val("1");
692         $("#jot-preview-content").show();
693         $.post(
694                 "item",
695                 $("#profile-jot-form").serialize(),
696                 function(data) {
697                         if (data.preview) {
698                                 $("#jot-preview-content").html(data.preview);
699                                 $("#jot-preview-content" + " a").click(function() {return false;});
700                                 document.dispatchEvent(new Event('postprocess_liveupdate'));
701                         }
702                 },
703                 "json"
704         );
705         $("#jot-preview").val("0");
706         return true;
707 }
708
709 function unpause() {
710         // unpause auto reloads if they are currently stopped
711         totStopped = false;
712         stopped = false;
713         $('#pause').html('');
714 }
715
716 // load more network content (used for infinite scroll)
717 function loadScrollContent() {
718         if (lockLoadContent) {
719                 return;
720         }
721         lockLoadContent = true;
722
723         $("#scroll-loader").fadeIn('normal');
724
725         // the page number to load is one higher than the actual
726         // page number
727         infinite_scroll.pageno+=1;
728
729         match = $("span.received").last();
730         if (match.length > 0) {
731                 received = match[0].innerHTML;
732         } else {
733                 received = "0000-00-00 00:00:00";
734         }
735
736         match = $("span.created").last();
737         if (match.length > 0) {
738                 created = match[0].innerHTML;
739         } else {
740                 created = "0000-00-00 00:00:00";
741         }
742
743         match = $("span.commented").last();
744         if (match.length > 0) {
745                 commented = match[0].innerHTML;
746         } else {
747                 commented = "0000-00-00 00:00:00";
748         }
749
750         match = $("span.id").last();
751         if (match.length > 0) {
752                 id = match[0].innerHTML;
753         } else {
754                 id = "0";
755         }
756
757         // get the raw content from the next page and insert this content
758         // right before "#conversation-end"
759         $.get(infinite_scroll.reload_uri + '&mode=raw&last_received=' + received + '&last_commented=' + commented + '&last_created=' + created + '&last_id=' + id + '&page=' + infinite_scroll.pageno, function(data) {
760                 $("#scroll-loader").hide();
761                 if ($(data).length > 0) {
762                         $(data).insertBefore('#conversation-end');
763                         lockLoadContent = false;
764                 } else {
765                         $("#scroll-end").fadeIn('normal');
766                 }
767
768                 document.dispatchEvent(new Event('postprocess_liveupdate'));
769         });
770 }
771
772 function bin2hex(s) {
773         // Converts the binary representation of data to hex
774         //
775         // version: 812.316
776         // discuss at: http://phpjs.org/functions/bin2hex
777         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
778         // +   bugfixed by: Onno Marsman
779         // +   bugfixed by: Linuxworld
780         // *     example 1: bin2hex('Kev');
781         // *     returns 1: '4b6576'
782         // *     example 2: bin2hex(String.fromCharCode(0x00));
783         // *     returns 2: '00'
784         var v,i, f = 0, a = [];
785         s += '';
786         f = s.length;
787
788         for (i = 0; i<f; i++) {
789                 a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
790         }
791
792         return a.join('');
793 }
794
795 function groupChangeMember(gid, cid, sec_token) {
796         $('body .fakelink').css('cursor', 'wait');
797         $.get('group/' + gid + '/' + cid + "?t=" + sec_token, function(data) {
798                         $('#group-update-wrapper').html(data);
799                         $('body .fakelink').css('cursor', 'auto');
800         });
801 }
802
803 function profChangeMember(gid,cid) {
804         $('body .fakelink').css('cursor', 'wait');
805         $.get('profperm/' + gid + '/' + cid, function(data) {
806                         $('#prof-update-wrapper').html(data);
807                         $('body .fakelink').css('cursor', 'auto');
808         });
809 }
810
811 function contactgroupChangeMember(checkbox, gid, cid) {
812         let url;
813         // checkbox.checked is the checkbox state after the click
814         if (checkbox.checked) {
815                 url = 'group/' + gid + '/add/' + cid;
816         } else {
817                 url = 'group/' + gid + '/remove/' + cid;
818         }
819         $('body').css('cursor', 'wait');
820         $.post(url)
821         .error(function () {
822                 // Restores previous state in case of error
823                 checkbox.checked = !checkbox.checked;
824         })
825         .always(function() {
826                 $('body').css('cursor', 'auto');
827         });
828
829         return true;
830 }
831
832 function checkboxhighlight(box) {
833         if ($(box).is(':checked')) {
834                 $(box).addClass('checkeditem');
835         } else {
836                 $(box).removeClass('checkeditem');
837         }
838 }
839
840 function notifyMarkAll() {
841         $.get('notify/mark/all', function(data) {
842                 if (timer) {
843                         clearTimeout(timer);
844                 }
845                 timer = setTimeout(NavUpdate,1000);
846                 force_update = true;
847         });
848 }
849
850 /**
851  * sprintf in javascript
852  *      "{0} and {1}".format('zero','uno');
853  **/
854 String.prototype.format = function() {
855         var formatted = this;
856         for (var i = 0; i < arguments.length; i++) {
857                 var regexp = new RegExp('\\{'+i+'\\}', 'gi');
858                 formatted = formatted.replace(regexp, arguments[i]);
859         }
860         return formatted;
861 };
862 // Array Remove
863 Array.prototype.remove = function(item) {
864         to=undefined; from=this.indexOf(item);
865         var rest = this.slice((to || from) + 1 || this.length);
866         this.length = from < 0 ? this.length + from : from;
867         return this.push.apply(this, rest);
868 };
869
870 function previewTheme(elm) {
871         theme = $(elm).val();
872         $.getJSON('pretheme?f=&theme=' + theme,function(data) {
873                         $('#theme-preview').html('<div id="theme-desc">' + data.desc + '</div><div id="theme-version">' + data.version + '</div><div id="theme-credits">' + data.credits + '</div><a href="' + data.img + '"><img src="' + data.img + '" width="320" height="240" alt="' + theme + '" /></a>');
874         });
875
876 }
877
878 // notification permission settings in localstorage
879 // set by settings page
880 function getNotificationPermission() {
881         if (window["Notification"] === undefined) {
882                 return null;
883         }
884
885         if (Notification.permission === 'granted') {
886                 var val = localStorage.getItem('notification-permissions');
887                 if (val === null) {
888                         return 'denied';
889                 }
890                 return val;
891         } else {
892                 return Notification.permission;
893         }
894 }
895
896 /**
897  * Show a dialog loaded from an url
898  * By defaults this load the url in an iframe in colorbox
899  * Themes can overwrite `show()` function to personalize it
900  */
901 var Dialog = {
902         /**
903          * Show the dialog
904          *
905          * @param string url
906          * @return object colorbox
907          */
908         show : function (url) {
909                 var size = Dialog._get_size();
910                 return $.colorbox({href: url, iframe:true,innerWidth: size.width+'px',innerHeight: size.height+'px'})
911         },
912
913         /**
914          * Show the Image browser dialog
915          *
916          * @param string name
917          * @param string id (optional)
918          * @return object
919          *
920          * The name will be used to build the event name
921          * fired by image browser dialog when the user select
922          * an image. The optional id will be passed as argument
923          * to the event handler
924          */
925         doImageBrowser : function (name, id) {
926                 var url = Dialog._get_url("image",name,id);
927                 return Dialog.show(url);
928         },
929
930         /**
931          * Show the File browser dialog
932          *
933          * @param string name
934          * @param string id (optional)
935          * @return object
936          *
937          * The name will be used to build the event name
938          * fired by file browser dialog when the user select
939          * a file. The optional id will be passed as argument
940          * to the event handler
941          */
942         doFileBrowser : function (name, id) {
943                 var url = Dialog._get_url("file",name,id);
944                 return Dialog.show(url);
945         },
946
947         _get_url : function(type, name, id) {
948                 var hash = name;
949                 if (id !== undefined) {
950                         hash = hash + "-" + id;
951                 }
952                 return baseurl + "/fbrowser/"+type+"/?mode=minimal#"+hash;
953         },
954
955         _get_size: function() {
956                 return {
957                         width: window.innerWidth-50,
958                         height: window.innerHeight-100
959                 };
960         }
961 }
962 // @license-end