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