]> git.mxchange.org Git - friendica.git/blob - view/js/main.js
Ensure the preview parameter is set to 1 when doing a preview
[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.match(/1/)) {
653                         $('#ignored-' + ident).addClass('ignored');
654                         $('#ignored-' + ident).removeClass('unignored');
655                         $('#ignore-' + ident).addClass('hidden');
656                         $('#unignore-' + ident).removeClass('hidden');
657                 } else {
658                         $('#ignored-' + ident).addClass('unignored');
659                         $('#ignored-' + ident).removeClass('ignored');
660                         $('#ignore-' + ident).removeClass('hidden');
661                         $('#unignore-' + ident).addClass('hidden');
662                 }
663                 $('#like-rotator-' + ident).hide();
664         });
665 }
666
667 function getPosition(e) {
668         var cursor = {x:0, y:0};
669
670         if (e.pageX || e.pageY) {
671                 cursor.x = e.pageX;
672                 cursor.y = e.pageY;
673         } else {
674                 if (e.clientX || e.clientY) {
675                         cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
676                         cursor.y = e.clientY + (document.documentElement.scrollTop  || document.body.scrollTop)  - document.documentElement.clientTop;
677                 } else if (e.x || e.y) {
678                         cursor.x = e.x;
679                         cursor.y = e.y;
680                 }
681         }
682         return cursor;
683 }
684
685 var lockvisible = false;
686
687 function lockview(event,id) {
688         event = event || window.event;
689         cursor = getPosition(event);
690         if (lockvisible) {
691                 lockviewhide();
692         } else {
693                 lockvisible = true;
694                 $.get('lockview/' + id, function(data) {
695                         $('#panel').html(data);
696                         $('#panel').css({'left': cursor.x + 5 , 'top': cursor.y + 5});
697                         $('#panel').show();
698                 });
699         }
700 }
701
702 function lockviewhide() {
703         lockvisible = false;
704         $('#panel').hide();
705 }
706
707 function post_comment(id) {
708         unpause();
709         commentBusy = true;
710         $('body').css('cursor', 'wait');
711         $.post(
712                 "item",
713                 $("#comment-edit-form-" + id).serialize(),
714                 function(data) {
715                         if (data.success) {
716                                 $("#comment-edit-wrapper-" + id).hide();
717                                 $("#comment-edit-text-" + id).val('');
718                                 var tarea = document.getElementById("comment-edit-text-" + id);
719                                 if (tarea) {
720                                         commentClose(tarea,id);
721                                 }
722                                 if (timer) {
723                                         clearTimeout(timer);
724                                 }
725                                 timer = setTimeout(NavUpdate,10);
726                                 force_update = true;
727                                 update_item = id;
728                         }
729                         if (data.reload) {
730                                 window.location.href=data.reload;
731                         }
732                 },
733                 "json"
734         );
735         return false;
736 }
737
738 function preview_comment(id) {
739         $("#comment-edit-preview-" + id).show();
740         $.post(
741                 "item",
742                 $("#comment-edit-form-" + id).serialize() + '&preview=1',
743                 function(data) {
744                         if (data.preview) {
745                                 $("#comment-edit-preview-" + id).html(data.preview);
746                                 $("#comment-edit-preview-" + id + " a").click(function() {return false;});
747                         }
748                 },
749                 "json"
750         );
751         return true;
752 }
753
754 function showHideComments(id) {
755         if ($('#collapsed-comments-' + id).is(':visible')) {
756                 $('#collapsed-comments-' + id).slideUp();
757                 $('#hide-comments-' + id).hide();
758                 $('#hide-comments-total-' + id).show();
759         } else {
760                 $('#collapsed-comments-' + id).slideDown();
761                 $('#hide-comments-' + id).show();
762                 $('#hide-comments-total-' + id).hide();
763         }
764 }
765
766 function preview_post() {
767         $("#jot-preview-content").show();
768         $.post(
769                 "item",
770                 $("#profile-jot-form").serialize() + '&preview=1',
771                 function(data) {
772                         if (data.preview) {
773                                 $("#jot-preview-content").html(data.preview);
774                                 $("#jot-preview-content" + " a").click(function() {return false;});
775                                 document.dispatchEvent(new Event('postprocess_liveupdate'));
776                         }
777                 },
778                 "json"
779         );
780         return true;
781 }
782
783 function unpause() {
784         // unpause auto reloads if they are currently stopped
785         totStopped = false;
786         stopped = false;
787         $('#pause').html('');
788 }
789
790 // load more network content (used for infinite scroll)
791 function loadScrollContent() {
792         if (lockLoadContent) {
793                 return;
794         }
795         lockLoadContent = true;
796
797         $("#scroll-loader").fadeIn('normal');
798
799         // the page number to load is one higher than the actual
800         // page number
801         infinite_scroll.pageno+=1;
802
803         match = $("span.received").last();
804         if (match.length > 0) {
805                 received = match[0].innerHTML;
806         } else {
807                 received = "0000-00-00 00:00:00";
808         }
809
810         match = $("span.created").last();
811         if (match.length > 0) {
812                 created = match[0].innerHTML;
813         } else {
814                 created = "0000-00-00 00:00:00";
815         }
816
817         match = $("span.commented").last();
818         if (match.length > 0) {
819                 commented = match[0].innerHTML;
820         } else {
821                 commented = "0000-00-00 00:00:00";
822         }
823
824         match = $("span.id").last();
825         if (match.length > 0) {
826                 id = match[0].innerHTML;
827         } else {
828                 id = "0";
829         }
830
831         // get the raw content from the next page and insert this content
832         // right before "#conversation-end"
833         $.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) {
834                 $("#scroll-loader").hide();
835                 if ($(data).length > 0) {
836                         $(data).insertBefore('#conversation-end');
837                         lockLoadContent = false;
838                 } else {
839                         $("#scroll-end").fadeIn('normal');
840                 }
841
842                 document.dispatchEvent(new Event('postprocess_liveupdate'));
843         });
844 }
845
846 function bin2hex(s) {
847         // Converts the binary representation of data to hex
848         //
849         // version: 812.316
850         // discuss at: http://phpjs.org/functions/bin2hex
851         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
852         // +   bugfixed by: Onno Marsman
853         // +   bugfixed by: Linuxworld
854         // *     example 1: bin2hex('Kev');
855         // *     returns 1: '4b6576'
856         // *     example 2: bin2hex(String.fromCharCode(0x00));
857         // *     returns 2: '00'
858         var v,i, f = 0, a = [];
859         s += '';
860         f = s.length;
861
862         for (i = 0; i<f; i++) {
863                 a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
864         }
865
866         return a.join('');
867 }
868
869 function groupChangeMember(gid, cid, sec_token) {
870         $('body .fakelink').css('cursor', 'wait');
871         $.get('group/' + gid + '/' + cid + "?t=" + sec_token, function(data) {
872                         $('#group-update-wrapper').html(data);
873                         $('body .fakelink').css('cursor', 'auto');
874         });
875 }
876
877 function profChangeMember(gid,cid) {
878         $('body .fakelink').css('cursor', 'wait');
879         $.get('profperm/' + gid + '/' + cid, function(data) {
880                         $('#prof-update-wrapper').html(data);
881                         $('body .fakelink').css('cursor', 'auto');
882         });
883 }
884
885 function contactgroupChangeMember(checkbox, gid, cid) {
886         let url;
887         // checkbox.checked is the checkbox state after the click
888         if (checkbox.checked) {
889                 url = 'group/' + gid + '/add/' + cid;
890         } else {
891                 url = 'group/' + gid + '/remove/' + cid;
892         }
893         $('body').css('cursor', 'wait');
894         $.post(url)
895         .error(function () {
896                 // Restores previous state in case of error
897                 checkbox.checked = !checkbox.checked;
898         })
899         .always(function() {
900                 $('body').css('cursor', 'auto');
901         });
902
903         return true;
904 }
905
906 function checkboxhighlight(box) {
907         if ($(box).is(':checked')) {
908                 $(box).addClass('checkeditem');
909         } else {
910                 $(box).removeClass('checkeditem');
911         }
912 }
913
914 function notifyMarkAll() {
915         $.get('notify/mark/all', function(data) {
916                 if (timer) {
917                         clearTimeout(timer);
918                 }
919                 timer = setTimeout(NavUpdate,1000);
920                 force_update = true;
921         });
922 }
923
924 /**
925  * sprintf in javascript
926  *      "{0} and {1}".format('zero','uno');
927  **/
928 String.prototype.format = function() {
929         var formatted = this;
930         for (var i = 0; i < arguments.length; i++) {
931                 var regexp = new RegExp('\\{'+i+'\\}', 'gi');
932                 formatted = formatted.replace(regexp, arguments[i]);
933         }
934         return formatted;
935 };
936 // Array Remove
937 Array.prototype.remove = function(item) {
938         to=undefined; from=this.indexOf(item);
939         var rest = this.slice((to || from) + 1 || this.length);
940         this.length = from < 0 ? this.length + from : from;
941         return this.push.apply(this, rest);
942 };
943
944 function previewTheme(elm) {
945         theme = $(elm).val();
946         $.getJSON('pretheme?f=&theme=' + theme,function(data) {
947                         $('#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>');
948         });
949
950 }
951
952 // notification permission settings in localstorage
953 // set by settings page
954 function getNotificationPermission() {
955         if (window["Notification"] === undefined) {
956                 return null;
957         }
958
959         if (Notification.permission === 'granted') {
960                 var val = localStorage.getItem('notification-permissions');
961                 if (val === null) {
962                         return 'denied';
963                 }
964                 return val;
965         } else {
966                 return Notification.permission;
967         }
968 }
969
970 /**
971  * Show a dialog loaded from an url
972  * By defaults this load the url in an iframe in colorbox
973  * Themes can overwrite `show()` function to personalize it
974  */
975 var Dialog = {
976         /**
977          * Show the dialog
978          *
979          * @param string url
980          * @return object colorbox
981          */
982         show : function (url) {
983                 var size = Dialog._get_size();
984                 return $.colorbox({href: url, iframe:true,innerWidth: size.width+'px',innerHeight: size.height+'px'})
985         },
986
987         /**
988          * Show the Image browser dialog
989          *
990          * @param string name
991          * @param string id (optional)
992          * @return object
993          *
994          * The name will be used to build the event name
995          * fired by image browser dialog when the user select
996          * an image. The optional id will be passed as argument
997          * to the event handler
998          */
999         doImageBrowser : function (name, id) {
1000                 var url = Dialog._get_url("image",name,id);
1001                 return Dialog.show(url);
1002         },
1003
1004         /**
1005          * Show the File browser dialog
1006          *
1007          * @param string name
1008          * @param string id (optional)
1009          * @return object
1010          *
1011          * The name will be used to build the event name
1012          * fired by file browser dialog when the user select
1013          * a file. The optional id will be passed as argument
1014          * to the event handler
1015          */
1016         doFileBrowser : function (name, id) {
1017                 var url = Dialog._get_url("file",name,id);
1018                 return Dialog.show(url);
1019         },
1020
1021         _get_url : function(type, name, id) {
1022                 var hash = name;
1023                 if (id !== undefined) {
1024                         hash = hash + "-" + id;
1025                 }
1026                 return baseurl + "/fbrowser/"+type+"/?mode=minimal#"+hash;
1027         },
1028
1029         _get_size: function() {
1030                 return {
1031                         width: window.innerWidth-50,
1032                         height: window.innerHeight-100
1033                 };
1034         }
1035 }
1036 // @license-end