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