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