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