]> git.mxchange.org Git - friendica.git/blob - view/theme/frio/js/theme.js
Merge pull request #3147 from rebeka-catalina/vier_dark_item_links
[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 ul.tabbar").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 == true) {
87                         $("a#item-delete-selected").fadeTo(400, 1);
88                         $("a#item-delete-selected").show();
89                 } else {
90                         $("a#item-delete-selected").fadeTo(400, 0, function(){
91                                 $("a#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         });
111
112         // initialize the bootstrap-select
113         $('.selectpicker').selectpicker();
114
115         // add search-heading to the seccond navbar
116         if( $(".search-heading").length) {
117                 $(".search-heading").appendTo("#topbar-second > .container > #tabmenu");
118         }
119
120         // add search results heading to the second navbar
121         // and insert the search value to the top nav search input
122         if( $(".search-content-wrapper").length ) {
123                 // get the text of the heading (we catch the plain text because we don't
124                 // want to have a h4 heading in the navbar
125                 var searchText = $(".section-title-wrapper > h2").text();
126                 // insert the plain text in a <h4> heading and give it a class
127                 var newText = '<h4 class="search-heading">'+searchText+'</h4>';
128                 // append the new heading to the navbar
129                 $("#topbar-second > .container > #tabmenu").append(newText);
130
131                 // try to get the value of the original search input to insert it 
132                 // as value in the nav-search-input
133                 var searchValue = $("#search-wrapper .form-group-search input").val();
134
135                 // if the orignal search value isn't available use the location path as value
136                 if( typeof searchValue === "undefined") {
137                         // get the location path
138                         var urlPath = window.location.search
139                         // and split it up in its parts
140                         var splitPath = urlPath.split(/(\?search?=)(.*$)/);
141
142                         if(typeof splitPath[2] !== 'undefined') {
143                                 // decode the path (e.g to decode %40 to the character @)
144                                 var searchValue = decodeURIComponent(splitPath[2]);
145                         }
146                 }
147
148                 if( typeof searchValue !== "undefined") {
149                         $("#nav-search-input-field").val(searchValue);
150                 }
151         }
152
153         // move the "Save the search" button to the second navbar
154         $(".search-content-wrapper #search-save-form ").appendTo("#topbar-second > .container > #navbar-button");
155
156         // append the vcard-short-info to the second nav after passing the element
157         // with .fn (vcard username). Use scrollspy to get the scroll position.
158         if( $("aside .vcard .fn").length) {
159                 $(".vcard .fn").scrollspy({
160                         min: $(".vcard .fn").position().top - 50,
161                         onLeaveTop: function onLeave(element) {
162                                 $("#vcard-short-info").fadeOut(500, function () {
163                                         $("#vcard-short-info").appendTo("#vcard-short-info-wrapper");
164                                 });
165                         },
166                         onEnter: function(element) {
167                                 $("#vcard-short-info").appendTo("#nav-short-info");
168                                 $("#vcard-short-info").fadeIn(500);
169                         },
170                 });
171         }
172
173         // move the forum contact information of the network page into the second navbar
174         if( $(".network-content-wrapper > #viewcontact_wrapper-network").length) {
175                 // get the contact-wrapper element and append it to the second nav bar
176                 // Note: We need the first() element with this class since at the present time we
177                 // store also the js template information in the html code and thats why
178                 // there are two elements with this class but we don't want the js template
179                 $(".network-content-wrapper > #viewcontact_wrapper-network .contact-wrapper").first().appendTo("#nav-short-info");
180         }
181
182         // move heading from network stream to the second navbar nav-short-info section
183         if( $(".network-content-wrapper > .section-title-wrapper").length) {
184                 // get the heading element
185                 var heading = $(".network-content-wrapper > .section-title-wrapper > h2");
186                 // get the text of the heading
187                 var headingContent = heading.text();
188                 // create a new element with the content of the heading
189                 var newText = '<h4 class="heading" data-toggle="tooltip" title="'+headingContent+'">'+headingContent+'</h4>';
190                 // remove the old heading element
191                 heading.remove(),
192                 // put the new element to the second nav bar
193                 $("#topbar-second #nav-short-info").append(newText);
194         }
195
196         if( $(".community-content-wrapper").length) {
197                 // get the heading element
198                 var heading = $(".community-content-wrapper > h3").first();
199                 // get the text of the heading
200                 var headingContent = heading.text();
201                 // create a new element with the content of the heading
202                 var newText = '<h4 class="heading">'+headingContent+'</h4>';
203                 // remove the old heading element
204                 heading.remove(),
205                 // put the new element to the second nav bar
206                 $("#topbar-second > .container > #tabmenu").append(newText);
207         }
208
209         // Dropdown menus with the class "dropdown-head" will display the active tab
210         // as button text
211         $("body").on('click', '.dropdown-head .dropdown-menu li a', function(){
212                 $(this).closest(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
213                 $(this).closest(".dropdown").find('.btn').val($(this).data('value'));
214                 $(this).closest("ul").children("li").show();
215                 $(this).parent("li").hide();
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 });
260 //function commentOpenUI(obj, id) {
261 //      $(document).unbind( "click.commentOpen", handler );
262 //
263 //      var handler = function() {
264 //              if(obj.value == '{{$comment}}') {
265 //                      obj.value = '';
266 //                      $("#comment-edit-text-" + id).addClass("comment-edit-text-full").removeClass("comment-edit-text-empty");
267 //                      // Choose an arbitrary tab index that's greater than what we're using in jot (3 of them)
268 //                      // The submit button gets tabindex + 1
269 //                      $("#comment-edit-text-" + id).attr('tabindex','9');
270 //                      $("#comment-edit-submit-" + id).attr('tabindex','10');
271 //                      $("#comment-edit-submit-wrapper-" + id).show();
272 //              }
273 //      };
274 //
275 //      $(document).bind( "click.commentOpen", handler );
276 //}
277 //
278 //function commentCloseUI(obj, id) {
279 //      $(document).unbind( "click.commentClose", handler );
280 //
281 //      var handler = function() {
282 //              if(obj.value === '') {
283 //              obj.value = '{{$comment}}';
284 //                      $("#comment-edit-text-" + id).removeClass("comment-edit-text-full").addClass("comment-edit-text-empty");
285 //                      $("#comment-edit-text-" + id).removeAttr('tabindex');
286 //                      $("#comment-edit-submit-" + id).removeAttr('tabindex');
287 //                      $("#comment-edit-submit-wrapper-" + id).hide();
288 //              }
289 //      };
290 //
291 //      $(document).bind( "click.commentClose", handler );
292 //}
293
294 function openClose(theID) {
295         var elem = document.getElementById(theID);
296
297         if( $(elem).is(':visible')) {
298                 $(elem).slideUp(200);
299         }
300         else {
301                 $(elem).slideDown(200);
302         }
303 }
304
305 function showHide(theID) {
306         if(document.getElementById(theID).style.display == "block") {
307                 document.getElementById(theID).style.display = "none"
308         }
309         else {
310                 document.getElementById(theID).style.display = "block"
311         }
312 }
313
314
315 function showHideComments(id) {
316         if( $('#collapsed-comments-' + id).is(':visible')) {
317                 $('#collapsed-comments-' + id).slideUp();
318                 $('#hide-comments-' + id).html(window.showMore);
319                 $('#hide-comments-total-' + id).show();
320         }
321         else {
322                 $('#collapsed-comments-' + id).slideDown();
323                 $('#hide-comments-' + id).html(window.showFewer);
324                 $('#hide-comments-total-' + id).hide();
325         }
326 }
327
328
329 function justifyPhotos() {
330         justifiedGalleryActive = true;
331         $('#photo-album-contents').justifiedGallery({
332                 margins: 3,
333                 border: 0,
334                 sizeRangeSuffixes: {
335                         'lt100': '-2',
336                         'lt240': '-2',
337                         'lt320': '-2',
338                         'lt500': '',
339                         'lt640': '-1',
340                         'lt1024': '-0'
341                 }
342         }).on('jg.complete', function(e){ justifiedGalleryActive = false; });
343 }
344
345 function justifyPhotosAjax() {
346         justifiedGalleryActive = true;
347         $('#photo-album-contents').justifiedGallery('norewind').on('jg.complete', function(e){ justifiedGalleryActive = false; });
348 }
349
350 function loadScript(url, callback) {
351         // Adding the script tag to the head as suggested before
352         var head = document.getElementsByTagName('head')[0];
353         var script = document.createElement('script');
354         script.type = 'text/javascript';
355         script.src = url;
356
357         // Then bind the event to the callback function.
358         // There are several events for cross browser compatibility.
359         script.onreadystatechange = callback;
360         script.onload = callback;
361
362         // Fire the loading
363         head.appendChild(script);
364 }
365
366 function random_digits(digits) {
367         var rn = "";
368         var rnd = "";
369
370         for(var i = 0; i < digits; i++) {
371                 var rn = Math.round(Math.random() * (9));
372                 rnd += rn;
373         }
374
375         return rnd;
376 }
377
378 // Does we need a ? or a & to append values to a url
379 function qOrAmp(url) {
380         if(url.search('\\?') < 0) {
381                 return '?';
382         } else {
383                 return '&';
384         }
385 }
386
387 function contact_filter(item) {
388         // get the html content from the js template of the contact-wrapper
389         contact_tpl = unescape($(".javascript-template[rel=contact-template]").html());
390
391         var variables = {
392                         id:             item.id,
393                         name:           item.name,
394                         username:       item.username,
395                         thumb:          item.thumb,
396                         img_hover:      item.img_hover,
397                         edit_hover:     item.edit_hover,
398                         account_type:   item.account_type,
399                         photo_menu:     item.photo_menu,
400                         alt_text:       item.alt_text,
401                         dir_icon:       item.dir_icon,
402                         sparkle:        item.sparkle,
403                         itemurl:        item.itemurl,
404                         url:            item.url,
405                         network:        item.network,
406                         tags:           item.tags,
407                         details:        item.details,
408         };
409
410         // open a new jSmart instance with the template
411         var tpl = new jSmart (contact_tpl);
412
413         // replace the variable with the values
414         var html = tpl.fetch(variables);
415
416         return html;
417 }
418
419 function filter_replace(item) {
420
421         return item.name;
422 }
423
424 (function( $ ) {
425         $.fn.contact_filter = function(backend_url, typ, autosubmit, onselect) {
426                 if(typeof typ === 'undefined') typ = '';
427                 if(typeof autosubmit === 'undefined') autosubmit = false;
428
429                 // Autocomplete contacts
430                 contacts = {
431                         match: /(^)([^\n]+)$/,
432                         index: 2,
433                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
434                         replace: filter_replace,
435                         template: contact_filter,
436                 };
437
438                 this.attr('autocomplete','off');
439                 var a = this.textcomplete([contacts], {className:'accontacts', appendTo: '#contact-list'});
440
441                 a.on('textComplete:select', function(e, value, strategy) { $(".dropdown-menu.textcomplete-dropdown.media-list").show(); });
442         };
443 })( jQuery );
444
445
446 // current time in milliseconds, to send each request to make sure
447 // we 're not getting 304 response
448 function timeNow() {
449         return new Date().getTime();
450 }
451
452 String.prototype.normalizeLink = function () {
453         var ret = this.replace('https:', 'http:');
454         var ret = ret.replace('//www', '//');
455         return ret.rtrim();
456 };
457
458 function cleanContactUrl(url) {
459         var parts = parseUrl(url);
460
461         if(! ("scheme" in parts) || ! ("host" in parts)) {
462                 return url;
463         }
464
465         var newUrl =parts["scheme"] + "://" + parts["host"];
466
467         if("port" in parts) {
468                 newUrl += ":" + parts["port"];
469         }
470
471         if("path" in parts) {
472                 newUrl += parts["path"];
473         }
474
475 //      if(url != newUrl) {
476 //              console.log("Cleaned contact url " + url + " to " + newUrl);
477 //      }
478
479         return newUrl;
480 }
481
482 function parseUrl (str, component) { // eslint-disable-line camelcase
483         //       discuss at: http://locutusjs.io/php/parse_url/
484         //      original by: Steven Levithan (http://blog.stevenlevithan.com)
485         // reimplemented by: Brett Zamir (http://brett-zamir.me)
486         //         input by: Lorenzo Pisani
487         //         input by: Tony
488         //      improved by: Brett Zamir (http://brett-zamir.me)
489         //           note 1: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
490         //           note 1: blog post at http://blog.stevenlevithan.com/archives/parseuri
491         //           note 1: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
492         //           note 1: Does not replace invalid characters with '_' as in PHP,
493         //           note 1: nor does it return false with
494         //           note 1: a seriously malformed URL.
495         //           note 1: Besides function name, is essentially the same as parseUri as
496         //           note 1: well as our allowing
497         //           note 1: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
498         //        example 1: parse_url('http://user:pass@host/path?a=v#a')
499         //        returns 1: {scheme: 'http', host: 'host', user: 'user', pass: 'pass', path: '/path', query: 'a=v', fragment: 'a'}
500         //        example 2: parse_url('http://en.wikipedia.org/wiki/%22@%22_%28album%29')
501         //        returns 2: {scheme: 'http', host: 'en.wikipedia.org', path: '/wiki/%22@%22_%28album%29'}
502         //        example 3: parse_url('https://host.domain.tld/a@b.c/folder')
503         //        returns 3: {scheme: 'https', host: 'host.domain.tld', path: '/a@b.c/folder'}
504         //        example 4: parse_url('https://gooduser:secretpassword@www.example.com/a@b.c/folder?foo=bar')
505         //        returns 4: { scheme: 'https', host: 'www.example.com', path: '/a@b.c/folder', query: 'foo=bar', user: 'gooduser', pass: 'secretpassword' }
506
507         var query
508
509         var mode = (typeof require !== 'undefined' ? require('../info/ini_get')('locutus.parse_url.mode') : undefined) || 'php'
510
511         var key = [
512                 'source',
513                 'scheme',
514                 'authority',
515                 'userInfo',
516                 'user',
517                 'pass',
518                 'host',
519                 'port',
520                 'relative',
521                 'path',
522                 'directory',
523                 'file',
524                 'query',
525                 'fragment'
526         ]
527
528         // For loose we added one optional slash to post-scheme to catch file:/// (should restrict this)
529         var parser = {
530                 php: new RegExp([
531                         '(?:([^:\\/?#]+):)?',
532                         '(?:\\/\\/()(?:(?:()(?:([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?))?',
533                         '()',
534                         '(?:(()(?:(?:[^?#\\/]*\\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'
535                 ].join('')),
536                 strict: new RegExp([
537                         '(?:([^:\\/?#]+):)?',
538                         '(?:\\/\\/((?:(([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?))?',
539                         '((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'
540                 ].join('')),
541                 loose: new RegExp([
542                         '(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?',
543                         '(?:\\/\\/\\/?)?',
544                         '((?:(([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?)',
545                         '(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))',
546                         '(?:\\?([^#]*))?(?:#(.*))?)'
547                 ].join(''))
548         }
549
550         var m = parser[mode].exec(str)
551         var uri = {}
552         var i = 14
553
554         while (i--) {
555                 if (m[i]) {
556                         uri[key[i]] = m[i]
557                 }
558         }
559
560         if (component) {
561                 return uri[component.replace('PHP_URL_', '').toLowerCase()]
562         }
563
564         if (mode !== 'php') {
565                 var name = (typeof require !== 'undefined' ? require('../info/ini_get')('locutus.parse_url.queryKey') : undefined) || 'queryKey'
566                 parser = /(?:^|&)([^&=]*)=?([^&]*)/g
567                 uri[name] = {}
568                 query = uri[key[12]] || ''
569                 query.replace(parser, function ($0, $1, $2) {
570                         if ($1) {
571                                 uri[name][$1] = $2
572                         }
573                 })
574         }
575
576         delete uri.source
577         return uri
578 }
579
580 // trim function to replace whithespace after the string
581 String.prototype.rtrim = function() {
582         var trimmed = this.replace(/\s+$/g, '');
583         return trimmed;
584 };
585
586 // Scroll to a specific item and highlight it
587 // Note: jquery.color.js is needed
588 function scrollToItem(itemID) {
589         if( typeof itemID === "undefined")
590                 return;
591
592         var elm = $('#'+itemID);
593         // Test if the Item exists
594         if(!elm.length)
595                 return;
596
597         // Define the colors which are used for highlighting
598         var colWhite = {backgroundColor:'#F5F5F5'};
599         var colShiny = {backgroundColor:'#FFF176'};
600
601         // Get the Item Position (we need to substract 100 to match
602         // correct position
603         var itemPos = $(elm).offset().top - 100;
604
605         // Scroll to the DIV with the ID (GUID)
606         $('html, body').animate({
607                 scrollTop: itemPos
608         }, 400, function() {
609                 // Highlight post/commenent with ID  (GUID)
610                 $(elm).animate(colWhite, 1000).animate(colShiny).animate(colWhite, 600);
611         });
612 }
613
614 // format a html string to pure text
615 function htmlToText(htmlString) {
616         // Replace line breaks with spaces
617         var text = htmlString.replace(/<br>/g, ' ');
618         // Strip the text out of the html string
619         text = text.replace(/<[^>]*>/g, '');
620
621         return text;
622 }