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