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