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