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