Yandex Extra Buttons

Add buttons (last 1/2/3 days, weeks, PDF search etc.) for Yandex search page

目前为 2016-03-08 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Yandex Extra Buttons
  3. // @name:ru Yandex_Extra_Buttons
  4. // @description Add buttons (last 1/2/3 days, weeks, PDF search etc.) for Yandex search page
  5. // @description:ru Кнопки вариантов поиска для страницы результатов поиска Yandex (1-2-3 дня, недели, PDF, ...)
  6. // @version 4.2016.1.22
  7. // @namespace spmbt.github.com
  8. // @include https://www.yandex.*
  9. // @include https://yandex.*/search*
  10. // @include https://yandex.*/yandsearch*
  11. // @include https://spmbt.github.io/googleSearchExtraButtons/saveYourLocalStorage.html
  12. // @update buttons style like arrows (pentagonal)
  13. // ==/UserScript==
  14. if(location.host=='spmbt.github.io'){
  15. window.addEventListener('message', function(ev){
  16. if(/^https?:\/\/www\.yandex\./.test(ev.origin)){
  17. var d = typeof ev.data =='string' && ev.data[0] =='{' ? JSON.parse(ev.data) : ev.data;
  18. if(!d.do) return;
  19. var tok = d.tok, key = d.key;
  20. switch(d.do){
  21. case 'set':
  22. var prev = localStorage[key];
  23. if(d.val !==undefined)
  24. localStorage[key] = JSON.stringify(d.val);
  25. else
  26. localStorage.removeItem(key);
  27. break;
  28. case 'get':
  29. prev = localStorage[key];
  30. prev = prev === undefined || typeof prev =='string'&& prev[0] !='{'? prev : JSON.parse(prev);
  31. break;
  32. case 'remove':
  33. prev = localStorage[key];
  34. if(prev !==undefined)
  35. localStorage.removeItem(key);
  36. }
  37. //console.log('[io]', tok, 'prev=', prev);
  38. //ev.source.postMessage(JSON.stringify(prev !==undefined ? {tok: tok, prev: prev} : {tok: tok, undef:1}), ev.origin);
  39. }},!1);
  40. }else
  41.  
  42. (function(setts){ //lang, sites, lastHoursLess
  43.  
  44. var $x = function(el, h){if(h) for(var i in h) el[i] = h[i]; return el;} //===extend===
  45. ,$pd = function(ev){ev.preventDefault();}
  46. ,$q = function(q, el){return (el||document).querySelector(q)}
  47. ,$qA = function(q, el){return (el||document).querySelectorAll(q)}
  48. ,lh = location.href
  49. ,d = document
  50. ,$e = function(g){ //===create or use existing element=== //g={el|clone,cl,ht,cs,at,atRemove,on,apT}
  51. g.el = g.el || g.clone ||'DIV';
  52. var o = g.o = g.clone && g.clone.cloneNode && g.clone.cloneNode(!0)
  53. || (typeof g.el =='string' ? d.createElement(g.el) : g.el);
  54. if(o){ //execute if exist
  55. if(g.cl)
  56. o.className = g.cl;
  57. if(g.clAdd)
  58. o.classList.add(g.clAdd);
  59. if(g.cs)
  60. $x(o.style, g.cs);
  61. if(g.ht || g.at){
  62. var at = g.at ||{}; if(g.ht) at.innerHTML = g.ht;}
  63. if(at)
  64. for(var i in at){
  65. if(i=='innerHTML') o[i] = at[i];
  66. else o.setAttribute(i, at[i]);}
  67. if(g.atRemove)
  68. for(var i in g.atRemove)
  69. o.removeAttribute(g.atRemove[i]);
  70. if(g.on)
  71. for(var i in g.on) if(g.on[i])
  72. o.addEventListener(i, g.on[i],!1);
  73. g.ap && o.appendChild(g.ap);
  74. g.apT && g.apT.appendChild(o);
  75. }
  76. return o;
  77. },
  78. addRules = function(css){
  79. var heads = d.getElementsByTagName('head')
  80. ,node = d.createElement('style');
  81. heads.length && heads[0].appendChild(node);
  82. node.appendChild(d.createTextNode(css));
  83. };
  84. /**
  85. * check occurrence of third-party event with growing interval
  86. * @constructor
  87. * @param{Number} h.t start period of check
  88. * @param{Number} h.i number of checks
  89. * @param{Number} h.m multiplier of period increment
  90. * @param{Function} h.check event condition
  91. * @param{Function} h.occur event handler
  92. */
  93. var Tout = function(h){
  94. var th = this;
  95. (function(){
  96. if((h.dat = h.check() )) //wait of positive result, then occurs
  97. h.occur();
  98. else if(h.i-- >0) //next slower step
  99. th.ww = setTimeout(arguments.callee, (h.t *= h.m) );
  100. })();
  101. }
  102. //for xLocStor:
  103. ,xLocStorOrigin = d.location.protocol +'//spmbt.github.io'
  104. ,qr, qrs ={} //set of queries "key-calls" (ок, toutLitt, toutLong, noService, noStorage)
  105. ,qrI = 0 //queries counter
  106. ,qrN = 12 //max number of waiting queries
  107. ,errIMax = 120, errNMax = errIMax //max number of errors
  108. ,ns ='googXButtons_' //namespace for keys
  109. ,listenMsg
  110. /**
  111. * external localStorage for using another domain if current domain storage is erased anywhere
  112. * @param{String} h.do - action: set|get|remove
  113. * @param{String} h.key
  114. * @param{Object|undefined} h.val (any type)
  115. * @param{Number|undefined} h.toutLitt
  116. * @param{Number|undefined} h.tout
  117. * @param{Function} h.cB - callback with 2 arguments
  118. * @param{Function|undefined} h.err - callback for err with one argument
  119. */
  120. ,xLocStor = function(h){
  121. var h0 = h;
  122. h.toutLitt = h.toutLitt || 400;
  123. h.tout = h.tout || 4000;
  124. var ifr = $q('#xLocStor')
  125. ,query = function(){
  126. if((qrI += 1) > qrN){
  127. xCatch('longQrs', null, h);
  128. return;}
  129. ifr.contentWindow.postMessage(JSON.stringify($x({
  130. do: h.do
  131. ,tok: token
  132. ,key: ns + h.key
  133. }, h.val !==undefined ? {val: h.val}:{}) )
  134. , xLocStorOrigin);
  135. qrs[token] = $x({ //for wait of response
  136. wToutLitt: (function(h, qrI, errIMax){return setTimeout(function(){
  137. qrI -= 1;
  138. if((errIMax -= 1) >=0)
  139. ;//console.warn('toutLitt', h);
  140. chkErrMax();
  141. }, h.toutLitt);})(h, qrI, errIMax)
  142. ,wTout: (function(h, qrI){return setTimeout(function(){
  143. qrI -= 1;
  144. //xCatch('tout', null, h);
  145. //xLocStor(h0);
  146. }, h.tout);})(h, qrI)
  147. }, h);
  148. }
  149. ,token = +new Date() + (Math.random()+'').substr(1,8)
  150. ,el = h.el;
  151. delete h.el;
  152. if(ifr) query();
  153. else ifr = $e({
  154. el: 'iframe',
  155. at:{id: 'xLocStor'
  156. ,src: xLocStorOrigin +'/googleSearchExtraButtons/saveYourLocalStorage.html'},
  157. cs: {display: 'none'},
  158. on: {load: query},
  159. apT: el || d.body
  160. });
  161. if(!listenMsg) addEventListener('message', function(ev){
  162. if(ev.origin == xLocStorOrigin){ // {"tok":"<value>"[,"err":"<txt>"],"h":...}
  163. //console.log('from_io', JSON.parse(ev.data))
  164. var resp = ev.data && ev.data[0] =='{' && JSON.parse(ev.data);
  165. if(!resp) xCatch('bad_format', resp, h);
  166. if(( qr = qrs[resp.tok] )){
  167. qrI -= 1;
  168. qr.cB(resp.prev, resp.undef);
  169. var er = qr.err;
  170. delete qrs[resp.tok];} // else ignore unsufficient token
  171. if(resp.err && (!er || er(resp.err)) ) //individual or common error processing depends of er()
  172. xCatch(resp.err, resp, h);
  173. }},!1);
  174. listenMsg =1;
  175. },
  176. //for tests: localStorage.googXButtons_dwmyh = JSON.stringify({h:[1,2,1,1,1]})
  177. //$('#xLocStor').contentWindow.postMessage('{"do":"get","key":"googXButtons_dwmyh"}','https://spmbt.github.io')
  178. xCatch = function(er, resp, h){
  179. if((errIMax -= 1) >=0)
  180. console.error('tok:', resp && resp.tok ||'--','; err:', er,'; h:', h,'; respH:', resp && resp.h);
  181. chkErrMax();
  182. },
  183. chkErrMax = function(){if(!errIMax) console.error('Too many err messages:', errNMax)}
  184. ,type ='PDF,DOC,docx,RTF,SWF,XLS,PPT,ODT,ODS,ODP,ODG'.split(',').map(function(x){return '&nbsp; '+x+'&nbsp; '})
  185. ,$l ={ru:{
  186. 'search in PDF files':'поиск по документам PDF'
  187. ,'search in':'искать по'
  188. ,'from / to':'за период'
  189. ,'last':['за последний','за последние','за последнюю']
  190. ,'day':'сутки'
  191. ,'days':['дня','дней']
  192. ,'week':'неделю'
  193. ,'weeks':['недели','недель']
  194. ,'month':'месяц'
  195. ,'months':['месяца','месяцев']
  196. ,'year':'год'
  197. ,'years':['года','лет']
  198. ,'hour':'час'
  199. ,'hours':['часа','часов']
  200. ,'Settings':'Настройки'
  201. ,'of userscript':'юзерскрипта'
  202. ,'reload page for effect':'перезагрузить страницу'
  203. ,'Interface language':'Язык интерфейса'
  204. ,'Less positions at the end of selects':'Меньше выбора в конце селектов'
  205. ,'Sites':'Сайты'
  206. },ua:{
  207. 'search in PDF files':'пошук по документах PDF'
  208. ,'search in':'шукати по'
  209. ,'from / to':'за період'
  210. ,'last':['за останній','за останні','за останню']
  211. ,'day':'добу'
  212. ,'days':['дні','днів']
  213. ,'week':'тиждень'
  214. ,'weeks':['тижня','тижнів']
  215. ,'month':'місяць'
  216. ,'months':['місяці','місяців']
  217. ,'year':'рiк'
  218. ,'years':['роки','рокiв']
  219. ,'hour':'годину'
  220. ,'hours':['години','годин']
  221. ,'Settings':'Настройки'
  222. ,'of userscript':'юзерскрипту'
  223. ,'reload page for effect':'перезавантажити сторінку'
  224. ,'Interface language':'Мова інтерфейсу'
  225. ,'Less positions at the end of selects':'Менше вибору в кінці селектів'
  226. ,'Sites':'Сайти'
  227. },by:{
  228. 'search in PDF files':'пошук па дакументах PDF'
  229. ,'search in':'шукаць па'
  230. ,'from / to':'за перыяд'
  231. ,'last':['за апошні','за апошнія','за апошнюю']
  232. ,'day':'суткі'
  233. ,'days':['дня','дзён']
  234. ,'week':'тыдзень'
  235. ,'weeks':['тыдня','тыдняў']
  236. ,'month':'месяц'
  237. ,'months':['месяца','месяцаў']
  238. ,'year':'год'
  239. ,'years':['года','гадоў']
  240. ,'hour':'гадзіну'
  241. ,'hours':['гадзіны','гадзін']
  242. ,'Settings':'Налады'
  243. ,'of userscript':'юзерскрипта'
  244. ,'reload page for effect':'перазагрузіць старонку'
  245. ,'Interface language':'Мова інтэрфейсу'
  246. ,'Less positions at the end of selects':'Менш выбару ў канцы селект'
  247. ,'Sites':'Сайты'
  248. },fr:{
  249. 'search in PDF files':'la recherche dans les fichiers PDF'
  250. ,'search in':'rechercher dans'
  251. ,'from / to':'pour la période'
  252. ,'last':['le dernier','dans les derniers','dans les derniers']
  253. ,'day':'jour'
  254. ,'days':['jours','jours']
  255. ,'week':'semaine'
  256. ,'weeks':['semaines','semaines']
  257. ,'month':'mois'
  258. ,'months':['mois','mois']
  259. ,'year':'an'
  260. ,'years':['ans','ans']
  261. ,'hour':'heure'
  262. ,'hours':['heures','heures']
  263. ,'Settings':'Paramètres'
  264. ,'of userscript':'de Userscript'
  265. ,'reload page for effect':'recharger la page pour effet'
  266. ,'Interface language':'Langue de l\'interface'
  267. ,'Less positions at the end of selects':'Moins de choix les longues listes'
  268. ,'Sites':'Les sites'
  269. },de:{
  270. 'search in PDF files':'Suche in PDF-Dateien'
  271. ,'search in':'Suche in'
  272. ,'from / to':'im Zeitraum'
  273. ,'last':['letzter','letztes','letzte']
  274. ,'day':'Tag'
  275. ,'days':['Tage','Tage']
  276. ,'week':'Woche'
  277. ,'weeks':['Wochen','Wochen']
  278. ,'month':'Monat'
  279. ,'months':['Monate','Monate']
  280. ,'year':'Jahr'
  281. ,'years':['Jahre','Jahre']
  282. ,'hour':'Stunde'
  283. ,'hours':['Stunden','Stunden']
  284. ,'Settings':'Einstellungen'
  285. ,'of userscript':'von Userscript'
  286. ,'reload page for effect':'Seite neu laden'
  287. ,'Interface language':'Sprache'
  288. ,'Less positions at the end of selects':'Weniger Auswahl in langen Listen'
  289. ,'Sites':'Websites'
  290. },es:{
  291. 'search in PDF files':'búsqueda en archivos PDF'
  292. ,'search in':'busca en'
  293. ,'from / to':'para el período'
  294. ,'last':['el último','en los últimos','en los últimos']
  295. ,'day':'día'
  296. ,'days':['días','días']
  297. ,'week':'Semana'
  298. ,'weeks':['semanas','semanas']
  299. ,'month':'mes'
  300. ,'months':['meses','meses']
  301. ,'year':'año'
  302. ,'years':['años','años']
  303. ,'hour':'hora'
  304. ,'hours':['horas','horas']
  305. ,'Settings':'Ajustes'
  306. ,'of userscript':'de userscript'
  307. ,'reload page for effect':'página para efecto de recargar'
  308. ,'Interface language':'Idioma de interfaz'
  309. ,'Less positions at the end of selects':'Menos elección en listas largas'
  310. ,'Sites':'Sitios'
  311. }}; //if !lang, then no hints
  312. addRules('.z-index-group_level_9{z-index: 11002}' //buttons above suggest
  313. +'.lsbb .xButt,.search2__button >.siteList, .search2__button .suggest2-form__button:not([role="button"]){'
  314. +'z-index: 11002; width: 34px; height:17px; padding: 0 2px; line-height:14px; font-size:14px;'
  315. +'border:1px solid transparent; border-radius: 1px; background-color: rgba(214, 188, 76, 0.92); color:#fff; opacity:.6}'
  316. +'.search2__button >.siteList{width:31px; height:auto; padding: 1px 0 2px; text-align:center; font-weight: bold;'
  317. +'background-color: rgba(228, 189, 17, 0.7);} .search2__button >.siteList .lsb{font-weight: normal; color:#ece3dd}'
  318. +'.search2__button >.siteList:after{display:block; border-left:3px solid rgba(228, 189, 17, 0.7); border-top:8px solid transparent; border-bottom:9px solid transparent; content:""; position: absolute; left:32px; top:0; height:2px;}'
  319. +'.search2__button .suggest2-form__button:hover,.search2__button .xButt:hover{opacity:.85; color:#6f6e69;}'
  320. +'.search2__button .xButt:not(.sett):hover{background-color: rgba(226, 194, 27, 0.47);}'
  321. +'.search2__button .xButt .suggest2-form__button:hover{background-color: #e4d68c}'
  322. +'.siteList .xButt{display: block} .siteList .xButt .txt{padding: 0 2px 0 1px;} .siteList .sett .txt{background-color: #e2c043}'
  323. +'.siteList .settIn{display: none; width: 250px; padding: 2px 4px; text-align: left; border:1px solid #dacb97;'
  324. +'background-color: rgba(239, 235, 217, 0.94); color: #653} .siteList .settIn hr{margin:2px 0}'
  325. +'.sbibtd .sfsbc .nojsb, .siteList .sett:hover .settIn, .siteList .settIn.changed,'
  326. +'.siteList .settIn.changed .reload{display: block}.siteList .settIn .reload, .siteList.hiddn{display: none}'
  327. +'.select .button.button_checked_yes, .select .button.button_checked_yes .button__text{background-color: rgba(245, 226, 140, 0.7)}');
  328. xLocStor({do:'get', key:'sett', val:setts, cB: function(prev,undef){
  329. S = prev || setts;
  330. S.dwmyh = S.dwmyh || setts.dwmyh; //temp. transitional expr.
  331. console.timeStamp = function(){};
  332.  
  333. new Tout({t:120, i:8, m: 1.6
  334. ,check: function(){
  335. return d && $q('.suggest2-form__button');
  336. },
  337. occur: function(){
  338. var lang = S.lang != null && S.lang || setts.lang
  339. ,sites = S.sites && (S.sites.length && S.sites[0] || S.sites.length >1) && S.sites
  340. || typeof sites =='string'&& [sites] || !S.sites && setts.sites || null;
  341. var strSites = sites && sites.join('\n').replace(/^\n/,'\n\n') ||''
  342. ,$L = $l[lang] || $l.ru; //default template of lang
  343. if(!lang || !$l[lang] || lang =='en') for(var l in $L){ //replace 'en' lang for default or substitution
  344. if($L[l] instanceof Array) for(var l2 in $L[l])
  345. $L[l][l2] = l;
  346. else
  347. $L[l] = l;
  348. }
  349. var $LSettings = $L['Settings'];
  350. if(sites && sites.length)
  351. sites.push($LSettings);
  352. var mainPg = /\/search\?/.test(lh)
  353. ,inputSearch = $q('.suggest2-form .input__control.input__input') || $q('.input__control') //trueth place for 1 of 2 pages
  354. ,buttSearch = this.dat
  355. ,ua = lang=='ua', by = lang=='by',de = lang=='de'
  356. ,buttS ={
  357. site:{url:'site:'+ S.sites[0], txt:$L['search in']+' '+ S.sites[0], one:'day'} //you may comment this line
  358. ,'.. : ..':{url:'', txt:$L['from / to']}
  359. ,'1D':{url:'&tbs=qdr:d', txt:$L['last'][de?0:ua?2:1] +' '+ $L['day'], one:'day', up:13,lett:'D',itrv:1}
  360. ,'1W':{url:'&tbs=qdr:w', txt:$L['last'][ua||by?0:2] +' '+ $L['week'], one:'week', up:14,lett:'W',itrv:7}
  361. ,'1M':{url:'&tbs=qdr:m', txt:$L['last'][0] +' '+ $L['month'], one:'month', up:20,lett:'M',itrv:30.5}
  362. ,'1Y':{url:'&tbs=qdr:y', txt:$L['last'][de?1:0] +' '+ $L['year'], one:'year', up:10,lett:'Y',itrv:365.24}
  363. //,'1H':{url:'&tbs=qdr:h', txt:$L['last'][ua||de||by?2:0] +' '+ $L['hour'], one:'hour', up:23,lett:'H',itrv:1/24}
  364. //,DOC:{url:'&mime=doc', txt:$L['search in PDF files'].replace(/PDF/,'DOC'), up: type.length}
  365. ,PDF:{url:'&mime=pdf', txt:$L['search in PDF files'], up: type.length}
  366. }, ii = 0, iD = -1;
  367. !sites && delete buttS.site;
  368. buttSearch.parentNode.style.position ='relative';
  369. if(buttSearch && top == self) for(var i in buttS) if(i !='site'|| S.sites){ //buttons under search input line
  370. if(i.length ==2) iD++; else iD=-1;
  371. var bI = buttS[i], titl
  372. ,Gesch = ({m:'letzter',f:'letzte',n:'letztes'})['m,f,m,n,f'.split(',')[iD]]
  373. ,hint = function(j){return (j+1) +' '+ (j % 10 || j==10 ? $L[bI.one +'s'][j % 10 <4 && (j/10|0)!=1 ?0:1] : $L[bI.one]) }
  374. ,butt2 = $e({clone: i =='site'|| i.length ==2 || i=='PDF'
  375. ? $e({cl: 'siteList', cs: {cursor:'default'}, at: {site: S.sites[0], date: bI.url} })
  376. : i !='.. : ..'|| mainPg ? buttSearch : $e({cl: 'siteList hiddn'})
  377. ,clAdd:'xButt'
  378. ,atRemove: ['id', 'name','role']
  379. ,at: {value: iD !=-1 && S.dwmyh[iD] !=1 ? S.dwmyh[iD] + bI.lett : i
  380. ,innerHTML: '<span class=txt onclick=this.parentNode.click();return!1 title="' +(titl = lang || i=='site'|| i=='.. : ..'
  381. ? (iD==-1 || S.dwmyh[iD]==1 ? bI.txt : $L['last'][1] +' '+ hint(S.dwmyh[iD]-1)).replace(/letztes/,Gesch) :'')+'">'
  382. +(iD !=-1 && S.dwmyh[iD] !=1 ? S.dwmyh[iD] + bI.lett : i) +'</span>'
  383. ,title: titl}
  384. ,cs: {position: 'absolute', top: '33px', left: (-127 + 37 * (ii++ - (ii >2 && !mainPg))) +'px'}
  385. ,on: {click: (function(bI, i, iD){
  386. return /PDF|DOC|site/.test(i)
  387. ? function(ev){
  388. var doc, t = ev.target
  389. ,dat = (t.getAttribute('date')||t.parentNode.getAttribute('date')||'').replace(/^&\w+=/,'').toLowerCase();
  390. if(t.className =='defa')
  391. saveLocStor('','','remove'); $pd(ev);
  392. if(((t.getAttribute('site') ==null && t.parentNode.getAttribute('site') ==null)
  393. || t.getAttribute('site')==$LSettings || t.parentNode.getAttribute('site')==$LSettings)
  394. && !/PDF|DOC/.test(t.getAttribute('value'))) return;
  395. inputSearch.value = inputSearch.value.replace(/ site\:[\w.]*$/ig,'') +(/site/.test(i)
  396. ?' site:'+ (t.getAttribute('site') || t.parentNode.getAttribute('site')||''):'');
  397. //console.log('clic:',i,dat,bI,ev, t.className, inputSearch.value, ev.currentTarget, buttSearch.form)
  398. if(/PDF|DOC/.test(i)){
  399. if(doc = $q('select[name="mime"]')){
  400. var opts = Array.prototype.slice.call(doc).reduce(function(memo, el, i){
  401. memo[el.value] = el; return memo;},{});
  402. var opt = opts[dat];
  403. if(opt)
  404. opt.selected = opt.selected ?'':'selected';
  405. }else
  406. $e({el: buttSearch.form, ap: $e({el: $q('input[name="mime"]')||'input'
  407. ,at:{type:'hidden', name:'mime', value: dat}}) });}
  408. //console.log('clic2:', /xButt|txt/.test(t.className) && i !='site', opt, opts)
  409. if(/xButt|txt/.test(t.className) && !(i=='site' && !(/list/.test(t.parentNode.className)
  410. || /list/.test(t.parentNode.parentNode.className)))) buttSearch.click();
  411. }: !bI.url ? function(ev){ //from-to date
  412. var el = $q('#cdrlnk'), o;
  413. el && el.dispatchEvent(((o = d.createEvent('Events')).initEvent('click', !0, !1), o));
  414. $pd(ev);
  415. }: function(ev){ //last interval
  416. var val = (ev.target.getAttribute('value')||ev.target.parentNode.getAttribute('value')).replace(/\D/g,'')
  417. ,dat = ev.target.getAttribute('date')||ev.target.parentNode.getAttribute('date')
  418. ,daysAgo = buttS['1'+ ((dat.match(/:(\w)/) ||[])[1] ||'d').toUpperCase()].itrv * val
  419. ,date = function(d){
  420. d = new Date(+new Date() - d * 86400000)
  421. return (d.getDate()>9?'':'0') + d.getDate() +'.'+ (d.getMonth()>8?'':'0')
  422. +(d.getMonth()+1) +'.'+ d.getFullYear();
  423. };
  424. location.href = '/search?text='+ encodeURIComponent(inputSearch.value)
  425. +('&from_date_full='+ date(daysAgo) +'&to_date_full='+ date(-1) || bI.url);
  426. //+(/[&?]tbm=/.test(lh) ? '&'+/tbm=[^&]*/.exec(lh)[0]:''); //saving type of page
  427. S.dwmyh[iD] = +val;
  428. $pd(ev);
  429. ev.stopPropagation();
  430. saveLocStor();
  431. }
  432. })(bI, i, iD),
  433. mouseover: i =='site' || i.length ==2 || i=='PDF'? (function(bI,i){return function(ev){
  434. clearTimeout(bI.ww);
  435. $q('.list', ev.currentTarget).style.display ='block';
  436. }})(bI,i) :'',
  437. mouseout: i =='site' || i.length ==2 || i=='PDF'? (function(bI,i){return function(ev){
  438. var t = ev.currentTarget;
  439. if(ev.relatedTarget && /^<option/i.test(ev.relatedTarget.innerHTML)){
  440. ($q('.settIn')||{classList: {add:function(){}}}).classList.add('changed'); return;}
  441. clearTimeout(bI.ww);
  442. bI.ww = setTimeout(function(){
  443. $q('.list',t).style.display ='none';
  444. }, 450);
  445. }})(bI,i) :'',
  446. change: saveLocStor
  447. }
  448. ,apT: buttSearch.parentNode
  449. });
  450. bI.el = butt2;
  451. if(i =='site'|| i.length ==2 || i =='PDF'){ //dropdown lists under some buttons
  452. var siteList = $e({cl:'list',cs:{display:'none'}, apT: butt2}), arr =[];
  453. for(var j =0; j <= bI.up -1 -(i=='1W'&& S.lastHoursLess ?4:0) -(i=='1M'&& S.lastHoursLess ?9:0); j++)
  454. if(i!='PDF' &&(i !='1H' || !S.lastHoursLess || j < 8 || j % 2 ))
  455. arr.push(hint(j));
  456. //console.log(S.sites,i, S.dwmyh);
  457. var list = i == 'site' ? sites||[] : i =='1D'&& !sites ? arr.concat([$LSettings])
  458. : i=='PDF' ? type : arr;
  459. for(var j in list) if(j !=0 || iD !=-1 && S.dwmyh[iD] !=1)
  460. var sI = list[j]
  461. ,butt3 = $e({clone: sI==$LSettings
  462. ? $e({cl: 'sett lsb'})
  463. : buttSearch
  464. ,clAdd:'xButt'
  465. ,atRemove:['id','name','role']
  466. ,at:{value: sI
  467. ,site: sI
  468. ,date: bI.url.replace(/doc$/, sI.replace(/&nbsp; /g,'').toLowerCase())
  469. ,title: sI==$LSettings || !lang ?'':(/site|PDF/.test(i) ? $L['search in'] +' '+ sI.replace(/&nbsp; /g,'')
  470. : j==0 ? bI.txt : $L['last'][1] +' '+ sI).replace(/letztes/,Gesch)
  471. ,innerHTML:'<span class=txt>'+ sI +'</span>'+ (sI != $LSettings &&!(!S.sites && i =='1H')
  472. ?'':'<div class="settIn">'
  473. +$LSettings +' '+ $L['of userscript'] +'<br>"Yandex Extra Buttons"<hr>'
  474. +$L['Interface language'] +': <select class="lang" style="width:70px">'
  475. +(function(){var s='<option'+ (lang=='en'?' selected':'') +'>en</option>';
  476. for(var i in $l)
  477. s+='<option'+ (lang==i ?' selected':'') +'>'+ i +'</option>';
  478. return s +'<option value="" '+ (lang==''?'selected':'') +'>en w/o hints</option>'})()
  479. +'</select><br>'
  480. +'<input type="checkbox" class="less" id="hoursLess" '+ (S.lastHoursLess ?'checked':'') +'/>'
  481. +'<label for="hoursLess" id="hoursLessL">'+ $L['Less positions at the end of selects'] +'</label><br>'
  482. +'<i><a href="#" class="defa" style="float: right">Default settings</a></i>'
  483. +$L.Sites +': <br><textarea class="sites" style="width:97%" rows=8>'
  484. + strSites +'</textarea><br>'
  485. +'<a class="reload" href=# onclick="location.reload();return!1">'
  486. + $L['reload page for effect'] +'</a>'
  487. +'</div>')}
  488. ,cs: {position: sI != $LSettings ?'static':'absolute',display:'block', width:'auto', height: sI != $LSettings ?'18px':'16px'
  489. ,margin:'2px 0 -1px -13px', padding:0, textAlign:'left', fontWeight:'normal', opacity:1}
  490. ,on:{click: function(ev){
  491. //console.log('c3',ev.target.outerHTML);
  492. var chk = $q('#hoursLess');
  493. if(chk && /hoursLess/.test(ev.target.id)){
  494. chk.outerHTML = '<input type="checkbox" class="less" id="hoursLess"'
  495. +(chk.getAttribute('checked')!=null ?'':' checked="checked"')+'>';
  496. saveLocStor();
  497. }
  498. $pd(ev);}}
  499. ,apT: siteList
  500. });
  501. siteList.style.height ='auto'; siteList.style.textAlign ='center';
  502. }
  503. }
  504. }
  505. });
  506.  
  507. }, el: d.body});
  508. var saveLocStor = function(ev, val, do2){ var aaa,aab,aac, t = ev && ev.target.form || document.documentElement || document.body;
  509. xLocStor({do: do2 ||'set', key:'sett'
  510. , val:{lang: (aaa=d.querySelectorAll('.lang', t))[aaa.length-1].value
  511. ,sites: (aab=d.querySelectorAll('.sites', t))[aab.length-1].value.replace(/^[ \t]*|[ \n\t]*$/g,'')
  512. .split('\n')
  513. ,lastHoursLess: (aac=d.querySelectorAll('.less', t))[aac.length-1].checked
  514. ,dwmyh: S.dwmyh || setts.dwmyh
  515. }
  516. ,cB: function(prev){
  517. console.info('Settings are saved. prev=', prev);}
  518. });
  519. $q('.siteList .settIn').classList.add('changed');
  520. };
  521.  
  522. })({ //write "lang:''," to remove hints; 'en' for English hints (fr - Français, es - espagnol), 'ru' for Russian
  523. lang:''|| (navigator.languages && navigator.languages[1] || navigator.language.substr(0,2)) //='' if hide hints, or 2 letters from $l{}
  524. ,sites: [ //=array or one site in string
  525. '','slashdot.org','reddit.com','techcrunch.com','habrahabr.ru','geektimes.ru'
  526. ,'smashingmagazine.com','engadget.com'] //write your favorite sites
  527. ,lastHoursLess: 1 //=boolean - not show odd some values of hours after 8 h
  528. ,dwmyh: [1,1,1,1,1] //=array of numbers - current vals of days, weeks, months, years, hours
  529. });