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