]> git.mxchange.org Git - friendica.git/blob - view/js/main.js
Add global Javascript Element.matches polyfill
[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+"/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         $("#comment-preview-inp-" + id).val("0");
636         $.post(
637                 "item",
638                 $("#comment-edit-form-" + id).serialize(),
639                 function(data) {
640                         if (data.success) {
641                                 $("#comment-edit-wrapper-" + id).hide();
642                                 $("#comment-edit-text-" + id).val('');
643                                 var tarea = document.getElementById("comment-edit-text-" + id);
644                                 if (tarea) {
645                                         commentClose(tarea,id);
646                                 }
647                                 if (timer) {
648                                         clearTimeout(timer);
649                                 }
650                                 timer = setTimeout(NavUpdate,10);
651                                 force_update = true;
652                                 update_item = id;
653                         }
654                         if (data.reload) {
655                                 window.location.href=data.reload;
656                         }
657                 },
658                 "json"
659         );
660         return false;
661 }
662
663 function preview_comment(id) {
664         $("#comment-preview-inp-" + id).val("1");
665         $("#comment-edit-preview-" + id).show();
666         $.post(
667                 "item",
668                 $("#comment-edit-form-" + id).serialize(),
669                 function(data) {
670                         if (data.preview) {
671                                 $("#comment-edit-preview-" + id).html(data.preview);
672                                 $("#comment-edit-preview-" + id + " a").click(function() {return false;});
673                         }
674                 },
675                 "json"
676         );
677         return true;
678 }
679
680 function showHideComments(id) {
681         if ($('#collapsed-comments-' + id).is(':visible')) {
682                 $('#collapsed-comments-' + id).slideUp();
683                 $('#hide-comments-' + id).hide();
684                 $('#hide-comments-total-' + id).show();
685         } else {
686                 $('#collapsed-comments-' + id).slideDown();
687                 $('#hide-comments-' + id).show();
688                 $('#hide-comments-total-' + id).hide();
689         }
690 }
691
692 function preview_post() {
693         $("#jot-preview").val("1");
694         $("#jot-preview-content").show();
695         $.post(
696                 "item",
697                 $("#profile-jot-form").serialize(),
698                 function(data) {
699                         if (data.preview) {
700                                 $("#jot-preview-content").html(data.preview);
701                                 $("#jot-preview-content" + " a").click(function() {return false;});
702                                 document.dispatchEvent(new Event('postprocess_liveupdate'));
703                         }
704                 },
705                 "json"
706         );
707         $("#jot-preview").val("0");
708         return true;
709 }
710
711 function unpause() {
712         // unpause auto reloads if they are currently stopped
713         totStopped = false;
714         stopped = false;
715         $('#pause').html('');
716 }
717
718 // load more network content (used for infinite scroll)
719 function loadScrollContent() {
720         if (lockLoadContent) {
721                 return;
722         }
723         lockLoadContent = true;
724
725         $("#scroll-loader").fadeIn('normal');
726
727         // the page number to load is one higher than the actual
728         // page number
729         infinite_scroll.pageno+=1;
730
731         match = $("span.received").last();
732         if (match.length > 0) {
733                 received = match[0].innerHTML;
734         } else {
735                 received = "0000-00-00 00:00:00";
736         }
737
738         match = $("span.created").last();
739         if (match.length > 0) {
740                 created = match[0].innerHTML;
741         } else {
742                 created = "0000-00-00 00:00:00";
743         }
744
745         match = $("span.commented").last();
746         if (match.length > 0) {
747                 commented = match[0].innerHTML;
748         } else {
749                 commented = "0000-00-00 00:00:00";
750         }
751
752         match = $("span.id").last();
753         if (match.length > 0) {
754                 id = match[0].innerHTML;
755         } else {
756                 id = "0";
757         }
758
759         // get the raw content from the next page and insert this content
760         // right before "#conversation-end"
761         $.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) {
762                 $("#scroll-loader").hide();
763                 if ($(data).length > 0) {
764                         $(data).insertBefore('#conversation-end');
765                         lockLoadContent = false;
766                 } else {
767                         $("#scroll-end").fadeIn('normal');
768                 }
769
770                 document.dispatchEvent(new Event('postprocess_liveupdate'));
771         });
772 }
773
774 function bin2hex(s) {
775         // Converts the binary representation of data to hex
776         //
777         // version: 812.316
778         // discuss at: http://phpjs.org/functions/bin2hex
779         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
780         // +   bugfixed by: Onno Marsman
781         // +   bugfixed by: Linuxworld
782         // *     example 1: bin2hex('Kev');
783         // *     returns 1: '4b6576'
784         // *     example 2: bin2hex(String.fromCharCode(0x00));
785         // *     returns 2: '00'
786         var v,i, f = 0, a = [];
787         s += '';
788         f = s.length;
789
790         for (i = 0; i<f; i++) {
791                 a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
792         }
793
794         return a.join('');
795 }
796
797 function groupChangeMember(gid, cid, sec_token) {
798         $('body .fakelink').css('cursor', 'wait');
799         $.get('group/' + gid + '/' + cid + "?t=" + sec_token, function(data) {
800                         $('#group-update-wrapper').html(data);
801                         $('body .fakelink').css('cursor', 'auto');
802         });
803 }
804
805 function profChangeMember(gid,cid) {
806         $('body .fakelink').css('cursor', 'wait');
807         $.get('profperm/' + gid + '/' + cid, function(data) {
808                         $('#prof-update-wrapper').html(data);
809                         $('body .fakelink').css('cursor', 'auto');
810         });
811 }
812
813 function contactgroupChangeMember(checkbox, gid, cid) {
814         let url;
815         // checkbox.checked is the checkbox state after the click
816         if (checkbox.checked) {
817                 url = 'group/' + gid + '/add/' + cid;
818         } else {
819                 url = 'group/' + gid + '/remove/' + cid;
820         }
821         $('body').css('cursor', 'wait');
822         $.post(url)
823         .error(function () {
824                 // Restores previous state in case of error
825                 checkbox.checked = !checkbox.checked;
826         })
827         .always(function() {
828                 $('body').css('cursor', 'auto');
829         });
830
831         return true;
832 }
833
834 function checkboxhighlight(box) {
835         if ($(box).is(':checked')) {
836                 $(box).addClass('checkeditem');
837         } else {
838                 $(box).removeClass('checkeditem');
839         }
840 }
841
842 function notifyMarkAll() {
843         $.get('notify/mark/all', function(data) {
844                 if (timer) {
845                         clearTimeout(timer);
846                 }
847                 timer = setTimeout(NavUpdate,1000);
848                 force_update = true;
849         });
850 }
851
852 /**
853  * sprintf in javascript
854  *      "{0} and {1}".format('zero','uno');
855  **/
856 String.prototype.format = function() {
857         var formatted = this;
858         for (var i = 0; i < arguments.length; i++) {
859                 var regexp = new RegExp('\\{'+i+'\\}', 'gi');
860                 formatted = formatted.replace(regexp, arguments[i]);
861         }
862         return formatted;
863 };
864 // Array Remove
865 Array.prototype.remove = function(item) {
866         to=undefined; from=this.indexOf(item);
867         var rest = this.slice((to || from) + 1 || this.length);
868         this.length = from < 0 ? this.length + from : from;
869         return this.push.apply(this, rest);
870 };
871
872 function previewTheme(elm) {
873         theme = $(elm).val();
874         $.getJSON('pretheme?f=&theme=' + theme,function(data) {
875                         $('#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>');
876         });
877
878 }
879
880 // notification permission settings in localstorage
881 // set by settings page
882 function getNotificationPermission() {
883         if (window["Notification"] === undefined) {
884                 return null;
885         }
886
887         if (Notification.permission === 'granted') {
888                 var val = localStorage.getItem('notification-permissions');
889                 if (val === null) {
890                         return 'denied';
891                 }
892                 return val;
893         } else {
894                 return Notification.permission;
895         }
896 }
897
898 /**
899  * Show a dialog loaded from an url
900  * By defaults this load the url in an iframe in colorbox
901  * Themes can overwrite `show()` function to personalize it
902  */
903 var Dialog = {
904         /**
905          * Show the dialog
906          *
907          * @param string url
908          * @return object colorbox
909          */
910         show : function (url) {
911                 var size = Dialog._get_size();
912                 return $.colorbox({href: url, iframe:true,innerWidth: size.width+'px',innerHeight: size.height+'px'})
913         },
914
915         /**
916          * Show the Image browser dialog
917          *
918          * @param string name
919          * @param string id (optional)
920          * @return object
921          *
922          * The name will be used to build the event name
923          * fired by image browser dialog when the user select
924          * an image. The optional id will be passed as argument
925          * to the event handler
926          */
927         doImageBrowser : function (name, id) {
928                 var url = Dialog._get_url("image",name,id);
929                 return Dialog.show(url);
930         },
931
932         /**
933          * Show the File browser dialog
934          *
935          * @param string name
936          * @param string id (optional)
937          * @return object
938          *
939          * The name will be used to build the event name
940          * fired by file browser dialog when the user select
941          * a file. The optional id will be passed as argument
942          * to the event handler
943          */
944         doFileBrowser : function (name, id) {
945                 var url = Dialog._get_url("file",name,id);
946                 return Dialog.show(url);
947         },
948
949         _get_url : function(type, name, id) {
950                 var hash = name;
951                 if (id !== undefined) {
952                         hash = hash + "-" + id;
953                 }
954                 return baseurl + "/fbrowser/"+type+"/?mode=minimal#"+hash;
955         },
956
957         _get_size: function() {
958                 return {
959                         width: window.innerWidth-50,
960                         height: window.innerHeight-100
961                 };
962         }
963 }
964 // @license-end