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