stuppid_bot

Untitled

May 9th, 2013
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. © All rights reserved x9a.ru, 2013
  3.  
  4. порядковые имена переменных:
  5. var, var1, var2
  6.  
  7. краткие имена переменных:
  8. b - булев
  9. n - число
  10. s - строка
  11. o - обьект
  12. a - массив
  13. p - property
  14. e - error
  15. m - match
  16. l - length
  17. k - key
  18. v - value
  19. t - time
  20. ts - timestamp
  21. dt - datetime
  22. re - regExp
  23. el - element
  24. ev - event
  25. fn - function
  26. cb - callback
  27. im, img - image
  28. dst - destination
  29. src - source
  30. txt - text
  31. ctx - context
  32. out
  33. htm, html
  34. opts - options
  35. data
  36. temp - temporary
  37. i, j, k - счетчики
  38.  
  39. преффиксы функций: get, load, add, delete, remove, update
  40.  
  41. побитовые аналоги:
  42. x | 0 == x >> 0 == Math.floor(x)
  43. x + (x <= 0 ? 0 : 1) | 0 == Math.ceil(x)
  44. x + (x < 0 ? -.5 : .5) | 0 == Math.round(x)
  45. 1 << x == Math.pow(2, x)
  46. */
  47. Object.values = function(o) {
  48.     var a = [];
  49.  
  50.     for (var p in o) {
  51.         if ( o.hasOwnProperty(p) ) {
  52.             a.push(o[p]);
  53.         }
  54.     }
  55.    
  56.     return a;
  57. };
  58.  
  59. String.prototype.repeat = function(n) {
  60.     return new Array(++n).join(this);
  61. };
  62.  
  63. String.prototype.pad = function(requiredLength, paddingStr, paddingType) {    
  64.     var n = requiredLength - this.length;
  65.    
  66.     if (n > 0) {
  67.         paddingType = paddingType ? paddingType.toLowerCase() : '';
  68.         paddingStr = paddingStr || ' ';
  69.         paddingStr = paddingStr.repeat( Math.ceil(n / paddingStr.length) ).substr(0, n);
  70.        
  71.         if (paddingType == 'both') {
  72.             n /= 2;
  73.             return paddingStr.substr( 0, Math.ceil(n) ) + this + paddingStr.substr( 0, Math.floor(n) );
  74.         }  
  75.        
  76.         if (paddingType == 'left') {
  77.             return paddingStr + this;
  78.         }
  79.        
  80.         return this + paddingStr;
  81.     }
  82.    
  83.     return this + '';
  84. };
  85.  
  86. // синтаксис аналогичен printf
  87. // 'Привет, %s!'.format('мир') -> "Привет, мир!"
  88. // '%.1s.%.1s. %s'.format('Иван', 'Иванович', 'Иванов') -> "И.И. Иванов"
  89. // http://ru.wikipedia.org/wiki/Printf
  90. ( function() {
  91.     function addPlus(n, flags) {
  92.         return (n > 0 && flags && /\+/.test(flags) ? '+' : '') + n;
  93.     };
  94.    
  95.     String.prototype.format = function() {
  96.         var q = 0, w = arguments, e;
  97.  
  98.         return this.replace(/%(?:%|([-+0]+)?([1-9]\d*)?(?:\.([1-9]\d*))?([a-z]))/gi, function(m, flags, width, precision, type) {      
  99.             if (m == '%%') {
  100.                 return '%';
  101.             }      
  102.  
  103.             e = w[q++];
  104.  
  105.             switch (type) {
  106.                 case 'd':
  107.                     e = addPlus( Math.round(e), flags );
  108.                     break;
  109.  
  110.                 case 'f':
  111.                     e = addPlus( e.toFixed(precision || 6), flags );
  112.                     break;
  113.  
  114.                 case 's':
  115.                     e += '';
  116.                     e = precision ? e.substr(0, precision) : e;
  117.                     break;
  118.  
  119.                 default:
  120.                     return m;
  121.             }
  122.  
  123.             if (width) {
  124.                 e = e.pad( width, /0/.test(flags) ? '0' : ' ', /-/.test(flags) ? 'right' : 'left' );
  125.             }
  126.  
  127.             return e;
  128.         });
  129.     };
  130. } )();
  131.  
  132. // this.name = 'Вася';
  133. // console.log( 'Привет, ${name}!'.template(this) );
  134. // "Привет, Вася!"
  135. String.prototype.template = function(context) {
  136.     return this.replace(/\$\{(.*?)\}/g, function(match, name) {
  137.         return context[name];
  138.     });
  139. };
  140.  
  141. ( function() {
  142.     var entities = {'<': 'lt', '>': 'gt', '&': 'amp'},
  143.         re = new RegExp('[' + Object.keys(entities).join('') + ']', 'g');
  144.        
  145.     String.prototype.escape = function() {
  146.         return this.replace(re, function(m) {
  147.             return '&' + entities[m] + ';';
  148.         });
  149.     }
  150. } )();
  151.  
  152. String.prototype.addslashes = function() {
  153.     return this.replace(/([\\'"])/g, '\\$1');
  154. };
  155.  
  156. String.prototype.stripslashes = function() {
  157.     return this.replace(/\\([\\'"])/g, '$1');
  158. };
  159.  
  160. String.prototype.reverse = function() {
  161.     return this.split(/|/).reverse().join('');
  162. };
  163.  
  164. Array.prototype.shuffle = function() {
  165.     var i = 0, l = this.length, r, swap;
  166.  
  167.     while (i < l) {
  168.         r = Math.floor( Math.random() * l );
  169.         swap = this[r];
  170.         this[r] = this[i];
  171.         this[i++] = swap;
  172.     }
  173. };
  174.  
  175. // [1, 2, 3, 4, 5].rand() -> 4
  176. Array.prototype.rand = function() {
  177.     return this[Math.floor( Math.random() * this.length )];
  178. };
  179.  
  180. HTMLCanvasElement.prototype.toBlob = function(type, quality) {
  181.     var dataURL = this.toDataURL(type, quality), binary = atob( dataURL.substr( dataURL.indexOf(',') + 1 ) ), i = binary.length, view = new Uint8Array(i);
  182.  
  183.     while (i--) {
  184.         view[i] = binary.charCodeAt(i);
  185.     }
  186.    
  187.     return new Blob([view], {type: type});
  188. };
  189.  
  190. ( function() {
  191.     var cache = {};
  192.    
  193.     gid = function(x) {
  194.         return cache[x] ? cache[x] : cache[x] = document.getElementById(x);
  195.     };
  196. } )();
  197.  
  198. function loadScript(url, cb) {
  199.     var d = document, s = d.createElement('script');
  200.     s.src = url;
  201.     s.onload = cb;
  202.     d.head.appendChild(s);
  203. }
  204.  
  205. function loadScripts(urls, cb) {
  206.     loadScript( urls.shift(), function() {
  207.         if (urls.length) {
  208.             return loadScripts(urls, cb);
  209.         }
  210.        
  211.         cb && cb();
  212.     } );
  213. }
  214.  
  215. function onHashChange(cb) {
  216.     var cur = location.hash;
  217.    
  218.     setInterval( function() {
  219.         if (cur != location.hash) {
  220.             cur = location.hash;
  221.             cb();
  222.         }
  223.     }, 100 );
  224. }
  225.  
  226. function extend(dst, src) {
  227.     for (var p in src) {
  228.         if( src.hasOwnProperty(p) ) {
  229.             dst[p] = src[p];
  230.         }
  231.     }
  232.    
  233.     return dst;
  234. }
  235.  
  236. function clone(o) {
  237.     return JSON.parse( JSON.stringify(o) );
  238. }
  239.  
  240. function rand(min, max) {
  241.     return min + Math.floor( Math.random() * (max + 1 - min) );
  242. }
  243.  
  244. function deg2rad(n) {
  245.     return n * (Math.PI / 180);
  246. }
  247.  
  248. function moveAtAngle(sx, sy, angle, distance) {
  249.     return [sx +  Math.cos(angle) * distance, sy + Math.sin(angle) * distance]
  250. }
  251.  
  252. function hexToRgb(s) {
  253.     if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(s) ) {
  254.         var hex = s.substr(1), rgb = parseInt( hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex, 16 );              
  255.         return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
  256.     }
  257.    
  258.     return false;
  259. }
  260.  
  261. function rgbToHex(red, green, blue) {
  262.     var out = '#';
  263.    
  264.     for (var i = 0; i < 3; ++i) {
  265.         var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);
  266.        
  267.         if (isNaN(n) || n < 0 || n > 255) {
  268.             return false;
  269.         }
  270.        
  271.         out += (n < 16 ? '0' : '') + n.toString(16);
  272.     }
  273.    
  274.     return out;
  275. }
  276.  
  277. /**
  278.  * Возвращает размер в байтах в понятном для человека формате.
  279.  *
  280.  * @param size размер в байтах, целое число
  281.  * @param standard стандарт, 'si' | 'iec'
  282.  * @return string
  283.  */
  284. function formatSize(size, standard) {
  285.     var n = 0, base = standard == 'si' ? 1000 : 1024, prefixes = ' KMGTPEZY';
  286.     standard = standard ? standard.toLowerCase() : standard;  
  287.  
  288.     if (size < 1) {
  289.         return 0;
  290.     }
  291.     else if (size >= base) {
  292.         n = Math.floor( Math.log(size) / Math.log(base) );
  293.  
  294.         if (n >= prefixes.length) {
  295.             return 'N/A';
  296.         }
  297.  
  298.         size = ( size / Math.pow(base, n) ).toFixed(2) * 1 + ' ';
  299.     }
  300.  
  301.     return size + prefixes[n] + (n && standard == 'iec' ? 'i' : '') + 'B';
  302. }
  303.  
  304. /**
  305.  * Возвращает продолжительность времени.
  306.  *
  307.  * @param ms миллисекунды
  308.  * @return string
  309.  */
  310. function duration(ms) {
  311.     var hours = ms / 3600000, minutes = hours % 1 * 60, seconds = Math.round(minutes % 1 * 60);
  312.     minutes = Math.floor(minutes);
  313.     return (hours >= 1 ? Math.floor(hours) + ':' : '') + (hours >= 1 && minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
  314. }
  315.  
  316. /**
  317.  * Склоняет слово в зависимости от количества.
  318.  *
  319.  * @param count количество
  320.  * @param base основа слова
  321.  * @param singular окончание для ед.ч.
  322.  * @param plural1 1-ое окончание для мн.ч.
  323.  * @param plural2 2-ое окончание для мн.ч.
  324.  * @return string
  325.  */
  326. function pluralize(count, base, singular, plural1, plural2) {
  327.     return count + ' ' + base + ( ( count = (count %= 100) > 20 ? count % 10 : count ) == 0 || count > 4 ? plural2 : count > 1 ? plural1 : singular );
  328. }
  329.  
  330. /**
  331.  * Возвращает продолжительность времени словами.
  332.  *
  333.  * @param ms миллисекунды
  334.  * @return string
  335.  */
  336. // 'Скачивание начнется через ' + durationWords(1.35 * 60000).replace(/(т|д)а/g, '$1у') -> "Скачивание начнется через 1 минуту 21 секунду"
  337. function durationWords(ms) {
  338.     // годов и месяцев нет, так как они имееют разную длительность
  339.     var weeks = ms / 604800000, days = weeks % 1 * 7, hours = days % 1 * 24, minutes = hours % 1 * 60, seconds = minutes % 1 * 60, parts = [];
  340.     weeks >= 1 && parts.push( pluralize( Math.floor(weeks), 'недел', 'я', 'и', 'ь' ) );
  341.     days >= 1 && parts.push( pluralize( Math.floor(days), 'д', 'ень', 'ня', 'ней' ) );
  342.     hours >= 1 && parts.push( pluralize( Math.floor(hours), 'час', '', 'а', 'ов' ) );
  343.     minutes >= 1 && parts.push( pluralize( Math.floor(minutes), 'минут', 'а', 'ы', '' ) );
  344.     seconds >= 0.5 && parts.push( pluralize( Math.round(seconds), 'секунд', 'а', 'ы', '') );
  345.     return parts.join(' ');
  346. }
  347.  
  348. // setCookie('test', 'Test', new Date().getTime() + 24 * 3600000);
  349. function setCookie(name, value, expires, path, domain, secure, httponly) {
  350.     document.cookie = name + '=' + encodeURIComponent(value) + ( expires === undefined ? '' : '; Expires=' + new Date(expires).toUTCString() ) + (path ? '; Path=' + path : '') + (domain ? '; Domain=' + domain : '') + (secure ? '; Secure' : '') + (httponly ? '; HttpOnly' : '');
  351. }
  352.  
  353. function deleteCookie(name, path, domain) {
  354.     setCookie(name, '', 0, path, domain);
  355. }
  356.  
  357. ( function() {
  358.     var s = '^!"#$%&\'()*+,./:;<=>?@\\[\\\\\\]^_`{|}~',
  359.         s1 = '[' + s + '-]+(?:[' + s + ']+[' + s + '-])*',
  360.         re = new RegExp( '^' + [
  361.             // протокол
  362.             '(?:([^:@/?#]*:)\\/\\/)?',
  363.             // пользователь и пароль
  364.             '(?:([^:@/?#]*)(?::([^:@/?#]*))?@)?',
  365.             // хост и порт
  366.             '((' + s1 + '(?:\\.' + s1 + ')*)(?::(\\d+))?)?',
  367.             // путь
  368.             '(/[^?#]*)?',
  369.             // часть после вопроса
  370.             '(\\?[^#]*)?',
  371.             // хеш
  372.             '(#.*)?'
  373.         ].join('') + '$' );
  374.     // console.log(re);
  375.    
  376.     parseURL = function(s) {
  377.         // проверяем на наличие символов с ascii кодами меньше 33, а так же на правильность кодирования
  378.         if ( /^(?:[^\x00-\x20%]|%[a-zA-Z0-9]{2})*$/.test(s) ) {
  379.             var parts = re.exec(s);
  380.  
  381.             if (parts !== null) {
  382.                 var scheme = ['protocol', 'user', 'password', 'hostname', 'host', 'port', 'pathname', 'search', 'hash'], i = 0, l = scheme.length, o = {};
  383.  
  384.                 while (i < l) {
  385.                     o[scheme[i]] = parts[++i] === undefined ? '' : parts[i];
  386.                 }
  387.  
  388.  
  389.                 if (o.pathname) {
  390.                     o.pathname = o.pathname.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
  391.                 }
  392.  
  393.                 return o;            
  394.             }
  395.         }
  396.  
  397.         return false;
  398.     };
  399. } )();
  400.  
  401. querystring = {
  402.     parse: function(s, sep, eq) {
  403.         var o = {};
  404.         eq = eq || '=';      
  405.  
  406.         if (s) {
  407.             var a = s.split(sep || '&'), i = 0, l = a.length, a1, k, v;
  408.  
  409.             while (i < l) {
  410.                 a1 = a[i++].split(eq);
  411.                 k = a1[0];
  412.                 v = a1[1];                    
  413.  
  414.                 if (k !== '') {
  415.                     k = decodeURIComponent(k);
  416.                     v = v === undefined ? '' : decodeURIComponent(v);
  417.                    
  418.                     if (k in o) {
  419.                         if (typeof o[k] == 'string') {
  420.                             o[k] = new Array(o[k]);
  421.                         }
  422.                        
  423.                         o[k].push(v);
  424.                     }
  425.                     else {
  426.                         o[k] = v;
  427.                     }
  428.                 }
  429.             }
  430.         }
  431.  
  432.         return o;
  433.     },
  434.    
  435.     stringify: function(o, sep, eq) {
  436.         var p, i, l, a, a1 = [];
  437.         sep = sep || '&';
  438.         eq = eq || '=';      
  439.  
  440.         for (p in o) {
  441.             if ( o.hasOwnProperty(p) ) {
  442.                 a = Array.prototype.concat(o[p]);
  443.                 p = encodeURIComponent(p);
  444.                
  445.                 for (i = 0, l = a.length; i < l; ++i) {
  446.                     a1.push( p + ( a[i] === '' ? '' : eq + encodeURIComponent(a[i]) ) );
  447.                 }
  448.             }
  449.         }
  450.  
  451.         return a1.join(sep);
  452.     }
  453. };
  454. // query = querystring.parse( location.search.substr(1) );
  455. // cookie = querystring.parse(document.cookie, /;\s*/);
  456.  
  457. /**
  458.  * Ajax-обертка
  459.  */
  460. ajax = new ( function(){
  461.     var parseResponse = this.parseResponse = function(xhr, type) {
  462.         if (type) {
  463.             switch ( type.toLowerCase() ) {
  464.                 case 'document':
  465.                 case 'xml':
  466.                     return xhr.responseXML;
  467.  
  468.                 case 'json':
  469.                     return JSON.parse(xhr.responseText);
  470.  
  471.                 case 'script':
  472.                     return eval(xhr.responseText);
  473.             }
  474.         }
  475.        
  476.         return xhr.responseText;
  477.     }
  478.    
  479.     var request = this.request = function(method, url, data, opts) {
  480.         var xhr = new XMLHttpRequest, response, error;
  481.         opts = opts || {};            
  482.        
  483.         if (opts.done || opts.fail || opts.complete) {  
  484.             xhr.onreadystatechange = function() {
  485.                 if (xhr.readyState == 4) {              
  486.                     if (xhr.status >= 200 && xhr.status < 300) {
  487.                         response = parseResponse(xhr, opts.responseType);
  488.                        
  489.                         if (opts.done) {
  490.                             return opts.done(response, xhr);
  491.                         }
  492.                     }
  493.                     else {
  494.                         error = xhr.responseText;
  495.                        
  496.                         if (opts.fail) {
  497.                             return opts.fail(error, xhr);
  498.                         }
  499.                     }
  500.                    
  501.                     opts.complete(error, response, xhr);
  502.                 }
  503.             }
  504.         }      
  505.  
  506.         xhr.open(method, url);
  507.        
  508.         if (opts.contentType) {
  509.             xhr.setRequestHeader('Content-Type', opts.contentType);
  510.         }
  511.        
  512.         xhr.send(data);  
  513.     };
  514.      
  515.     this.get = function(url, opts) {
  516.         request('GET', url, null, opts);
  517.     };
  518.    
  519.     this.rawpost = function(url, data, opts) {
  520.         request('POST', url, data, opts);
  521.     };
  522.    
  523.     this.put = function(url, data, opts) {
  524.         request('PUT', url, data, opts);
  525.     };
  526.  
  527.     /**
  528.      * Отправить данные методом POST
  529.      *  
  530.      * @param url адрес документа
  531.      * @param data ассоциативный массив
  532.      * @param opts.contentType тип передаваемых данных
  533.      * @param opts.responseType тип получаемых данных: 'xml', 'json', 'script'
  534.      * @param opts.done function(data, xhr) { ... } функция-обработчик, которая вызывается при успешном выполнении запроса
  535.      * @param opts.fail function(err, xhr) { ... } функция-обработчик, которая вызывается при возвращении сервером статуса отличного от 2XX
  536.      * @param opts.complete function(err, data, xhr) { ... } объединяет в себе done и fail
  537.      */
  538.     this.post = function(url, data, opts) {
  539.         opts = opts || {};
  540.         opts.contentType = opts.contentType || 'application/x-www-form-urlencoded';
  541.         this.rawpost( url, querystring.stringify(data), opts );
  542.     };  
  543. } )();
  544.  
  545. ( function() {
  546.     var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  547.    
  548.     base62 = {
  549.         encode: function(n) {
  550.             var s = '';
  551.            
  552.             do {
  553.                 s = chars[n % 62] + s;
  554.             }
  555.             while ( n = Math.floor(n / 62) );
  556.            
  557.             return s;
  558.         },
  559.        
  560.         decode: function(s) {
  561.             var q = s.length, w, e = 0, r = 0;
  562.                
  563.             while (q--) {
  564.                 if ( ( w = chars.indexOf(s[q]) ) == -1 ) {
  565.                     return false;                  
  566.                 }
  567.                
  568.                 if (w) {
  569.                     r += w * Math.pow(62, e);
  570.                 }
  571.                
  572.                 ++e;
  573.             }
  574.            
  575.             return r;
  576.         }
  577.     }
  578. } )();
Advertisement
Add Comment
Please, Sign In to add comment