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