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