]> git.mxchange.org Git - friendica.git/blob - view/theme/frio/js/theme.js
Merge remote-tracking branch 'friendica/stable' into develop
[friendica.git] / view / theme / frio / js / theme.js
1
2 var jotcache = ''; //The jot cache. We use it as cache to restore old/original jot content
3
4 $(document).ready(function(){
5         // Destroy unused perfect scrollbar in aside element
6         $('aside').perfectScrollbar('destroy');
7
8         //fade in/out based on scrollTop value
9         var scrollStart;
10
11         $(window).scroll(function () {
12                 let currentScroll = $(this).scrollTop();
13
14                 // Top of the page or going down = hide the button
15                 if (!scrollStart || !currentScroll || currentScroll > scrollStart) {
16                         $("#back-to-top").fadeOut();
17                         scrollStart = currentScroll;
18                 }
19
20                 // Going up enough = show the button
21                 if (scrollStart - currentScroll > 100) {
22                         $("#back-to-top").fadeIn();
23                         scrollStart = currentScroll;
24                 }
25         });
26
27         // scroll body to 0px on click
28         $("#back-to-top").click(function () {
29                 $("body,html").animate({
30                         scrollTop: 0
31                 }, 400);
32                 return false;
33         });
34
35         // add the class "selected" to group widges li if li > a does have the class group-selected
36         if( $("#sidebar-group-ul li a").hasClass("group-selected")) {
37                 $("#sidebar-group-ul li a.group-selected").parent("li").addClass("selected");
38         }
39
40         // add the class "selected" to forums widges li if li > a does have the class forum-selected
41         if( $("#forumlist-sidbar-ul li a").hasClass("forum-selected")) {
42                 $("#forumlist-sidbar-ul li a.forum-selected").parent("li").addClass("selected");
43         }
44
45         // add the class "active" to tabmenuli if li > a does have the class active
46         if( $("#tabmenu ul li a").hasClass("active")) {
47                 $("#tabmenu ul li a.active").parent("li").addClass("active");
48         }
49
50         // give select fields an boostrap classes
51         // @todo: this needs to be changed in friendica core
52         $(".field.select, .field.custom").addClass("form-group");
53         $(".field.select > select, .field.custom > select").addClass("form-control");
54
55         // move the tabbar to the second nav bar
56         $("section .tabbar-wrapper").first().appendTo("#topbar-second > .container > #tabmenu");
57
58         // add mask css url to the logo-img container
59         //
60         // This is for firefox - we use a mask which looks like the friendica logo to apply user collers
61         // to the friendica logo (the mask is in nav.tpl at the botom). To make it work we need to apply the
62         // correct url. The only way which comes to my mind was to do this with js
63         // So we apply the correct url (with the link to the id of the mask) after the page is loaded.
64         if($("#logo-img").length ) {
65                 var pageurl = "url('" + window.location.href + "#logo-mask')";
66                 $("#logo-img").css({"mask": pageurl});
67         }
68
69         // make responsive tabmenu with flexmenu.js
70         // the menupoints which doesn't fit in the second nav bar will moved to a
71         // dropdown menu. Look at common_tabs.tpl
72         $("ul.tabs.flex-nav").flexMenu({
73                 'cutoff': 2,
74                 'popupClass': "dropdown-menu pull-right",
75                 'popupAbsolute': false,
76                 'target': ".flex-target"
77         });
78
79         // add Jot button to the second navbar
80         let $jotButton = $("#jotOpen");
81         if ($jotButton.length) {
82                 $jotButton.appendTo("#topbar-second > .container > #navbar-button");
83                 if ($("#jot-popup").is(":hidden")) {
84                         $jotButton.hide();
85                 }
86                 $jotButton.on('click', function (e) {
87                         e.preventDefault();
88                         jotShow();
89                 });
90         }
91
92         let $body = $('body');
93
94         // show bulk deletion button at network page if checkbox is checked
95         $body.change("input.item-select", function(){
96                 var checked = false;
97
98                 // We need to get all checked items, so it would close the delete button
99                 // if we uncheck one item and others are still checked.
100                 // So return checked = true if there is any checked item
101                 $('input.item-select').each( function() {
102                         if($(this).is(':checked')) {
103                                 checked = true;
104                                 return false;
105                         }
106                 });
107
108                 if(checked) {
109                         $("#item-delete-selected").fadeTo(400, 1);
110                         $("#item-delete-selected").show();
111                 } else {
112                         $("#item-delete-selected").fadeTo(400, 0, function(){
113                                 $("#item-delete-selected").hide();
114                         });
115                 }
116         });
117
118         // initialize the bootstrap tooltips
119         $body.tooltip({
120                 selector: '[data-toggle="tooltip"]',
121                 container: 'body',
122                 animation: true,
123                 html: true,
124                 placement: 'auto',
125                 trigger: 'hover',
126                 delay: {
127                         show: 500,
128                         hide: 100
129                 },
130                 sanitizeFn: function (content) {
131                         return DOMPurify.sanitize(content)
132                 },
133         });
134
135         // initialize the bootstrap-select
136         $('.selectpicker').selectpicker();
137
138         // add search-heading to the seccond navbar
139         if( $(".search-heading").length) {
140                 $(".search-heading").appendTo("#topbar-second > .container > #tabmenu");
141         }
142
143         // add search results heading to the second navbar
144         // and insert the search value to the top nav search input
145         if( $(".search-content-wrapper").length ) {
146                 // get the text of the heading (we catch the plain text because we don't
147                 // want to have a h4 heading in the navbar
148                 var searchText = $(".section-title-wrapper > h2").text();
149                 // insert the plain text in a <h4> heading and give it a class
150                 var newText = '<h4 class="search-heading">'+searchText+'</h4>';
151                 // append the new heading to the navbar
152                 $("#topbar-second > .container > #tabmenu").append(newText);
153
154                 // try to get the value of the original search input to insert it
155                 // as value in the nav-search-input
156                 var searchValue = $("#search-wrapper .form-group-search input").val();
157
158                 // if the orignal search value isn't available use the location path as value
159                 if( typeof searchValue === "undefined") {
160                         // get the location path
161                         var urlPath = window.location.search
162                         // and split it up in its parts
163                         var splitPath = urlPath.split(/(\?search?=)(.*$)/);
164
165                         if(typeof splitPath[2] !== 'undefined') {
166                                 // decode the path (e.g to decode %40 to the character @)
167                                 var searchValue = decodeURIComponent(splitPath[2]);
168                         }
169                 }
170
171                 if( typeof searchValue !== "undefined") {
172                         $("#nav-search-input-field").val(searchValue);
173                 }
174         }
175
176         // move the "Save the search" button to the second navbar
177         $(".search-content-wrapper #search-save").appendTo("#topbar-second > .container > #navbar-button");
178
179         // append the vcard-short-info to the second nav after passing the element
180         // with .fn (vcard username). Use scrollspy to get the scroll position.
181         if( $("aside .vcard .fn").length) {
182                 $(".vcard .fn").scrollspy({
183                         min: $(".vcard .fn").position().top - 50,
184                         onLeaveTop: function onLeave(element) {
185                                 $("#vcard-short-info").fadeOut(500, function () {
186                                         $("#vcard-short-info").appendTo("#vcard-short-info-wrapper");
187                                 });
188                         },
189                         onEnter: function(element) {
190                                 $("#vcard-short-info").appendTo("#nav-short-info");
191                                 $("#vcard-short-info").fadeIn(500);
192                         },
193                 });
194         }
195
196         // move the forum contact information of the network page into the second navbar
197         if( $(".network-content-wrapper > #viewcontact_wrapper-network").length) {
198                 // get the contact-wrapper element and append it to the second nav bar
199                 // Note: We need the first() element with this class since at the present time we
200                 // store also the js template information in the html code and thats why
201                 // there are two elements with this class but we don't want the js template
202                 $(".network-content-wrapper > #viewcontact_wrapper-network .contact-wrapper").first().appendTo("#nav-short-info");
203         }
204
205         // move heading from network stream to the second navbar nav-short-info section
206         if( $(".network-content-wrapper > .section-title-wrapper").length) {
207                 // get the heading element
208                 var heading = $(".network-content-wrapper > .section-title-wrapper > h2");
209                 // get the text of the heading
210                 var headingContent = heading.text();
211                 // create a new element with the content of the heading
212                 var newText = '<h4 class="heading" data-toggle="tooltip" title="'+headingContent+'">'+headingContent+'</h4>';
213                 // remove the old heading element
214                 heading.remove(),
215                 // put the new element to the second nav bar
216                 $("#topbar-second #nav-short-info").append(newText);
217         }
218
219         if( $(".community-content-wrapper").length) {
220                 // get the heading element
221                 var heading = $(".community-content-wrapper > h3").first();
222                 // get the text of the heading
223                 var headingContent = heading.text();
224                 // create a new element with the content of the heading
225                 var newText = '<h4 class="heading">'+headingContent+'</h4>';
226                 // remove the old heading element
227                 heading.remove(),
228                 // put the new element to the second nav bar
229                 $("#topbar-second > .container > #tabmenu").append(newText);
230         }
231
232         // Dropdown menus with the class "dropdown-head" will display the active tab
233         // as button text
234         $body.on('click', '.dropdown-head .dropdown-menu li a, .dropdown-head .dropdown-menu li button', function(){
235                 toggleDropdownText(this);
236         });
237
238         // Change the css class while clicking on the switcher elements
239         $(".toggle label, .toggle .toggle-handle").click(function(event){
240                 event.preventDefault();
241                 // Get the value of the input element
242                 var input = $(this).siblings("input");
243                 var val = 1-input.val();
244                 var id = input.attr("id");
245
246                 // The css classes for "on" and "off"
247                 var onstyle = "btn-primary";
248                 var offstyle = "btn-default off";
249
250                 // According to the value of the input element we need to decide
251                 // which class need to be added and removed when changing the switch
252                 var removedclass = (val == 0 ? onstyle : offstyle);
253                 var addedclass = (val == 0 ? offstyle : onstyle)
254                 $("#"+id+"_onoff").addClass(addedclass).removeClass(removedclass);
255
256                 // After changing the switch the input element is getting
257                 // the newvalue
258                 input.val(val);
259         });
260
261         // Set the padding for input elements with inline buttons
262         //
263         // In Frio we use some input elements where the submit button is visually
264         // inside the the input field (through css). We need to set a padding-right
265         // to the input element where the padding value would be at least the width
266         // of the button. Otherwise long user input would be invisible because it is
267         // behind the button.
268         $body.on('click', '.form-group-search > input', function() {
269                 // Get the width of the button (if the button isn't available
270                 // buttonWidth will be null
271                 var buttonWidth = $(this).next('.form-button-search').outerWidth();
272
273                 if (buttonWidth) {
274                         // Take the width of the button and ad 5px
275                         var newWidth = buttonWidth + 5;
276                         // Set the padding of the input element according
277                         // to the width of the button
278                         $(this).css('padding-right', newWidth);
279                 }
280
281         });
282
283         /*
284          * This event handler hides all comment UI when the user clicks anywhere on the page
285          * It ensures that we aren't closing the current comment box
286          *
287          * We are making an exception for buttons because of a race condition with the
288          * comment opening button that results in an already closed comment UI.
289          */
290         $(document).on('mousedown', function(event) {
291                 if (event.target.type === 'button') {
292                         return true;
293                 }
294
295                 var $dontclosethis = $(event.target).closest('.wall-item-comment-wrapper').find('.comment-edit-form');
296                 $('.wall-item-comment-wrapper .comment-edit-submit-wrapper:visible').each(function() {
297                         var $parent = $(this).parent('.comment-edit-form');
298                         var itemId = $parent.data('itemId');
299
300                         if ($dontclosethis[0] != $parent[0]) {
301                                 var textarea = $parent.find('textarea').get(0)
302
303                                 commentCloseUI(textarea, itemId);
304                         }
305                 });
306         });
307
308         // Customize some elements when the app is used in standalone mode on Android
309         if (window.matchMedia('(display-mode: standalone)').matches) {
310                 // Open links to source outside of the webview
311                 $('body').on('click', '.plink', function (e) {
312                         $(e.target).attr('target', '_blank');
313                 });
314         }
315
316         /*
317          * This event listeners ensures that the textarea size is updated event if the
318          * value is changed externally (textcomplete, insertFormatting, fbrowser...)
319          */
320         $(document).on('change', 'textarea', function(event) {
321                 autosize.update(event.target);
322         });
323
324         /*
325          * Sticky aside on page scroll
326          * We enable the sticky aside only when window is wider than
327          * 976px - which is the maximum width where the aside is shown in
328          * mobile style - because on chrome-based browsers (desktop and
329          * android) the sticky plugin in mobile style causes the browser to
330          * scroll back to top the main content, making it impossible
331          * to navigate.
332          * A side effect is that the sitky aside isn't really responsive,
333          * since is enabled or not at page loading time.
334          */
335         if ($(window).width() > 976) {
336                 $("aside").stick_in_parent({
337                         offset_top: 100, // px, header + tab bar + spacing
338                         recalc_every: 10
339                 });
340                 // recalculate sticky aside on clicks on <a> elements
341                 // this handle height changes on expanding submenus
342                 $("aside").on("click", "a", function(){
343                         $(document.body).trigger("sticky_kit:recalc");
344                 });
345         }
346
347         /*
348          * Add or remove "aside-out" class to body tag
349          * when the mobile aside is shown or hidden.
350          * The class is used in css to disable scroll in page when the aside
351          * is shown.
352          */
353         $("aside")
354                 .on("shown.bs.offcanvas", function() {
355                         $body.addClass("aside-out");
356                 })
357                 .on("hidden.bs.offcanvas", function() {
358                         $body.removeClass("aside-out");
359                 });
360
361         // Event listener for 'Show & hide event map' button in the network stream.
362         $body.on("click", ".event-map-btn", function() {
363                 showHideEventMap(this);
364         });
365
366         // Comment form submit
367         $body.on('submit', '.comment-edit-form', function(e) {
368                 let $form = $(this);
369                 let id = $form.data('item-id');
370
371                 // Compose page form exception: id is always 0 and form must not be submitted asynchronously
372                 if (id === 0) {
373                         return;
374                 }
375
376                 e.preventDefault();
377
378                 let $commentSubmit = $form.find('.comment-edit-submit').button('loading');
379
380                 unpause();
381                 commentBusy = true;
382
383                 $.post(
384                         'item',
385                         $form.serialize(),
386                         'json'
387                 )
388                 .then(function(data) {
389                         if (data.success) {
390                                 $('#comment-edit-wrapper-' + id).hide();
391                                 let $textarea = $('#comment-edit-text-' + id);
392                                 $textarea.val('');
393                                 if ($textarea.get(0)) {
394                                         commentClose($textarea.get(0), id);
395                                 }
396                                 if (timer) {
397                                         clearTimeout(timer);
398                                 }
399                                 timer = setTimeout(NavUpdate,10);
400                                 force_update = true;
401                                 update_item = id;
402                         }
403                         if (data.reload) {
404                                 window.location.href = data.reload;
405                         }
406                 })
407                 .always(function() {
408                         $commentSubmit.button('reset');
409                 });
410         });
411
412         $body.on('submit', '.modal-body #poke-wrapper', function(e) {
413                 e.preventDefault();
414
415                 let $form = $(this);
416                 let $pokeSubmit = $form.find('button[type=submit]').button('loading');
417
418                 $.post(
419                         $form.attr('action'),
420                         $form.serialize(),
421                         'json'
422                 )
423                 .then(function(data) {
424                         if (data.success) {
425                                 $('#modal').modal('hide');
426                         }
427                 })
428                 .always(function() {
429                         $pokeSubmit.button('reset');
430                 });
431         })
432 });
433
434 function openClose(theID) {
435         var elem = document.getElementById(theID);
436
437         if( $(elem).is(':visible')) {
438                 $(elem).slideUp(200);
439         }
440         else {
441                 $(elem).slideDown(200);
442         }
443 }
444
445 function showHide(theID) {
446         var elem = document.getElementById(theID);
447         var edit = document.getElementById("comment-edit-submit-wrapper-" + theID.match('[0-9$]+'));
448
449         if ($(elem).is(':visible')) {
450                 if (!$(edit).is(':visible')) {
451                         edit.style.display = "block";
452                 }
453                 else {
454                         elem.style.display = "none";
455                 }
456         }
457         else {
458                 elem.style.display = "block";
459         }
460 }
461
462 // Show & hide event map in the network stream by button click.
463 function showHideEventMap(elm) {
464         // Get the id of the map element - it should be provided through
465         // the atribute "data-map-id".
466         var mapID = elm.getAttribute('data-map-id');
467
468         // Get translation labels.
469         var mapshow = elm.getAttribute('data-show-label');
470         var maphide = elm.getAttribute('data-hide-label');
471
472         // Change the button labels.
473         if (elm.innerText == mapshow) {
474                 $('#' + elm.id).text(maphide);
475         } else {
476                 $('#' + elm.id).text(mapshow);
477         }
478         // Because maps are iframe elements, we cant hide it through css (display: none).
479         // We solve this issue by putting the map outside the screen with css.
480         // So the first time the 'Show map' button is pressed we move the map
481         // element into the screen area.
482         var mappos = $('#' + mapID).css('position');
483
484         if (mappos === 'absolute') {
485                 $('#' + mapID).hide();
486                 $('#' + mapID).css({position: 'relative', left: 'auto', top: 'auto'});
487                 openClose(mapID);
488         } else {
489                 openClose(mapID);
490         }
491         return false;
492 }
493
494 function justifyPhotos() {
495         justifiedGalleryActive = true;
496         $('#photo-album-contents').justifiedGallery({
497                 margins: 3,
498                 border: 0,
499                 sizeRangeSuffixes: {
500                         'lt48': '-6',
501                         'lt80': '-5',
502                         'lt300': '-4',
503                         'lt320': '-2',
504                         'lt640': '-1',
505                         'lt1024': '-0'
506                 }
507         }).on('jg.complete', function(e){ justifiedGalleryActive = false; });
508 }
509
510 // Load a js script to the html head.
511 function loadScript(url, callback) {
512         // Check if the script is already in the html head.
513         var oscript = $('head script[src="' + url + '"]');
514
515         // Delete the old script from head.
516         if (oscript.length > 0) {
517                 oscript.remove();
518         }
519         // Adding the script tag to the head as suggested before.
520         var head = document.getElementsByTagName('head')[0];
521         var script = document.createElement('script');
522         script.type = 'text/javascript';
523         script.src = url;
524
525         // Then bind the event to the callback function.
526         // There are several events for cross browser compatibility.
527         script.onreadystatechange = callback;
528         script.onload = callback;
529
530         // Fire the loading.
531         head.appendChild(script);
532 }
533
534 // Does we need a ? or a & to append values to a url
535 function qOrAmp(url) {
536         if(url.search('\\?') < 0) {
537                 return '?';
538         } else {
539                 return '&';
540         }
541 }
542
543 String.prototype.normalizeLink = function () {
544         var ret = this.replace('https:', 'http:');
545         var ret = ret.replace('//www', '//');
546         return ret.rtrim();
547 };
548
549 function cleanContactUrl(url) {
550         var parts = parseUrl(url);
551
552         if(! ("scheme" in parts) || ! ("host" in parts)) {
553                 return url;
554         }
555
556         var newUrl =parts["scheme"] + "://" + parts["host"];
557
558         if("port" in parts) {
559                 newUrl += ":" + parts["port"];
560         }
561
562         if("path" in parts) {
563                 newUrl += parts["path"];
564         }
565
566 //      if(url != newUrl) {
567 //              console.log("Cleaned contact url " + url + " to " + newUrl);
568 //      }
569
570         return newUrl;
571 }
572
573 function parseUrl (str, component) { // eslint-disable-line camelcase
574         //       discuss at: http://locutusjs.io/php/parse_url/
575         //      original by: Steven Levithan (http://blog.stevenlevithan.com)
576         // reimplemented by: Brett Zamir (http://brett-zamir.me)
577         //         input by: Lorenzo Pisani
578         //         input by: Tony
579         //      improved by: Brett Zamir (http://brett-zamir.me)
580         //           note 1: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
581         //           note 1: blog post at http://blog.stevenlevithan.com/archives/parseuri
582         //           note 1: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
583         //           note 1: Does not replace invalid characters with '_' as in PHP,
584         //           note 1: nor does it return false with
585         //           note 1: a seriously malformed URL.
586         //           note 1: Besides function name, is essentially the same as parseUri as
587         //           note 1: well as our allowing
588         //           note 1: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
589         //        example 1: parse_url('http://user:pass@host/path?a=v#a')
590         //        returns 1: {scheme: 'http', host: 'host', user: 'user', pass: 'pass', path: '/path', query: 'a=v', fragment: 'a'}
591         //        example 2: parse_url('http://en.wikipedia.org/wiki/%22@%22_%28album%29')
592         //        returns 2: {scheme: 'http', host: 'en.wikipedia.org', path: '/wiki/%22@%22_%28album%29'}
593         //        example 3: parse_url('https://host.domain.tld/a@b.c/folder')
594         //        returns 3: {scheme: 'https', host: 'host.domain.tld', path: '/a@b.c/folder'}
595         //        example 4: parse_url('https://gooduser:secretpassword@www.example.com/a@b.c/folder?foo=bar')
596         //        returns 4: { scheme: 'https', host: 'www.example.com', path: '/a@b.c/folder', query: 'foo=bar', user: 'gooduser', pass: 'secretpassword' }
597
598         var query
599
600         var mode = (typeof require !== 'undefined' ? require('../info/ini_get')('locutus.parse_url.mode') : undefined) || 'php'
601
602         var key = [
603                 'source',
604                 'scheme',
605                 'authority',
606                 'userInfo',
607                 'user',
608                 'pass',
609                 'host',
610                 'port',
611                 'relative',
612                 'path',
613                 'directory',
614                 'file',
615                 'query',
616                 'fragment'
617         ]
618
619         // For loose we added one optional slash to post-scheme to catch file:/// (should restrict this)
620         var parser = {
621                 php: new RegExp([
622                         '(?:([^:\\/?#]+):)?',
623                         '(?:\\/\\/()(?:(?:()(?:([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?))?',
624                         '()',
625                         '(?:(()(?:(?:[^?#\\/]*\\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'
626                 ].join('')),
627                 strict: new RegExp([
628                         '(?:([^:\\/?#]+):)?',
629                         '(?:\\/\\/((?:(([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?))?',
630                         '((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'
631                 ].join('')),
632                 loose: new RegExp([
633                         '(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?',
634                         '(?:\\/\\/\\/?)?',
635                         '((?:(([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?)',
636                         '(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))',
637                         '(?:\\?([^#]*))?(?:#(.*))?)'
638                 ].join(''))
639         }
640
641         var m = parser[mode].exec(str)
642         var uri = {}
643         var i = 14
644
645         while (i--) {
646                 if (m[i]) {
647                         uri[key[i]] = m[i]
648                 }
649         }
650
651         if (component) {
652                 return uri[component.replace('PHP_URL_', '').toLowerCase()]
653         }
654
655         if (mode !== 'php') {
656                 var name = (typeof require !== 'undefined' ? require('../info/ini_get')('locutus.parse_url.queryKey') : undefined) || 'queryKey'
657                 parser = /(?:^|&)([^&=]*)=?([^&]*)/g
658                 uri[name] = {}
659                 query = uri[key[12]] || ''
660                 query.replace(parser, function ($0, $1, $2) {
661                         if ($1) {
662                                 uri[name][$1] = $2
663                         }
664                 })
665         }
666
667         delete uri.source
668         return uri
669 }
670
671 // trim function to replace whithespace after the string
672 String.prototype.rtrim = function() {
673         var trimmed = this.replace(/\s+$/g, '');
674         return trimmed;
675 };
676
677 /**
678  * Scroll the screen to the item element whose id is provided, then highlights it
679  *
680  * Note: jquery.color.js is required
681  *
682  * @param {string} elementId The item element id
683  * @returns {undefined}
684  */
685 function scrollToItem(elementId) {
686         if (typeof elementId === "undefined") {
687                 return;
688         }
689
690         var $el = $('#' + elementId +  ' > .media');
691         // Test if the Item exists
692         if (!$el.length) {
693                 return;
694         }
695
696         // Define the colors which are used for highlighting
697         var colWhite = {backgroundColor:'#F5F5F5'};
698         var colShiny = {backgroundColor:'#FFF176'};
699
700         // Get the Item Position (we need to substract 100 to match correct position
701         var itemPos = $el.offset().top - 100;
702
703         // Scroll to the DIV with the ID (GUID)
704         $('html, body').animate({
705                 scrollTop: itemPos
706         }, 400).promise().done( function() {
707                 // Highlight post/commenent with ID  (GUID)
708                 $el.animate(colWhite, 1000).animate(colShiny).animate({backgroundColor: 'transparent'}, 600);
709         });
710 }
711
712 // format a html string to pure text
713 function htmlToText(htmlString) {
714         // Replace line breaks with spaces
715         var text = htmlString.replace(/<br>/g, ' ');
716         // Strip the text out of the html string
717         text = text.replace(/<[^>]*>/g, '');
718
719         return text;
720 }
721
722 /**
723  * Sends a /like API call and updates the display of the relevant action button
724  * before the update reloads the item.
725  *
726  * @param {int}     ident The id of the relevant item
727  * @param {string}  verb  The verb of the action
728  * @param {boolean} un    Whether to perform an activity removal instead of creation
729  */
730 function doLikeAction(ident, verb, un) {
731         if (verb.indexOf('attend') === 0) {
732                 $('.item-' + ident + ' .button-event:not(#' + verb + '-' + ident + ')').removeClass('active');
733         }
734         $('#' + verb + '-' + ident).toggleClass('active');
735
736         dolike(ident, verb, un);
737 }
738
739 // Decodes a hexadecimally encoded binary string
740 function hex2bin (s) {
741         //  discuss at: http://locutus.io/php/hex2bin/
742         // original by: Dumitru Uzun (http://duzun.me)
743         //   example 1: hex2bin('44696d61')
744         //   returns 1: 'Dima'
745         //   example 2: hex2bin('00')
746         //   returns 2: '\x00'
747         //   example 3: hex2bin('2f1q')
748         //   returns 3: false
749         var ret = [];
750         var i = 0;
751         var l;
752         s += '';
753
754         for (l = s.length; i < l; i += 2) {
755                 var c = parseInt(s.substr(i, 1), 16);
756                 var k = parseInt(s.substr(i + 1, 1), 16);
757                 if (isNaN(c) || isNaN(k)) {
758                         return false;
759                 }
760                 ret.push((c << 4) | k);
761         }
762         return String.fromCharCode.apply(String, ret);
763 }
764
765 // Convert binary data into hexadecimal representation
766 function bin2hex (s) {
767         // From: http://phpjs.org/functions
768         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
769         // +   bugfixed by: Onno Marsman
770         // +   bugfixed by: Linuxworld
771         // +   improved by: ntoniazzi (http://phpjs.org/functions/bin2hex:361#comment_177616)
772         // *     example 1: bin2hex('Kev');
773         // *     returns 1: '4b6576'
774         // *     example 2: bin2hex(String.fromCharCode(0x00));
775         // *     returns 2: '00'
776
777         var i, l, o = "", n;
778
779         s += "";
780
781         for (i = 0, l = s.length; i < l; i++) {
782                 n = s.charCodeAt(i).toString(16);
783                 o += n.length < 2 ? "0" + n : n;
784         }
785
786         return o;
787 }
788
789 // Dropdown menus with the class "dropdown-head" will display the active tab
790 // as button text
791 function toggleDropdownText(elm) {
792                 $(elm).closest(".dropdown").find('.btn').html($(elm).text() + ' <span class="caret"></span>');
793                 $(elm).closest(".dropdown").find('.btn').val($(elm).data('value'));
794                 $(elm).closest("ul").children("li").show();
795                 $(elm).parent("li").hide();
796 }
797
798 // Check if element does have a specific class
799 function hasClass(elem, cls) {
800         return (" " + elem.className + " " ).indexOf( " "+cls+" " ) > -1;
801 }