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