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