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