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