]> git.mxchange.org Git - friendica.git/blob - js/main.js
Merge pull request #3319 from Hypolite/issue/#3316
[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 && Number(e.seen) === 0) {
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                 // Scroll to the next/previous thread when pressing J and K
326                 $(document).keydown(function (event) {
327                         var threads = $('.thread_level_1');
328                         if ((event.keyCode === 74 || event.keyCode === 75) && !$(event.target).is('textarea, input')) {
329                                 var scrollTop = $(window).scrollTop();
330                                 if (event.keyCode === 75) {
331                                         threads = $(threads.get().reverse());
332                                 }
333                                 threads.each(function(key, item) {
334                                         var comparison;
335                                         var top = $(item).offset().top - 100;
336                                         if (event.keyCode === 74) {
337                                                 comparison = top > scrollTop + 1;
338                                         } else if (event.keyCode === 75) {
339                                                 comparison = top < scrollTop - 1;
340                                         }
341                                         if (comparison) {
342                                                 $('html, body').animate({ scrollTop: top }, 200);
343                                                 return false;
344                                         }
345                                 });
346                         }
347                 });
348
349                 // Set an event listener for infinite scroll
350                 if(typeof infinite_scroll !== 'undefined') {
351                         $(window).scroll(function(e){
352                                 if ($(document).height() != $(window).height()) {
353                                         // First method that is expected to work - but has problems with Chrome
354                                         if ($(window).scrollTop() > ($(document).height() - $(window).height() * 1.5))
355                                                 loadScrollContent();
356                                 } else {
357                                         // This method works with Chrome - but seems to be much slower in Firefox
358                                         if ($(window).scrollTop() > (($("section").height() + $("header").height() + $("footer").height()) - $(window).height() * 1.5))
359                                                 loadScrollContent();
360                                 }
361                         });
362                 }
363
364
365         });
366
367         function NavUpdate() {
368
369                 if (!stopped) {
370                         var pingCmd = 'ping?format=json' + ((localUser != 0) ? '&f=&uid=' + localUser : '');
371                         $.get(pingCmd, function(data) {
372                                 if (data.result) {
373                                         // send nav-update event
374                                         $('nav').trigger('nav-update', data.result);
375
376                                         // start live update
377                                         ['network', 'profile', 'community', 'notes', 'display'].forEach(function (src) {
378                                                 if ($('#live-' + src).length) {
379                                                         liveUpdate(src);
380                                                 }
381                                         });
382                                         if ($('#live-photos').length) {
383                                                 if (liking) {
384                                                         liking = 0;
385                                                         window.location.href = window.location.href;
386                                                 }
387                                         }
388                                 }
389                         }) ;
390                 }
391                 timer = setTimeout(NavUpdate, updateInterval);
392         }
393
394         function liveUpdate(src) {
395                 if((src == null) || (stopped) || (! profile_uid)) { $('.like-rotator').hide(); return; }
396                 if(($('.comment-edit-text-full').length) || (in_progress)) {
397                         if(livetime) {
398                                 clearTimeout(livetime);
399                         }
400                         livetime = setTimeout(function() {liveUpdate(src)}, 5000);
401                         return;
402                 }
403                 if(livetime != null)
404                         livetime = null;
405
406                 prev = 'live-' + src;
407
408                 in_progress = true;
409
410                 if ($(document).scrollTop() == 0)
411                         force_update = true;
412
413                 var udargs = ((netargs.length) ? '/' + netargs : '');
414                 var update_url = 'update_' + src + udargs + '&p=' + profile_uid + '&page=' + profile_page + '&force=' + ((force_update) ? 1 : 0);
415
416                 $.get(update_url,function(data) {
417                         in_progress = false;
418                         force_update = false;
419                         //                      $('.collapsed-comments',data).each(function() {
420                         //      var ident = $(this).attr('id');
421                         //      var is_hidden = $('#' + ident).is(':hidden');
422                         //      if($('#' + ident).length) {
423                         //              $('#' + ident).replaceWith($(this));
424                         //              if(is_hidden)
425                         //                      $('#' + ident).hide();
426                         //      }
427                         //});
428
429                         // add a new thread
430                         $('.toplevel_item',data).each(function() {
431                                 var ident = $(this).attr('id');
432
433                                 if($('#' + ident).length == 0 && profile_page == 1) {
434                                         $('img',this).each(function() {
435                                                 $(this).attr('src',$(this).attr('dst'));
436                                         });
437                                         $('#' + prev).after($(this));
438                                 }
439                                 else {
440                                         // Find out if the hidden comments are open, so we can keep it that way
441                                         // if a new comment has been posted
442                                         var id = $('.hide-comments-total', this).attr('id');
443                                         if(typeof id != 'undefined') {
444                                                 id = id.split('-')[3];
445                                                 var commentsOpen = $("#collapsed-comments-" + id).is(":visible");
446                                         }
447
448                                         $('img',this).each(function() {
449                                                 $(this).attr('src',$(this).attr('dst'));
450                                         });
451                                         //vScroll = $(document).scrollTop();
452                                         $('html').height($('html').height());
453                                         $('#' + ident).replaceWith($(this));
454
455                                         if(typeof id != 'undefined') {
456                                                 if(commentsOpen) showHideComments(id);
457                                         }
458                                         $('html').height('auto');
459                                         //$(document).scrollTop(vScroll);
460                                 }
461                                 prev = ident;
462                         });
463
464                         // reset vars for inserting individual items
465
466                         /*                      prev = 'live-' + src;
467
468                         $('.wall-item-outside-wrapper',data).each(function() {
469                                 var ident = $(this).attr('id');
470
471                                 if($('#' + ident).length == 0 && prev != 'live-' + src) {
472                                                 $('img',this).each(function() {
473                                                         $(this).attr('src',$(this).attr('dst'));
474                                                 });
475                                                 $('#' + prev).after($(this));
476                                 }
477                                 else {
478                                         $('#' + ident + ' ' + '.wall-item-ago').replaceWith($(this).find('.wall-item-ago'));
479                                         if($('#' + ident + ' ' + '.comment-edit-text-empty').length)
480                                                 $('#' + ident + ' ' + '.wall-item-comment-wrapper').replaceWith($(this).find('.wall-item-comment-wrapper'));
481                                         $('#' + ident + ' ' + '.hide-comments-total').replaceWith($(this).find('.hide-comments-total'));
482                                         $('#' + ident + ' ' + '.wall-item-like').replaceWith($(this).find('.wall-item-like'));
483                                         $('#' + ident + ' ' + '.wall-item-dislike').replaceWith($(this).find('.wall-item-dislike'));
484                                         $('#' + ident + ' ' + '.my-comment-photo').each(function() {
485                                                 $(this).attr('src',$(this).attr('dst'));
486                                         });
487                                 }
488                                 prev = ident;
489                         });
490                         */
491                         $('.like-rotator').hide();
492                         if(commentBusy) {
493                                 commentBusy = false;
494                                 $('body').css('cursor', 'auto');
495                         }
496                         /* autocomplete @nicknames */
497                         $(".comment-edit-form  textarea").editor_autocomplete(baseurl+"/acl");
498                         /* autocomplete bbcode */
499                         $(".comment-edit-form  textarea").bbco_autocomplete('bbcode');
500
501                         // setup videos, since VideoJS won't take care of any loaded via AJAX
502                         if(typeof videojs != 'undefined') videojs.autoSetup();
503                 });
504         }
505
506         function imgbright(node) {
507                 $(node).removeClass("drophide").addClass("drop");
508         }
509
510         function imgdull(node) {
511                 $(node).removeClass("drop").addClass("drophide");
512         }
513
514         // Since our ajax calls are asynchronous, we will give a few
515         // seconds for the first ajax call (setting like/dislike), then
516         // run the updater to pick up any changes and display on the page.
517         // The updater will turn any rotators off when it's done.
518         // This function will have returned long before any of these
519         // events have completed and therefore there won't be any
520         // visible feedback that anything changed without all this
521         // trickery. This still could cause confusion if the "like" ajax call
522         // is delayed and NavUpdate runs before it completes.
523
524         function dolike(ident,verb) {
525                 unpause();
526                 $('#like-rotator-' + ident.toString()).show();
527                 $.get('like/' + ident.toString() + '?verb=' + verb, NavUpdate );
528                 liking = 1;
529                 force_update = true;
530         }
531
532         function dosubthread(ident) {
533                 unpause();
534                 $('#like-rotator-' + ident.toString()).show();
535                 $.get('subthread/' + ident.toString(), NavUpdate );
536                 liking = 1;
537         }
538
539
540         function dostar(ident) {
541                 ident = ident.toString();
542                 $('#like-rotator-' + ident).show();
543                 $.get('starred/' + ident, function(data) {
544                         if(data.match(/1/)) {
545                                 $('#starred-' + ident).addClass('starred');
546                                 $('#starred-' + ident).removeClass('unstarred');
547                                 $('#star-' + ident).addClass('hidden');
548                                 $('#unstar-' + ident).removeClass('hidden');
549                         }
550                         else {
551                                 $('#starred-' + ident).addClass('unstarred');
552                                 $('#starred-' + ident).removeClass('starred');
553                                 $('#star-' + ident).removeClass('hidden');
554                                 $('#unstar-' + ident).addClass('hidden');
555                         }
556                         $('#like-rotator-' + ident).hide();
557                 });
558         }
559
560         function doignore(ident) {
561                 ident = ident.toString();
562                 $('#like-rotator-' + ident).show();
563                 $.get('ignored/' + ident, function(data) {
564                         if(data.match(/1/)) {
565                                 $('#ignored-' + ident).addClass('ignored');
566                                 $('#ignored-' + ident).removeClass('unignored');
567                                 $('#ignore-' + ident).addClass('hidden');
568                                 $('#unignore-' + ident).removeClass('hidden');
569                         }
570                         else {
571                                 $('#ignored-' + ident).addClass('unignored');
572                                 $('#ignored-' + ident).removeClass('ignored');
573                                 $('#ignore-' + ident).removeClass('hidden');
574                                 $('#unignore-' + ident).addClass('hidden');
575                         }
576                         $('#like-rotator-' + ident).hide();
577                 });
578         }
579
580         function getPosition(e) {
581                 var cursor = {x:0, y:0};
582                 if ( e.pageX || e.pageY  ) {
583                         cursor.x = e.pageX;
584                         cursor.y = e.pageY;
585                 }
586                 else {
587                         if( e.clientX || e.clientY ) {
588                                 cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
589                                 cursor.y = e.clientY + (document.documentElement.scrollTop  || document.body.scrollTop)  - document.documentElement.clientTop;
590                         }
591                         else {
592                                 if( e.x || e.y ) {
593                                         cursor.x = e.x;
594                                         cursor.y = e.y;
595                                 }
596                         }
597                 }
598                 return cursor;
599         }
600
601         var lockvisible = false;
602
603         function lockview(event,id) {
604                 event = event || window.event;
605                 cursor = getPosition(event);
606                 if(lockvisible) {
607                         lockviewhide();
608                 }
609                 else {
610                         lockvisible = true;
611                         $.get('lockview/' + id, function(data) {
612                                 $('#panel').html(data);
613                                 $('#panel').css({ 'left': cursor.x + 5 , 'top': cursor.y + 5});
614                                 $('#panel').show();
615                         });
616                 }
617         }
618
619         function lockviewhide() {
620                 lockvisible = false;
621                 $('#panel').hide();
622         }
623
624         function post_comment(id) {
625                 unpause();
626                 commentBusy = true;
627                 $('body').css('cursor', 'wait');
628                 $("#comment-preview-inp-" + id).val("0");
629                 $.post(
630                         "item",
631                         $("#comment-edit-form-" + id).serialize(),
632                         function(data) {
633                                 if(data.success) {
634                                         $("#comment-edit-wrapper-" + id).hide();
635                                         $("#comment-edit-text-" + id).val('');
636                                         var tarea = document.getElementById("comment-edit-text-" + id);
637                                         if(tarea)
638                                                 commentClose(tarea,id);
639                                         if(timer) clearTimeout(timer);
640                                         timer = setTimeout(NavUpdate,10);
641                                         force_update = true;
642                                 }
643                                 if(data.reload) {
644                                         window.location.href=data.reload;
645                                 }
646                         },
647                         "json"
648                 );
649                 return false;
650         }
651
652
653         function preview_comment(id) {
654                 $("#comment-preview-inp-" + id).val("1");
655                 $("#comment-edit-preview-" + id).show();
656                 $.post(
657                         "item",
658                         $("#comment-edit-form-" + id).serialize(),
659                         function(data) {
660                                 if(data.preview) {
661                                         $("#comment-edit-preview-" + id).html(data.preview);
662                                         $("#comment-edit-preview-" + id + " a").click(function() { return false; });
663                                 }
664                         },
665                         "json"
666                 );
667                 return true;
668         }
669
670
671
672         function showHideComments(id) {
673                 if( $("#collapsed-comments-" + id).is(":visible")) {
674                         $("#collapsed-comments-" + id).hide();
675                         $("#hide-comments-" + id).html(window.showMore);
676                 }
677                 else {
678                         $("#collapsed-comments-" + id).show();
679                         $("#hide-comments-" + id).html(window.showFewer);
680                 }
681         }
682
683
684
685         function preview_post() {
686                 $("#jot-preview").val("1");
687                 $("#jot-preview-content").show();
688                 $.post(
689                         "item",
690                         $("#profile-jot-form").serialize(),
691                         function(data) {
692                                 if(data.preview) {
693                                         $("#jot-preview-content").html(data.preview);
694                                         $("#jot-preview-content" + " a").click(function() { return false; });
695                                 }
696                         },
697                         "json"
698                 );
699                 $("#jot-preview").val("0");
700                 return true;
701         }
702
703
704         function unpause() {
705                 // unpause auto reloads if they are currently stopped
706                 totStopped = false;
707                 stopped = false;
708                 $('#pause').html('');
709         }
710
711         // load more network content (used for infinite scroll)
712         function loadScrollContent() {
713                 if (lockLoadContent) return;
714                 lockLoadContent = true;
715
716                 $("#scroll-loader").fadeIn('normal');
717
718                 // the page number to load is one higher than the actual
719                 // page number
720                 infinite_scroll.pageno+=1;
721
722                 // get the raw content from the next page and insert this content
723                 // right before "#conversation-end"
724                 $.get('network?mode=raw' + infinite_scroll.reload_uri + '&page=' + infinite_scroll.pageno, function(data) {
725                         $("#scroll-loader").hide();
726                         if ($(data).length > 0) {
727                                 $(data).insertBefore('#conversation-end');
728                                 lockLoadContent = false;
729                         } else {
730                                 $("#scroll-end").fadeIn('normal');
731                         }
732                 });
733         }
734
735     function bin2hex(s){
736         // Converts the binary representation of data to hex
737         //
738         // version: 812.316
739         // discuss at: http://phpjs.org/functions/bin2hex
740         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
741         // +   bugfixed by: Onno Marsman
742         // +   bugfixed by: Linuxworld
743         // *     example 1: bin2hex('Kev');
744         // *     returns 1: '4b6576'
745         // *     example 2: bin2hex(String.fromCharCode(0x00));
746         // *     returns 2: '00'
747         var v,i, f = 0, a = [];
748         s += '';
749         f = s.length;
750
751         for (i = 0; i<f; i++) {
752             a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
753         }
754
755         return a.join('');
756     }
757
758         function groupChangeMember(gid, cid, sec_token) {
759                 $('body .fakelink').css('cursor', 'wait');
760                 $.get('group/' + gid + '/' + cid + "?t=" + sec_token, function(data) {
761                                 $('#group-update-wrapper').html(data);
762                                 $('body .fakelink').css('cursor', 'auto');
763                 });
764         }
765
766         function profChangeMember(gid,cid) {
767                 $('body .fakelink').css('cursor', 'wait');
768                 $.get('profperm/' + gid + '/' + cid, function(data) {
769                                 $('#prof-update-wrapper').html(data);
770                                 $('body .fakelink').css('cursor', 'auto');
771                 });
772         }
773
774         function contactgroupChangeMember(gid,cid) {
775                 $('body').css('cursor', 'wait');
776                 $.get('contactgroup/' + gid + '/' + cid, function(data) {
777                                 $('body').css('cursor', 'auto');
778                 });
779         }
780
781
782 function checkboxhighlight(box) {
783   if($(box).is(':checked')) {
784         $(box).addClass('checkeditem');
785   }
786   else {
787         $(box).removeClass('checkeditem');
788   }
789 }
790
791 function notifyMarkAll() {
792         $.get('notify/mark/all', function(data) {
793                 if(timer) clearTimeout(timer);
794                 timer = setTimeout(NavUpdate,1000);
795                 force_update = true;
796         });
797 }
798
799 /**
800  * sprintf in javascript
801  *      "{0} and {1}".format('zero','uno');
802  **/
803 String.prototype.format = function() {
804     var formatted = this;
805     for (var i = 0; i < arguments.length; i++) {
806         var regexp = new RegExp('\\{'+i+'\\}', 'gi');
807         formatted = formatted.replace(regexp, arguments[i]);
808     }
809     return formatted;
810 };
811 // Array Remove
812 Array.prototype.remove = function(item) {
813   to=undefined; from=this.indexOf(item);
814   var rest = this.slice((to || from) + 1 || this.length);
815   this.length = from < 0 ? this.length + from : from;
816   return this.push.apply(this, rest);
817 };
818
819 function previewTheme(elm) {
820         theme = $(elm).val();
821         $.getJSON('pretheme?f=&theme=' + theme,function(data) {
822                         $('#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>');
823         });
824
825 }
826
827 // notification permission settings in localstorage
828 // set by settings page
829 function getNotificationPermission() {
830         if (window["Notification"] === undefined) {
831                 return null;
832         }
833     if (Notification.permission === 'granted') {
834         var val = localStorage.getItem('notification-permissions');
835                 if (val === null) return 'denied';
836                 return val;
837     } else {
838         return Notification.permission;
839     }
840 }
841
842 /**
843  * Show a dialog loaded from an url
844  * By defaults this load the url in an iframe in colorbox
845  * Themes can overwrite `show()` function to personalize it
846  */
847 var Dialog = {
848         /**
849          * Show the dialog
850          *
851          * @param string url
852          * @return object colorbox
853          */
854         show : function (url) {
855                 var size = Dialog._get_size();
856                 return $.colorbox({href: url, iframe:true,innerWidth: size.width+'px',innerHeight: size.height+'px'})
857         },
858
859         /**
860          * Show the Image browser dialog
861          *
862          * @param string name
863          * @param string id (optional)
864          * @return object
865          *
866          * The name will be used to build the event name
867          * fired by image browser dialog when the user select
868          * an image. The optional id will be passed as argument
869          * to the event handler
870          */
871         doImageBrowser : function (name, id) {
872                 var url = Dialog._get_url("image",name,id);
873                 return Dialog.show(url);
874         },
875
876         /**
877          * Show the File 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 file browser dialog when the user select
885          * a file. The optional id will be passed as argument
886          * to the event handler
887          */
888         doFileBrowser : function (name, id) {
889                 var url = Dialog._get_url("file",name,id);
890                 return Dialog.show(url);
891         },
892
893         _get_url : function(type, name, id) {
894                 var hash = name;
895                 if (id !== undefined) hash = hash + "-" + id;
896                 return baseurl + "/fbrowser/"+type+"/?mode=minimal#"+hash;
897         },
898
899         _get_size: function() {
900                 return {
901                         width: window.innerWidth-50,
902                         height: window.innerHeight-100
903                 };
904         }
905 }