]> git.mxchange.org Git - friendica.git/blob - view/theme/frio/js/theme.js
41a437de7d6a0fa4d802685add56475da033e0c2
[friendica.git] / view / theme / frio / js / theme.js
1
2 var jotcache = ''; //The jot cache. We use it as cache to restore old/original jot content
3
4 $(document).ready(function(){
5         //fade in/out based on scrollTop value
6         $(window).scroll(function () {
7                 if ($(this).scrollTop() > 1000) {
8                         $("#back-to-top").fadeIn();
9                 } else {
10                         $("#back-to-top").fadeOut();
11                 }
12         });
13
14         // scroll body to 0px on click
15         $("#back-to-top").click(function () {
16                 $("body,html").animate({
17                         scrollTop: 0
18                 }, 400);
19                 return false;
20         });
21
22         // add the class "selected" to group widges li if li > a does have the class group-selected
23         if( $("#sidebar-group-ul li a").hasClass("group-selected")) {
24                 $("#sidebar-group-ul li a.group-selected").parent("li").addClass("selected");
25         }
26
27         // add the class "selected" to forums widges li if li > a does have the class forum-selected
28         if( $("#forumlist-sidbar-ul li a").hasClass("forum-selected")) {
29                 $("#forumlist-sidbar-ul li a.forum-selected").parent("li").addClass("selected");
30         }
31
32         // add the class "active" to tabmenuli if li > a does have the class active
33         if( $("#tabmenu ul li a").hasClass("active")) {
34                 $("#tabmenu ul li a.active").parent("li").addClass("active");
35         }
36
37         // give select fields an boostrap classes
38         // @todo: this needs to be changed in friendica core
39         $(".field.select, .field.custom").addClass("form-group");
40         $(".field.select > select, .field.custom > select").addClass("form-control");
41
42         // move the tabbar to the second nav bar
43         $("section .tabbar-wrapper").first().appendTo("#topbar-second > .container > #tabmenu");
44
45         // add mask css url to the logo-img container
46         //
47         // This is for firefox - we use a mask which looks like the friendica logo to apply user collers
48         // to the friendica logo (the mask is in nav.tpl at the botom). To make it work we need to apply the
49         // correct url. The only way which comes to my mind was to do this with js
50         // So we apply the correct url (with the link to the id of the mask) after the page is loaded.
51         if($("#logo-img").length ) {
52                 var pageurl = "url('" + window.location.href + "#logo-mask')";
53                 $("#logo-img").css({"mask": pageurl});
54         }
55
56         // make responsive tabmenu with flexmenu.js
57         // the menupoints which doesn't fit in the second nav bar will moved to a
58         // dropdown menu. Look at common_tabs.tpl
59         $("ul.tabs.flex-nav").flexMenu({
60                 'cutoff': 2,
61                 'popupClass': "dropdown-menu pull-right",
62                 'popupAbsolute': false,
63                 'target': ".flex-target"
64         });
65
66         // add Jot botton to the scecond navbar
67         if( $("section #jotOpen").length ) {
68                 $("section #jotOpen").appendTo("#topbar-second > .container > #navbar-button");
69                 if( $("#jot-popup").is(":hidden")) $("#topbar-second > .container > #navbar-button #jotOpen").hide();
70         }
71
72         // show bulk deletion button at network page if checkbox is checked
73         $("body").change("input.item-select", function(){
74                 var checked = false;
75
76                 // We need to get all checked items, so it would close the delete button
77                 // if we uncheck one item and others are still checked.
78                 // So return checked = true if there is any checked item
79                 $('input.item-select').each( function() {
80                         if($(this).is(':checked')) {
81                                 checked = true;
82                                 return false;
83                         }
84                 });
85
86                 if(checked) {
87                         $("#item-delete-selected").fadeTo(400, 1);
88                         $("#item-delete-selected").show();
89                 } else {
90                         $("#item-delete-selected").fadeTo(400, 0, function(){
91                                 $("#item-delete-selected").hide();
92                         });
93                 }
94         });
95
96         //$('ul.flex-nav').flexMenu();
97
98         // initialize the bootstrap tooltips
99         $('body').tooltip({
100                 selector: '[data-toggle="tooltip"]',
101                 container: 'body',
102                 animation: true,
103                 html: true,
104                 placement: 'auto',
105                 trigger: 'hover',
106                 delay: {
107                         show: 500,
108                         hide: 100
109                 }
110         });
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, .dropdown-head .dropdown-menu li button', function(){
212                 toggleDropdownText(this);
213         });
214
215         /* setup onoff widgets */
216         // Add the correct class to the switcher according to the input
217         // value (On/Off)
218         $(".toggle input").each(function(){
219                 // Get the value of the input element
220                 val = $(this).val();
221                 id = $(this).attr("id");
222
223                 // The css classes for "on" and "off"
224                 onstyle = "btn-primary";
225                 offstyle = "btn-default off";
226
227                 // Add the correct class in dependence of input value (On/Off)
228                 toggleclass = (val == 0 ? offstyle : onstyle);
229                 $("#"+id+"_onoff").addClass(toggleclass);
230
231         });
232
233         // Change the css class while clicking on the switcher elements
234         $(".toggle label, .toggle .toggle-handle").click(function(event){
235                 event.preventDefault();
236                 // Get the value of the input element
237                 var input = $(this).siblings("input");
238                 var val = 1-input.val();
239                 var id = input.attr("id");
240
241                 // The css classes for "on" and "off"
242                 var onstyle = "btn-primary";
243                 var offstyle = "btn-default off";
244
245                 // According to the value of the input element we need to decide
246                 // which class need to be added and removed when changing the switch
247                 var removedclass = (val == 0 ? onstyle : offstyle);
248                 var addedclass = (val == 0 ? offstyle : onstyle)
249                 $("#"+id+"_onoff").addClass(addedclass).removeClass(removedclass);
250
251                 // After changing the switch the input element is getting
252                 // the newvalue
253                 input.val(val);
254         });
255
256         // Set the padding for input elements with inline buttons
257         //
258         // In Frio we use some input elements where the submit button is visually
259         // inside the the input field (through css). We need to set a padding-right
260         // to the input element where the padding value would be at least the width
261         // of the button. Otherwise long user input would be invisible because it is
262         // behind the button.
263         $("body").on('click', '.form-group-search > input', function() {
264                 // Get the width of the button (if the button isn't available
265                 // buttonWidth will be null
266                 var buttonWidth = $(this).next('.form-button-search').outerWidth();
267
268                 if (buttonWidth) {
269                         // Take the width of the button and ad 5px
270                         var newWidth = buttonWidth + 5;
271                         // Set the padding of the input element according
272                         // to the width of the button
273                         $(this).css('padding-right', newWidth);
274                 }
275
276         });
277
278         /*
279          * This event handler hides all comment UI when the user clicks anywhere on the page
280          * It ensures that we aren't closing the current comment box
281          *
282          * We are making an exception for buttons because of a race condition with the
283          * comment opening button that results in an already closed comment UI.
284          */
285         $(document).on('click', function(event) {
286                 if (event.target.type === 'button') {
287                         return true;
288                 }
289
290                 var $dontclosethis = $(event.target).closest('.wall-item-comment-wrapper').find('.comment-edit-form');
291                 $('.wall-item-comment-wrapper .comment-edit-submit-wrapper:visible').each(function() {
292                         var $parent = $(this).parent('.comment-edit-form');
293                         var itemId = $parent.data('itemId');
294
295                         if ($dontclosethis[0] != $parent[0]) {
296                                 var textarea = $parent.find('textarea').get(0)
297
298                                 commentCloseUI(textarea, itemId);
299                         }
300                 });
301         });
302
303         /*
304          * This event listeners ensures that the textarea size is updated event if the
305          * value is changed externally (textcomplete, insertFormatting, fbrowser...)
306          */
307         $(document).on('change', 'textarea', function(event) {
308                 autosize.update(event.target);
309         });
310 });
311
312 function openClose(theID) {
313         var elem = document.getElementById(theID);
314
315         if( $(elem).is(':visible')) {
316                 $(elem).slideUp(200);
317         }
318         else {
319                 $(elem).slideDown(200);
320         }
321 }
322
323 function showHide(theID) {
324         if(document.getElementById(theID).style.display == "block") {
325                 document.getElementById(theID).style.display = "none"
326         }
327         else {
328                 document.getElementById(theID).style.display = "block"
329         }
330 }
331
332
333 function showHideComments(id) {
334         if( $('#collapsed-comments-' + id).is(':visible')) {
335                 $('#collapsed-comments-' + id).slideUp();
336                 $('#hide-comments-' + id).html(window.showMore);
337                 $('#hide-comments-total-' + id).show();
338         }
339         else {
340                 $('#collapsed-comments-' + id).slideDown();
341                 $('#hide-comments-' + id).html(window.showFewer);
342                 $('#hide-comments-total-' + id).hide();
343         }
344 }
345
346
347 function justifyPhotos() {
348         justifiedGalleryActive = true;
349         $('#photo-album-contents').justifiedGallery({
350                 margins: 3,
351                 border: 0,
352                 sizeRangeSuffixes: {
353                         'lt100': '-2',
354                         'lt240': '-2',
355                         'lt320': '-2',
356                         'lt500': '',
357                         'lt640': '-1',
358                         'lt1024': '-0'
359                 }
360         }).on('jg.complete', function(e){ justifiedGalleryActive = false; });
361 }
362
363 function justifyPhotosAjax() {
364         justifiedGalleryActive = true;
365         $('#photo-album-contents').justifiedGallery('norewind').on('jg.complete', function(e){ justifiedGalleryActive = false; });
366 }
367
368 function loadScript(url, callback) {
369         // Adding the script tag to the head as suggested before
370         var head = document.getElementsByTagName('head')[0];
371         var script = document.createElement('script');
372         script.type = 'text/javascript';
373         script.src = url;
374
375         // Then bind the event to the callback function.
376         // There are several events for cross browser compatibility.
377         script.onreadystatechange = callback;
378         script.onload = callback;
379
380         // Fire the loading
381         head.appendChild(script);
382 }
383
384 function random_digits(digits) {
385         var rn = "";
386         var rnd = "";
387
388         for(var i = 0; i < digits; i++) {
389                 var rn = Math.round(Math.random() * (9));
390                 rnd += rn;
391         }
392
393         return rnd;
394 }
395
396 // Does we need a ? or a & to append values to a url
397 function qOrAmp(url) {
398         if(url.search('\\?') < 0) {
399                 return '?';
400         } else {
401                 return '&';
402         }
403 }
404
405 function contact_filter(item) {
406         // get the html content from the js template of the contact-wrapper
407         contact_tpl = unescape($(".javascript-template[rel=contact-template]").html());
408
409         var variables = {
410                         id:             item.id,
411                         name:           item.name,
412                         username:       item.username,
413                         thumb:          item.thumb,
414                         img_hover:      item.img_hover,
415                         edit_hover:     item.edit_hover,
416                         account_type:   item.account_type,
417                         photo_menu:     item.photo_menu,
418                         alt_text:       item.alt_text,
419                         dir_icon:       item.dir_icon,
420                         sparkle:        item.sparkle,
421                         itemurl:        item.itemurl,
422                         url:            item.url,
423                         network:        item.network,
424                         tags:           item.tags,
425                         details:        item.details,
426         };
427
428         // open a new jSmart instance with the template
429         var tpl = new jSmart (contact_tpl);
430
431         // replace the variable with the values
432         var html = tpl.fetch(variables);
433
434         return html;
435 }
436
437 function filter_replace(item) {
438
439         return item.name;
440 }
441
442 (function( $ ) {
443         $.fn.contact_filter = function(backend_url, typ, autosubmit, onselect) {
444                 if(typeof typ === 'undefined') typ = '';
445                 if(typeof autosubmit === 'undefined') autosubmit = false;
446
447                 // Autocomplete contacts
448                 contacts = {
449                         match: /(^)([^\n]+)$/,
450                         index: 2,
451                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
452                         replace: filter_replace,
453                         template: contact_filter,
454                 };
455
456                 this.attr('autocomplete','off');
457                 var a = this.textcomplete([contacts], {className:'accontacts', appendTo: '#contact-list'});
458
459                 a.on('textComplete:select', function(e, value, strategy) { $(".dropdown-menu.textcomplete-dropdown.media-list").show(); });
460         };
461 })( jQuery );
462
463
464 // current time in milliseconds, to send each request to make sure
465 // we 're not getting 304 response
466 function timeNow() {
467         return new Date().getTime();
468 }
469
470 String.prototype.normalizeLink = function () {
471         var ret = this.replace('https:', 'http:');
472         var ret = ret.replace('//www', '//');
473         return ret.rtrim();
474 };
475
476 function cleanContactUrl(url) {
477         var parts = parseUrl(url);
478
479         if(! ("scheme" in parts) || ! ("host" in parts)) {
480                 return url;
481         }
482
483         var newUrl =parts["scheme"] + "://" + parts["host"];
484
485         if("port" in parts) {
486                 newUrl += ":" + parts["port"];
487         }
488
489         if("path" in parts) {
490                 newUrl += parts["path"];
491         }
492
493 //      if(url != newUrl) {
494 //              console.log("Cleaned contact url " + url + " to " + newUrl);
495 //      }
496
497         return newUrl;
498 }
499
500 function parseUrl (str, component) { // eslint-disable-line camelcase
501         //       discuss at: http://locutusjs.io/php/parse_url/
502         //      original by: Steven Levithan (http://blog.stevenlevithan.com)
503         // reimplemented by: Brett Zamir (http://brett-zamir.me)
504         //         input by: Lorenzo Pisani
505         //         input by: Tony
506         //      improved by: Brett Zamir (http://brett-zamir.me)
507         //           note 1: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
508         //           note 1: blog post at http://blog.stevenlevithan.com/archives/parseuri
509         //           note 1: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
510         //           note 1: Does not replace invalid characters with '_' as in PHP,
511         //           note 1: nor does it return false with
512         //           note 1: a seriously malformed URL.
513         //           note 1: Besides function name, is essentially the same as parseUri as
514         //           note 1: well as our allowing
515         //           note 1: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
516         //        example 1: parse_url('http://user:pass@host/path?a=v#a')
517         //        returns 1: {scheme: 'http', host: 'host', user: 'user', pass: 'pass', path: '/path', query: 'a=v', fragment: 'a'}
518         //        example 2: parse_url('http://en.wikipedia.org/wiki/%22@%22_%28album%29')
519         //        returns 2: {scheme: 'http', host: 'en.wikipedia.org', path: '/wiki/%22@%22_%28album%29'}
520         //        example 3: parse_url('https://host.domain.tld/a@b.c/folder')
521         //        returns 3: {scheme: 'https', host: 'host.domain.tld', path: '/a@b.c/folder'}
522         //        example 4: parse_url('https://gooduser:secretpassword@www.example.com/a@b.c/folder?foo=bar')
523         //        returns 4: { scheme: 'https', host: 'www.example.com', path: '/a@b.c/folder', query: 'foo=bar', user: 'gooduser', pass: 'secretpassword' }
524
525         var query
526
527         var mode = (typeof require !== 'undefined' ? require('../info/ini_get')('locutus.parse_url.mode') : undefined) || 'php'
528
529         var key = [
530                 'source',
531                 'scheme',
532                 'authority',
533                 'userInfo',
534                 'user',
535                 'pass',
536                 'host',
537                 'port',
538                 'relative',
539                 'path',
540                 'directory',
541                 'file',
542                 'query',
543                 'fragment'
544         ]
545
546         // For loose we added one optional slash to post-scheme to catch file:/// (should restrict this)
547         var parser = {
548                 php: new RegExp([
549                         '(?:([^:\\/?#]+):)?',
550                         '(?:\\/\\/()(?:(?:()(?:([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?))?',
551                         '()',
552                         '(?:(()(?:(?:[^?#\\/]*\\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'
553                 ].join('')),
554                 strict: new RegExp([
555                         '(?:([^:\\/?#]+):)?',
556                         '(?:\\/\\/((?:(([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?))?',
557                         '((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'
558                 ].join('')),
559                 loose: new RegExp([
560                         '(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?',
561                         '(?:\\/\\/\\/?)?',
562                         '((?:(([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#]*)(?::(\\d*))?)',
563                         '(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))',
564                         '(?:\\?([^#]*))?(?:#(.*))?)'
565                 ].join(''))
566         }
567
568         var m = parser[mode].exec(str)
569         var uri = {}
570         var i = 14
571
572         while (i--) {
573                 if (m[i]) {
574                         uri[key[i]] = m[i]
575                 }
576         }
577
578         if (component) {
579                 return uri[component.replace('PHP_URL_', '').toLowerCase()]
580         }
581
582         if (mode !== 'php') {
583                 var name = (typeof require !== 'undefined' ? require('../info/ini_get')('locutus.parse_url.queryKey') : undefined) || 'queryKey'
584                 parser = /(?:^|&)([^&=]*)=?([^&]*)/g
585                 uri[name] = {}
586                 query = uri[key[12]] || ''
587                 query.replace(parser, function ($0, $1, $2) {
588                         if ($1) {
589                                 uri[name][$1] = $2
590                         }
591                 })
592         }
593
594         delete uri.source
595         return uri
596 }
597
598 // trim function to replace whithespace after the string
599 String.prototype.rtrim = function() {
600         var trimmed = this.replace(/\s+$/g, '');
601         return trimmed;
602 };
603
604 /**
605  * Scroll the screen to the item element whose id is provided, then highlights it
606  *
607  * Note: jquery.color.js is required
608  *
609  * @param {string} elementId The item element id
610  * @returns {undefined}
611  */
612 function scrollToItem(elementId) {
613         if (typeof elementId === "undefined") {
614                 return;
615         }
616
617         var $el = $(document.getElementById(elementId));
618         // Test if the Item exists
619         if (!$el.length) {
620                 return;
621         }
622
623         // Define the colors which are used for highlighting
624         var colWhite = {backgroundColor:'#F5F5F5'};
625         var colShiny = {backgroundColor:'#FFF176'};
626
627         // Get the Item Position (we need to substract 100 to match correct position
628         var itemPos = $el.offset().top - 100;
629
630         // Scroll to the DIV with the ID (GUID)
631         $('html, body').animate({
632                 scrollTop: itemPos
633         }, 400, function() {
634                 // Highlight post/commenent with ID  (GUID)
635                 $el.animate(colWhite, 1000).animate(colShiny).animate(colWhite, 600);
636         });
637 }
638
639 // format a html string to pure text
640 function htmlToText(htmlString) {
641         // Replace line breaks with spaces
642         var text = htmlString.replace(/<br>/g, ' ');
643         // Strip the text out of the html string
644         text = text.replace(/<[^>]*>/g, '');
645
646         return text;
647 }
648
649 /**
650  * Sends a /like API call and updates the display of the relevant action button
651  * before the update reloads the item.
652  *
653  * @param {string} ident The id of the relevant item
654  * @param {string} verb The verb of the action
655  * @returns {undefined}
656  */
657 function doLikeAction(ident, verb) {
658         unpause();
659
660         if (verb.indexOf('attend') === 0) {
661                 $('.item-' + ident + ' .button-event:not(#' + verb + '-' + ident + ')').removeClass('active');
662         }
663         $('#' + verb + '-' + ident).toggleClass('active');
664         $('#like-rotator-' + ident.toString()).show();
665         $.get('like/' + ident.toString() + '?verb=' + verb, NavUpdate );
666         liking = 1;
667         force_update = true;
668 }
669
670 // Decodes a hexadecimally encoded binary string
671 function hex2bin (s) {
672         //  discuss at: http://locutus.io/php/hex2bin/
673         // original by: Dumitru Uzun (http://duzun.me)
674         //   example 1: hex2bin('44696d61')
675         //   returns 1: 'Dima'
676         //   example 2: hex2bin('00')
677         //   returns 2: '\x00'
678         //   example 3: hex2bin('2f1q')
679         //   returns 3: false
680         var ret = [];
681         var i = 0;
682         var l;
683         s += '';
684
685         for (l = s.length; i < l; i += 2) {
686                 var c = parseInt(s.substr(i, 1), 16);
687                 var k = parseInt(s.substr(i + 1, 1), 16);
688                 if (isNaN(c) || isNaN(k)) {
689                         return false;
690                 }
691                 ret.push((c << 4) | k);
692         }
693         return String.fromCharCode.apply(String, ret);
694 }
695
696 // Convert binary data into hexadecimal representation
697 function bin2hex (s) {
698         // From: http://phpjs.org/functions
699         // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
700         // +   bugfixed by: Onno Marsman
701         // +   bugfixed by: Linuxworld
702         // +   improved by: ntoniazzi (http://phpjs.org/functions/bin2hex:361#comment_177616)
703         // *     example 1: bin2hex('Kev');
704         // *     returns 1: '4b6576'
705         // *     example 2: bin2hex(String.fromCharCode(0x00));
706         // *     returns 2: '00'
707
708         var i, l, o = "", n;
709
710         s += "";
711
712         for (i = 0, l = s.length; i < l; i++) {
713                 n = s.charCodeAt(i).toString(16);
714                 o += n.length < 2 ? "0" + n : n;
715         }
716
717         return o;
718 }
719
720 // Dropdown menus with the class "dropdown-head" will display the active tab
721 // as button text
722 function toggleDropdownText(elm) {
723                 $(elm).closest(".dropdown").find('.btn').html($(elm).text() + ' <span class="caret"></span>');
724                 $(elm).closest(".dropdown").find('.btn').val($(elm).data('value'));
725                 $(elm).closest("ul").children("li").show();
726                 $(elm).parent("li").hide();
727 }
728
729 // Check if element does have a specific class
730 function hasClass(elem, cls) {
731         return (" " + elem.className + " " ).indexOf( " "+cls+" " ) > -1;
732 }