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