]> git.mxchange.org Git - friendica.git/blob - js/main.js
Add jquery and jquery-colorbox to Composer
[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                         // setup videos, since VideoJS won't take care of any loaded via AJAX
503                         if(typeof videojs != 'undefined') videojs.autoSetup();
504                 });
505         }
506
507         function imgbright(node) {
508                 $(node).removeClass("drophide").addClass("drop");
509         }
510
511         function imgdull(node) {
512                 $(node).removeClass("drop").addClass("drophide");
513         }
514
515         // Since our ajax calls are asynchronous, we will give a few
516         // seconds for the first ajax call (setting like/dislike), then
517         // run the updater to pick up any changes and display on the page.
518         // The updater will turn any rotators off when it's done.
519         // This function will have returned long before any of these
520         // events have completed and therefore there won't be any
521         // visible feedback that anything changed without all this
522         // trickery. This still could cause confusion if the "like" ajax call
523         // is delayed and NavUpdate runs before it completes.
524
525         function dolike(ident,verb) {
526                 unpause();
527                 $('#like-rotator-' + ident.toString()).show();
528                 $.get('like/' + ident.toString() + '?verb=' + verb, NavUpdate );
529                 liking = 1;
530                 force_update = true;
531         }
532
533         function dosubthread(ident) {
534                 unpause();
535                 $('#like-rotator-' + ident.toString()).show();
536                 $.get('subthread/' + ident.toString(), NavUpdate );
537                 liking = 1;
538         }
539
540
541         function dostar(ident) {
542                 ident = ident.toString();
543                 $('#like-rotator-' + ident).show();
544                 $.get('starred/' + ident, function(data) {
545                         if(data.match(/1/)) {
546                                 $('#starred-' + ident).addClass('starred');
547                                 $('#starred-' + ident).removeClass('unstarred');
548                                 $('#star-' + ident).addClass('hidden');
549                                 $('#unstar-' + ident).removeClass('hidden');
550                         }
551                         else {
552                                 $('#starred-' + ident).addClass('unstarred');
553                                 $('#starred-' + ident).removeClass('starred');
554                                 $('#star-' + ident).removeClass('hidden');
555                                 $('#unstar-' + ident).addClass('hidden');
556                         }
557                         $('#like-rotator-' + ident).hide();
558                 });
559         }
560
561         function doignore(ident) {
562                 ident = ident.toString();
563                 $('#like-rotator-' + ident).show();
564                 $.get('ignored/' + ident, function(data) {
565                         if(data.match(/1/)) {
566                                 $('#ignored-' + ident).addClass('ignored');
567                                 $('#ignored-' + ident).removeClass('unignored');
568                                 $('#ignore-' + ident).addClass('hidden');
569                                 $('#unignore-' + ident).removeClass('hidden');
570                         }
571                         else {
572                                 $('#ignored-' + ident).addClass('unignored');
573                                 $('#ignored-' + ident).removeClass('ignored');
574                                 $('#ignore-' + ident).removeClass('hidden');
575                                 $('#unignore-' + ident).addClass('hidden');
576                         }
577                         $('#like-rotator-' + ident).hide();
578                 });
579         }
580
581         function getPosition(e) {
582                 var cursor = {x:0, y:0};
583                 if ( e.pageX || e.pageY  ) {
584                         cursor.x = e.pageX;
585                         cursor.y = e.pageY;
586                 }
587                 else {
588                         if( e.clientX || e.clientY ) {
589                                 cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
590                                 cursor.y = e.clientY + (document.documentElement.scrollTop  || document.body.scrollTop)  - document.documentElement.clientTop;
591                         }
592                         else {
593                                 if( e.x || e.y ) {
594                                         cursor.x = e.x;
595                                         cursor.y = e.y;
596                                 }
597                         }
598                 }
599                 return cursor;
600         }
601
602         var lockvisible = false;
603
604         function lockview(event,id) {
605                 event = event || window.event;
606                 cursor = getPosition(event);
607                 if(lockvisible) {
608                         lockviewhide();
609                 }
610                 else {
611                         lockvisible = true;
612                         $.get('lockview/' + id, function(data) {
613                                 $('#panel').html(data);
614                                 $('#panel').css({ 'left': cursor.x + 5 , 'top': cursor.y + 5});
615                                 $('#panel').show();
616                         });
617                 }
618         }
619
620         function lockviewhide() {
621                 lockvisible = false;
622                 $('#panel').hide();
623         }
624
625         function post_comment(id) {
626                 unpause();
627                 commentBusy = true;
628                 $('body').css('cursor', 'wait');
629                 $("#comment-preview-inp-" + id).val("0");
630                 $.post(
631                         "item",
632                         $("#comment-edit-form-" + id).serialize(),
633                         function(data) {
634                                 if(data.success) {
635                                         $("#comment-edit-wrapper-" + id).hide();
636                                         $("#comment-edit-text-" + id).val('');
637                                         var tarea = document.getElementById("comment-edit-text-" + id);
638                                         if(tarea)
639                                                 commentClose(tarea,id);
640                                         if(timer) clearTimeout(timer);
641                                         timer = setTimeout(NavUpdate,10);
642                                         force_update = true;
643                                 }
644                                 if(data.reload) {
645                                         window.location.href=data.reload;
646                                 }
647                         },
648                         "json"
649                 );
650                 return false;
651         }
652
653
654         function preview_comment(id) {
655                 $("#comment-preview-inp-" + id).val("1");
656                 $("#comment-edit-preview-" + id).show();
657                 $.post(
658                         "item",
659                         $("#comment-edit-form-" + id).serialize(),
660                         function(data) {
661                                 if(data.preview) {
662                                         $("#comment-edit-preview-" + id).html(data.preview);
663                                         $("#comment-edit-preview-" + id + " a").click(function() { return false; });
664                                 }
665                         },
666                         "json"
667                 );
668                 return true;
669         }
670
671
672
673         function showHideComments(id) {
674                 if( $("#collapsed-comments-" + id).is(":visible")) {
675                         $("#collapsed-comments-" + id).hide();
676                         $("#hide-comments-" + id).html(window.showMore);
677                 }
678                 else {
679                         $("#collapsed-comments-" + id).show();
680                         $("#hide-comments-" + id).html(window.showFewer);
681                 }
682         }
683
684
685
686         function preview_post() {
687                 $("#jot-preview").val("1");
688                 $("#jot-preview-content").show();
689                 $.post(
690                         "item",
691                         $("#profile-jot-form").serialize(),
692                         function(data) {
693                                 if(data.preview) {
694                                         $("#jot-preview-content").html(data.preview);
695                                         $("#jot-preview-content" + " a").click(function() { return false; });
696                                 }
697                         },
698                         "json"
699                 );
700                 $("#jot-preview").val("0");
701                 return true;
702         }
703
704
705         function unpause() {
706                 // unpause auto reloads if they are currently stopped
707                 totStopped = false;
708                 stopped = false;
709                 $('#pause').html('');
710         }
711
712         // load more network content (used for infinite scroll)
713         function loadScrollContent() {
714                 if (lockLoadContent) return;
715                 lockLoadContent = true;
716
717                 $("#scroll-loader").fadeIn('normal');
718
719                 // the page number to load is one higher than the actual
720                 // page number
721                 infinite_scroll.pageno+=1;
722
723                 match = $("span.received").last();
724                 if (match.length > 0) {
725                         received = match[0].innerHTML;
726                 } else {
727                         received = "0000-00-00 00:00:00";
728                 }
729
730                 match = $("span.created").last();
731                 if (match.length > 0) {
732                         created = match[0].innerHTML;
733                 } else {
734                         created = "0000-00-00 00:00:00";
735                 }
736
737                 match = $("span.commented").last();
738                 if (match.length > 0) {
739                         commented = match[0].innerHTML;
740                 } else {
741                         commented = "0000-00-00 00:00:00";
742                 }
743
744                 match = $("span.id").last();
745                 if (match.length > 0) {
746                         id = match[0].innerHTML;
747                 } else {
748                         id = "0";
749                 }
750                 // console.log("Received: " + received + " - Commented: " + commented+ " - Created: " + created + " - ID: " + id);
751
752                 // get the raw content from the next page and insert this content
753                 // right before "#conversation-end"
754                 $.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) {
755                         $("#scroll-loader").hide();
756                         if ($(data).length > 0) {
757
758                                 $(data).insertBefore('#conversation-end');
759                                 lockLoadContent = false;
760                         } else {
761                                 $("#scroll-end").fadeIn('normal');
762                         }
763                 });
764         }
765
766     function bin2hex(s){
767         // Converts the binary representation of data to hex
768         //
769         // version: 812.316
770         // discuss at: http://phpjs.org/functions/bin2hex
771         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
772         // +   bugfixed by: Onno Marsman
773         // +   bugfixed by: Linuxworld
774         // *     example 1: bin2hex('Kev');
775         // *     returns 1: '4b6576'
776         // *     example 2: bin2hex(String.fromCharCode(0x00));
777         // *     returns 2: '00'
778         var v,i, f = 0, a = [];
779         s += '';
780         f = s.length;
781
782         for (i = 0; i<f; i++) {
783             a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
784         }
785
786         return a.join('');
787     }
788
789         function groupChangeMember(gid, cid, sec_token) {
790                 $('body .fakelink').css('cursor', 'wait');
791                 $.get('group/' + gid + '/' + cid + "?t=" + sec_token, function(data) {
792                                 $('#group-update-wrapper').html(data);
793                                 $('body .fakelink').css('cursor', 'auto');
794                 });
795         }
796
797         function profChangeMember(gid,cid) {
798                 $('body .fakelink').css('cursor', 'wait');
799                 $.get('profperm/' + gid + '/' + cid, function(data) {
800                                 $('#prof-update-wrapper').html(data);
801                                 $('body .fakelink').css('cursor', 'auto');
802                 });
803         }
804
805         function contactgroupChangeMember(gid,cid) {
806                 $('body').css('cursor', 'wait');
807                 $.get('contactgroup/' + gid + '/' + cid, function(data) {
808                                 $('body').css('cursor', 'auto');
809                 });
810         }
811
812
813 function checkboxhighlight(box) {
814   if($(box).is(':checked')) {
815         $(box).addClass('checkeditem');
816   }
817   else {
818         $(box).removeClass('checkeditem');
819   }
820 }
821
822 function notifyMarkAll() {
823         $.get('notify/mark/all', function(data) {
824                 if(timer) clearTimeout(timer);
825                 timer = setTimeout(NavUpdate,1000);
826                 force_update = true;
827         });
828 }
829
830 /**
831  * sprintf in javascript
832  *      "{0} and {1}".format('zero','uno');
833  **/
834 String.prototype.format = function() {
835     var formatted = this;
836     for (var i = 0; i < arguments.length; i++) {
837         var regexp = new RegExp('\\{'+i+'\\}', 'gi');
838         formatted = formatted.replace(regexp, arguments[i]);
839     }
840     return formatted;
841 };
842 // Array Remove
843 Array.prototype.remove = function(item) {
844   to=undefined; from=this.indexOf(item);
845   var rest = this.slice((to || from) + 1 || this.length);
846   this.length = from < 0 ? this.length + from : from;
847   return this.push.apply(this, rest);
848 };
849
850 function previewTheme(elm) {
851         theme = $(elm).val();
852         $.getJSON('pretheme?f=&theme=' + theme,function(data) {
853                         $('#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>');
854         });
855
856 }
857
858 // notification permission settings in localstorage
859 // set by settings page
860 function getNotificationPermission() {
861         if (window["Notification"] === undefined) {
862                 return null;
863         }
864     if (Notification.permission === 'granted') {
865         var val = localStorage.getItem('notification-permissions');
866                 if (val === null) return 'denied';
867                 return val;
868     } else {
869         return Notification.permission;
870     }
871 }
872
873 /**
874  * Show a dialog loaded from an url
875  * By defaults this load the url in an iframe in colorbox
876  * Themes can overwrite `show()` function to personalize it
877  */
878 var Dialog = {
879         /**
880          * Show the dialog
881          *
882          * @param string url
883          * @return object colorbox
884          */
885         show : function (url) {
886                 var size = Dialog._get_size();
887                 return $.colorbox({href: url, iframe:true,innerWidth: size.width+'px',innerHeight: size.height+'px'})
888         },
889
890         /**
891          * Show the Image browser dialog
892          *
893          * @param string name
894          * @param string id (optional)
895          * @return object
896          *
897          * The name will be used to build the event name
898          * fired by image browser dialog when the user select
899          * an image. The optional id will be passed as argument
900          * to the event handler
901          */
902         doImageBrowser : function (name, id) {
903                 var url = Dialog._get_url("image",name,id);
904                 return Dialog.show(url);
905         },
906
907         /**
908          * Show the File browser dialog
909          *
910          * @param string name
911          * @param string id (optional)
912          * @return object
913          *
914          * The name will be used to build the event name
915          * fired by file browser dialog when the user select
916          * a file. The optional id will be passed as argument
917          * to the event handler
918          */
919         doFileBrowser : function (name, id) {
920                 var url = Dialog._get_url("file",name,id);
921                 return Dialog.show(url);
922         },
923
924         _get_url : function(type, name, id) {
925                 var hash = name;
926                 if (id !== undefined) hash = hash + "-" + id;
927                 return baseurl + "/fbrowser/"+type+"/?mode=minimal#"+hash;
928         },
929
930         _get_size: function() {
931                 return {
932                         width: window.innerWidth-50,
933                         height: window.innerHeight-100
934                 };
935         }
936 }