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