My Function library

enter something useful

当前为 2017-08-17 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/9160/212447/My%20Function%20library.js

  1. /**
  2. * Created by Magnus Fohlström on 2016-09-24 at 22:56
  3. * with file name
  4. * in project TampermonkeyUserscripts.
  5. */
  6. "use strict";
  7. //// ==UserScript==
  8. // @name My Function library
  9. // @namespace http://use.i.E.your.homepage/
  10. // @version 0.51
  11. // @description enter something useful
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // @grant GM_deleteValue
  15. // @grant GM_listValues
  16. // @grant GM_xmlhttpRequest
  17. // @run-at document-start
  18.  
  19. // @created 2015-04-06
  20. // @released 2014-00-00
  21. // @updated 2014-00-00
  22. // @history @version 0.25 - first version: public@released - 2015-04-12
  23. // @history @version 0.30 - Second version: public@released - 2015-12-10
  24. // @history @version 0.35 - Second version: public@released - 2016-03-04
  25. // @history @version 0.45 - Second version: public@released - 2016-09-24
  26. // @history @version 0.45 - third version: public@released - 2017-01-10
  27. // @compatible Greasemonkey, Tampermonkey
  28. // @license GNU GPL v3 (http://www.gnu.org/copyleft/gpl.html)
  29. // @copyright 2014+, Magnus Fohlström
  30. // ==/UserScript==
  31. /*global $, jQuery*/
  32. /*jshint -W014, -W030, -W082*/
  33. // -W014, laxbreak, Bad line breaking before '+'
  34. // -W030, Expected assignment or function call instead saw an expression
  35. // -W082, a function declaration inside a block statement
  36.  
  37. /*
  38. $("li").not(function() {
  39. // returns true for those elements with at least one span as child element
  40. return $(this).children('span').length > 0
  41. }).each(function() { /* ... })
  42. */
  43. //noinspection JSUnresolvedFunction,JSUnresolvedVariable,BadExpressionStatementJS,JSPotentiallyInvalidConstructorUsage, JSPrimitiveTypeWrapperUsage
  44. //noinspection BadExpressionStatementJS,JSUnresolvedVariable,JSDeprecatedSymbols
  45. performance;
  46. var window = window, console = console;
  47. function setGM(window2) {
  48. window2 = window2 || window;
  49. console.log('setGM' );
  50. var localStorage = localStorage;
  51. window2.GM_getValue = function( key, def ){
  52. return localStorage[key] || def;
  53. };
  54. window2.GM_setValue = function( key, value ){
  55. localStorage[key] = value;
  56. };
  57. window2.GM_deleteValue = function( key ){
  58. delete localStorage[ key ];
  59. };
  60. window2.GM_listValues = function( ){
  61. return Object.keys( localStorage );
  62. };
  63. window2.GM_lister = function( remove, item ){
  64. var keys = GM_listValues(), i = 0, val;
  65. for ( i; i <= keys.length; i++ ) {
  66. val = keys[i];
  67. //noinspection JSUnresolvedVariable
  68. val !== undefined && (
  69. console.log( 'GM_ListItem: ' + val + ':', GM_getValue( val ) ),
  70. ( ( item !== undefined && val.inElem( item ) ) || item === undefined )
  71. && Boolean.parse( remove ) && GM_deleteValue( val ) );
  72. }
  73. };
  74. }
  75.  
  76. console.log('isFunction( GM_getValue() )', $.isFunction( window.GM_getValue ) );
  77.  
  78. !!$.isFunction( window.GM_getValue ) || setGM();
  79.  
  80. (function(){
  81.  
  82. var eventMatchers = {
  83. 'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
  84. 'MouseEvents': /^(?:click|mouse(?:down|up|over|move|enter|out))$/
  85. //'MouseEvents': /^(?:click|dblclick|hover|contextmenu|mouse(?:down|up|over|move|enter|leave|out))$/
  86. };
  87.  
  88. var defaultOptions = {
  89. pointerX: 0,
  90. pointerY: 0,
  91. button: 0,
  92. ctrlKey: false,
  93. altKey: false,
  94. shiftKey: false,
  95. metaKey: false,
  96. bubbles: true,
  97. cancelable: true
  98. };
  99.  
  100. jQuery.fn.simulate = function(eventName) {
  101. var element = this[0];
  102. var options = $.extend(true, defaultOptions, arguments[2] || { });
  103. var oEvent, eventType = null;
  104.  
  105. for (var name in eventMatchers) {
  106. if (eventMatchers[name].test(eventName)) { eventType = name; break; }
  107. }
  108.  
  109. if (!eventType)
  110. throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
  111. //noinspection JSUnresolvedVariable
  112. if (document.createEvent) {
  113. //noinspection JSUnresolvedFunction
  114. oEvent = document.createEvent(eventType);
  115. if (eventType == 'HTMLEvents') {
  116. oEvent.initEvent(eventName, options.bubbles, options.cancelable);
  117. }
  118. else {
  119. //noinspection JSDeprecatedSymbols,noinspection JSUnresolvedVariable
  120. oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
  121. options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
  122. options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
  123. }
  124. element.dispatchEvent(oEvent);
  125. }
  126. else {
  127. options.clientX = options.pointerX;
  128. options.clientY = options.pointerY;
  129. //noinspection JSUnresolvedFunction
  130. oEvent = $.extend(document.createEventObject(), options);
  131. element.fireEvent('on' + eventName, oEvent);
  132. }
  133. return element;
  134. };
  135. })();
  136.  
  137. /*window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
  138. console.debug('Error: ' + errorMsg + '\nScript: ' + url + '\nLine: ' + lineNumber
  139. + '\nColumn: ' + column + '\nStackTrace: ' + errorObj);
  140. };*/
  141. /**
  142. * @namespace waitUntilExists_Intervals
  143. */
  144. $.fn.waitUntilExists = function (handler, shouldRunHandlerOnce, isChild){
  145. var found = 'found',
  146. $this = $(this.selector),
  147. $elements = $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);
  148. if( !isChild ) {
  149. (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
  150. window.setInterval(function () {
  151. $this.waitUntilExists(
  152. handler, shouldRunHandlerOnce, true);
  153. }, 500);
  154. }
  155. else if (shouldRunHandlerOnce && $elements.length){
  156. window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
  157. }
  158. return $this;
  159. };
  160.  
  161. $.extend( $.easing,{
  162. easeOutBounceSmall : function(x, t, b, c, d) {
  163. var ts=(t/=d)*t;
  164. var tc=ts*t;
  165. return b+c*(-16.195*tc*ts + 49.935*ts*ts + -53.785*tc + 21.795*ts + -0.75*t);
  166. },
  167. easeOutSmoothBounce : function(x, t, b, c, d) {
  168. var ts=(t/=d)*t;
  169. var tc=ts*t;
  170. return b+c*(-19.4293*tc*ts + 53.3838*ts*ts + -49.8485*tc + 15.8081*ts + 1.08586*t);
  171. },
  172. easeInOutCubic : function(x, t, b, c, d) {
  173. if ((t/=d/2) < 1) return c/2*t*t*t + b;
  174. return c/2*((t-=2)*t*t + 2) + b;
  175. }
  176. });
  177.  
  178. $.extend( $.fn, {
  179. // Name of our method & one argument (the parent selector)
  180. /**
  181. * Suppress all rules containing "unused" in this
  182. * class
  183. *
  184. * @SuppressWarnings("unused")
  185. */
  186. //noinspection JSUnusedProperty
  187. within: function( pSelector ) {
  188. // Returns a subset of items using jQuery.filter
  189. return this.filter(function(){
  190. // Return truthy/falsey based on presence in parent
  191. return $(this).closest( pSelector ).length;
  192. });
  193. /* Example
  194. $("li").within(".x").css("background", "red");
  195.  
  196. This selects all list items on the document, and then filters to only
  197. those that have .x as an ancestor. Because this uses jQuery internally,
  198. you could pass in a more complicated selector:
  199.  
  200. $("li").within(".x, .y").css("background", "red");
  201.  
  202. http://stackoverflow.com/questions/2389540/jquery-hasparent
  203. http://stackoverflow.com/a/2389549
  204. */
  205. }
  206. });
  207. $.fn.extend({
  208. ifExists : function ( fn ) {
  209. this.length && fn( this );
  210. return this.length && this;
  211. /*
  212. $("#element").ifExists( function( $this ){
  213. $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
  214. });
  215. */
  216. }
  217. });
  218. $.fn.extend({
  219. exists : function () {
  220. return !!this.length;
  221. },
  222. Exists : function ( callback ) {
  223. var self = this;
  224. var wrapper = (function(){
  225. function notExists(){}
  226. //noinspection JSPotentiallyInvalidConstructorUsage
  227. notExists.prototype.ExistsNot = function( fallback ){
  228. !self.length && fallback.call(); };
  229. //noinspection JSPotentiallyInvalidConstructorUsage
  230. return new notExists;
  231. })();
  232. self.length && callback.call();
  233. return wrapper;
  234.  
  235. /* And now i can write code like this -
  236. $("#elem").Exists(function(){
  237. alert ("it exists");
  238. }).ExistsNot(function(){
  239. alert ("it doesn't exist");
  240. });
  241. */
  242. },
  243. ifExists : function ( fn ) {
  244. this.length && fn( this );
  245. return this.length && this;
  246. /*
  247. $("#element").ifExists( function( $this ){
  248. $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
  249. });
  250. */
  251. },
  252. iff : function ( bool, fn ) {
  253. ( bool && this.length || !bool && !this.length) && fn( this );
  254. return ( bool && this.length || !bool && !this.length ) && this;
  255. /*
  256. $("#element").if( true, function( $this ){);
  257. $("#element").if( false, function( $this ){);
  258. */
  259. },
  260. ifs : function ( fnTrue, fnFalse ) {
  261. fn( this.length ? fnTrue : fnFalse );
  262. /*
  263. $("#element").ifs( function( $this ){}, function( $this ){});
  264. */
  265. },
  266.  
  267. hasId : function ( id ) {
  268. return id === this.attr('id');
  269. },
  270. hasClasses : function ( classes, any ) {
  271. classes = classes.split( classes.inElem(',') ? ',' : ' ' );
  272. var check = 0, i = 0;
  273. for ( i; i < classes.length; i++ ) {
  274. this.hasClass( classes[ i ] ) && check++;
  275. if ( any !== undefined && check !== 0 ) return true;
  276. }
  277. return check === classes.length;
  278. },
  279. hasClassLongerThan : function ( length, addClass ) {
  280. var str = $( this ).addClass('å').attr('class'),
  281. classes = str.split( ' ' ),
  282. check = 0, i = 0;
  283.  
  284. for ( i; i < classes.length; i++ ) {
  285. check = classes[ i ].length >= length ? check++ : check;
  286. classes[ i ].length >= length && $( this ).addClass( addClass );
  287. $( this ).removeClass('å');
  288. }
  289. return check;
  290. },
  291. hasIdLongerThan : function ( length, addClass ) {
  292. var str = $( this ).hasAttr('id') ? $( this ).attr('id') : ' ', check = 0;
  293. check = str.length >= length ? check++ : check;
  294.  
  295. str.length >= length && $( this ).addClass( addClass );
  296.  
  297. return check;
  298. },
  299. hasAttrLength : function ( attar, length, addClass ) {
  300. var str = $( this ).attr( attar ),
  301. attribs = str.attr( attar, $( this ).attr( attar ) + ' ' ).split( ' ' ),
  302. check = 0, i = 0;
  303.  
  304. for ( i; i < attribs.length; i++ ) {
  305. check = attribs[ i ].length >= length ? check++ : check;
  306. //attribs[ i ].length >= length
  307. check && $( this ).addClass( addClass );
  308. }
  309. return check;
  310. },
  311. hasSiblings : function ( find ) {
  312. return !!$(this).siblings( find ).length;
  313. },
  314. hasNoChildren : function ( selection ) {
  315. return $( this ).filter( function(){
  316. return $( this ).children( selection ).length === 0;
  317. });
  318. },
  319. /* hasParent : function( parentSelection ){
  320. return parentSelection.inElem('#')
  321. ? this.parent().hasId( parentSelection.split('#').shift() )
  322. : this.parent().hasClass( parentSelection.split('.').shift() );
  323. },
  324. */
  325. hasAncestor : function ( Ancestor ) {
  326. return this.filter(function() {
  327. return !!$( this ).closest( Ancestor ).length;
  328. });
  329. //$('.element').hasAncestor('.container').myAction();
  330. },
  331. hasParent : function ( selection ) {
  332. return !!$( this ).parent( selection ).length;
  333. },
  334. hasParents : function ( selection ) {
  335. return !!$( this ).parents( selection ).length;
  336. },
  337. hasQuery : function ( query ) {
  338. return document.querySelector(query).length;
  339. },
  340. hasAttr : function ( name, val ) {
  341. var thisAttr = $( this ).attr( name );
  342. thisAttr =
  343. val !== undefined
  344. ? thisAttr === val
  345. : thisAttr;
  346. return ( typeof thisAttr !== "undefined" && thisAttr !== false && thisAttr !== null );
  347.  
  348. //return val !== undefined
  349. // ? attrName === val
  350. // : typeof( attrName ) !== 'undefined'; //$( this )[0].hasAttribute( name );
  351. },
  352.  
  353. isTag : function ( tag ) {
  354. var e = this[0] || $('<undefined/>'),
  355. nodename = e.nodeName;
  356. return nodename !== undefined && e.nodeName.toLowerCase() === tag.toLowerCase();
  357. },
  358. isNode : function ( node ) {
  359. var e = this[0] || $('<undefined/>'),
  360. nodename = e.nodeName;
  361. return nodename !== undefined && e.nodeName.toLowerCase() === node.toLowerCase();
  362. },
  363.  
  364. swapClass : function ( replace, newClass) {
  365. this.className.replace(replace, newClass);
  366. },
  367. toggleClasses : function ( add, remove, if_none) {
  368. var $this = $(this.selector);
  369. if_none !== undefined && !$this.hasClass(add) && !$this.hasClass(remove) && $this.addClass(if_none);
  370. $this.addClass(add).removeClass(remove);
  371. },
  372. searchAttr : function ( search, type, chkLen ) { //bool name value length or 1 2 3 4
  373. var Attributes = this[0].attributes;
  374.  
  375. if ( arguments.length === 0 ) {
  376. var obj = {};
  377. $.each( Attributes, function() {
  378. this.specified && ( obj[ this.name ] = this.value );
  379. });
  380. return obj;
  381. } else if( search != undefined ) {
  382. var name = '', val = '';
  383. $.each( Attributes, function() {
  384. if( this.specified && type == 'length' ) {
  385. if( this.name.length > chkLen ) {
  386. name = this.name;
  387. c.i('Attributes', Attributes);
  388. return false;
  389. }
  390. }
  391. else {
  392. if( this.specified && this.name.inElem( search ) ) {
  393. name = this.name;
  394. val = this.value;
  395. return false;
  396. }
  397. }
  398. });
  399. return ( type == 'bool' || type == 1 ) ? name.length :
  400. ( type == 'name' || type == 2 ) ? name :
  401. ( type == 'value' || type == 3 ) ? val :
  402. ( type == 'length' || type == 4 ) && name;
  403. }
  404. },
  405. findClass : function ( Class ) {
  406. return this.find('.' + Class);
  407. },
  408. findNextSibling : function ( thisSelector, bool ) {
  409. bool = bool || true;
  410. return bool ? this.eq(0).nextAll( thisSelector ).eq(0) : this.nextAll( thisSelector ).eq(0) ;
  411. },
  412. findPrevSibling : function ( thisSelector, bool ) {
  413. bool = bool || true;
  414. return bool ? this.eq(0).prevAll( thisSelector ).eq(0) : this.prevAll( thisSelector ).eq(0) ;
  415. },
  416.  
  417. nthChildClass: function(expr) {
  418. return this.filter(':nth-child('+ expr +')');
  419. },
  420.  
  421. href : function ( newURL ) {
  422. return arguments.length === 0 ? this.attr('href') : this.attr('href', newURL);
  423. },
  424. src : function ( newSRC ) {
  425. return arguments.length === 0 ? this.attr('src') : this.attr('src', newSRC);
  426. },
  427.  
  428. refreshElement : function ( speed, parentBoolean ) {
  429. var $elem = parentBoolean ? this.parent() : this, data = $elem.html();
  430. $elem.hide( speed / 2 ).empty().html( data ).fadeIn( speed );
  431. },
  432. replaceElementOld : function ( newTagName, addAttr ) {
  433.  
  434. function stringifyAttr( attrs ){
  435. var attrString = '', newAttr = addAttr || '';
  436. $.each( attrs, function( index ){
  437. attrString += ' ' + attrs[ index ].name + '="' + attrs[ index ].value + '"';
  438. });
  439. return newAttr.length ? attrString + ' ' + newAttr : attrString;
  440. }
  441.  
  442. $( this ).each(function(){
  443. var attributes = stringifyAttr( this.attributes ),
  444. StartTag = '<' + newTagName + attributes +'>',
  445. EndTag = '</' + newTagName + '>';
  446. $( this ).replaceWith( StartTag + $( this ).html() + EndTag );
  447. });
  448. },
  449. replaceElement : function ( newNodeName, htmlElement ) {
  450.  
  451. newNodeName = $('<'+ newNodeName +'/>');
  452. htmlElement = htmlElement !== undefined ? htmlElement : $('<span/>',{ 'data-tmp':'TemparyAttribute'});
  453.  
  454. function newElem_addAttr( attrs, newAttr, newElem ){
  455. $.each( attrs, function( index ){
  456. newElem.attr( attrs[ index ].name, attrs[ index ].value ); });
  457. $.each( newAttr, function( index ){
  458. newElem.attr( newAttr[ index ].name, newAttr[ index ].value ); });
  459. return newElem;
  460. }
  461.  
  462. $( this ).each(function(){
  463. $( this ).replaceWith( newElem_addAttr(
  464. this.attributes, htmlElement[0].attributes, newNodeName ).html( $( this ).html() ).removeAttr('data-tmp') );
  465. });
  466.  
  467. return this;
  468. },
  469.  
  470. equals : function ( compareTo ) {
  471. if (!compareTo || this.length != compareTo.length)
  472. return false;
  473.  
  474. for (var i = 0; i < this.length; ++i) {
  475. if (this[i] !== compareTo[i])
  476. return false;
  477. }
  478. return true;
  479. },
  480.  
  481. justText : function ( newText, prepend ) {
  482. var $children = null,
  483. placement = prepend === undefined ? 'prepend':'append';
  484. if ( newText ) {
  485. $children = $( this )
  486. .children()
  487. .clone();
  488. $( this )
  489. .children()
  490. .remove()
  491. .end()
  492. .text( newText )
  493. [ placement ]( $children );
  494. return $(this);
  495. }
  496. else {
  497. return $.trim( $( this )
  498. .clone()
  499. .children()
  500. .remove()
  501. .end()
  502. .text());
  503. }
  504. },
  505. uncomment : function ( recurse ) {
  506. //<!-- hidden --> // this will reveal, whats inside. In this case it will bi the word hidden
  507. $( this ).contents().each(function() {
  508. if ( recurse && this.hasChildNodes() ) {
  509. $( this ).uncomment(recurse);
  510. } else {
  511. if ( this.nodeType == 8 ) {
  512. // Need to "evaluate" the HTML content,
  513. // otherwise simple text won't replace
  514. var e = $('<span>' + this.nodeValue + '</span>');
  515. $( this ).replaceWith( e.contents() );
  516. }
  517. }
  518. });
  519. // $('#uncomment').uncomment( true );
  520. // http://stackoverflow.com/a/22439787
  521. },
  522. getComment : function ( getValue ) {
  523. var COMMENT_NODE = this.contents().filter(function(){
  524. return this.nodeType == Node.COMMENT_NODE;
  525. });
  526. return getValue
  527. ? COMMENT_NODE.each(function(){
  528. return $( this ).nodeValue.str2html(); })
  529. : COMMENT_NODE;
  530. },
  531. getURL : function ( url, how ) {
  532. //$.get('defaultComp/foot.html', function(dataContent) {$('#foot').replaceWith(dataContent); });
  533. how = how || 'html';
  534. var that = this;
  535. $.get( url, function(dataContent) {
  536. $(that)[ how ](dataContent);
  537. });
  538. return this;
  539. },
  540.  
  541. scrollTuneAdv : function ( opt ){
  542. // $("body").scrollTune({ pps: 1700, pageY: config.pageY, easing:'easeOutSmoothBounce', hsc: true }).promise()
  543. // .done( function() { setTimeout(function(){ toggleClassState( config, 'fullPlayer', type ); },100); })
  544. console.log('scrollTune');
  545.  
  546. var position,
  547. defaults = {
  548. tune: 0,
  549. speed: 0,
  550. pps: false, // pixel per second
  551. ppsM: 1000,
  552. pageYmini: 0,
  553. pageY: false, //{ pps: 300, pageY: event.pageY }
  554. hsc: false, // height speed compensation
  555. animate: false,
  556. // require http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js or jQueryUI - if other than ' swing or linear '
  557. easing: "easeInOutCubic", // easeInOutCubic easeInOutQuad easeInOutElastic http://easings.net/
  558. delay: 0,
  559. varStore: '',
  560. varAltStore:false,
  561. name: false,
  562. start: false,
  563. startTime: 0,
  564. step: false,
  565. stepTime: 0,
  566. complete: false,
  567. completeTime: 0,
  568. done: false,
  569. doneTime: 0,
  570. goTo: $('body')
  571. },
  572. heightSpeedComp = function(){
  573. return opt.hsc ? 1 + ( ( $(document).height() / opt.pageY ) / 1.4 ) : 1 ;
  574. },
  575. varStore = function( action, step ){
  576. (console.log(action,step),
  577. opt.name !== false
  578. ? opt.varAltStore !== false
  579. ? ( console.log('Store'), opt.varAltStore[opt.name][ action ](step) )
  580. : ( console.log('Store false'), opt.name[ action ](step) )
  581. : opt.pageYmini < opt.pageY || opt.varStore === config
  582. ? ( console.log('config'), opt.varStore[ action ](step) )
  583. : ( console.log('config false'), opt.varStore(step) ));
  584. };
  585. console.log('opt.pageY',opt.pageY);
  586. opt = $.extend( {}, defaults, opt );
  587. position = ( $( this ).offset().top + opt.tune ) + 'px';
  588.  
  589. opt.pps !== false || opt.animate !== false || ( typeof opt.speed === 'string' ? opt.speed.length !== 0 : opt.speed !== 0 )
  590. ? (
  591. opt.speed = opt.pps !== false ? parseInt( ( opt.pageY / opt.pps * heightSpeedComp() ) * opt.ppsM ) : opt.speed,
  592. opt.goTo.delay( opt.delay ).animate(
  593. { scrollTop : position },
  594. { duration : opt.speed, easing: opt.easing,
  595. start : function(){
  596. opt.start && setTimeout(function(){
  597. varStore('start');
  598. }, opt.startTime );
  599. },
  600. step : function(i){
  601. opt.step && setTimeout(function(){
  602. varStore('step',i);
  603. }, opt.stepTime );
  604. },
  605. complete : function(){
  606. opt.complete && setTimeout(function(){
  607. varStore('complete');
  608. }, opt.completeTime );
  609. },
  610. done : function(){
  611. opt.done && setTimeout(function(){
  612. varStore('done');
  613. }, opt.doneTime );
  614. }
  615. }
  616. )
  617. )
  618. : opt.goTo.scrollTop( position );
  619.  
  620. return this; // for chaining...
  621.  
  622. },
  623. scrollTuneNew : function ( opt ){
  624. var defaultOptions = {
  625. tune: 0,
  626. speed: 512,
  627. animate: true,
  628. easing: 'swing',
  629. goTo: $('html, body')
  630. },
  631. element = $( this ),
  632. options = $.extend({}, defaultOptions, $.fn.scrollTuneNew.changeDefaults, opt ),
  633. position = ( element.offset().top + options.tune ) + 'px';
  634.  
  635. options.animate
  636. ? options.goTo.animate({ scrollTop: position }, options.speed, options.easing )
  637. : options.goTo.scrollTop( position );
  638.  
  639. return element; // for chaining...
  640. },
  641. simulateMouseEvent : function ( MouseEvents ){
  642. var $this = this[0], evt,
  643. mEvent = MouseEvents || 'click';
  644. //noinspection JSUnresolvedVariable, noinspection JSUnresolvedFunction
  645. document.createEvent
  646. //noinspection JSUnresolvedFunction
  647. ? ( evt = document.MouseEvents('MouseEvents'),
  648. //evt.initCustomEvent(type, bubbles, cancelable, detail)
  649. //evt.initCustomEvent("MyEventType", true, true, "Any Object Here");
  650. evt.initEvent(mEvent, true, false),
  651. $this.dispatchEvent(evt) )
  652.  
  653. : //noinspection JSUnresolvedFunction
  654. document.createEventObject
  655. ? $this.fireEvent('onclick')
  656. : typeof node['on' + mEvent] == 'function' && $this['on' + mEvent]();
  657. },
  658. simulateMouse : function ( typeOfEvent ){
  659. var $this = this[0],
  660. evt = document.createEvent("MouseEvents"),
  661. mEvent = typeOfEvent || 'click';
  662. //noinspection JSDeprecatedSymbols
  663. evt.initMouseEvent( mEvent, true, true, $this.ownerDocument.defaultView,
  664. 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  665. $this !== undefined && $this.dispatchEvent(evt);
  666. return this;
  667. },
  668. simulateMouseAdv : function ( typeOfEvent, options ){
  669.  
  670. var target = this[0],
  671. event = document.createEvent("MouseEvents"),
  672. defaults = {
  673. mButton : 'left',
  674. type : typeOfEvent || 'click',
  675. canBubble : true,
  676. cancelable : true,
  677. view : target.ownerDocument.defaultView, //window, //
  678. detail : 1,
  679. screenX : 0, //The coordinates within the entire page
  680. screenY : 0,
  681. clientX : 0, //The coordinates within the viewport
  682. clientY : 0,
  683. ctrlKey : false,
  684. altKey : false,
  685. shiftKey : false,
  686. metaKey : false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
  687. button : 0, //0 = left, 1 = middle, 2 = right
  688. relatedTarget : null
  689. },
  690. opts = $.extend({}, defaults, $.fn.simulateMouseAdv.changeDefaults, options ),
  691. oButton = {
  692. left:0, middle:1, right:2
  693. };
  694.  
  695. console.log('oButton', opts.mButton );
  696. opts.button = oButton[ opts.mButton ];
  697.  
  698. //Pass in the options
  699. //noinspection JSDeprecatedSymbols
  700. event.initMouseEvent(
  701. opts.type,
  702. opts.canBubble,
  703. opts.cancelable,
  704. opts.view,
  705. opts.detail,
  706. opts.screenX,
  707. opts.screenY,
  708. opts.clientX,
  709. opts.clientY,
  710. opts.ctrlKey,
  711. opts.altKey,
  712. opts.shiftKey,
  713. opts.metaKey,
  714. opts.button,
  715. opts.relatedTarget
  716. );
  717.  
  718. //Fire the event
  719. target.dispatchEvent(event);
  720. },
  721.  
  722. thisCompStyle : function ( cssStyle ) {
  723. return cssStyle !== undefined ? this.getComputedStyle().getPropertyValue( cssStyle ) : this.getComputedStyle();
  724. },
  725. hasEvent : function ( event ) {
  726. var eventHandlerType;
  727. $( this ).on( event, clickEventHandler ).triggerHandler( event );
  728. function clickEventHandler( e ) {
  729. eventHandlerType = e.type;
  730. }
  731. return eventHandlerType === event;
  732. },
  733. qUnWrap : function (){
  734. $( this ).find(':first-child').unwrap();
  735. },
  736. designMode : function ( state, contenteditable ) {
  737. state = ( state === true || state === 1 || state === 'on' ) ? 'on' :
  738. ( state === false || state === 0 || state === 'off' ) && 'off';
  739. contenteditable = contenteditable || 'off';
  740. contenteditable !== 'off'
  741. ? contenteditable === 'document'
  742. ? document.designMode = state
  743. : contenteditable
  744. ? this.attr('contenteditable', true)
  745. : this.removeAttr('contenteditable')
  746. : this.contentWindow.document.designMode = state;
  747. },
  748. getThisComputedStyle : function ( style ) {
  749. return window.getComputedStyle( $(this), null ).getPropertyValue( style );
  750. }
  751. });
  752. function getTheStyle(){
  753. var elem = document.getElementById("elem-container");
  754. var theCSSprop;
  755. theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("height");
  756. document.getElementById("output").innerHTML = theCSSprop;
  757. }
  758. //$.fn.scrollTune.changeDefault = {};
  759.  
  760. $.extend({
  761. confirm: function (title, message, yesText, noText, yesCallback) {
  762. //dialog needs jQueryUI
  763. /*
  764. $.confirm(
  765. "CONFIRM", //title
  766. "Delete " + filename + "?", //message
  767. "Delete", //button text
  768. deleteOk //"yes" callback
  769. );
  770. */
  771. $("<div></div>").dialog( {
  772. buttons: [{
  773. text: yesText,
  774. click: function() {
  775. yesCallback();
  776. $( this ).remove();
  777. }
  778. },
  779. {
  780. text: noText,
  781. click: function() {
  782. $( this ).remove();
  783. }
  784. }
  785. ],
  786. close: function (event, ui) { $(this).remove(); },
  787. resizable: false,
  788. title: title,
  789. modal: true
  790. }).text(message).parent().addClass("alert");
  791. }
  792. });
  793.  
  794. $.extend( $.expr[":"], {
  795. ldata: function(el, idx, selector) {
  796. var attr = selector[3].split(", ");
  797. return el.dataset[attr[0]] === attr[1];
  798. },
  799. value: function(el, idx, selector) {
  800. return el.value === selector[selector.length - 1];
  801. },
  802. isEmptyTrimmed: function(el){
  803. return !$.trim($(el).html());
  804. },
  805. lengthBetween: function(elem, i, match) {
  806. var params = match[3].split(","); //split our parameter string by commas
  807. var elemLen = $(elem).val().length; //cache current element length
  808. return ((elemLen >= params[0] - 0) && (elemLen <= params[1] - 0)); //perform our check
  809. },
  810. data: $.expr.createPseudo
  811. ? $.expr.createPseudo(function( dataName ) {
  812. return function( elem ) {
  813. return !!$.data( elem, dataName );
  814. };
  815. })
  816. // support: jQuery <1.8
  817. : function( elem, i, match ) {
  818. return !!$.data( elem, match[ 3 ] );
  819. }
  820. });
  821. $.extend( $.expr[":"], {
  822. 'nth-class': function(elem, index, match) {
  823. return $(elem).is(':nth-child('+ match[3] +')');
  824. },
  825. 'nth-last-class': function(elem, index, match) {
  826. return $(elem).is(':nth-last-child('+ match[3] +')');
  827. },
  828. 'nth-class-of-type': function(elem, index, match) {
  829. return $(elem).is(':nth-of-type('+ match[3] +')');
  830. },
  831. 'nth-last-class-of-type': function(elem, index, match) {
  832. return $(elem).is(':nth-last-of-type('+ match[3] +')');
  833. },
  834. 'only-class-of-type': function(elem, index, match) {
  835. return $(elem).is(':first-of-type');
  836. },
  837. 'first-class-of-type': function(elem, index, match) {
  838. return $(elem).is(':first-of-type');
  839. },
  840. 'last-class-of-type': function(elem, index, match) {
  841. return $(elem).is(':last-of-type');
  842. },
  843. 'first-class': function(elem, index, match) {
  844. return $(elem).is(':first-child');
  845. },
  846. 'last-class': function(elem, index, match) {
  847. return $(elem).is(':last-child');
  848. },
  849. 'has': function(elem, index, match) {
  850. return $(elem).has( match[3] );
  851. },
  852. 'nth-class-leftOver' : function(elem, index, match, array){
  853. var elemLen = $(elem).length,
  854. div = index % match[3],
  855. indexLT = ( ( $(elem).length % match[3] === 0 ) * match[3] ) + 1;
  856.  
  857. var N= document.getElementsByTagName('*');
  858. c.i('indexOf',Array.prototype.indexOf.call(elem, $(elem).parent()));
  859.  
  860. c.i('elem.eq', $(elem).eq( ));
  861. c.i('elem', $(elem));
  862. c.i('elemLen', elemLen);
  863. c.i('index', index);
  864. c.i('div', div);
  865. c.i('indexLT', indexLT);
  866. return $(elem).is(':lt(' + indexLT + ')');
  867. //return $(elem).lt( ( ( $(elem).length % match[3] === 0 ) * match[3] ) + 1 );
  868. },
  869. external: function(element,index,match) {
  870. if(!element.href) {return false;}
  871. return element.hostname && match[3] !== undefined || false
  872. ? element.hostname !== window.location.hostname
  873. && element.hostname.search( match[3] ) === window.location.hostname.search( match[3] )
  874. : element.hostname !== window.location.hostname;
  875. },
  876. inView: function(element) {
  877. var st = (document.documentElement.scrollTop || document.body.scrollTop),
  878. ot = $(element).offset().top,
  879. wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();
  880. return ot > st && ($(element).height() + ot) < (st + wh);
  881. },
  882. width: function(element,index,match) {
  883. // Usage: $('div:width(>200)'); // Select all DIVs that have a width greater than 200px
  884. // Alternative usage: ('div:width(>200):width(<300)');
  885. if(!match[3]||!(/^(<|>)d+$/).test(match[3])) {return false;}
  886. return match[3].substr(0,1) === '>' ?
  887. $(element).width() > match[3].substr(1) : $(element).width() < match[3].substr(1);
  888. },
  889. containsNC: function(elem, i, match, array) {
  890. return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
  891. },
  892. containsExact: function( element, index, details, collection ){
  893. return $(element).text() === details[3];
  894. }
  895.  
  896. });
  897.  
  898. jQuery.expr[":"].Contains = $.expr.createPseudo(function(selector) {
  899. return function( elem ) {
  900. return jQuery(elem).text().toUpperCase().indexOf(selector.toUpperCase()) >= 0;
  901. };
  902. });
  903. jQuery.expr[':']['new-nth-class'] = function(elem, index, match) {
  904. return $(elem).is(':nth-child('+ match[3] +')');
  905. };
  906. jQuery.expr[':']['new-nth-class'] = $.expr.createPseudo( function( matchSelection ) {
  907. return function( elem ) {
  908. return $(elem).is(':nth-child('+ matchSelection +')');
  909. };
  910. });
  911.  
  912. $.isInArray = function( item, array ) {
  913. return !!~$.inArray(item, array);
  914. };
  915. $.allVar = function( array, value, all, atLeast ) {
  916. var count = 0,
  917. arrLength = array.length,
  918. isBool = typeof value === 'boolean';
  919.  
  920. $.each( array, function( i, e ){
  921. value === ( isBool ? !!e : e ) && count++;
  922. });
  923.  
  924. return all ? count === arrLength : count >= atLeast;
  925. };
  926. /*
  927. Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
  928. //$( selector ).get(0).playing;
  929. get: function(){
  930. return !!( this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2 );
  931. }
  932. });
  933. */
  934. /* Object.prototype.hasAttribute = function( attrName, val ){
  935. var thisAttr =
  936. this.attr
  937. ? val !== undefined
  938. ? this.attr( attrName ) === val
  939. : this.attr( attrName )
  940. : this.getAttribute( attrName );
  941. return ( typeof thisAttr !== "undefined" && thisAttr !== false && thisAttr !== null );
  942. };
  943. */
  944. Array.prototype.findArrayObj = function( findKey, exactValue ){
  945. return $.grep( this, function( obj ){
  946. return obj[ findKey ] === exactValue;
  947. })[0];
  948. //This prototype doesn't modify the array,
  949. // it gets the element that contains key with correct value and
  950. // the returns that element
  951. };
  952. Array.prototype.removeArrayObj = function( findKey, exactValue ){
  953. //my own example test: http://jsfiddle.net/aPH7m/82/
  954. //This prototype doesn't modify the array, needs to be overwritten or put into new var array
  955. return $.grep( this, function( obj ) {
  956. return obj[ findKey ] !== exactValue;
  957. });
  958. };
  959. Array.prototype.addKeyToArrayObj = function( findKey, exactValue, newKey, newValue ){
  960. return $.grep( this, function( obj ){
  961. return obj[ findKey ] === exactValue ? obj[ newKey ] = newValue : obj[ findKey ] !== exactValue;
  962. });
  963. // This prototype doesn't modify the array,
  964. // it gets the element that contains key with correct value and
  965. // adds a new key with its value to that element
  966. };
  967.  
  968. Array.prototype.filterArrayObj = function( doWhat, findKey, exactValue, newKey, newValue ){
  969. return doWhat === 'remove'
  970. ? this.filter(function( obj ) {
  971. return obj[ findKey ] !== exactValue;
  972. })
  973. : doWhat === 'addKey'
  974. ? this.filter(function( obj ){
  975. return obj[ findKey ] === exactValue
  976. ? obj[ newKey ] = newValue
  977. : obj[ findKey ] !== exactValue;
  978. })
  979. : doWhat === 'find'
  980. && this.filter(function( obj ){
  981. return obj[ findKey ] === exactValue;
  982. })[0];
  983. };
  984. Array.prototype.grepArrayObj = function( doWhat, idKey, uniqueValue, theKey, theValue ){
  985. doWhat = doWhat === 'updateKey' ? 'addKey' : doWhat;
  986. return doWhat === 'remove'
  987. ? $.grep( this, function( obj ){
  988. return obj[ idKey ] !== uniqueValue;
  989. })
  990. : doWhat === 'addKey'
  991. ? $.grep( this, function( obj ){
  992. return obj[ idKey ] === uniqueValue
  993. ? (
  994. obj[ theKey ] = theValue,
  995. obj[ idKey ] === uniqueValue
  996. )
  997. : obj[ idKey ] !== uniqueValue;
  998. })
  999. : doWhat === 'find'
  1000. ? $.grep( this, function( obj ){
  1001. return obj[ idKey ] === uniqueValue;
  1002. })[0]
  1003. : doWhat === 'deleteKey'
  1004. && $.grep( this, function( obj ){
  1005. return obj[ idKey ] === uniqueValue
  1006. ? (
  1007. delete obj[ theKey ],
  1008. obj[ idKey ] === uniqueValue
  1009. )
  1010. : obj[ idKey ] !== uniqueValue;
  1011. });
  1012. };
  1013. /*Array.prototype.sortObjArray = function( key, reverse ){
  1014. this.sort(function(a, b){
  1015. return ( reverse || false ) ? b[key] - a[key] : a[key] - b[key];
  1016. })
  1017. };*/
  1018.  
  1019. //noinspection JSPrimitiveTypeWrapperUsage
  1020. Boolean.parse = function(val) {
  1021. // http://stackoverflow.com/a/24744599
  1022. var falsely = /^(?:f(?:alse)?|no?|0+)$/i;
  1023. return !falsely.test(val) && !!val;
  1024. };
  1025.  
  1026.  
  1027. /*
  1028. Object.prototype.isObjectType = function( type, showType ){ //"[object Number]"
  1029. var objectString = Object.prototype.toString.call( this );
  1030. return showType === 'show' ? objectString :
  1031. showType === 'exact' ? objectString === type :
  1032. showType === 'search' && objectString.toLowerCase().inElem( type.toLowerCase() );
  1033. };
  1034.  
  1035. Object.defineProperty(String.prototype, "_defineBool", {
  1036. //myBool.toString()._defineBool()
  1037. get : function() {
  1038. var falsely = /^(?:f(?:alse)?|no?|off?|n?|failure?|sudumoo?|0+)$/i,
  1039. truely = /^(?:t(?:rue)?|yes?|on?|y?|success?|yabbdoo?|1+)$/i,
  1040. stateBool = !!this;
  1041.  
  1042. return ( truely.test( this ) === stateBool ) ? true : ( falsely.test( this ) === stateBool ) ? false : !isNaN(parseFloat( this )) && isFinite( this ) ? true : null;
  1043. }
  1044. });
  1045. Object.prototype.obj2Str = function( obj ){
  1046. var objArr = $.makeArray( obj );
  1047. return objArr[0].outerHTML;
  1048. };
  1049. */
  1050. String.prototype.splitEvery = function( splitter, every ){
  1051. var array = this.split( splitter ), returnString = '';
  1052. $.each( array, function( index, elem ){
  1053. returnString += elem + ( index < array.length - 1 || index % every === 0 ) ? '' : splitter;
  1054. });
  1055. return returnString;
  1056. };
  1057. String.prototype.advSplit = function( chr, nbr ){
  1058. var str = this.split(chr),
  1059. strLen = str.length,
  1060. chrLen = chr.length,
  1061. returnStr = ['',''],
  1062. newArr = [];
  1063.  
  1064. $.each( str, function( index ){
  1065. returnStr[ index < nbr ? 0 : 1 ] += str[ index ] + chr;
  1066. });
  1067.  
  1068. $.each( returnStr, function( index ){
  1069. returnStr[ index ] = returnStr[ index ].slice(0, - chrLen);
  1070. returnStr[ index ].length > 0 && newArr.push( returnStr[ index] );
  1071. });
  1072.  
  1073. return newArr;
  1074. };
  1075. String.prototype.advSplitJoin = function( chr, nbr, ips ){
  1076.  
  1077. var str = this.split(chr),
  1078. strLen = str.length,
  1079. ipsLen = ips.length,
  1080. returnStr = '',
  1081. returnStrLen;
  1082.  
  1083. $.each( str, function( index ) {
  1084. var add = index < strLen - 1
  1085. ? chr
  1086. : '';
  1087. returnStr += index + 1 === nbr
  1088. ? str[index] + ips
  1089. : str[index] + add;
  1090. });
  1091.  
  1092. returnStrLen = returnStr.length;
  1093. returnStr.slice( returnStrLen - ipsLen ) === ips
  1094. && ( returnStr = returnStr.slice( 0, returnStrLen - ipsLen ) );
  1095.  
  1096. return returnStr;
  1097. };
  1098. String.prototype.extract = function( start, end, inside, newWay ){
  1099. var str = this,
  1100. myArray = [ true, 1, 'yes', 'inside' ],
  1101. startCharIndex = str.indexOf( start ),
  1102. endCharIndex = str.indexOf( end );
  1103.  
  1104. newWay = newWay !== undefined ? $.inArray( newWay, myArray ) !== -1 : false;
  1105. inside = inside !== undefined ? $.inArray( inside, myArray ) !== -1 : false;
  1106.  
  1107. function simpler() {
  1108. return inside
  1109. ? str.split( start ).pop().split( end ).shift()
  1110. : start + str.split( start ).pop().split( end ).shift() + end;
  1111. }
  1112. function older() {
  1113. return inside //old buggy way, some old scripts may depends on it
  1114. ? str.replace( start, '').replace( end, '')
  1115. : str.substr( startCharIndex, endCharIndex );
  1116. }
  1117. return newWay ? simpler() : older();
  1118. };
  1119. String.prototype.extractNew = function( start, end, inside ){
  1120. var str = this;
  1121. return inside !== undefined && inside
  1122. ? str.split( start ).pop().split( end ).shift()
  1123. : inside
  1124. || start + str.split( start ).pop().split( end ).shift() + end;
  1125. };
  1126.  
  1127. String.prototype.charTrim = function( char ){
  1128. // alert("...their.here.".charTrim('.'));
  1129. var first_pos = 0,
  1130. last_pos = this.length- 1, i ;
  1131. //find first non needle char position
  1132. for( i = 0; i < this.length; i++ ){
  1133. if( this.charAt( i ) !== char ){
  1134. first_pos = ( i === 0 ? 0 : i );
  1135. break;
  1136. }
  1137. }
  1138. //find last non needle char position
  1139. for( i = this.length - 1; i > 0; i-- ){
  1140. if( this.charAt( i ) !== char ){
  1141. last_pos = ( i == this.length ? this.length: i + 1 );
  1142. break;
  1143. }
  1144. }
  1145. return this.substring( first_pos, last_pos );
  1146. };
  1147. String.prototype.reduceWhiteSpace = function(){
  1148. return this.replace(/\s+/g, ' ');
  1149. };
  1150. String.prototype.formatString = function(){
  1151.  
  1152. var inputStr = this.toString().reduceWhiteSpace()
  1153. .split('!').join(' !').split('!;').join("!important;")
  1154. .split(/\s+/g).join(' ')
  1155. .split('{').join('{\n\t')
  1156. .split('; ').join(';')
  1157.  
  1158.  
  1159.  
  1160. .split('( ').join('(')
  1161. .split(' )').join(')')
  1162.  
  1163. .split(' :').join(':')
  1164.  
  1165. .split(';').join(';\n\t')
  1166. .split('*/').join('*/\n')
  1167. .split(')*(').join(') * (')
  1168. .split('}').join('}\n'),
  1169. returnStr = '\t', pop;
  1170.  
  1171. $.each( inputStr.split('\n'), function ( i, elem ) {
  1172.  
  1173. elem.search( '{' ) === -1 && elem.search( ': ' ) === -1
  1174. && ( elem.search( ':' ) > 1
  1175. ? ( pop = elem.split(': ').join(':').split( ':' ).pop(), elem = elem.split( pop ).shift() + ' ' + pop )
  1176. : elem.search(':') === 1 && ( elem = elem.split(': ').join(':').split( ':' ).join( ': ' ) ) );
  1177. // : elem.search( '{' ) === 1 && ( elem.search( ': ' ) !== -1 || elem.search( ' :' ) !== -1 || elem.search( ' : ' ) !== -1 )
  1178. // && ( elem = elem.split( ': ' ).join( ' :' ).split( ' :' ).join( ':' ).split( ' : ' ).join( ': ' ) );
  1179.  
  1180. returnStr += elem + '\n\t';
  1181. });
  1182. returnStr = returnStr.split('>').join(' > ').split(' > ').join(' > ').split( ': //' ).join( '://' ).split( ':url' ).join( ': url' );
  1183. return returnStr.slice( 0, returnStr.lastIndexOf('}') ) + '}';
  1184. };
  1185.  
  1186. /**
  1187. * Parses mixed type values into booleans. This is the same function as filter_var in PHP using boolean validation
  1188. * //@return {Boolean|Null}
  1189. */
  1190. String.prototype.parseBooleanStyle = function( onNull ){
  1191. //myBool.toString().parseBooleanStyle()
  1192. onNull = onNull || false;
  1193. var bool, $this = this.toString().toLowerCase();
  1194. switch( $this ){
  1195. case 'true':
  1196. case '1':
  1197. case 'on':
  1198. case 'y':
  1199. case 'yes':
  1200. bool = true;
  1201. break;
  1202. case 'false':
  1203. case '0':
  1204. case 'off':
  1205. case 'n':
  1206. case 'no':
  1207. bool = false;
  1208. break;
  1209. default:
  1210. bool = typeof bool === 'boolean' ? bool : null;
  1211. break;
  1212. }
  1213. return onNull && bool == null || parseInt( $this ) > 0 || bool;
  1214. };
  1215. String.prototype.parseBool = function(){
  1216. //myBool.toString().parseBool()
  1217. var thisStr = ( parseInt( this ) ? this === 0 ? 'false' : !isNaN( parseFloat( this ) ) && 'true' : '' + this ).toLowerCase().trim(),
  1218. trueArray = [ 'on', 'yes','y', 'j', 'success', 'true', true ],
  1219. falseArray = [ 'off', 'no', 'n', 'failure', 'false', false ];
  1220.  
  1221. thisStr = thisStr.toLowerCase().trim();
  1222.  
  1223. return $.inArray( thisStr, trueArray ) !== -1 ? true : $.inArray( thisStr, falseArray ) !== -1 ? false : null;
  1224. };
  1225. String.prototype.defineBool = function(){
  1226. var falsely = /^(?:f(?:alse)?|no?|off?|n?|failure?|sudumoo?|0+)$/i,
  1227. truely = /^(?:t(?:rue)?|yes?|on?|y?|success?|yabbdoo?|1+)$/i,
  1228. stateBool = !!this,
  1229. $string = this;
  1230.  
  1231. return ( truely.test( this ) === stateBool )
  1232. ? true : ( falsely.test( this ) === stateBool )
  1233. ? false : $string != 0 && !isNaN(parseFloat($string)) && ( (typeof $string === 'number' || typeof $string === 'string') && isFinite($string) ) ? true : null;
  1234. };
  1235.  
  1236. String.prototype.isType = function( type ){
  1237. return !!$.type( this ) === type;
  1238. };
  1239. String.prototype.undef = function( replace ){
  1240. return this === undefined ? replace : this;
  1241. };
  1242. String.prototype.isUndefined = function( state, replace ){
  1243. state = state !== undefined ? state : true;
  1244. replace = replace !== undefined ? replace : true;
  1245. return state ? this === undefined ? replace : this : state;
  1246. };
  1247. String.prototype.isNumber = function ( float ) {
  1248. var reg = new RegExp( "^[-]?[0-9]+[\.]?[0-9]+$" );
  1249. return reg.test( this );
  1250. };
  1251.  
  1252. String.prototype.inURL = function(){
  1253. var winLoc = window.location.href;
  1254. return winLoc.search(this) !== -1;
  1255. };
  1256. String.prototype.inString = function( string ){
  1257. return string !== undefined ? string.search(this) !== -1 : false;
  1258. };
  1259. String.prototype.inElem = function( search ){
  1260. return this !== undefined ? this.search(search) !== -1 : false;
  1261. };
  1262. String.prototype.inElemX = function( search, exact ){
  1263.  
  1264. var isAll,isNone,inArr,checkInArr,
  1265. string = this,
  1266. countAll = 0, countNone = 0;
  1267.  
  1268. exact = exact || false;
  1269. isAll = exact === 'all';
  1270. isNone = exact === 'none';
  1271. exact = isNone || isAll ? false : exact;
  1272.  
  1273. checkInArr = function( search, all ){
  1274. inArr = false;
  1275. $.each( search, function( i, e ){
  1276. if(string.search( e ) !== -1 || string.search( e ) === -1){
  1277. inArr = true;
  1278. if( all ) string.search( e ) !== -1 ? countAll++ : string.search( e ) === -1 && countNone++;
  1279. else return false;
  1280. }
  1281. });
  1282. return all ? inArr && ( string.length === countAll || string.length === countNone ) : inArr;
  1283. };
  1284.  
  1285. return exact
  1286. ? string === search
  1287. : $.isArray( search )
  1288. ? checkInArr( search, isAll || isNone )
  1289. : isNone
  1290. ? string.search( search ) === -1
  1291. : string.search( search ) !== -1;
  1292. };
  1293. String.prototype.count = function( char, UpperCase ){
  1294. var numberOf = this.toString().match( new RegExp( char, ( UpperCase ? "gi" : "g" ) ) );
  1295. return numberOf !== null ? numberOf.length : 0;
  1296. };
  1297. String.prototype.startsWith = function( str ){
  1298. return this.slice(0, str.length) == str;
  1299. };
  1300. String.prototype.removeStarts = function( many ){
  1301. return this.substring( many - 1, this.length );
  1302. };
  1303. String.prototype.removeEnds = function( many ){
  1304. return this.substring( 0, this.length - many );
  1305. };
  1306. String.prototype.endsWith = function( str ){
  1307. return this.slice( -str.length ) == str;
  1308. };
  1309. String.prototype.capitalizeFirst = function(){
  1310. return this.charAt(0).toUpperCase() + this.slice(1);
  1311. };
  1312. String.prototype.lpad = function( padString, length ){
  1313. var str = this;
  1314. while ( str.length < length ) {
  1315. str = padString + str; }
  1316. return str;
  1317. };
  1318.  
  1319. // use full to convert String URL, so that you can use location commands
  1320. String.prototype.toLocation = function(){
  1321. var a = document.createElement('a');
  1322. a.href = this;
  1323. return a;
  1324. };
  1325.  
  1326. String.prototype.HTMLEncodedParserHTML = function(){
  1327. return $('<div/>').html( $( $.parseHTML( decodeURI(this) ) ) ).contents();
  1328. };
  1329. String.prototype.strParserHTML = function(){
  1330. return $($.parseHTML(this));
  1331. };
  1332. String.prototype.strDOMParser = function(){
  1333. return new DOMParser().parseFromString(this, "text/html");
  1334. };
  1335. String.prototype.str2html = function(){
  1336. return $('<div/>').html( this ).contents();
  1337. };
  1338.  
  1339. String.prototype.toStyle = function( styleId, append ){
  1340. append = append || 'head';
  1341. var cssID,
  1342. cssSplit = this.split('¤'),
  1343. cssStyled = cssSplit.pop().formatString();
  1344. styleId = styleId !== undefined ? styleId : cssSplit.shift();
  1345. cssID = $( append + ' #' + styleId );
  1346. cssID.length
  1347. ? cssID.html( cssStyled )
  1348. : $( $( '<style/>',{ id: styleId, class:'mySuperStyles', html: cssStyled } ) ).appendTo( append );
  1349. };
  1350.  
  1351. //HTMLObjectElement.prototype.obj2Str = function(){var objArr = $.makeArray( this ); return objArr[0].outerHTML;};
  1352. /*
  1353. String.prototype.replaceAll = function( target, replacement ) {
  1354. return this.split(target).join(replacement);
  1355. };
  1356. */
  1357. function ScrollZoomTune( selection, zooms, tune, ani, speed ){
  1358. //ScrollZoomTune("div.thumb .title a",1,-25,1,'slow');
  1359. var body = $('body'), sel = $( selection), position;
  1360. //noinspection JSValidateTypes
  1361. sel.size() !== 0 && (
  1362. body.css('zoom',zooms),
  1363. position = sel.position().top + tune,
  1364. ani === 1
  1365. ? body.animate({ scrollTop: position * zooms }, speed )
  1366. : body.scrollTop( position * zooms )
  1367. );
  1368. }
  1369. function refreshElement( elem , speed ){ //refreshElement('.videoPlayer','slow');
  1370. var $elem = $( elem ), data = $elem.html();
  1371. $elem.empty().html( data ).fadeIn( speed );
  1372. }
  1373.  
  1374. !!$.isFunction( $.fn.execCommand ) || ($.fn.execCommand = function(){});
  1375.  
  1376. function autoCopyToClipboard( input ){
  1377. var $copyThis = $( '#copyThis' );
  1378. $( 'body' ).append( $('<textarea/>',{ id:'copyThis', rows:"4", cols:"50", type:"text", value: input }) );
  1379. $copyThis.focus().select();
  1380. document.execCommand("copy");
  1381. $copyThis.remove();
  1382. }
  1383. function toStyle( styleId, str, append ){
  1384. append = append || 'head';
  1385. var $id = $( append + ' #' + styleId ),
  1386. cssID = str.formatString();
  1387.  
  1388. $id.length
  1389. ? $id.html( cssID )
  1390. : $( $( '<style/>',{ id: styleId, class:'mySuperStyles', html: cssID } ) ).appendTo( append );
  1391. }
  1392. function obj2Str( obj ){
  1393. var objArr = $.makeArray(obj);
  1394. return objArr[0].outerHTML;
  1395. }
  1396. function orderBy(key, reverse){
  1397. return function (a, b) {
  1398. return ( reverse || false ) ? b[ key ] - a[ key ] : a[ key ] - b[ key ];
  1399. };
  1400. }
  1401. function sortBy(key, reverse){
  1402. var R = reverse || false;
  1403. return function (a, b) {
  1404. var A = a[ key ], B = b[ key ];
  1405. return A < B ? R ? 1 : -1 : A > B ? R ? -1 : 1 : 0;
  1406. };
  1407. }
  1408. function sortByOLD(key, reverse){
  1409. // Usage: array.sort( sortBy( key, reverse ) )
  1410. // Move smaller items towards the front
  1411. // or back of the array depending on if
  1412. // we want to sort the array in reverse
  1413. // order or not.
  1414. var moveSmaller = reverse ? 1 : -1;
  1415. // Move larger items towards the front
  1416. // or back of the array depending on if
  1417. // we want to sort the array in reverse
  1418. // order or not.
  1419. var moveLarger = reverse ? -1 : 1;
  1420. /**
  1421. * @param {*} a
  1422. * @param {*} b
  1423. * @return {Number}
  1424. */
  1425. return function (a, b) {
  1426. if (a[key] < b[key]) {
  1427. return moveSmaller;
  1428. }
  1429. if (a[key] > b[key]) {
  1430. return moveLarger;
  1431. }
  1432. return 0;
  1433. };
  1434. }
  1435.  
  1436. /**
  1437. @function sec2timeFormat
  1438. @description convert second to time format in 4+ different ways into @example DD:HH:MM:SS.ms
  1439. @param {(string|Number)} totalSeconds - @desc it will convert to millisecond inside of @function
  1440. @param {Boolean} [complete] - @example true 02:45:05 or 02h 45m 05s false 2:45:05 or 2h 45m 05s
  1441. @param {(string|Boolean)} [divider] - @example common ':' or '-' or '/'
  1442. @param {Number} [toFix] - @desc millisecond after second - @default 2 - @example 45:05.44 or 5.44s
  1443. @return {string}
  1444. @copyright May 2017 - Magnus Fohlström
  1445. @license MIT
  1446. */
  1447. function sec2timeFormat( totalSeconds, complete, divider, toFix ){
  1448. totalSeconds = typeof totalSeconds === 'string' ? parseInt(totalSeconds) : totalSeconds;
  1449. toFix = toFix !== undefined ? ( toFix === 0 ? 0 : toFix ) : 2;
  1450. var bFull = complete !== undefined ? complete && true : false,
  1451. div = divider !== undefined ? divider !== false : false,
  1452.  
  1453. date = new Date( totalSeconds * 1000 ),
  1454. d = Math.floor( totalSeconds / 3600 / 24 ),
  1455. // d = date.getUTCDate() - 1,
  1456. h = date.getUTCHours(),
  1457. m = date.getUTCMinutes(),
  1458. s = date.getSeconds(),
  1459. ms = totalSeconds - Math.floor( totalSeconds ),
  1460.  
  1461. preD = div ? divider : 'd ', dPreD = d + preD,
  1462. dd = bFull
  1463. ? d === 0 ? '00' + preD : (d < 10 ? '0':'') + dPreD
  1464. : d === 0 ? '' : dPreD,
  1465.  
  1466. preH = div ? divider : 'h ', hPreH = h + preH,
  1467. hh = dd.length > 0
  1468. ? h === 0 ? '00' + preH : (h < 10 ? '0':'') + hPreH
  1469. : h === 0 ? bFull ? h < 10 ? '0' + hPreH : hPreH : '' : hPreH,
  1470.  
  1471. preM = div ? divider : 'm ', mPreM = m + preM,
  1472. mm = hh.length > 0
  1473. ? m === 0 ? '00' + preM : (m < 10 ? '0':'') + mPreM
  1474. : m === 0 ? bFull ? m < 10 ? '0' + mPreM : mPreM : '' : mPreM,
  1475.  
  1476. preMS = ( s + ms ).toFixed( toFix ),
  1477. preS = div ? '' : 's', sPreS = preMS + preS,
  1478. ss = mm.length > 0
  1479. ? s === 0 ? '00' + preS : (s < 10 ? '0':'') + sPreS
  1480. : sPreS;
  1481.  
  1482. return ( dd + hh + mm + ss ).toString();
  1483. }
  1484.  
  1485. function VideoTitleA( elem , state ){
  1486. //VideoTitleA("div.thumb .title a",'on');
  1487. $( elem ).each(function(){
  1488. var $this = $(this),
  1489. strTitle = $this.attr('title'),
  1490. strText = $this.attr('data-text'),
  1491. strHtml = $this.text();
  1492. state === 'on' ? $this.text(strTitle).attr('data-text',strHtml) : $this.text(strText);
  1493. });
  1494. }
  1495. /**
  1496. * @return {string}
  1497. */
  1498. function MultiString( f ){
  1499. return f.toString().split('\n').slice(1, -1).join('\n');
  1500. }
  1501. function wrapWithTag( tag, text, selection ){
  1502. var thisAttr = selection !== undefined && selection.startsWith('.') ? 'class' : selection.startsWith('#') && 'id',
  1503. thisTag = $('<' + tag + '/>', { text: text });
  1504. return thisAttr.length ? thisTag.attr( thisAttr, selection.splice( 1 ) ) : thisTag;
  1505. }
  1506.  
  1507. function clean( node ) {
  1508. /*
  1509. So to clean those unwanted nodes from inside the <body> element, you would simply do this:
  1510.  
  1511. clean(document.body);
  1512. Alternatively, to clean the entire document, you could do this:
  1513.  
  1514. clean(document);
  1515. */
  1516. for( var n = 0; n < node.childNodes.length; n ++ ){
  1517. var child = node.childNodes[ n ];
  1518. ( child.nodeType === 8 || ( child.nodeType === 3 && !/\S/.test( child.nodeValue ) ) )
  1519. ? (
  1520. node.removeChild( child ),
  1521. n --
  1522. )
  1523. : child.nodeType === 1 && clean( child );
  1524. }
  1525. }
  1526. function commentsCleaner( array ){
  1527. array = array === undefined ? [ '*', document, 'html' ] : array;
  1528.  
  1529. // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
  1530. // http://stackoverflow.com/a/2364760
  1531. $.each( array, function( i, e ) {
  1532. $( e ).contents().each( function() {
  1533. this.nodeType === Node.COMMENT_NODE && $( this ).remove(); }); });
  1534. }
  1535.  
  1536. function newUrlNoReload( title, url ){
  1537. window.history.pushState("string", title, url );
  1538. }
  1539. function inURLo( search, exact ){
  1540. exact = exact || false;
  1541. var winLoc = window.location.href;
  1542. return exact ? winLoc === search : winLoc.search( search ) !== -1;
  1543. }
  1544. function inURLe( search, exact ){
  1545. exact = exact || false;
  1546. var inArr,
  1547. winLoc = window.location.href,
  1548. tiA = function( search ){
  1549. inArr = false;
  1550. $.each( search, function(i,e){
  1551. if( winLoc.search( search ) !== -1 ){
  1552. inArr = true;
  1553. return false;
  1554. }
  1555. });
  1556. return inArr;
  1557. };
  1558. return exact ? winLoc === search : $.isArray( search ) ? tiA( search ) : winLoc.search( search ) !== -1;
  1559. }
  1560. function inURL( search, exact ){
  1561.  
  1562. var isAll,isNone,inArr,checkInArr,
  1563. winLoc = window.location.href,
  1564. countAll = 0, countNone = 0;
  1565.  
  1566. exact = exact || false;
  1567. isAll = exact === 'all';
  1568. isNone = exact === 'none';
  1569. exact = isNone || isAll ? false : exact;
  1570.  
  1571. checkInArr = function( search, all ){
  1572. inArr = false;
  1573. $.each( search, function( i, e ){
  1574. if(winLoc.search( e ) !== -1 || winLoc.search( e ) === -1){
  1575. inArr = true;
  1576. if( all ) winLoc.search( e ) !== -1 ? countAll++ : winLoc.search( e ) === -1 && countNone++;
  1577. else return false;
  1578. }
  1579. /*
  1580. if( winLoc.search( e ) !== -1 ){
  1581. inArr = true;
  1582. if( all ) countAll++; else return false;
  1583. }
  1584. else if( winLoc.search( e ) === -1 ){
  1585. inArr = true;
  1586. if( all ) countNone++; else return false;
  1587. }
  1588. */
  1589. });
  1590. return all ? inArr && ( search.length === countAll || search.length === countNone ) : inArr;
  1591. };
  1592.  
  1593. return exact
  1594. ? winLoc === search
  1595. : $.isArray( search )
  1596. ? checkInArr( search, isAll || isNone )
  1597. : isNone
  1598. ? winLoc.search( search ) === -1
  1599. : winLoc.search( search ) !== -1;
  1600. }
  1601. function loadDoc( href ){
  1602. $( location ).attr('href', href );
  1603. }
  1604.  
  1605. function isPrimitiveType( value ){
  1606. // will return true if the value is a primitive value
  1607. switch ( typeof value ) {
  1608. case 'string': case 'number': case 'boolean': case 'undefined': {
  1609. return true;
  1610. }
  1611. case 'object': {
  1612. return !value;
  1613. }
  1614. }
  1615. return false;
  1616. }
  1617. function checkDividedIsInteger( num, div ){
  1618. return ( num % div === 0 );
  1619. }
  1620. function isEven( value ){
  1621. return ( value % 2 === 0 );
  1622. }
  1623. function inDom( array, onElement ) {
  1624. var found = false,
  1625. isArrayFN = function(){
  1626. $.each( array, function( i, value ){
  1627.  
  1628. value = onElement !== undefined
  1629. ? onElement + value
  1630. : value;
  1631.  
  1632. if( $( value ).length ){
  1633. found = true;
  1634. return false;
  1635. }
  1636. });
  1637. };
  1638.  
  1639. $.isArray( array )
  1640. ? isArrayFN()
  1641. : $( array ).length && ( found = true );
  1642.  
  1643. /**
  1644. * @return {boolean}
  1645. */
  1646. return found;
  1647. }
  1648. function isHTMLObject( obj ){
  1649. obj = typeof obj == 'string' ? obj : $( obj );
  1650. return obj.length
  1651. ? !!~( obj instanceof HTMLElement || obj[0] instanceof HTMLElement)
  1652. : !!( obj && ( obj.nodeName || ( obj.prop && obj.attr && obj.find ) ) );
  1653. }
  1654.  
  1655. function isFunction( functionToCheck ){
  1656. var getType = {};
  1657. return functionToCheck && getType.toString.call( functionToCheck ) === '[object Function]';
  1658. }
  1659. function isNumeric( value ){
  1660. return /^\d+$/.test( value );
  1661. }
  1662. function is_Numeric(n) {
  1663. return !isNaN(parseFloat(n)) && isFinite(n);
  1664. }
  1665.  
  1666. function parse_Boolean( Boolean, onNull, nullIs ) {
  1667. var falsely = /^(?:f(?:alse)?|no?|off?|n?|failure?|sudumoo?|0+)$/i,
  1668. truely = /^(?:t(?:rue)?|yes?|on?|y?|success?|yabbdoo?|1+)$/i;
  1669.  
  1670. //noinspection JSUnresolvedVariable
  1671. return truely.test( Boolean ) === !!Boolean ? true : falsely.test( Boolean ) === !!Boolean ? false
  1672. : !isNaN(parseFloat( Boolean )) && isFinite( Boolean ) ? true
  1673. : ( onNull || false ) ? bool == null ? nullIs : false : null;
  1674. }
  1675. function parseBoolean( Boolean , Type ) {
  1676. // http://stackoverflow.com/a/24744599
  1677. Type = Type || false;
  1678. var falsely = /^(?:f(?:alse)?|no?|0+)$/i,
  1679. truely = /^(?:t(?:rue)?|yes?|1+)$/i;
  1680. return Type ? !truely.test( Boolean ) && !!Boolean : !falsely.test( Boolean ) && !!Boolean;
  1681. }
  1682. function parseBooleanStyle( str, onNull, nullIs ){
  1683. onNull = onNull || false;
  1684. var bool, $this = this.toString().toLowerCase();
  1685. switch( $this ){
  1686. case 'true':
  1687. case '1':
  1688. case 'on':
  1689. case 'y':
  1690. case 'yes':
  1691. bool = true;
  1692. break;
  1693. case 'false':
  1694. case '0':
  1695. case 'off':
  1696. case 'n':
  1697. case 'no':
  1698. bool = false;
  1699. break;
  1700. default:
  1701. bool = typeof bool === 'boolean' ? bool : null;
  1702. break;
  1703. }
  1704. return ( onNull || false ) && ( bool === null && nullIs || false ) || parseInt( $this ) !== 0 || bool;
  1705. }
  1706.  
  1707. /**
  1708. * Search for correct object in array and return it.
  1709. * @function getObjKeyVal
  1710. * @param {Array} array - The array you wanna search trough
  1711. * @param {string} findKey - The key to search for
  1712. * @param {string} exactValue - Check correct key is found
  1713. * @param {string} [getObjKeyVal] - get a key value in that object
  1714. */
  1715. function getObjKeyVal( array, findKey, exactValue, getObjKeyVal ){
  1716. var obj, node;
  1717. for( node in array )
  1718. for( findKey in obj = array[ node ] )
  1719. if( obj.hasOwnProperty( findKey ) && obj[ findKey ] == exactValue )
  1720. return getObjKeyVal || false ? obj[ getObjKeyVal ] : obj;
  1721. return false;
  1722. }
  1723. /**
  1724. * Search for all matched objects in array and return those.
  1725. * @function getAllMatchedObj
  1726. * @param {Array} array - The array you wanna search trough
  1727. * @param {string} findKey - The key to search for
  1728. * @param {string} exactValue - Check correct key found
  1729. */
  1730. function getAllMatchedObj( array, findKey, exactValue ){
  1731. var newArr = [], obj, node;
  1732. for( node in array )
  1733. for( findKey in obj = array[ node ] )
  1734. if( obj.hasOwnProperty( findKey ) && obj[ findKey ] == exactValue ) newArr.push( obj );
  1735. return newArr;
  1736. }
  1737. /**
  1738. * Search for all matched objects in array and return those.
  1739. * @function getAllMatchedObjByObject
  1740. * @param {Array} mainArray - The array you wanna search trough
  1741. * @param {Array} filterObject - Is one array object to match object in main array,
  1742. * this object has multiple keys one each for a search criteria example "{ joined:'2012', rank:5, gender:'female' }"
  1743. */
  1744. function getAllMatchedObjByObject( mainArray, filterObject ){
  1745. var newArr = [], objectCount = 0, mainLen = mainArray.length, mainObj, filterLen;
  1746. for ( objectCount; objectCount != mainLen; objectCount++ ){
  1747.  
  1748. mainObj = mainArray[ objectCount ];
  1749. filterLen = Object.keys( filterObject ).length;
  1750.  
  1751. Object.keys( filterObject ).forEach( function( filterKey, index ){
  1752. mainObj.hasOwnProperty( filterKey ) && mainObj[ filterKey ] == filterObject[ filterKey ] && ++index === filterLen && newArr.push( mainObj );
  1753. });
  1754. }
  1755. return newArr;
  1756. }
  1757. /**
  1758. * Do something with an array then return it
  1759. * @function arrayDo
  1760. * @param {string} what - what function is going to be used on an array
  1761. * @param {(string|string[])} array - The array you wanna search trough
  1762. * @param {string} findKey - The key to search for
  1763. * @param {string} [keyValue] - Check correct key found
  1764. * @param {string} [getKeyVal] - Get a key value from correct object found, or add in conjunction with newVal
  1765. * @param {string} [newVal] - Set a new Value to a key
  1766. */
  1767. function arrayDo( what, array, findKey, keyValue, getKeyVal, newVal) {
  1768.  
  1769. what = what === 'newKey' ? 'updateKey' : what;
  1770. /*
  1771. index = array.findIndex( function( obj ){
  1772. return obj.hasOwnProperty( findKey ) && obj[ findKey ] === keyValue;
  1773. })
  1774. */
  1775. var index = -1, i=0, len = array.length;
  1776.  
  1777. // if( !!~$.inArray( doWhat, ['allMatched','add','sort'] ) === true )
  1778. for ( i; i != len ; i++ ) {
  1779. var obj = array[ i ];
  1780. if( obj.hasOwnProperty( findKey ) && obj[ findKey ] === keyValue ){
  1781. c.i('inArray',obj[ findKey ]);
  1782. index = i;
  1783. break;
  1784. }
  1785. }
  1786.  
  1787. var object = array[ index ],
  1788. doWhat = {
  1789. find : function(){
  1790. array = object;
  1791. },
  1792. remove : function(){
  1793. index !== -1 && array.splice( index, 1 );
  1794. },
  1795. keyVal : function(){
  1796. var obj = object[ getKeyVal ];
  1797. array = obj !== undefined ? obj : '';
  1798. },
  1799. updateKey : function(){ //newKey
  1800. /* c.i('updateKey array ', JSON.stringify( array ) )
  1801. c.i('updateKey index ', index )
  1802. c.i('updateKey Value ', keyValue)
  1803. c.i('updateKey newVal', newVal )
  1804. c.i('getKeyVal before', array[ index ] )
  1805. c.i('updateKey', '____________________')
  1806. */
  1807. index !== -1 && ( array[ index ][ getKeyVal ] = newVal );
  1808. // c.i('getKeyVal after ', array[ index ] )
  1809.  
  1810. },
  1811. deleteKey : function(){
  1812. index !== -1 && delete array[ index ][ getKeyVal ];
  1813. },
  1814. add : function(){
  1815. array.push( newVal );
  1816. },
  1817. sort : function(){
  1818. array.sort( sortBy( findKey, keyValue ) );
  1819. },
  1820. allMatched : function(){
  1821. var newArr = [], i = 0,
  1822. secondMatch = ( getKeyVal !== undefined && newVal !== undefined );
  1823.  
  1824. for ( i; i != len; i++ ) {
  1825. var obj = array[ i ];
  1826. ( obj.hasOwnProperty( findKey ) && obj[ findKey ] === keyValue )
  1827. && ( secondMatch ? ( obj.hasOwnProperty( getKeyVal ) && obj[ getKeyVal ] === newVal ) : true )
  1828. && newArr.push( obj );
  1829. }
  1830.  
  1831. array = newArr;
  1832. }
  1833. };
  1834.  
  1835. doWhat[ what ]();
  1836. return array;
  1837. }
  1838.  
  1839. function getsComputedStyle( style, elem ) {
  1840. elem = elem || 'body';
  1841. return window.getComputedStyle( document[ elem ] )[ style ] !== undefined;
  1842. }
  1843. function isPropertySupported( property, elem ){
  1844. elem = elem || 'body';
  1845. return property in document[ elem ].style;
  1846. }
  1847. function cssPropertyValueSupported( prop, value, elem ) {
  1848. //cssPropertyValueSupported('width', '1px');
  1849. elem = elem || 'div';
  1850. var d = document.createElement( elem );
  1851. d.style[ prop ] = value;
  1852. return d.style[ prop ] === value;
  1853. }
  1854.  
  1855. var cssSupports = (function(){
  1856. // http://code.tutsplus.com/tutorials/quick-tip-detect-css3-support-in-browsers-with-javascript--net-16444
  1857. /*
  1858. if ( supports('textShadow') ) {
  1859. document.documentElement.className += ' textShadow';
  1860. }
  1861. */
  1862. var div = document.createElement('div'),
  1863. vendors = 'Khtml Ms O Moz Webkit'.split(' '),
  1864. len = vendors.length;
  1865.  
  1866. return function(prop) {
  1867. if ( prop in div.style ) return true;
  1868.  
  1869. prop = prop.replace(/^[a-z]/, function(val) {
  1870. return val.toUpperCase();
  1871. });
  1872.  
  1873. while(len--) {
  1874. if ( vendors[len] + prop in div.style ) {
  1875. // browser supports box-shadow. Do what you need.
  1876. // Or use a bang (!) to test if the browser doesn't.
  1877. return true;
  1878. }
  1879. }
  1880. return false;
  1881. };
  1882. })();
  1883.  
  1884. function toggleClassState( config, Class, state, elem ){
  1885. config === undefined ? window.config = {} : config;
  1886. config = config || ( window.config = {} );
  1887.  
  1888. config[ Class ] = typeof state === 'string' ? !config[ Class ] : state;
  1889. $( elem || 'html' )[ config[ Class ] ? 'addClass' : 'removeClass' ]( Class );
  1890. }
  1891. function filterClick( e, $this ){
  1892. return e.which == 1 && e.target == $this;
  1893. }
  1894. function dispatchEventResize() {
  1895. //noinspection JSClosureCompilerSyntax,JSUnresolvedFunction
  1896. window.dispatchEvent(new Event('resize'));
  1897. }
  1898.  
  1899. /**
  1900. * @return {string}
  1901. */
  1902. function Undefined( check, replace ){
  1903. return check === undefined ? replace.toString() : check.toString();
  1904. }
  1905. function checkJqueryUI( maxCount, timeout, module ){
  1906. //noinspection JSUnresolvedVariable
  1907. if( typeof jQuery.ui != 'undefined' ){
  1908. //noinspection JSUnresolvedVariable
  1909. return module !== undefined ? typeof jQuery.ui[ module ] != 'undefined' : true; }
  1910. else
  1911. setTimeout(function(){
  1912. if( counter.setGet('chkJQ') > maxCount ){
  1913. counter.del('chkJQ');
  1914. return false;
  1915. }
  1916. else checkJqueryUI( maxCount, timeout );
  1917. }, timeout );
  1918. }
  1919.  
  1920. function getGlobal(){
  1921. return (function(){
  1922. return this;
  1923. })();
  1924. }
  1925. function GM_lister( remove, item ){
  1926. var keys = GM_listValues();
  1927. for (var i = 0, key = null; key = keys[i]; i++) {
  1928. GM_listValues()[i] !== undefined && (
  1929. c.i('GM_ListItem: ' + GM_listValues()[i] + ':', GM_getValue(key)),
  1930. ( ( item !== undefined && GM_listValues()[i].inElem( item ) ) || item === undefined )
  1931. && ( remove === true || remove === 'yes' || remove === 1 ) && GM_deleteValue(key));
  1932. }
  1933. }
  1934.  
  1935. function roundFloat( num, dec ){
  1936. var d = 1;
  1937. for ( var i=0; i<dec; i++ ){
  1938. d += "0";
  1939. }
  1940. return Math.round(num * d) / d;
  1941. }
  1942. function randomFloatBetween( min, max, dec ){
  1943. dec = typeof( dec ) == 'undefined' ? 2 : dec;
  1944. return parseFloat( Math.min( min + ( Math.random() * ( max - min ) ), max ).toFixed( dec ) );
  1945. }
  1946. function random( max ) {
  1947. var min = 1,
  1948. rand = function(){
  1949. return Math.floor( Math.random() * ( max - min + 1 ) + min );
  1950. },
  1951. num1 = rand(),
  1952. num2 = rand();
  1953.  
  1954. return ( num1 > num2 ? num2/num1 : num1/num2 ) * max;
  1955. }
  1956. function roundNearPeace( number, peaces, dec ) {
  1957. return ( Math.round( number * peaces ) / peaces ).toFixed( dec );
  1958. }
  1959.  
  1960. var w = window,
  1961. glob = w,
  1962. $w = $( w ),
  1963. $l = $( location ),
  1964. locDoc = window.location.href,
  1965. d = document,
  1966. $d = $( d ),
  1967.  
  1968. c = {
  1969. defaultState: 3,
  1970. cute : function( type, msg, color ) {
  1971. color = color || "black";
  1972. var newColor, bgc = "White";
  1973. switch ( color ) {
  1974. case "success": newColor = "Green"; bgc = "LimeGreen"; break;
  1975. case "info": newColor = "DodgerBlue"; bgc = "Turquoise"; break;
  1976. case "error": newColor = "Red"; bgc = "Black"; break;
  1977. case "start": newColor = "OliveDrab"; bgc = "PaleGreen"; break;
  1978. case "warning": newColor = "Tomato"; bgc = "Black"; break;
  1979. case "end": newColor = "Orchid"; bgc = "MediumVioletRed"; break;
  1980. default: //noinspection SillyAssignmentJS
  1981. newColor = color;
  1982. }
  1983.  
  1984. typeof msg == "object" ?
  1985. window.console[ type ]( msg )
  1986. : typeof color == "object" ? (
  1987. window.console[ type ]("%c" + msg, "color: PowderBlue;font-weight:bold; background-color: RoyalBlue;"),
  1988. window.console[ type ]( newColor )
  1989. ) :
  1990. window.console[ type ]("%c" + msg, "color:" + newColor + "; background-color: " + bgc + ";");
  1991. },
  1992. show: function( showThis, type ){
  1993. var State = GM_getValue( type + 'StateValue' ) || this.defaultState;
  1994. return showThis !== 0 && State !== 0 && State === ( showThis || State ) || State === 'all';
  1995. },
  1996. pre: function( type, name, fn, line, color ){
  1997. line = line === undefined ? '' : line + ': ';
  1998. /**
  1999. * @return {string}
  2000. */
  2001. var Fn = function(){ return fn !== undefined ? fn : ''; };
  2002. typeof fn == "object"
  2003. ? window.console[ type ]( name, Fn() )
  2004. : c.cute( type, line + name + ': ' + Fn(), color );
  2005. },
  2006. type: function( type, name, fn, line, color, showThis ){
  2007. this.show( showThis, type ) && this.pre( type, name, fn, line, color );
  2008. },
  2009. l: function( name, fn, line, color, showThis ){
  2010. this.type( 'log', name, fn, line, color, showThis );
  2011. },
  2012. h: function( name, fn, line, color, showThis ){
  2013. this.type( 'handled', name, fn, line, color, showThis );
  2014. },
  2015. //c.l('name', 'fn'=='fn', 'line', 'blue')
  2016. i: function( name, fn, line, color, showThis ){
  2017. this.type( 'info', name, fn, line, color, showThis );
  2018. },
  2019. d: function( name, fn, line, color, showThis ){
  2020. this.type( 'debug', name, fn, line, color, showThis );
  2021. }
  2022. },
  2023. localStorageObj = {
  2024. name : 'setName', //important
  2025. localArray : function(){
  2026. return window.localStorage.getItem( this.name );
  2027. },
  2028. getArray : function(){
  2029. return this.localArray() === null ? [] : JSON.parse( this.localArray() );
  2030. },
  2031. removeArray : function(){
  2032. window.localStorage.removeItem( this.name );
  2033. },
  2034. stringify : function( array ){
  2035. c.i('[stringify]', JSON.stringify(array) );
  2036. window.localStorage.setItem( this.name, JSON.stringify(array) );
  2037. },
  2038. check : function( key, value ){
  2039. var array = this.getArray();
  2040. return array.grepArrayObj('find', key, value );
  2041. },
  2042. viewConsole : function( json ){
  2043. var array = this.getArray();
  2044. // $.toJSON() --- https://github.com/Krinkle/jquery-json/blob/master/src/jquery.json.js
  2045. // array.join('\n');
  2046. c.d( this.name, array ); //debug mode important to make this work
  2047. c.i( this.name, json ? isFunction( $.toJSON() ) ? $.toJSON( array ) : JSON.stringify( array ) : array.toSource() );
  2048. },
  2049. addTo : function() {
  2050.  
  2051. },
  2052. add : function( key, value, obj ){
  2053. var array = this.getArray(),
  2054. inA = array.toString();
  2055. c.i('[check array 1]', inA );
  2056. this.check( array, key, value )
  2057. || (
  2058. array.push( obj ),
  2059. c.i('[Added Object into array]', obj ),
  2060. c.i('[check array 2]', array )
  2061. );
  2062. this.stringify( array );
  2063. },
  2064. remove : function( key, value, obj ){
  2065. var array = this.getArray();
  2066. this.check( array, key, value )
  2067. && (
  2068. array = array.grepArrayObj('remove', key, value ),
  2069. c.i('[Removed Object from array]', obj )
  2070. );
  2071. this.stringify( array );
  2072. }
  2073. },
  2074. booleanTimer = {
  2075. timers : [],
  2076. start : function( name, ms ){
  2077. var that = this, value = name,
  2078. stop = setTimeout(function(){
  2079. that.stop( value );
  2080. }, ms );
  2081. this.timers.push( { 'name': value, stop:stop } );
  2082. //setTimeout(function(){that.stop( value );}, ms );
  2083. },
  2084. check : function( value ){
  2085. return this.timers.grepArrayObj( 'find', 'name', value ) !== undefined;
  2086. },
  2087. stop : function( value ){
  2088. this.timers = this.timers.grepArrayObj( 'remove', 'name', value );
  2089. }
  2090. },
  2091. advTimer = {
  2092. timers : [],
  2093. start : function( name, ms ){
  2094. var that = this, value = name,
  2095. stop = setTimeout(function(){
  2096. that.stop( value );
  2097. }, ms );
  2098. //noinspection JSUnresolvedVariable
  2099. this.timers.push({ 'name':value, start:window.performance.now(), timeout:ms, stop:stop });
  2100. },
  2101. check : function( value ){
  2102. var findObj = this.timers.grepArrayObj( 'find', 'name', value );
  2103. //noinspection JSUnresolvedVariable
  2104. return findObj !== undefined
  2105. ? findObj.timeout - ( window.performance.now() - findObj.start )
  2106. : false;
  2107. },
  2108. stop : function( value ){
  2109. this.timers = this.timers.grepArrayObj( 'remove', 'name', value );
  2110. }
  2111. },
  2112. lap = {
  2113. data : {},
  2114. tid : function(){
  2115. //noinspection JSUnresolvedVariable
  2116. return performance.now();
  2117. },
  2118. set : function(name){
  2119. this.data[name] = this.tid();
  2120. },
  2121. get : function(name){
  2122. return this.tid() - this.data[name];
  2123. },
  2124. end : function(name){
  2125. this.print(name);
  2126. this.del(name);
  2127. },
  2128. del : function(name){
  2129. delete this.data[name];
  2130. },
  2131. print: function(name){
  2132. var get = this.get( name );
  2133. c.i( 'Lap: ' + name, isNaN( get ) ? 'There is no such a name ' : get + 'ms' );
  2134. }
  2135. },
  2136. timer = {
  2137. ms : 0,
  2138. set : function(ms){
  2139. var that = this;
  2140. this.ms = ms;
  2141. setTimeout(function(){
  2142. that.ms = 0;
  2143. }, ms );
  2144. }
  2145. },
  2146. counter = {
  2147. data : {},
  2148. setGet : function(name, decrease, reset) {
  2149.  
  2150. this.exists(name) && ( reset || false )
  2151. && this.set(name,0);
  2152.  
  2153. this.exists(name)
  2154. ? this[ ( decrease || false ) ? 'decrease' : 'increase' ](name)
  2155. : this.set(name);
  2156.  
  2157. return this.get(name);
  2158. },
  2159. set : function(name, start, base){
  2160. this.data[name] = start || 0;
  2161. this.data[name+'Default'] = base || 1;
  2162. },
  2163. get : function(name){
  2164. return this.data[name];
  2165. },
  2166. is : function(name, count){
  2167. return this.data[name] === count;
  2168. },
  2169. lessThen: function(name, count, equal ){
  2170. return ( equal || false ) ? this.data[name] <= count : this.data[name] < count;
  2171. },
  2172. moreThen: function(name, count, equal){
  2173. return ( equal || false ) ? this.data[name] >= count : this.data[name] > count;
  2174. },
  2175. del : function(name){
  2176. delete this.data[name];
  2177. },
  2178. exists : function(name) {
  2179. return this.data[name] !== undefined;
  2180. },
  2181. plus : function(name, num){
  2182. this.exists(name) || this.set(name);
  2183. this.data[name] = this.data[name] + ( num === undefined ? this.data[name+'Default'] : num );
  2184. },
  2185. minus : function(name, num){
  2186. this.exists(name) || this.set(name);
  2187. this.data[name] = this.data[name] - ( num === undefined ? this.data[name+'Default'] : num );
  2188. },
  2189. increase: function (name, num) {
  2190. this.plus(name, num);
  2191. },
  2192. decrease: function (name, num) {
  2193. this.minus(name, num);
  2194. },
  2195. '+' : function (name, num) {
  2196. this.plus(name, num);
  2197. },
  2198. '-' : function (name, num) {
  2199. this.minus(name, num);
  2200. },
  2201. up : function (name, num) {
  2202. this.plus(name, num);
  2203. },
  2204. down : function (name, num) {
  2205. this.minus(name, num);
  2206. },
  2207. add : function (name, num) {
  2208. this.plus(name, num);
  2209. },
  2210. subtract: function (name, num) {
  2211. this.minus(name, num);
  2212. },
  2213. withdraw: function (name, num) {
  2214. this.minus(name, num);
  2215. }
  2216. },
  2217. g = {
  2218. locDoc : window.location.href,
  2219. ms : 0,
  2220. timer : function(ms){
  2221. g.ms = ms;
  2222. setTimeout(function(){ g.ms = 0; }, ms );
  2223. },
  2224.  
  2225. GM : {
  2226. engine : function( mode, val, range ){
  2227. switch (mode){
  2228. case 'set': GM_setValue( val.name, val.default );
  2229. break;
  2230. case 'get': range ? config[ val.name ] = GM_getValue( val.name ):
  2231. ui.config[ val.name ] = GM_getValue( val.name );
  2232. break;
  2233. case 'del': GM_deleteValue( val.name );
  2234. }
  2235. },
  2236. manager : function( mode, array, range ){
  2237. $.each( array, function( i, val ){ this.engine( mode, val, range === undefined ); });
  2238. mode === 'del' && ( GM_deleteValue( 'firstRun' ), GM_deleteValue( 'yourVer' ) );
  2239. }
  2240. }
  2241. },
  2242.  
  2243. testPerformance = function( name, fn, testCycles ) {
  2244. lap.set( name );
  2245. var i = 0;
  2246. for ( i ; i < testCycles; i++ ){
  2247. fn();
  2248. }
  2249. lap.end( name );
  2250. },
  2251. perf = function (testName, fn) {
  2252. var startTime = new Date().getTime();
  2253. fn();
  2254. var endTime = new Date().getTime();
  2255. console.log( testName + ": " + ( endTime - startTime ) + "ms" );
  2256. };
  2257.  
  2258. $(document).on('click','*',function(e){
  2259. this == e.target && c.i('target:', $(this)[0] );
  2260. });
  2261.  
  2262. c.i('my Function Library ÖÖö');
  2263. /*
  2264. isScrolledIntoView = (elem) ->
  2265. docViewTop = $(window).scrollTop()
  2266. docViewBottom = docViewTop + $(window).height()
  2267. elemTop = $(elem).offset().top
  2268. elemBottom = elemTop + $(elem).height()
  2269.  
  2270. (elemBottom - 200 < docViewBottom) and (elemBottom + $(elem).height() > docViewBottom )
  2271. */
  2272.  
  2273.