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