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