]> git.mxchange.org Git - friendica.git/blob - view/js/main.js
Allow macOS users to use Ctrl + Cmd + Space to bring up the emoji picker in Friendica...
[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.photo.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-circle-li .notify").removeClass("show");
293                 $(data.circles).each(function(key, circle) {
294                         var gid = circle.id;
295                         var gcount = circle.count;
296                         $(".circle-"+gid+" .notify").addClass("show").text(gcount);
297                 });
298
299                 $(".group-widget-entry .notify").removeClass("show");
300                 $(data.groups).each(function(key, group) {
301                         var fid = group.id;
302                         var fcount = group.count;
303                         $(".group-"+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                 // Pause/Break or Ctrl + Space
382                 if (event.which === 19 || (!event.shiftKey && !event.altKey && event.ctrlKey && event.which === 32)) {
383                         event.preventDefault();
384                         if (stopped === false) {
385                                 stopped = true;
386                                 if (event.ctrlKey) {
387                                         totStopped = true;
388                                 }
389                                 $('#pause').html('<img src="images/pause.gif" alt="pause" style="border: 1px solid black;" />');
390                         } else {
391                                 unpause();
392                         }
393                 } else if (!totStopped) {
394                         unpause();
395                 }
396         });
397
398         // Scroll to the next/previous thread when pressing J and K
399         $(document).keydown(function (event) {
400                 var threads = $('.thread_level_1');
401                 if ((event.keyCode === 74 || event.keyCode === 75) && !$(event.target).is('textarea, input')) {
402                         var scrollTop = $(window).scrollTop();
403                         if (event.keyCode === 75) {
404                                 threads = $(threads.get().reverse());
405                         }
406                         threads.each(function(key, item) {
407                                 var comparison;
408                                 var top = $(item).offset().top - 100;
409                                 if (event.keyCode === 74) {
410                                         comparison = top > scrollTop + 1;
411                                 } else if (event.keyCode === 75) {
412                                         comparison = top < scrollTop - 1;
413                                 }
414                                 if (comparison) {
415                                         $('html, body').animate({scrollTop: top}, 200);
416                                         return false;
417                                 }
418                         });
419                 }
420         });
421
422         // Set an event listener for infinite scroll
423         if (typeof infinite_scroll !== 'undefined') {
424                 $(window).scroll(function(e) {
425                         if ($(document).height() != $(window).height()) {
426                                 // First method that is expected to work - but has problems with Chrome
427                                 if ($(window).scrollTop() > ($(document).height() - $(window).height() * 1.5))
428                                         loadScrollContent();
429                         } else {
430                                 // This method works with Chrome - but seems to be much slower in Firefox
431                                 if ($(window).scrollTop() > (($("section").height() + $("header").height() + $("footer").height()) - $(window).height() * 1.5)) {
432                                         loadScrollContent();
433                                 }
434                         }
435                 });
436         }
437 });
438
439 /**
440  * Inserts a BBCode tag in the comment textarea identified by id
441  *
442  * @param {string} BBCode
443  * @param {int} id
444  * @returns {boolean}
445  */
446 function insertFormatting(BBCode, id) {
447         let textarea = document.getElementById('comment-edit-text-' + id);
448
449         if (textarea.value === '') {
450                 $(textarea)
451                         .addClass("comment-edit-text-full")
452                         .removeClass("comment-edit-text-empty");
453                 closeMenu("comment-fake-form-" + id);
454                 openMenu("item-comments-" + id);
455         }
456
457         insertBBCodeInTextarea(BBCode, textarea);
458
459         return true;
460 }
461
462 /**
463  * Inserts a BBCode tag in the provided textarea element, wrapping the currently selected text.
464  * For URL BBCode, it discriminates between link text and non-link text to determine where to insert the selected text.
465  *
466  * @param {string} BBCode
467  * @param {HTMLTextAreaElement} textarea
468  */
469 function insertBBCodeInTextarea(BBCode, textarea) {
470         let selectionStart = textarea.selectionStart;
471         let selectionEnd = textarea.selectionEnd;
472         let selectedText = textarea.value.substring(selectionStart, selectionEnd);
473         let openingTag = '[' + BBCode + ']';
474         let closingTag = '[/' + BBCode + ']';
475         let cursorPosition = selectionStart + openingTag.length + selectedText.length;
476
477         if (BBCode === 'url') {
478                 if (urlRegex.test(selectedText)) {
479                         openingTag = '[' + BBCode + '=' + selectedText + ']';
480                         selectedText = '';
481                         cursorPosition = selectionStart + openingTag.length;
482                 } else {
483                         openingTag = '[' + BBCode + '=]';
484                         cursorPosition = selectionStart + openingTag.length - 1;
485                 }
486         }
487
488         textarea.value = textarea.value.substring(0, selectionStart) + openingTag + selectedText + closingTag + textarea.value.substring(selectionEnd, textarea.value.length);
489         textarea.setSelectionRange(cursorPosition, cursorPosition);
490         textarea.dispatchEvent(new Event('change'));
491         textarea.focus();
492 }
493
494 function NavUpdate() {
495         if (!stopped) {
496                 var pingCmd = 'ping';
497                 $.get(pingCmd, function(data) {
498                         if (data.result) {
499                                 // send nav-update event
500                                 $('nav').trigger('nav-update', data.result);
501
502                                 // start live update
503                                 ['network', 'profile', 'channel', 'community', 'notes', 'display', 'contact'].forEach(function (src) {
504                                         if ($('#live-' + src).length) {
505                                                 liveUpdate(src);
506                                         }
507                                 });
508                                 if ($('#live-photos').length) {
509                                         if (liking) {
510                                                 liking = 0;
511                                                 window.location.href = window.location.href;
512                                         }
513                                 }
514                         }
515                 });
516         }
517         timer = setTimeout(NavUpdate, updateInterval);
518 }
519
520 function updateConvItems(data) {
521         // add a new thread
522         $('.toplevel_item',data).each(function() {
523                 var ident = $(this).attr('id');
524
525                 // Add new top-level item.
526                 if ($('#' + ident).length === 0
527                         && (!getUrlParameter('page')
528                                 && !getUrlParameter('max_id')
529                                 && !getUrlParameter('min_id')
530                                 || getUrlParameter('page') === '1'
531                         )
532                 ) {
533                         $('#' + prev).after($(this));
534
535                 // Replace already existing thread.
536                 } else {
537                         // Find out if the hidden comments are open, so we can keep it that way
538                         // if a new comment has been posted
539                         var id = $('.hide-comments-total', this).attr('id');
540                         if (typeof id != 'undefined') {
541                                 id = id.split('-')[3];
542                                 var commentsOpen = $("#collapsed-comments-" + id).is(":visible");
543                         }
544
545                         $('#' + ident).replaceWith($(this));
546
547                         if (typeof id != 'undefined') {
548                                 if (commentsOpen) {
549                                         showHideComments(id);
550                                 }
551                         }
552                 }
553                 prev = ident;
554         });
555
556         $('.like-rotator').hide();
557         if (commentBusy) {
558                 commentBusy = false;
559                 $('body').css('cursor', 'auto');
560         }
561 }
562
563 function liveUpdate(src) {
564         if ((src == null) || stopped || !profile_uid) {
565                 $('.like-rotator').hide(); return;
566         }
567
568         if (($('.comment-edit-text-full').length) || in_progress) {
569                 if (livetime) {
570                         clearTimeout(livetime);
571                 }
572                 livetime = setTimeout(function() {liveUpdate(src)}, 5000);
573                 return;
574         }
575
576         if (livetime != null) {
577                 livetime = null;
578         }
579         prev = 'live-' + src;
580
581         in_progress = true;
582
583         let force = force_update || $(document).scrollTop() === 0;
584
585         var orgHeight = $("section").height();
586
587         var udargs = ((netargs.length) ? '/' + netargs : '');
588
589         var update_url = 'update_' + src + udargs + '&p=' + profile_uid + '&force=' + (force ? 1 : 0) + '&item=' + update_item;
590
591         if (force_update) {
592                 force_update = false;
593         }
594
595         if (getUrlParameter('page')) {
596                 update_url += '&page=' + getUrlParameter('page');
597         }
598         if (getUrlParameter('min_id')) {
599                 update_url += '&min_id=' + getUrlParameter('min_id');
600         }
601         if (getUrlParameter('max_id')) {
602                 update_url += '&max_id=' + getUrlParameter('max_id');
603         }
604
605         match = $("span.received").first();
606         if (match.length > 0) {
607                 update_url += '&first_received=' + match[0].innerHTML;
608         }
609
610         match = $("span.created").first();
611         if (match.length > 0) {
612                 update_url += '&first_created=' + match[0].innerHTML;
613         }
614
615         match = $("span.commented").first();
616         if (match.length > 0) {
617                 update_url += '&first_commented=' + match[0].innerHTML;
618         }
619
620         match = $("span.uriid").first();
621         if (match.length > 0) {
622                 update_url += '&first_uriid=' + match[0].innerHTML;
623         }
624
625         $.get(update_url, function(data) {
626                 in_progress = false;
627                 update_item = 0;
628
629                 if ($('.wall-item-body', data).length == 0) {
630                         return;
631                 }
632
633                 $('.wall-item-body', data).imagesLoaded(function() {
634                         updateConvItems(data);
635
636                         document.dispatchEvent(new Event('postprocess_liveupdate'));
637
638                         // Update the scroll position.
639                         $(window).scrollTop($(window).scrollTop() + $("section").height() - orgHeight);
640                 });
641         });
642 }
643
644 function imgbright(node) {
645         $(node).removeClass("drophide").addClass("drop");
646 }
647
648 function imgdull(node) {
649         $(node).removeClass("drop").addClass("drophide");
650 }
651
652 // Since our ajax calls are asynchronous, we will give a few
653 // seconds for the first ajax call (setting like/dislike), then
654 // run the updater to pick up any changes and display on the page.
655 // The updater will turn any rotators off when it's done.
656 // This function will have returned long before any of these
657 // events have completed and therefore there won't be any
658 // visible feedback that anything changed without all this
659 // trickery. This still could cause confusion if the "like" ajax call
660 // is delayed and NavUpdate runs before it completes.
661
662 /**
663  * @param {int}     ident The id of the relevant item
664  * @param {string}  verb  The verb of the action
665  * @param {boolean} un    Whether to perform an activity removal instead of creation
666  */
667 function doActivityItem(ident, verb, un) {
668         unpause();
669         $('#like-rotator-' + ident.toString()).show();
670         verb = un ? 'un' + verb : verb;
671         $.post('item/' + ident.toString() + '/activity/' + verb, NavUpdate);
672         liking = 1;
673         force_update = true;
674         update_item = ident.toString();
675 }
676
677 function doFollowThread(ident) {
678         unpause();
679         $('#like-rotator-' + ident.toString()).show();
680         $.post('item/' + ident.toString() + '/follow', NavUpdate);
681         liking = 1;
682         force_update = true;
683         update_item = ident.toString();
684 }
685
686 function doStar(ident) {
687         ident = ident.toString();
688         $('#like-rotator-' + ident).show();
689         $.post('item/' + ident + '/star')
690         .then(function(data) {
691                 if (data.state === 1) {
692                         $('#starred-' + ident)
693                                 .addClass('starred')
694                                 .removeClass('unstarred');
695                         $('#star-' + ident).addClass('hidden');
696                         $('#unstar-' + ident).removeClass('hidden');
697                 } else {
698                         $('#starred-' + ident)
699                                 .addClass('unstarred')
700                                 .removeClass('starred');
701                         $('#star-' + ident).removeClass('hidden');
702                         $('#unstar-' + ident).addClass('hidden');
703                 }
704         })
705         .always(function () {
706                 $('#like-rotator-' + ident).hide();
707         });
708 }
709
710 function doPin(ident) {
711         ident = ident.toString();
712         $('#like-rotator-' + ident).show();
713         $.post('item/' + ident + '/pin')
714         .then(function(data) {
715                 if (data.state === 1) {
716                         $('#pinned-' + ident)
717                                 .addClass('pinned')
718                                 .removeClass('unpinned');
719                         $('#pin-' + ident).addClass('hidden');
720                         $('#unpin-' + ident).removeClass('hidden');
721                 } else {
722                         $('#pinned-' + ident)
723                                 .addClass('unpinned')
724                                 .removeClass('pinned');
725                         $('#pin-' + ident).removeClass('hidden');
726                         $('#unpin-' + ident).addClass('hidden');
727                 }
728         })
729         .always(function () {
730                 $('#like-rotator-' + ident).hide();
731         });
732 }
733
734 function doIgnoreThread(ident) {
735         ident = ident.toString();
736         $('#like-rotator-' + ident).show();
737         $.post('item/' + ident + '/ignore', function(data) {
738                 if (data.state === 1) {
739                         $('#ignored-' + ident)
740                                 .addClass('ignored')
741                                 .removeClass('unignored');
742                         $('#ignore-' + ident).addClass('hidden');
743                         $('#unignore-' + ident).removeClass('hidden');
744                 } else {
745                         $('#ignored-' + ident)
746                                 .addClass('unignored')
747                                 .removeClass('ignored');
748                         $('#ignore-' + ident).removeClass('hidden');
749                         $('#unignore-' + ident).addClass('hidden');
750                 }
751                 $('#like-rotator-' + ident).hide();
752         });
753 }
754
755 function getPosition(e) {
756         var cursor = {x:0, y:0};
757
758         if (e.pageX || e.pageY) {
759                 cursor.x = e.pageX;
760                 cursor.y = e.pageY;
761         } else {
762                 if (e.clientX || e.clientY) {
763                         cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
764                         cursor.y = e.clientY + (document.documentElement.scrollTop  || document.body.scrollTop)  - document.documentElement.clientTop;
765                 } else if (e.x || e.y) {
766                         cursor.x = e.x;
767                         cursor.y = e.y;
768                 }
769         }
770         return cursor;
771 }
772
773 var lockvisible = false;
774
775 function lockview(event, type, id) {
776         event = event || window.event;
777         cursor = getPosition(event);
778         if (lockvisible) {
779                 lockvisible = false;
780                 $('#panel').hide();
781         } else {
782                 lockvisible = true;
783                 $.get('permission/tooltip/' + type + '/' + id, function(data) {
784                         $('#panel')
785                                 .html(data)
786                                 .css({'left': cursor.x + 5 , 'top': cursor.y + 5})
787                                 .show();
788                 });
789         }
790 }
791
792 function post_comment(id) {
793         unpause();
794         commentBusy = true;
795         $('body').css('cursor', 'wait');
796         $.post(
797                 "item",
798                 $("#comment-edit-form-" + id).serialize(),
799                 function(data) {
800                         if (data.success) {
801                                 $("#comment-edit-wrapper-" + id).hide();
802                                 $("#comment-edit-text-" + id).val('');
803                                 var tarea = document.getElementById("comment-edit-text-" + id);
804                                 if (tarea) {
805                                         commentClose(tarea,id);
806                                 }
807                                 if (timer) {
808                                         clearTimeout(timer);
809                                 }
810                                 timer = setTimeout(NavUpdate,10);
811                                 force_update = true;
812                                 update_item = id;
813                         }
814                         if (data.reload) {
815                                 window.location.href=data.reload;
816                         }
817                 },
818                 "json"
819         );
820         return false;
821 }
822
823 function preview_comment(id) {
824         $("#comment-edit-preview-" + id).show();
825         $.post(
826                 "item",
827                 $("#comment-edit-form-" + id).serialize() + '&preview=1',
828                 function(data) {
829                         if (data.preview) {
830                                 $("#comment-edit-preview-" + id).html(data.preview);
831                                 $("#comment-edit-preview-" + id + " a").click(function() {return false;});
832                         }
833                 },
834                 "json"
835         );
836         return true;
837 }
838
839 function showHideComments(id) {
840         if ($('#collapsed-comments-' + id).is(':visible')) {
841                 $('#collapsed-comments-' + id).slideUp();
842                 $('#hide-comments-' + id).hide();
843                 $('#hide-comments-total-' + id).show();
844         } else {
845                 $('#collapsed-comments-' + id).slideDown();
846                 $('#hide-comments-' + id).show();
847                 $('#hide-comments-total-' + id).hide();
848         }
849 }
850
851 function preview_post() {
852         $("#jot-preview-content").show();
853         $.post(
854                 "item",
855                 $("#profile-jot-form").serialize() + '&preview=1',
856                 function(data) {
857                         if (data.preview) {
858                                 $("#jot-preview-content").html(data.preview);
859                                 $("#jot-preview-content" + " a").click(function() {return false;});
860                                 document.dispatchEvent(new Event('postprocess_liveupdate'));
861                         }
862                 },
863                 "json"
864         );
865         return true;
866 }
867
868 function unpause() {
869         // unpause auto reloads if they are currently stopped
870         totStopped = false;
871         stopped = false;
872         $('#pause').html('');
873 }
874
875 // load more network content (used for infinite scroll)
876 function loadScrollContent() {
877         if (lockLoadContent) {
878                 return;
879         }
880         lockLoadContent = true;
881
882         $("#scroll-loader").fadeIn('normal');
883
884         match = $("span.received").last();
885         if (match.length > 0) {
886                 received = match[0].innerHTML;
887         } else {
888                 received = "0000-00-00 00:00:00";
889         }
890
891         match = $("span.created").last();
892         if (match.length > 0) {
893                 created = match[0].innerHTML;
894         } else {
895                 created = "0000-00-00 00:00:00";
896         }
897
898         match = $("span.commented").last();
899         if (match.length > 0) {
900                 commented = match[0].innerHTML;
901         } else {
902                 commented = "0000-00-00 00:00:00";
903         }
904
905         match = $("span.uriid").last();
906         if (match.length > 0) {
907                 uriid = match[0].innerHTML;
908         } else {
909                 uriid = "0";
910         }
911
912         // get the raw content from the next page and insert this content
913         // right before "#conversation-end"
914         $.get({
915                 url: infinite_scroll.reload_uri,
916                 data: {
917                         'mode'          : 'raw',
918                         'last_received' : received,
919                         'last_commented': commented,
920                         'last_created'  : created,
921                         'last_uriid'    : uriid
922                 }
923         })
924         .done(function(data) {
925                 $("#scroll-loader").hide();
926                 if ($(data).length > 0) {
927                         $(data).insertBefore('#conversation-end');
928                 } else {
929                         $("#scroll-end").fadeIn('normal');
930                 }
931
932                 document.dispatchEvent(new Event('postprocess_liveupdate'));
933         })
934         .always(function () {
935                 $("#scroll-loader").hide();
936                 lockLoadContent = false;
937         });
938 }
939
940 function bin2hex(s) {
941         // Converts the binary representation of data to hex
942         //
943         // version: 812.316
944         // discuss at: http://phpjs.org/functions/bin2hex
945         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
946         // +   bugfixed by: Onno Marsman
947         // +   bugfixed by: Linuxworld
948         // *     example 1: bin2hex('Kev');
949         // *     returns 1: '4b6576'
950         // *     example 2: bin2hex(String.fromCharCode(0x00));
951         // *     returns 2: '00'
952         var v,i, f = 0, a = [];
953         s += '';
954         f = s.length;
955
956         for (i = 0; i<f; i++) {
957                 a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
958         }
959
960         return a.join('');
961 }
962
963 function circleChangeMember(gid, cid, sec_token) {
964         $('body .fakelink').css('cursor', 'wait');
965         $.get('circle/' + gid + '/' + cid + "?t=" + sec_token, function(data) {
966                         $('#circle-update-wrapper').html(data);
967                         $('body .fakelink').css('cursor', 'auto');
968         });
969 }
970
971 function contactCircleChangeMember(checkbox, gid, cid) {
972         let url;
973         // checkbox.checked is the checkbox state after the click
974         if (checkbox.checked) {
975                 url = 'circle/' + gid + '/add/' + cid;
976         } else {
977                 url = 'circle/' + gid + '/remove/' + cid;
978         }
979         $('body').css('cursor', 'wait');
980         $.post(url)
981         .error(function () {
982                 // Restores previous state in case of error
983                 checkbox.checked = !checkbox.checked;
984         })
985         .always(function() {
986                 $('body').css('cursor', 'auto');
987         });
988
989         return true;
990 }
991
992 function checkboxhighlight(box) {
993         if ($(box).is(':checked')) {
994                 $(box).addClass('checkeditem');
995         } else {
996                 $(box).removeClass('checkeditem');
997         }
998 }
999
1000 function notificationMarkAll() {
1001         $.get('notification/mark/all', function(data) {
1002                 if (timer) {
1003                         clearTimeout(timer);
1004                 }
1005                 timer = setTimeout(NavUpdate,1000);
1006                 force_update = true;
1007         });
1008 }
1009
1010 /**
1011  * sprintf in javascript
1012  *      "{0} and {1}".format('zero','uno');
1013  **/
1014 String.prototype.format = function() {
1015         var formatted = this;
1016         for (var i = 0; i < arguments.length; i++) {
1017                 var regexp = new RegExp('\\{'+i+'\\}', 'gi');
1018                 formatted = formatted.replace(regexp, arguments[i]);
1019         }
1020         return formatted;
1021 };
1022 // Array Remove
1023 Array.prototype.remove = function(item) {
1024         to=undefined; from=this.indexOf(item);
1025         var rest = this.slice((to || from) + 1 || this.length);
1026         this.length = from < 0 ? this.length + from : from;
1027         return this.push.apply(this, rest);
1028 };
1029
1030 function previewTheme(elm) {
1031         theme = $(elm).val();
1032         $.getJSON('pretheme?theme=' + theme,function(data) {
1033                         $('#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>');
1034         });
1035
1036 }
1037
1038 // notification permission settings in localstorage
1039 // set by settings page
1040 function getNotificationPermission() {
1041         if (window["Notification"] === undefined) {
1042                 return null;
1043         }
1044
1045         if (Notification.permission === 'granted') {
1046                 var val = localStorage.getItem('notification-permissions');
1047                 if (val === null) {
1048                         return 'denied';
1049                 }
1050                 return val;
1051         } else {
1052                 return Notification.permission;
1053         }
1054 }
1055
1056 /**
1057  * Show a dialog loaded from an url
1058  * By defaults this load the url in an iframe in colorbox
1059  * Themes can overwrite `show()` function to personalize it
1060  */
1061 var Dialog = {
1062         /**
1063          * Show the dialog
1064          *
1065          * @param string url
1066          * @return object colorbox
1067          */
1068         show : function (url) {
1069                 var size = Dialog._get_size();
1070                 return $.colorbox({href: url, iframe:true,innerWidth: size.width+'px',innerHeight: size.height+'px'})
1071         },
1072
1073         /**
1074          * Show the Image browser dialog
1075          *
1076          * @param string name
1077          * @param string id (optional)
1078          * @return object
1079          *
1080          * The name will be used to build the event name
1081          * fired by image browser dialog when the user select
1082          * an image. The optional id will be passed as argument
1083          * to the event handler
1084          */
1085         doImageBrowser : function (name, id) {
1086                 var url = Dialog._get_url('photo', name, id);
1087                 return Dialog.show(url);
1088         },
1089
1090         /**
1091          * Show the File browser dialog
1092          *
1093          * @param string name
1094          * @param string id (optional)
1095          * @return object
1096          *
1097          * The name will be used to build the event name
1098          * fired by file browser dialog when the user select
1099          * a file. The optional id will be passed as argument
1100          * to the event handler
1101          */
1102         doFileBrowser : function (name, id) {
1103                 var url = Dialog._get_url('attachment', name, id);
1104                 return Dialog.show(url);
1105         },
1106
1107         _get_url : function(type, name, id) {
1108                 var hash = name;
1109                 if (id !== undefined) {
1110                         hash = hash + "-" + id;
1111                 }
1112                 return 'media/' + type + '/browser?mode=minimal#' + hash;
1113         },
1114
1115         _get_size: function() {
1116                 return {
1117                         width: window.innerWidth-50,
1118                         height: window.innerHeight-100
1119                 };
1120         }
1121 }
1122 // @license-end