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