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