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