main.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. function $(id) {return document.getElementById(id);}
  2. // ############### Mobile Device ################
  3. if (window.screen.width < 769) {
  4. $('nav').style.display = 'none';
  5. }
  6. $('menu-icon').onclick = function(){
  7. $('nav').style.display = $('nav').style.display == 'none' ? 'block' : 'none';
  8. };
  9. //########## Main Page Alert Handler ############
  10. // fadeIn animation special for alerts
  11. function fadeIns(el){
  12. el.style.opacity = 0;
  13. (function fade() {
  14. var val = parseFloat(el.style.opacity);
  15. if (((val += 0.03) > 1) !== true) {
  16. el.style.opacity = val;
  17. var request = window.requestFrame('request');
  18. request(fade);
  19. }
  20. })();
  21. }
  22. var ac = $('AC'),
  23. dc = $('DC'),
  24. in_freq = $('in_freq'),
  25. out_freq = $('out_freq'),
  26. pwr = $('pwr'),
  27. bat_rem_cap = $('bat_rem_cap'),
  28. inner_temp = $('inner_temp'),
  29. battimeleft = $('bat_time_left'),
  30. // alarm = $('alarm'),
  31. sPower = $('sPower'),
  32. sBattery = $('sBattery');
  33. var battempCtrlChecked;
  34. function dataFadeIn(){
  35. var x = [
  36. ac,
  37. dc,
  38. in_freq,
  39. out_freq,
  40. pwr,
  41. bat_rem_cap,
  42. inner_temp,
  43. battimeleft,
  44. sPower,
  45. sBattery
  46. ];
  47. for (var i = 0; i < x.length; i++){
  48. fadeIns(x[i]);
  49. }
  50. }
  51. // Alarm colors
  52. var ALARM_RED = '#ff5050',
  53. ALARM_YELLOW = '#f0ad4e',
  54. ALARM_GREEN = '#33cc00';
  55. //########## Settings Inform Boxes ############
  56. function HTMLcreate(htmlStr) {
  57. var frag = document.createDocumentFragment(),
  58. temp = document.createElement('div');
  59. temp.innerHTML = htmlStr;
  60. while (temp.firstChild) {
  61. frag.appendChild(temp.firstChild);
  62. }
  63. return frag;
  64. }
  65. // fade in animation
  66. function fadeIn(el, display){
  67. el.style.opacity = 0;
  68. el.style.display = display || 'block';
  69. (function fade() {
  70. var val = parseFloat(el.style.opacity);
  71. if (((val += 0.05) > 1) !== true) {
  72. el.style.opacity = val;
  73. var request = window.requestFrame('request');
  74. request(fade);
  75. }
  76. })();
  77. }
  78. //########## Settings Form ############
  79. function formValidation(){
  80. var read_community,write_community,managerIP,managerIP2,managerIP3,managerIP4,managerIP5,
  81. ups_cell_min, ups_cell_max,
  82. ipaddr, gw, mask, tn_port/*, ntpservip*/;
  83. read_community = $('read_community'),
  84. write_community = $('write_community'),
  85. managerIP = $('managerIP'),
  86. managerIP2 = $('managerIP2'),
  87. managerIP3 = $('managerIP3'),
  88. managerIP4 = $('managerIP4'),
  89. managerIP5 = $('managerIP5'),
  90. ipaddr = $('ipaddr'),
  91. gw = $('gw'),
  92. mask = $('mask'),
  93. tn_port = $('tn_port');
  94. ups_cell_min = +$('ups_cell_min').children[0].value;
  95. ups_cell_max = +$('ups_cell_max').children[0].value;
  96. // ntpservip = $('ntpservip');
  97. var flag = true;
  98. if (!$('dhcp').checked) {
  99. if(!ValidateIPaddress(ipaddr, ' IP-адрес устройства')) flag = false;
  100. if(!ValidateIPaddress(gw, ' IP-адрес шлюза')) flag = false;
  101. if(!ValidateIPaddress(mask, 'а Маска подсети')) flag = false;
  102. }
  103. if ($('tn_enabled').checked) {
  104. if(!ValidateNumber(tn_port, ' Порт Telnet')) flag = false;
  105. }
  106. if(ups_cell_min > ups_cell_max) {
  107. var warn = document.createElement('li');
  108. warn.innerHTML = 'Минимальное напряжение на ячейке не может быть больше максимального!';
  109. $('validation-box').appendChild(warn);
  110. flag = false;
  111. }
  112. if(!ValidateIPaddress(managerIP, ' Сервер SNMP 1')) flag = false;
  113. if(!ValidateAlphanumeric(read_community, 'Read Community')) flag = false;
  114. if(!ValidateAlphanumeric(write_community, 'Write Community')) flag = false;
  115. if(!ValidateIPaddress(managerIP2, ' Сервер SNMP 2')) flag = false;
  116. if(!ValidateIPaddress(managerIP3, ' Сервер SNMP 3')) flag = false;
  117. if(!ValidateIPaddress(managerIP4, ' Сервер SNMP 4')) flag = false;
  118. if(!ValidateIPaddress(managerIP5, ' Сервер SNMP 5')) flag = false;
  119. if ($('ntp-inp') && !$('ntp-inp').disabled) {
  120. if(!ValidateIPaddress($('ntp-inp'), ' IP адрес NTP сервера')) flag = false;
  121. }
  122. return flag;
  123. }
  124. function ValidateIPaddress(ipaddress, z) {
  125. var warn = document.createElement('li');
  126. warn.innerHTML = 'Неправильно задан' + z + '!';
  127. if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress.value)) {
  128. return true;
  129. }
  130. $('validation-box').appendChild(warn);
  131. return false;
  132. }
  133. function ValidateNumber(n, z) {
  134. var warn = document.createElement('li');
  135. warn.innerHTML = 'Неправильно задан' + z + '!';
  136. if(/^-?[\d.]+(?:e-?\d+)?$/.test(n.value)) {
  137. return true;
  138. }
  139. $('validation-box').appendChild(warn);
  140. return false;
  141. }
  142. function ValidateAlphanumeric(uadd, z) {
  143. var warn = document.createElement('li');
  144. var letter = /^[0-9a-zA-Z]+$/;
  145. warn.innerHTML = 'Поле ' + z + ' может содержать только латинские буквы и цифры';
  146. if (letter.test(uadd.value)) {return true;}
  147. $('validation-box').appendChild(warn);
  148. return false;
  149. }
  150. function validateUpload(oForm) {
  151. var file = oForm.elements.datafile.files[0];
  152. var fnmreg = /^.{1,}\.crt$/g;
  153. if (file && fnmreg.test(file.name) ) {
  154. upload(file);
  155. } else {
  156. alert('Файл сертификата не указан или не валиден!');
  157. }
  158. return false;
  159. }
  160. function submitForms() {
  161. if (confirm('Вы уверены что хотите применить настройки?')) {
  162. if ($('ntp-inp')) {
  163. $('ntpservip').options[3].value = $('ntp-inp').value;
  164. }
  165. if (formValidation()) {
  166. $('form1').submit();
  167. }
  168. else{
  169. $('validation-box').style.display = 'block';
  170. }
  171. }
  172. }
  173. function upload(file) {
  174. var fl = new FormData();
  175. fl.append('file', file);
  176. var xhr = new XMLHttpRequest();
  177. xhr.open('POST', '/srv_crt_upload.cgi', true);
  178. // обработчик для закачки
  179. xhr.upload.onprogress = function(event) {
  180. var progress = Math.floor((event.loaded / event.total) * 100);
  181. console.log(progress + '%');
  182. };
  183. xhr.onload = xhr.onerror = function() {
  184. if (this.status == 200) {
  185. if (+xhr.responseText == '1') {
  186. alert('Успешно');
  187. window.location.reload();
  188. } else {
  189. alert('Ошибка установки сертификата');
  190. }
  191. } else {
  192. alert('Ошибка ' + this.status);
  193. }
  194. };
  195. xhr.send(fl);
  196. }
  197. function checkPWD(){
  198. // $('checkUpdatePass').style.display = 'none';
  199. $('count-wrap').style.display = 'block';
  200. $('countdown').style.display = 'block';
  201. countdown();
  202. }
  203. function checkChangePWD(){
  204. var user = $('changePasswordUser').value;
  205. var oldpass = $('oldpwd').value;
  206. var newpass = $('newpwd').value;
  207. var newpassrepeat = $('newpwdrepeat').value;
  208. var letter = /^[0-9a-zA-Z.,/\\\-_*#()[\]+:'"@!^%&?|${}`~<>]+$/;
  209. if (oldpass.length === 0 || newpass.length === 0 || newpassrepeat.length === 0){
  210. alert('Поля не заполнены!');
  211. } else if (newpass !== newpassrepeat){
  212. alert('Поля с новым паролем не совпадают!');
  213. $('oldpwd').value = '';
  214. $('newpwd').value = '';
  215. $('newpwdrepeat').value = '';
  216. } else if (user === ''){
  217. alert('Не выбран пользователь для которого необходимо сменить пароль!');
  218. } else {
  219. if (letter.test(oldpass) && letter.test(newpass) && letter.test(newpassrepeat)) {
  220. loadXMLDoc('changepwd.cgi?username=' + encodeURIComponent(user) + '&oldpass=' + encodeURIComponent(oldpass) + '&newpass=' + encodeURIComponent(newpass), 'GET', function(){
  221. alert(this.responseText);
  222. window.location.reload();
  223. });
  224. } else {
  225. alert('Пароль задан неправильно');
  226. $('oldpwd').value = '';
  227. $('newpwd').value = '';
  228. $('newpwdrepeat').value = '';
  229. }
  230. }
  231. }
  232. function timesetType(el) {
  233. if (el.selectedIndex === 0) {
  234. $('ntpservip_l').className += ' hidden';
  235. $('ntpservip').className += ' hidden';
  236. $('ntpservip').setAttribute('disabled', 'disabled');
  237. if ($('ntp-inp')) {
  238. $('ntp-inp').className += ' hidden';
  239. $('ntp-inp').setAttribute('disabled', 'disabled');
  240. }
  241. $('lastsynctime_l').className += ' hidden';
  242. $('lastsynctime').className += ' hidden';
  243. // -----------------
  244. $('date_l').className = 'col span_1_of_2';
  245. $('date').className = 'form-control';
  246. $('time_l').className = 'col span_1_of_2';
  247. $('time').className = 'form-control';
  248. $('date').removeAttribute('disabled');
  249. $('time').removeAttribute('disabled');
  250. } else {
  251. $('ntpservip_l').className = 'col span_1_of_2';
  252. $('ntpservip').className = 'form-control';
  253. $('ntpservip').removeAttribute('disabled');
  254. if ($('ntp-inp')) {
  255. $('ntp-inp').className = 'form-control';
  256. $('ntp-inp').removeAttribute('disabled');
  257. }
  258. $('lastsynctime_l').className = 'col span_1_of_2';
  259. $('lastsynctime').className = 'form-control';
  260. // -------------
  261. $('date_l').className += ' hidden';
  262. $('date').className += ' hidden';
  263. $('time_l').className += ' hidden';
  264. $('time').className += ' hidden';
  265. $('date').setAttribute('disabled', 'disabled');
  266. $('time').setAttribute('disabled', 'disabled');
  267. }
  268. }
  269. function countdown(rel) {
  270. var countDown = 10;
  271. setInterval(function () {
  272. if (countDown == 1 && rel === true) {
  273. location.reload(true);
  274. }
  275. else if (countDown == 1 && rel !== true){
  276. window.location.href = 'http:' + window.location.origin.substring(window.location.protocol.length);
  277. }
  278. if (countDown > 0){countDown--;}
  279. $('count-number').innerHTML = countDown;
  280. return countDown;
  281. }, 1000);
  282. }
  283. function dhcpState() {
  284. if ($('dhcp').checked) {
  285. $('ipaddr').setAttribute('disabled', 'disabled');
  286. $('gw').setAttribute('disabled', 'disabled');
  287. $('mask').setAttribute('disabled', 'disabled');
  288. } else {
  289. $('ipaddr').removeAttribute('disabled');
  290. $('gw').removeAttribute('disabled');
  291. $('mask').removeAttribute('disabled');
  292. }
  293. }
  294. function telnetState() {
  295. if (!$('tn_enabled').checked) {
  296. $('tn_port').setAttribute('disabled', 'disabled');
  297. } else {
  298. $('tn_port').removeAttribute('disabled');
  299. }
  300. }
  301. //########## Info Form Validation ############
  302. function infoValidation(){
  303. var sysname, owner, sysLocation,comment;
  304. sysname = $('sysname').value,
  305. owner = $('owner').value,
  306. sysLocation = $('sysLocation').value,
  307. comment = $('comment').value;
  308. var flag = true;
  309. if(!ValidateAlphanumeric2(sysname, 'Название устройства')){flag = false;}
  310. if(!ValidateAlphanumeric2(owner, 'Владелец')){flag = false;}
  311. if(!ValidateAlphanumeric2(sysLocation, 'Местоположение')){flag = false;}
  312. if(!ValidateAlphanumeric2(comment, 'Комментарии')){flag = false;}
  313. return flag;
  314. }
  315. function ValidateAlphanumeric2(uadd, z) {
  316. var warn = document.createElement('li');
  317. // var letter = /^[0-9a-zA-Z]+[^\u0430-\u044f\u0410-\u042f\u0451\u0401\?]+$/m;
  318. var letter = /^[0-9a-zA-Z.,/\-_*#()[\]+=;:'"@!^%&?|${}`~<>]+$/m;
  319. warn.innerHTML = 'Поле ' + z + ' может содержать только латинские буквы, цифры и символы .,/-_*#()[]+=;:\'"@!^%&?|${}`~<>';
  320. if (letter.test(uadd) || !uadd) {
  321. return true;
  322. }
  323. $('validation-box').appendChild(warn);
  324. return false;
  325. }
  326. function submitInfo() {
  327. if (confirm('Вы уверены что хотите применить изменения?')) {
  328. if (infoValidation()) {
  329. $('SNMPinfo').submit();
  330. // loadXMLDoc('info.cgi?owner='+ $('owner').value + '&sysLocation='+ $('location').value + '&comment='+ decodeURIComponent($('comment').value), 'GET', function(){
  331. // console.log('Сохранено');
  332. // });
  333. }
  334. else {
  335. $('validation-box').style.display = 'block';
  336. }
  337. }
  338. }
  339. function getJSON(url, successHandler, errorHandler) {
  340. var xhr;
  341. xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP');
  342. xhr.open('GET', url, true);
  343. xhr.onreadystatechange = function () {
  344. var status;
  345. var data;
  346. if (xhr.readyState == 4) {
  347. status = xhr.status;
  348. if (status == 200) {
  349. data = JSON.parse(xhr.responseText);
  350. successHandler(data);
  351. } else {
  352. errorHandler(status);
  353. }
  354. }
  355. };
  356. xhr.send();
  357. }
  358. function updatepage(){
  359. var loc = location.pathname.slice(1, -5);
  360. switch(loc){
  361. case 'settings':
  362. setTimeout(settingsGET, 1000);
  363. break;
  364. case 'history':
  365. getPage($('currentpage').value);
  366. break;
  367. }
  368. }
  369. function getCGI(url) {
  370. var xmlhttp;
  371. var q;
  372. if (url == 'reset.cgi') {
  373. q = confirm('Вы уверены что хотите сбросить в заводские настройки?');
  374. }
  375. if (url == 'reboot.cgi') {
  376. q = confirm('Вы уверены что хотите перезагрузить устройство?');
  377. }
  378. if (url == 'update.cgi') {
  379. q = confirm('Вы уверены что хотите обновить прошивку устройства?');
  380. }
  381. if (q) {
  382. if (window.XMLHttpRequest) {
  383. xmlhttp = new XMLHttpRequest();
  384. } else {
  385. xmlhttp = new window.ActiveXObject('Microsoft.XMLHTTP');
  386. }
  387. // xmlhttp.onreadystatechange = true;
  388. xmlhttp.open('GET', url, true);
  389. xmlhttp.send();
  390. return true;
  391. }
  392. // else {alert(a);}
  393. }
  394. function Alarm(bitmask, num) {
  395. // Bit mask format DEC <NUMBER>
  396. var answ = (bitmask & (1 << num)) >> num;
  397. return answ;
  398. }
  399. function setIcons(containerID, icnName) {
  400. $(containerID).innerHTML ='';
  401. var icons = typeof icnName === 'string' ? [icnName] : icnName;
  402. for (var i = 0; i < icons.length; i++) {
  403. var icnContainer = document.createElement('i');
  404. icnContainer.innerHTML = Icons[icons[i]]['icn'];
  405. icnContainer.style.paddingLeft = '10px';
  406. icnContainer.title = Icons[icons[i]]['title'];
  407. $(containerID).appendChild(icnContainer);
  408. }
  409. }
  410. function paramsRefresh() {
  411. getJSON('getJson.cgi'+'?'+Math.random(), function (data) {
  412. var alrm = +data.u_alarm;
  413. var ma = +data.m_alarm;
  414. var pstate = [];
  415. var bstate = [];
  416. var ups_bypass = Alarm(alrm, 5),
  417. ups_alarm = Alarm(alrm, 4) || Alarm(alrm, 7),
  418. ups_standby = Alarm(alrm, 3),
  419. ups_shutdown = Alarm(alrm, 1),
  420. bat_low = Alarm(alrm, 6),
  421. bat_test = Alarm(alrm, 2);
  422. // PPS
  423. $('AC').innerHTML = parseFloat(data.AC) + ' В';
  424. $('AC').style.color = Alarm(alrm, 7) ? ALARM_RED : ALARM_GREEN;
  425. $('DC').innerHTML = parseFloat(data.DC) + ' В';
  426. $('DC').style.color = Alarm(ma, 7) ? ALARM_RED : ALARM_GREEN;
  427. $('in_freq').innerHTML = parseFloat(data.in_freq) + ' Гц';
  428. $('in_freq').style.color = Alarm(alrm, 7) ? ALARM_RED : ALARM_GREEN;
  429. $('out_freq').innerHTML = parseFloat(data.out_freq) + ' Гц';
  430. $('out_freq').style.color = Alarm(ma, 7) ? ALARM_RED : ALARM_GREEN;
  431. $('pwr').innerHTML = parseFloat(data.pwr) + ' %';
  432. $('pwr').style.color = Alarm(ma, 0) ? ALARM_RED : ALARM_GREEN;
  433. $('pmode').innerHTML = ups_bypass ? 'Bypass' : 'Boost or Buck';
  434. // State
  435. ups_alarm ? pstate.push('exclamination') : pstate.push('normal');
  436. // ups_standby ? pstate.push('clock') : null;
  437. ups_shutdown ? pstate.push('shutdown') : null;
  438. !Alarm(ma, 3) && !bat_low ? bstate.push('normal') : null;
  439. Alarm(ma, 3) ? bstate.push('exclamination') : null;
  440. bat_low ? bstate.push('batteryLow') : null;
  441. bat_test ? bstate.push('batTest') : null;
  442. setIcons('pstate_icons', pstate);
  443. setIcons('bstate_icons', bstate);
  444. // ACB
  445. $('bat_rem_cap').innerHTML = parseFloat(data.bat_rem_cap) + ' %';
  446. $('bat_rem_cap').style.color = bat_low ? ALARM_RED : ALARM_GREEN;
  447. $('inner_temp').innerHTML = parseFloat(data.inner_temp) + ' °C';
  448. $('inner_temp').style.color = Alarm(ma, 1) || Alarm(ma, 5) ? ALARM_RED : ALARM_GREEN;
  449. $('bat_time_left').innerHTML = parseFloat(data.bat_time_left) + ' мин';
  450. $('bat_time_left').style.color = bat_low ? ALARM_RED : ALARM_GREEN;
  451. // Inputs
  452. $('di1').innerHTML = +data.di1 ? 'Разомкнут' : 'Замкнут';
  453. $('di1').style.color = Alarm(ma, 4) ? ALARM_RED : ALARM_GREEN;
  454. $('ro1').innerHTML = +data.ro1 ? 'Замкнут' : 'Разомкнут';
  455. $('ro1').style.color = +data.ro1 ? ALARM_GREEN : ALARM_RED;
  456. $('ro2').innerHTML = +data.ro2 ? 'Замкнут' : 'Разомкнут';
  457. $('ro2').style.color = +data.ro2 ? ALARM_GREEN : ALARM_RED;
  458. $('ro3').innerHTML = +data.ro3 ? 'Замкнут' : 'Разомкнут';
  459. $('ro3').style.color = +data.ro3 ? ALARM_GREEN : ALARM_RED;
  460. // checkState();
  461. window.setCookie('netsettings_changed', data.netsettings_changed);
  462. window.setCookie('device-error', Alarm(ma, 2));
  463. checkNotify();
  464. setTimeout(paramsRefresh, 1000);
  465. }, function (status) {
  466. if (status !== 0){
  467. alert('Не удалось получить данные.');
  468. setTimeout(paramsRefresh, 15000);
  469. }
  470. });
  471. }
  472. var mint;
  473. //########## History ############
  474. var ctrl_inputs = [
  475. 'h_param_',
  476. 'h_event_',
  477. 'h_datetime_'
  478. ];
  479. function getPage(pn){
  480. getJSON('history.cgi?page=' + pn, function(data){
  481. $('history_data').textContent = '';
  482. var n = data.page;
  483. $('currentpage').value = pn;
  484. $('pagelimit').innerHTML = data.pages;
  485. for (var i in n){
  486. var tr = document.createElement('tr');
  487. for (var num = 0; num < ctrl_inputs.length; num++) {
  488. var td = document.createElement('td');
  489. td.innerHTML = n[i].split(';')[num];
  490. td.id = ctrl_inputs[num] + i;
  491. tr.appendChild(td);
  492. }
  493. $('history_data').appendChild(tr);
  494. }
  495. window.setCookie('netsettings_changed', data.netsettings_changed);
  496. checkNotify();
  497. clearTimeout(mint);
  498. mint = setTimeout(history_dataref, 5000);
  499. }, function(){
  500. $('table').display = 'none';
  501. $('content').innerHTML =
  502. '<h1>Журнал событий</h1>'+
  503. '<div class="panel panel-default">'+
  504. '<div class="panel-heading">Ошибка</div>'+
  505. '<p style="text-align: center;">Данные отсутствуют.</p>'+
  506. '</div>';
  507. });
  508. }
  509. function history_dataref() {
  510. var pn = parseInt($('currentpage').value);
  511. getJSON('history.cgi?page=' + pn, function(data) {
  512. var p = data.page;
  513. for (var j in p) {
  514. for (var num = 0; num < ctrl_inputs.length; num++) {
  515. $(ctrl_inputs[num] + j).innerHTML = p[j].split(';')[num];
  516. }
  517. $('pagelimit').innerHTML = data.pages;
  518. }
  519. clearTimeout(mint);
  520. mint = setTimeout(history_dataref, 5000);
  521. });
  522. }
  523. function nextPage(){
  524. var next = parseInt($('currentpage').value);
  525. if (next < parseInt($('pagelimit').textContent)) {
  526. next = next + 1;
  527. getPage(next);
  528. }
  529. }
  530. function prevPage(){
  531. var prev = parseInt($('currentpage').value);
  532. if (prev != 1) {
  533. prev = prev - 1;
  534. getPage(prev);
  535. }
  536. }
  537. //########## UPS History ############
  538. var ups_inputs = [
  539. { id: 'h_inputv_', unit: ' В', parse: 'float' },
  540. { id: 'h_inputfv_', unit: ' В', parse: 'float' },
  541. { id: 'h_outputv_', unit: ' В', parse: 'float' },
  542. { id: 'h_outputc_', unit: '%', parse: 'float' },
  543. { id: 'h_inputf_', unit: ' Гц', parse: 'float' },
  544. { id: 'h_batv_', unit: ' В', parse: 'float' },
  545. { id: 'h_temp_', unit: ' °C', parse: 'float' },
  546. { id: 'h_status_', unit: '', parse: 'string' },
  547. { id: 'h_time_', unit: '', parse: 'string' }
  548. ];
  549. function getUPSPage(pn){
  550. getJSON('ups_history.cgi?page=' + pn, function(data){
  551. $('history_data').textContent = '';
  552. var n = data.page;
  553. $('currentpage').value = pn;
  554. $('pagelimit').innerHTML = data.pages;
  555. for (var i in n){
  556. var tr = document.createElement('tr');
  557. for (var num = 0; num < ups_inputs.length; num++) {
  558. var td = document.createElement('td');
  559. td.innerHTML = ups_inputs[num].parse === 'float' ? parseFloat(n[i].split(';')[num]) + ups_inputs[num].unit : n[i].split(';')[num] + ups_inputs[num].unit;
  560. td.id = ups_inputs[num].id + i;
  561. tr.appendChild(td);
  562. }
  563. $('history_data').appendChild(tr);
  564. }
  565. window.setCookie('netsettings_changed', data.netsettings_changed);
  566. checkNotify();
  567. clearTimeout(mint);
  568. mint = setTimeout(ups_history_dataref, 5000);
  569. }, function(){
  570. $('table').display = 'none';
  571. $('content').innerHTML =
  572. '<h1>Журнал событий</h1>'+
  573. '<div class="panel panel-default">'+
  574. '<div class="panel-heading">Ошибка</div>'+
  575. '<p style="text-align: center;">Данные отсутствуют.</p>'+
  576. '</div>';
  577. });
  578. }
  579. function ups_history_dataref() {
  580. var pn = parseInt($('currentpage').value);
  581. getJSON('ups_history.cgi?page=' + pn, function(data) {
  582. var p = data.page;
  583. for (var j in p) {
  584. for (var num = 0; num < ups_inputs.length; num++) {
  585. $(ups_inputs[num].id + j).innerHTML = ups_inputs[num].parse === 'float' ? parseFloat(p[j].split(';')[num]) + ups_inputs[num].unit : p[j].split(';')[num] + ups_inputs[num].unit;
  586. }
  587. $('pagelimit').innerHTML = data.pages;
  588. }
  589. clearTimeout(mint);
  590. mint = setTimeout(ups_history_dataref, 5000);
  591. });
  592. }
  593. function nextUPSPage(){
  594. var next = parseInt($('currentpage').value);
  595. if (next < parseInt($('pagelimit').textContent)) {
  596. next = next + 1;
  597. getUPSPage(next);
  598. }
  599. }
  600. function prevUPSPage(){
  601. var prev = parseInt($('currentpage').value);
  602. if (prev != 1) {
  603. prev = prev - 1;
  604. getUPSPage(prev);
  605. }
  606. }
  607. function utf8_decode (s) {
  608. var bb = '', c = 0;
  609. for (var i = 0; i < s.length; i++) {
  610. c = s.charCodeAt(i);
  611. if (c > 127) {
  612. if (c > 1024) {
  613. if (c == 1025) {
  614. c = 1016;
  615. } else if (c == 1105) {
  616. c = 1032;
  617. }
  618. bb += String.fromCharCode(c - 848);
  619. }
  620. } else {
  621. bb += s.charAt(i);
  622. }
  623. }
  624. return bb;
  625. }
  626. function msieversion() {
  627. var ua = window.navigator.userAgent;
  628. var msie = ua.indexOf('MSIE ');
  629. if (msie != -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) /*If IE, return version number*/ return true;
  630. return false;
  631. }
  632. function blobLoad(requestUrl, fileName, buttonID){
  633. if(isMobile.iOS()){
  634. alert('На данном устройстве сохранение не доступно.');
  635. return false;
  636. }
  637. var old = $(buttonID).children[0].textContent;
  638. var pgFlag = 'Обработка';
  639. var pgFlagLen = pgFlag.length;
  640. var d = new Date();
  641. var fName;
  642. if (fileName === 'settings.dat') {
  643. fName = fileName;
  644. } else {
  645. fName = d.getDate()+'_'+(d.getMonth()+1)+'_'+d.getHours()+d.getMinutes() + '_' + fileName;
  646. }
  647. var xhr = new XMLHttpRequest();
  648. var fURL = requestUrl.split('.').pop() == 'cgi' ? requestUrl+'?' : requestUrl+'&';
  649. xhr.open('GET', fURL+'_='+ new Date().getTime());
  650. xhr.responseType = 'blob';
  651. $(buttonID).setAttribute('disabled', 'disabled');
  652. xhr.addEventListener('load', function(){
  653. $(buttonID).children[1].style.width = 0;
  654. $(buttonID).children[0].textContent = old;
  655. $(buttonID).removeAttribute('disabled');
  656. });
  657. xhr.onload = function(){
  658. if (this.status === 200) {
  659. var blob = this.response;
  660. if(msieversion()){
  661. if (window.navigator.msSaveOrOpenBlob) {
  662. window.navigator.msSaveOrOpenBlob(blob, fName);
  663. } else {
  664. var IEwindow = window.open(requestUrl);
  665. }
  666. } else {
  667. var objectUrl = URL.createObjectURL(blob);
  668. var uri = objectUrl;
  669. var link = document.createElement('a');
  670. link.href = uri;
  671. link.style = 'visibility:hidden';
  672. link.download = fName;
  673. document.body.appendChild(link);
  674. link.click();
  675. document.body.removeChild(link);
  676. }
  677. }
  678. };
  679. xhr.onprogress = function(event) {
  680. $(buttonID).children[0].textContent = parseInt((event.loaded / event.total) * 100) + '%';
  681. $(buttonID).children[1].style.width = parseInt((event.loaded / event.total) * 100) + '%';
  682. };
  683. xhr.send();
  684. }
  685. var isMobile = {
  686. Android: function() {
  687. return navigator.userAgent.match(/Android/i);
  688. },
  689. BlackBerry: function() {
  690. return navigator.userAgent.match(/BlackBerry/i);
  691. },
  692. iOS: function() {
  693. return navigator.userAgent.match(/iPhone|iPad|iPod/i);
  694. },
  695. Opera: function() {
  696. return navigator.userAgent.match(/Opera Mini/i);
  697. },
  698. Windows: function() {
  699. return navigator.userAgent.match(/IEMobile/i);
  700. },
  701. any: function() {
  702. return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  703. }
  704. };
  705. function checkOther(ele) {
  706. if (ele.selectedIndex == 3) {
  707. var newInput = document.createElement('input');
  708. newInput.type = 'text';
  709. newInput.className = 'form-control';
  710. newInput.id = 'ntp-inp';
  711. newInput.value = ntpservipValue;
  712. newInput.style.marginTop = '10px';
  713. ele.parentNode.insertBefore(newInput, ele.nextSibling);
  714. }
  715. else if ($('ntp-inp')) {
  716. var d = $('ntp-inp');
  717. ele.parentNode.removeChild(d);
  718. }
  719. }
  720. // ################################################################################
  721. function fillTempRange(id, min, max) {
  722. var obj = $(id);
  723. for (var i = min; i <= max; i++) {
  724. var opt = document.createElement('option');
  725. opt.value = i;
  726. opt.text = i;
  727. obj.appendChild(opt);
  728. }
  729. }
  730. function settingsGET(){
  731. getJSON('settings.cgi', function(data) {
  732. //SNMP params
  733. $('managerIP').value = data.managerIP;
  734. $('read_community').value = data.read_community;
  735. $('write_community').value = data.write_community;
  736. $('managerIP2').value = data.managerIP2;
  737. $('managerIP3').value = data.managerIP3;
  738. $('managerIP4').value = data.managerIP4;
  739. $('managerIP5').value = data.managerIP5;
  740. $('di1').value = +data.di1;
  741. $('ro1').value = +data.ro1;
  742. $('ro2').value = +data.ro2;
  743. $('ro3').value = +data.ro3;
  744. // Network params
  745. $('ipaddr').value = data.ipaddr;
  746. $('gw').value = data.gw;
  747. $('mask').value = data.mask;
  748. $('dhcp').checked = data.dhcp;
  749. // Alarms
  750. fillTempRange('temp_high', 40, 80);
  751. fillTempRange('temp_low', -40, 0);
  752. fillTempRange('loadvolt_high', 60, 120);
  753. fillTempRange('mainvolt_low', 110, 200);
  754. fillTempRange('mainvolt_high', 220, 250);
  755. $('temp_high').value = data.temp_high;
  756. $('temp_low').value = data.temp_low;
  757. ups_cell_min = new SpinBox('ups_cell_min', {
  758. 'value': data.ups_cell_min,
  759. 'name':'ups_cell_min',
  760. 'minimum':0,
  761. 'maximum':3.0,
  762. 'decimals':2,
  763. 'step':0.01
  764. });
  765. ups_cell_max = new SpinBox('ups_cell_max', {
  766. 'value': data.ups_cell_max,
  767. 'name':'ups_cell_max',
  768. 'minimum':0,
  769. 'maximum':3.0,
  770. 'decimals':2,
  771. 'step':0.01
  772. });
  773. temp_hist = new SpinBox('temp_hist', {
  774. 'name':'temp_hist','minimum':0.5,'maximum':2.0,'step':0.1,'decimals':1, 'value': data.temp_hist
  775. });
  776. $('loadvolt_high').value = data.loadvolt_high;
  777. loadvolt_hist = new SpinBox('loadvolt_hist', {
  778. 'name':'loadvolt_hist','minimum':0.5,'maximum':2.0,'step':0.1,'decimals':1, 'value': data.loadvolt_hist
  779. });
  780. $('mainvolt_low').value = data.mainvolt_low;
  781. $('mainvolt_high').value = data.mainvolt_high;
  782. mainvolt_hist = new SpinBox('mainvolt_hist', {
  783. 'name':'mainvolt_hist','minimum':10,'maximum':30,'step':1, 'value': data.mainvolt_hist
  784. });
  785. //
  786. $('tn_enabled').checked = data.tn_enabled;
  787. $('tn_port').value = data.tn_port;
  788. // DateTime
  789. if (data.ntpservip != $('ntpservip').options[0].value &&
  790. data.ntpservip != $('ntpservip').options[1].value &&
  791. data.ntpservip != $('ntpservip').options[2].value )
  792. {
  793. var newInput = document.createElement('input');
  794. newInput.type = 'text';
  795. newInput.className = 'form-control';
  796. newInput.id = 'ntp-inp';
  797. newInput.style.marginTop = '10px';
  798. $('ntpservip').options[3].selected = 'selected';
  799. $('ntpservip').options[3].value = data.ntpservip;
  800. $('ntpservip').parentNode.insertBefore(newInput, $('ntpservip').nextSibling);
  801. window.ntpservipValue = data.ntpservip;
  802. newInput.value = window.ntpservipValue;
  803. } else {
  804. window.ntpservipValue = data.ntpservip;
  805. $('ntpservip').value = window.ntpservipValue;
  806. }
  807. $('utc').value = data.utc;
  808. $('date').value = data.date;
  809. $('time').value = data.time;
  810. $('lastsynctime').value = data.lastsynctime;
  811. $('ntp').value = data.ntp;
  812. dhcpState();
  813. telnetState();
  814. timesetType($('ntp'));
  815. window.setCookie('netsettings_changed', data.netsettings_changed);
  816. checkNotify();
  817. }, function() {
  818. alert('Не удалось получить данные.');
  819. });
  820. }
  821. function batTest(options) {
  822. this.options = (options ? options : {});
  823. if (this.options.time) {
  824. if (typeof this.options.time !== 'number' && this.options.time > 99) {
  825. return alert('Ошибка заданного времени');
  826. }
  827. }
  828. var str = '';
  829. for (var option in options) {
  830. str += option + '=' + options[option] + '&';
  831. }
  832. str = str.slice(0, -1);
  833. var url = 'bat_test.cgi';
  834. loadXMLDoc(url + '?' + str, 'GET', function(){
  835. this.responseText ? alert(this.responseText) : null;
  836. });
  837. }
  838. function UPSPowerOff(options) {
  839. this.options = (options ? options : {});
  840. if (typeof this.options.after !== 'number' && this.options.after > 9999) {
  841. return alert('Ошибка заданного времени отключения');
  842. }
  843. var str = '';
  844. for (var option in options) {
  845. str += option + '=' + options[option] + '&';
  846. }
  847. str = str.slice(0, -1);
  848. var url = 'ups_power.cgi';
  849. loadXMLDoc(url + '?' + str, 'GET', function(){
  850. this.responseText ? alert(this.responseText) : null;
  851. });
  852. }
  853. var apply_settings = new NotificationBox('apply-settings',
  854. {
  855. 'message': 'Внимание, для применения сетевых настроек необходимо их подтвердить. Иначе они будут сброшены в течении 10 минут.',
  856. 'bgcolor':'#ffcc00',
  857. 'textcolor': '#333',
  858. 'url': 'confirm.cgi',
  859. 'show': window.getCookie('role') < 2
  860. });
  861. var device_error = new NotificationBox('device-error',
  862. {
  863. 'message': 'Внимание, связь с UPS не установлена!',
  864. 'bgcolor':'#ec0035',
  865. 'textcolor': '#fff'
  866. });
  867. // ################################################################################
  868. function infoGet() {
  869. getJSON('info.cgi', function(data) {
  870. // Cotroller Info
  871. $('uptime').innerHTML = data.uptime;
  872. $('model').innerHTML = data.model;
  873. $('prodate').innerHTML = data.prodate;
  874. $('fwversion').innerHTML = data.fwversion;
  875. $('macaddr').innerHTML = data.macaddr;
  876. $('serno').innerHTML = data.serno;
  877. $('ups_fwversion').innerHTML = data.ups_fwversion;
  878. $('ups_model').innerHTML = data.ups_model;
  879. var info_labels = {
  880. sysname: ['Название устройства', data.sysname, 19],
  881. owner: ['Владелец', data.owner, 49],
  882. sysLocation:['Местоположение', data.sysLocation, 109],
  883. comment: ['Комментарии', data.comment, 109]
  884. };
  885. for (var i in info_labels) {
  886. var row = document.createElement('tr');
  887. var label = document.createElement('td');
  888. label.innerHTML = info_labels[i][0];
  889. var val = document.createElement('td');
  890. val.id = i+'_wr';
  891. if (getCookie('role') <= 1) {
  892. var inp = document.createElement('input');
  893. inp.type = 'text';
  894. inp.id = i;
  895. inp.name = i;
  896. inp.className = 'form-control';
  897. inp.maxLength = info_labels[i][2];
  898. inp.value = info_labels[i][1];
  899. val.appendChild(inp);
  900. } else {
  901. val.innerHTML = info_labels[i][1];
  902. }
  903. row.appendChild(label);
  904. row.appendChild(val);
  905. $('ctrl_info').appendChild(row);
  906. }
  907. if (getCookie('role') <= 1) {
  908. var sbmt = document.createElement('button');
  909. sbmt.className = 'btn btn-primary-inverted';
  910. sbmt.type = 'button';
  911. sbmt.setAttribute('onclick', 'submitInfo(); return false;');
  912. sbmt.innerHTML = 'Сохранить';
  913. $('SNMPinfo').appendChild(sbmt);
  914. }
  915. window.setCookie('netsettings_changed', data.netsettings_changed);
  916. checkNotify();
  917. }, function() {
  918. alert('Не удалось получить данные.');
  919. });
  920. }
  921. // ################################################################################
  922. /*
  923. SpinBox.js
  924. Implements a spin box interface for a text field
  925. Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
  926. the terms of the CC0 1.0 Universal legal code:
  927. http://creativecommons.org/publicdomain/zero/1.0/legalcode
  928. */
  929. /* Creates a spin box. The parameter is:
  930. *
  931. * container - either the DOM node to contain the spin box or the ID of the node
  932. * options - an object containing various parameters; this optional parameter
  933. * defaults to the empty object
  934. *
  935. * The options object may contain the following keys:
  936. *
  937. * className - a class name to apply to the container; the class name with the
  938. * suffixes 'Up' and 'Down' will be applied to the up and down
  939. * buttons. The default value is 'spinBox'.
  940. * value - the initial value for the spin box. The default is 0 (subject to
  941. * restrictions on the minimum and maximum value) if the input
  942. * element did not already exist, or the existing value if the input
  943. * element did already exist.
  944. * step - the value by which to increment or decrement the value. The
  945. * default value is 1.
  946. * minimum - the minimum allowed value. The default is not to have a minimum
  947. * value.
  948. * maximum - the maximum allowed value. The default is not to have a maximum
  949. * value.
  950. * decimals - the number of decimal places allowed. The default is 0.
  951. * name - input name attribute.
  952. *
  953. * Note that the minimum, maximum, and decimal places restrictions are enforced
  954. * for values set by the spin box, but a value outside of these restrictions may
  955. * be typed by the user.
  956. */
  957. function SpinBox(container, options) {
  958. // fetch the DOM node if a string was supplied
  959. if (typeof container == 'string') {
  960. container = document.getElementById(container);
  961. container.innerHTML = '';
  962. }
  963. // store the options and set the default values
  964. this.options = (options ? options : {});
  965. if (!('className' in this.options)) this.options.className = 'spinBox';
  966. if (!('step' in this.options)) this.options.step = 1;
  967. if (!('decimals' in this.options)) this.options.decimals = 0;
  968. // check whether the input field should be created
  969. var inputs = container.getElementsByTagName('input');
  970. if (inputs.length === 0) {
  971. // create the input node
  972. this.input = document.createElement('input');
  973. this.input.setAttribute('minimum', this.options.minimum);
  974. this.input.setAttribute('maximum', this.options.maximum);
  975. this.setValue('value' in this.options ? this.options.value : 0);
  976. this.setName('name' in this.options ? this.options.name : '');
  977. container.appendChild(this.input);
  978. } else {
  979. // store a reference to the input node
  980. this.input = inputs[0];
  981. this.setValue(this.options.value ? this.options.value : this.input.value);
  982. }
  983. // create the up button
  984. var upButton = document.createElement('span');
  985. upButton.appendChild(document.createElement('span'));
  986. upButton.innerHTML = '+';
  987. container.appendChild(upButton);
  988. // create the down button
  989. var downButton = document.createElement('span');
  990. downButton.appendChild(document.createElement('span'));
  991. downButton.innerHTML = '-';
  992. container.appendChild(downButton);
  993. // apply the classes
  994. container.className += ' ' + this.options.className;
  995. upButton.className = this.options.className + 'Up';
  996. downButton.className = this.options.className + 'Down';
  997. // add the listeners
  998. this.addEventListener(this.input, 'mousewheel', this.handleMouseWheel, [], true);
  999. this.addEventListener(this.input, 'DOMMouseScroll', this.handleMouseWheel, [], true);
  1000. this.addEventListener(this.input, 'keydown', this.handleKeyDown, [], true);
  1001. this.addEventListener(this.input, 'keypress', this.handleKeyPress, [], true);
  1002. this.addEventListener(this.input, 'keyup', this.stop);
  1003. this.addEventListener(this.input, 'blur', this.loseFocus);
  1004. this.addEventListener(upButton, 'mousedown', this.start, [true]);
  1005. this.addEventListener(upButton, 'mouseup', this.stop);
  1006. this.addEventListener(upButton, 'mouseout', this.stop);
  1007. this.addEventListener(downButton, 'mousedown', this.start, [false]);
  1008. this.addEventListener(downButton, 'mouseup', this.stop);
  1009. this.addEventListener(downButton, 'mouseout', this.stop);
  1010. }
  1011. /* Returns the current value. This will be a number, or the value NaN if the
  1012. * current contents of the input field do not start with a valid number.
  1013. */
  1014. SpinBox.prototype.getValue = function () {
  1015. // parse and return the value
  1016. return parseFloat(this.input.value);
  1017. };
  1018. SpinBox.prototype.loseFocus = function () {
  1019. if ('minimum' in this.options && this.input.value < this.options.minimum) this.input.value = this.options.minimum.toFixed(this.options.decimals ? this.options.decimals : 0);
  1020. if ('maximum' in this.options && this.input.value > this.options.maximum) this.input.value = this.options.maximum.toFixed(this.options.decimals ? this.options.decimals : 0);
  1021. };
  1022. SpinBox.prototype.setName = function (name) {
  1023. // asign input name
  1024. this.input.name = name;
  1025. };
  1026. /* Sets the value. Restrictions on the minimum and maximum value are enforced.
  1027. * The parameter is:
  1028. *
  1029. * value - the value
  1030. */
  1031. SpinBox.prototype.setValue = function (value) {
  1032. // ensure the value is within the permitted range
  1033. if ('minimum' in this.options) value = Math.max(this.options.minimum, value);
  1034. if ('maximum' in this.options) value = Math.min(this.options.maximum, value);
  1035. // store the sign
  1036. var sign = (value < 0 ? '-' : '');
  1037. value = Math.abs(value);
  1038. // determine the multiplier for rounding
  1039. var multiplier = Math.pow(10, this.options.decimals);
  1040. // split the value in to integer and fractional parts
  1041. value = Math.round(value * multiplier);
  1042. var integer = (value - value % multiplier) / multiplier;
  1043. var fractional = '' + value % multiplier;
  1044. // add leading zeros to the fractional part
  1045. while (fractional.length < this.options.decimals) {
  1046. fractional = '0' + fractional;
  1047. }
  1048. // set the value
  1049. this.input.value =
  1050. sign + integer + (this.options.decimals > 0 ? '.' + fractional : '');
  1051. // check whether the browser can dispatch events
  1052. if ('dispatchEvent' in this.input){
  1053. // create the event
  1054. try{
  1055. var event = new Event('change', {bubbles : true, cancelable : true});
  1056. }catch (e){
  1057. var event = document.createEvent('Event');
  1058. event.initEvent('change', true, true);
  1059. }
  1060. // dispatch the event
  1061. this.input.dispatchEvent(event);
  1062. }
  1063. };
  1064. /* Adds an event listener to a node. The event listener is bound to the current
  1065. * value of 'this'. The parameters are:
  1066. *
  1067. * node - the node
  1068. * event - the event name
  1069. * listener - the listener functions
  1070. * parameters - an array of additional parameters to pass to the listener;
  1071. * these are placed after the event parameter
  1072. * allowDefault - true if the default action should not be prevented
  1073. */
  1074. SpinBox.prototype.addEventListener = function (
  1075. node, event, listener, parameters, allowDefault) {
  1076. // store a reference to the 'this' object
  1077. var thisObject = this;
  1078. // create the bound listener
  1079. function boundListener(e) {
  1080. // get the event if it is not supplied
  1081. if (!e) e = window.event;
  1082. // call the listener
  1083. listener.apply(thisObject, [e].concat(parameters));
  1084. // prevent the default action if necessary
  1085. if (!allowDefault) {
  1086. if (e.preventDefault) {
  1087. e.preventDefault();
  1088. } else {
  1089. e.returnValue = false;
  1090. }
  1091. }
  1092. }
  1093. // add the event listener
  1094. if (node.addEventListener) {
  1095. node.addEventListener(event, boundListener, false);
  1096. } else {
  1097. node.attachEvent('on' + event, boundListener);
  1098. }
  1099. };
  1100. /* Handles a mouse wheel event by updating the value if the field is active. The
  1101. * parameter is:
  1102. *
  1103. * e - the event object
  1104. */
  1105. SpinBox.prototype.handleMouseWheel = function (e) {
  1106. // check whether the field is active
  1107. if (document.activeElement == this.input) {
  1108. // update the value
  1109. if (e.wheelDelta) {
  1110. this.start(e, e.wheelDelta > 1);
  1111. } else if (e.detail) {
  1112. this.start(e, e.detail < 1);
  1113. }
  1114. this.stop();
  1115. // prevent the default action
  1116. if (e.preventDefault) {
  1117. e.preventDefault();
  1118. } else {
  1119. e.returnValue = false;
  1120. }
  1121. }
  1122. };
  1123. /* Handles a key down event by starting updating if appropriate. The parameter
  1124. * is:
  1125. *
  1126. * e - the event object
  1127. */
  1128. SpinBox.prototype.handleKeyDown = function (e) {
  1129. // if the up or down keys were pressed, start updating
  1130. if (e.keyCode == 38) this.start(e, true);
  1131. if (e.keyCode == 40) this.start(e, false);
  1132. };
  1133. /* Handles a key press event by filtering out invalid characters. The parameter
  1134. * is:
  1135. *
  1136. * e - the event object
  1137. */
  1138. SpinBox.prototype.handleKeyPress = function (e) {
  1139. // determine the character code
  1140. var charCode = ('charCode' in e ? e.charCode : e.keyCode);
  1141. // allow special key presses
  1142. if (charCode === 0 || e.altKey || e.ctrlKey || e.metaKey) return;
  1143. // allow a minus sign if the value can be negative
  1144. if (charCode == 45 && (!('minimum' in this.options) || this.options.minimum < 0)) {
  1145. return;
  1146. }
  1147. // allow a decimal point if the value may contain decimals
  1148. if (charCode == 46 && this.options.decimals > 0) return;
  1149. // allow digits
  1150. if (charCode >= 48 && charCode <= 57) return;
  1151. // prevent the default action
  1152. if (e.preventDefault) {
  1153. e.preventDefault();
  1154. } else {
  1155. e.returnValue = false;
  1156. }
  1157. };
  1158. /* Starts updating the value. The parameters are:
  1159. *
  1160. * e - the event object
  1161. * up - true to increment the value, false to decrement the value
  1162. */
  1163. SpinBox.prototype.start = function (e, up) {
  1164. // if the field is disabled or we are already updating, return immediately
  1165. if (this.input.disabled || 'timeout' in this) return;
  1166. // set the update step
  1167. this.updateStep = (up ? this.options.step : -this.options.step);
  1168. // initialise the timeout delay
  1169. this.timeoutDelay = 500;
  1170. // update the value
  1171. this.update();
  1172. };
  1173. // Stops update the value.
  1174. SpinBox.prototype.stop = function () {
  1175. // clear the timeout if it exists
  1176. if ('timeout' in this) {
  1177. window.clearTimeout(this.timeout);
  1178. delete this.timeout;
  1179. }
  1180. };
  1181. // Updates the value.
  1182. SpinBox.prototype.update = function () {
  1183. // determine the current value
  1184. var value = parseFloat(this.input.value);
  1185. if (isNaN(value)) value = 0;
  1186. // update the value
  1187. this.setValue(value + this.updateStep);
  1188. // reduce the delay
  1189. this.timeoutDelay = Math.max(20, Math.floor(this.timeoutDelay * 0.9));
  1190. // call this function again
  1191. var thisObject = this;
  1192. this.timeout = window.setTimeout(function () { thisObject.update(); }, this.timeoutDelay);
  1193. };
  1194. /*
  1195. This code is from Dynamic Web Coding at dyn-web.com
  1196. Copyright 2009-12 by Sharon Paine
  1197. See Terms of Use at www.dyn-web.com/business/terms.php
  1198. regarding conditions under which you may use this code.
  1199. This notice must be retained in the code as is!
  1200. */
  1201. // DYN_WEB is namespace used for code from dyn-web.com
  1202. // replacing previous use of dw_ prefix for object names
  1203. var DYN_WEB = DYN_WEB || {};
  1204. DYN_WEB.Event = {
  1205. add: document.addEventListener ? function (obj, etype, fp, cap) {
  1206. cap = cap || false;
  1207. obj.addEventListener(etype, fp, cap);
  1208. } : function (obj, etype, fp) {
  1209. obj.attachEvent('on' + etype, fp);
  1210. },
  1211. remove: document.removeEventListener ? function (obj, etype, fp, cap) {
  1212. cap = cap || false;
  1213. obj.removeEventListener(etype, fp, cap);
  1214. } : function (obj, etype, fp) {
  1215. obj.detachEvent('on' + etype, fp);
  1216. },
  1217. DOMit: function (e) {
  1218. e = e ? e : window.event;
  1219. if (!e.target) e.target = e.srcElement;
  1220. if (!e.preventDefault) e.preventDefault = function () {
  1221. e.returnValue = false;
  1222. return false;
  1223. };
  1224. if (!e.stopPropagation) e.stopPropagation = function () {
  1225. e.cancelBubble = true;
  1226. };
  1227. return e;
  1228. },
  1229. getTarget: function (e) {
  1230. e = dw_Event.DOMit(e);
  1231. var tgt = e.target;
  1232. if (tgt.nodeType != 1) tgt = tgt.parentNode;
  1233. return tgt;
  1234. }
  1235. };
  1236. DYN_WEB.Cookie = {
  1237. set: function (name, value, days, path, domain, secure) {
  1238. var date, expires;
  1239. if (typeof days == 'number') {
  1240. date = new Date();
  1241. date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  1242. expires = date.toGMTString();
  1243. }
  1244. document.cookie = name + '=' + encodeURIComponent(value) + (
  1245. (expires) ? '; expires=' + expires : ''
  1246. ) + (
  1247. (path) ? '; path=' + path : ''
  1248. ) + (
  1249. (domain) ? '; domain=' + domain : ''
  1250. ) + (
  1251. (secure) ? '; secure' : '');
  1252. },
  1253. get: function (name) {
  1254. var c, cookies = document.cookie.split(/;\s/g);
  1255. for (var i = 0; cookies[i]; i++) {
  1256. c = cookies[i];
  1257. if (c.indexOf(name + '=') === 0) {
  1258. return decodeURIComponent(c.slice(name.length + 1, c.length));
  1259. }
  1260. }
  1261. return null;
  1262. },
  1263. del: function (name, path, domain) {
  1264. if (dw_Cookie.get(name)) {
  1265. document.cookie = name + '=' + (
  1266. (path) ? '; path=' + path : ''
  1267. ) + (
  1268. (domain) ? '; domain=' + domain : ''
  1269. ) + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
  1270. }
  1271. }
  1272. };
  1273. if (!DYN_WEB.Util) {
  1274. DYN_WEB.Util = {
  1275. // add props of Obj2 to Obj1
  1276. augment: function (Obj1, Obj2) {
  1277. var prop;
  1278. for (prop in Obj2) {
  1279. if (Obj2.hasOwnProperty(prop) && !Obj1[prop]) {
  1280. Obj1[prop] = Obj2[prop];
  1281. }
  1282. }
  1283. },
  1284. $: function (id) {
  1285. return document.getElementById(id);
  1286. }
  1287. };
  1288. }
  1289. DYN_WEB.Tabs = (function () {
  1290. // obj holds props: id, useCookies, etc.
  1291. function Constr(obj) {
  1292. this.useCookies = obj.useCookies;
  1293. this.before_hide = obj.before_hide || function () {};
  1294. this.on_activate = obj.on_activate || function () {};
  1295. this.on_init = obj.on_init || function () {};
  1296. Constr.col[obj.id] = this;
  1297. Constr.init(obj.id);
  1298. }
  1299. Constr.col = {};
  1300. Constr.prototype = {
  1301. current: null // id of currently active pane
  1302. };
  1303. return Constr;
  1304. })();
  1305. (function () {
  1306. var Ut = DYN_WEB.Util,
  1307. Ev = DYN_WEB.Event,
  1308. Cookie = DYN_WEB.Cookie,
  1309. Tabs = DYN_WEB.Tabs;
  1310. Ut.augment(Tabs, {
  1311. // static props/methods for DYN_WEB.Tabs
  1312. setup: function () {
  1313. var obj, settings = [];
  1314. if (Tabs.hasBrowserSupport()) {
  1315. for (var i = 0; obj = arguments[i]; i++) {
  1316. if (obj.css) {
  1317. Ut.writeStyleSheet(obj.css);
  1318. }
  1319. settings[i] = obj; // save to pass to constructor onload
  1320. }
  1321. Ev.add(window, 'load', function () {
  1322. for (var i = 0; settings[i]; i++) {
  1323. new Tabs(settings[i]);
  1324. }
  1325. });
  1326. }
  1327. },
  1328. hasBrowserSupport: function () {
  1329. if (document.getElementById && document.getElementsByTagName && typeof decodeURI !== 'undefined' && (document.addEventListener || document.attachEvent)) {
  1330. return true;
  1331. }
  1332. return false;
  1333. },
  1334. init: function (tabsetId) {
  1335. var _this = Tabs.col[tabsetId],
  1336. links = Tabs.getTabs(tabsetId),
  1337. // code uses hash in tab links but tabs can also link to other pages
  1338. // so compare current location to link's href
  1339. loc = Ut.getURLtoHash(location),
  1340. lnk, pg, paneId, pane, sel, dflt, cur, c, q, hash;
  1341. q = Ut.getValueFromQueryString(tabsetId);
  1342. if (_this.useCookies) {
  1343. c = Tabs.checkCookie(tabsetId);
  1344. }
  1345. // tab in query string or cookie?
  1346. sel = q ? q : c ? c : null;
  1347. // add ids and event handlers to links ...
  1348. for (var i = 0; lnk = links[i]; i++) {
  1349. paneId = '', pane = ''; // reset
  1350. pg = Ut.getURLtoHash(lnk);
  1351. hash = Ut.getHash(lnk);
  1352. if (lnk.hash && (loc == pg)) { // has hash and points to current page
  1353. paneId = hash;
  1354. lnk.id = tabsetId + '__' + paneId; // double underscore between
  1355. }
  1356. // if tab associated with tabpane, set up onclick fn
  1357. if (paneId) {
  1358. try {
  1359. pane = Ut.$(paneId);
  1360. } catch (err) { // showClicked fn throws
  1361. }
  1362. // first tab/pane is default
  1363. if (!dflt) {
  1364. dflt = paneId;
  1365. }
  1366. // if set active in markup, hold as current
  1367. if (pane && Ut.hasClass(lnk, 'activeTab') && Ut.hasClass(pane, 'activePane')) {
  1368. _this.current = cur = paneId;
  1369. }
  1370. // to pass paneId, tabsetId to showClicked...
  1371. Ev.add(lnk, 'click', function (paneId, tabsetId) {
  1372. return function (e) {
  1373. Tabs.showClicked(e, paneId, tabsetId);
  1374. };
  1375. }(paneId, tabsetId));
  1376. }
  1377. }
  1378. // check if tab and pane for sel
  1379. if (sel && (lnk = Ut.$(tabsetId + '__' + sel)) && (pane = Ut.$(sel))) {
  1380. if (cur && cur !== sel) {
  1381. Tabs.hideCurrent(tabsetId, cur);
  1382. }
  1383. Ut.addClass(lnk, 'activeTab');
  1384. Ut.addClass(pane, 'activePane');
  1385. _this.current = sel;
  1386. } else if (!cur && dflt) {
  1387. Ut.addClass(Ut.$(tabsetId + '__' + dflt), 'activeTab');
  1388. Ut.addClass(Ut.$(dflt), 'activePane');
  1389. _this.current = dflt;
  1390. }
  1391. _this.on_init();
  1392. },
  1393. getTabs: function (id) {
  1394. var set = Ut.$(id),
  1395. list, links;
  1396. if (!set) {
  1397. throw new Error('No element matching tabset id found.');
  1398. return [];
  1399. }
  1400. list = Ut.getElementsByClassName('tabnavs', 'ul', set);
  1401. if (list.length === 0) {
  1402. throw new Error('No tabnavs were found in the tabset.');
  1403. return [];
  1404. }
  1405. links = list[0].getElementsByTagName('a');
  1406. return links;
  1407. },
  1408. showClicked: function (e, paneId, tabsetId) {
  1409. var tabId = tabsetId + '__' + paneId;
  1410. var _this = Tabs.col[tabsetId];
  1411. _this.before_hide(tabId, paneId, tabsetId);
  1412. Tabs.hideCurrent(tabsetId, _this.current);
  1413. Ut.addClass(Ut.$(tabId), 'activeTab');
  1414. try {
  1415. Ut.addClass(Ut.$(paneId), 'activePane');
  1416. } catch (err) {
  1417. throw new Error('showClicked can\'t find pane associated with tab. Check tab hash and pane id.');
  1418. return false;
  1419. }
  1420. _this.current = paneId;
  1421. if (_this.useCookies) {
  1422. Tabs.setCookie(tabsetId, paneId);
  1423. }
  1424. _this.on_activate(tabId, paneId, tabsetId);
  1425. if (e) {
  1426. Ev.DOMit(e);
  1427. e.preventDefault();
  1428. }
  1429. return false;
  1430. },
  1431. hideCurrent: function (tabsetId, cur) {
  1432. var tab = Ut.$(tabsetId + '__' + cur),
  1433. pane = Ut.$(cur);
  1434. Ut.removeClass(tab, 'activeTab');
  1435. Ut.removeClass(pane, 'activePane');
  1436. },
  1437. checkCookie: function (tabsetId) {
  1438. var c, cookies, tab_cookies = Cookie.get('dw_Tabs');
  1439. if (tab_cookies) {
  1440. cookies = tab_cookies.split(',');
  1441. for (var i = 0; cookies[i]; i++) {
  1442. c = cookies[i];
  1443. if (c.indexOf(tabsetId + ':') === 0) {
  1444. return decodeURI(c.slice(tabsetId.length + 1, c.length));
  1445. }
  1446. }
  1447. }
  1448. return null;
  1449. },
  1450. setCookie: function (tabsetId, paneId) {
  1451. // format for cookies (multiple tabsets supported): dw_Tabs=tabsetId:paneId,tabsetId:paneId;
  1452. var new_tab_cookies = '',
  1453. cookies,
  1454. tab_cookies = Cookie.get('dw_Tabs');
  1455. if (tab_cookies) {
  1456. cookies = tab_cookies.split(',');
  1457. for (var i = 0; cookies[i]; i++) {
  1458. if (cookies[i].indexOf(tabsetId + ':') === 0) {
  1459. cookies[i] = tabsetId + ':' + paneId;
  1460. new_tab_cookies = cookies.join(',');
  1461. break;
  1462. }
  1463. }
  1464. if (!new_tab_cookies) { // if no match for this tabsetId
  1465. new_tab_cookies = tab_cookies + ',' + tabsetId + ':' + paneId;
  1466. }
  1467. } else { // no dw_Tabs set yet
  1468. new_tab_cookies = tabsetId + ':' + paneId;
  1469. }
  1470. Cookie.set('dw_Tabs', new_tab_cookies, null, '/');
  1471. }
  1472. });
  1473. })();
  1474. // util
  1475. (function () {
  1476. var Ut = DYN_WEB.Util;
  1477. // add methods to DYN_WEB.Util
  1478. Ut.augment(Ut, {
  1479. trim: function (str) {
  1480. if (String.prototype.trim) {
  1481. return str.trim(); // ECMAScript 5
  1482. } else {
  1483. var re = /^\s+|\s+$/g;
  1484. return str.replace(re, '');
  1485. }
  1486. },
  1487. normalizeString: function (str) {
  1488. var re = /\s\s+/g;
  1489. return Ut.trim(str).replace(re, ' ');
  1490. },
  1491. hasClass: function (el, cl) {
  1492. var re = new RegExp('\\b' + cl + '\\b', 'i');
  1493. if (re.test(el.className)) {
  1494. return true;
  1495. }
  1496. return false;
  1497. },
  1498. addClass: function (el, cl) {
  1499. if (!Ut.hasClass(el, cl)) {
  1500. el.className = Ut.trim(el.className + ' ' + cl);
  1501. }
  1502. },
  1503. removeClass: function (el, cl) {
  1504. el.className = Ut.normalizeString(el.className.replace(cl, ' '));
  1505. },
  1506. getElementsByClassName: function (sClass, sTag, oCont) {
  1507. oCont = oCont ? oCont : document;
  1508. if (oCont.getElementsByClassName) {
  1509. return oCont.getElementsByClassName(sClass); // html5
  1510. } else {
  1511. sTag = sTag || '*';
  1512. var result = [],
  1513. re = new RegExp('\\b' + sClass + '\\b', 'i'),
  1514. list = oCont.getElementsByTagName(sTag);
  1515. for (var i = 0; list[i]; i++) {
  1516. if (re.test(list[i].className)) result.push(list[i]);
  1517. }
  1518. return result;
  1519. }
  1520. },
  1521. // obj: link or window.location
  1522. getValueFromQueryString: function (name, obj) {
  1523. obj = obj ? obj : window.location;
  1524. var pairs, set;
  1525. if (obj.search && obj.search.indexOf(name != -1)) {
  1526. pairs = obj.search.slice(1).split('&'); // name/value pairs
  1527. for (var i = 0; pairs[i]; i++) {
  1528. set = pairs[i].split('='); // Check each pair for match on name
  1529. if (set[0] == name && set[1]) {
  1530. return set[1];
  1531. }
  1532. }
  1533. }
  1534. return '';
  1535. },
  1536. getURLtoHash: function (obj) {
  1537. obj = obj ? obj : window.location;
  1538. var href = obj.href,
  1539. pt = href.indexOf('#'),
  1540. url = (pt != -1) ? href.slice(0, pt) : href; // remove hash from href
  1541. return url;
  1542. },
  1543. getHash: function (obj) {
  1544. obj = obj ? obj : window.location;
  1545. var hash = '';
  1546. if (obj.hash) { // some browsers say true if just #, some '' (ff)
  1547. hash = obj.hash.slice(1);
  1548. }
  1549. return hash;
  1550. },
  1551. // Alternate functions are available that use DOM methods instead of document.write
  1552. writeStyleSheet: function (file, bScreen) {
  1553. var screen = (bScreen !== false) ? '" media="screen" />\n' : '"/>\n';
  1554. document.write('\n<link rel="stylesheet" href="' + file + screen);
  1555. },
  1556. // used to set min-height (as on dyn-web home page)
  1557. writeStyleRule: function (rule, bScreen) {
  1558. var screen = (bScreen !== false) ? ' media="screen">' : '>';
  1559. document.write('\n<style type="text/css"' + screen + rule + '</style>');
  1560. }
  1561. });
  1562. })();
  1563. (function (window) {
  1564. /**
  1565. * @param {String} type - request | cancel | native.
  1566. * @return {Function} Timing function.
  1567. */
  1568. function requestFrame(type) {
  1569. // The only vendor prefixes required.
  1570. var vendors = ['moz', 'webkit'],
  1571. // Disassembled timing function abbreviations.
  1572. aF = 'AnimationFrame',
  1573. rqAF = 'Request' + aF,
  1574. // Final assigned functions.
  1575. assignedRequestAnimationFrame,
  1576. assignedCancelAnimationFrame,
  1577. // Initial time of the timing lapse.
  1578. previousTime = 0,
  1579. mozRAF = window.mozRequestAnimationFrame,
  1580. mozCAF = window.mozCancelAnimationFrame,
  1581. // Checks for firefox 4 - 10 function pair mismatch.
  1582. hasMozMismatch = mozRAF && !mozCAF,
  1583. func;
  1584. // Date.now polyfill, mainly for legacy IE versions.
  1585. if (!Date.now) {
  1586. Date.now = function() {
  1587. return new Date().getTime();
  1588. };
  1589. }
  1590. /**
  1591. * hasIOS6RequestAnimationFrameBug.
  1592. * @See {@Link https://gist.github.com/julienetie/86ac394ec41f1271ff0a}
  1593. * - for Commentary.
  1594. * @Copyright 2015 - Julien Etienne.
  1595. * @License: MIT.
  1596. */
  1597. function hasIOS6RequestAnimationFrameBug() {
  1598. var webkitRAF = window.webkitRequestAnimationFrame,
  1599. rAF = window.requestAnimationFrame,
  1600. // CSS/ Device with max for iOS6 Devices.
  1601. hasMobileDeviceWidth = screen.width <= 768 ? true : false,
  1602. // Only supports webkit prefixed requestAnimtionFrane.
  1603. requiresWebkitprefix = !(webkitRAF && rAF),
  1604. // iOS6 webkit browsers don't support performance now.
  1605. hasNoNavigationTiming = window.performance ? false : true,
  1606. iOS6Notice = 'setTimeout is being used as a substitiue for' +
  1607. 'requestAnimationFrame due to a bug within iOS 6 builds',
  1608. hasIOS6Bug = requiresWebkitprefix && hasMobileDeviceWidth &&
  1609. hasNoNavigationTiming;
  1610. function bugCheckresults(timingFnA, timingFnB, notice) {
  1611. if (timingFnA || timingFnB) {
  1612. console.warn(notice);
  1613. return true;
  1614. } else {
  1615. return false;
  1616. }
  1617. }
  1618. function displayResults() {
  1619. if (hasIOS6Bug) {
  1620. return bugCheckresults(webkitRAF, rAF, iOS6Notice);
  1621. } else {
  1622. return false;
  1623. }
  1624. }
  1625. return displayResults();
  1626. }
  1627. /**
  1628. * Native clearTimeout function.
  1629. * @return {Function}
  1630. */
  1631. function clearTimeoutWithId(id) {
  1632. clearTimeout(id);
  1633. }
  1634. /**
  1635. * Based on a polyfill by Erik, introduced by Paul Irish &
  1636. * further improved by Darius Bacon.
  1637. * @see {@link http://www.paulirish.com/2011/
  1638. * requestanimationframe-for-smart-animating}
  1639. * @see {@link https://github.com/darius/requestAnimationFrame/blob/
  1640. * master/requestAnimationFrame.js}
  1641. * @callback {Number} Timestamp.
  1642. * @return {Function} setTimeout Function.
  1643. */
  1644. function setTimeoutWithTimestamp(callback) {
  1645. var immediateTime = Date.now(),
  1646. lapsedTime = Math.max(previousTime + 16, immediateTime);
  1647. return setTimeout(function() {
  1648. callback(previousTime = lapsedTime);
  1649. },
  1650. lapsedTime - immediateTime);
  1651. }
  1652. /**
  1653. * Queries the native function, prefixed function
  1654. * or use the setTimeoutWithTimestamp function.
  1655. * @return {Function}
  1656. */
  1657. function queryRequestAnimationFrame() {
  1658. if (Array.prototype.filter) {
  1659. assignedRequestAnimationFrame = window['request' + aF] ||
  1660. window[vendors.filter(function(vendor) {
  1661. if (window[vendor + rqAF] !== undefined)
  1662. return vendor;
  1663. }) + rqAF] || setTimeoutWithTimestamp;
  1664. } else {
  1665. return setTimeoutWithTimestamp;
  1666. }
  1667. if (!hasIOS6RequestAnimationFrameBug()) {
  1668. return assignedRequestAnimationFrame;
  1669. } else {
  1670. return setTimeoutWithTimestamp;
  1671. }
  1672. }
  1673. /**
  1674. * Queries the native function, prefixed function
  1675. * or use the clearTimeoutWithId function.
  1676. * @return {Function}
  1677. */
  1678. function queryCancelAnimationFrame() {
  1679. var cancellationNames = [];
  1680. if (Array.prototype.map) {
  1681. vendors.map(function(vendor) {
  1682. return ['Cancel', 'CancelRequest'].map(
  1683. function(cancellationNamePrefix) {
  1684. cancellationNames.push(vendor +
  1685. cancellationNamePrefix + aF);
  1686. });
  1687. });
  1688. } else {
  1689. return clearTimeoutWithId;
  1690. }
  1691. /**
  1692. * Checks for the prefixed cancelAnimationFrame implementation.
  1693. * @param {Array} prefixedNames - An array of the prefixed names.
  1694. * @param {Number} i - Iteration start point.
  1695. * @return {Function} prefixed cancelAnimationFrame function.
  1696. */
  1697. function prefixedCancelAnimationFrame(prefixedNames, i) {
  1698. var cancellationFunction;
  1699. for (; i < prefixedNames.length; i++) {
  1700. if (window[prefixedNames[i]]) {
  1701. cancellationFunction = window[prefixedNames[i]];
  1702. break;
  1703. }
  1704. }
  1705. return cancellationFunction;
  1706. }
  1707. // Use truthly function
  1708. assignedCancelAnimationFrame = window['cancel' + aF] ||
  1709. prefixedCancelAnimationFrame(cancellationNames, 0) ||
  1710. clearTimeoutWithId;
  1711. // Check for iOS 6 bug
  1712. if (!hasIOS6RequestAnimationFrameBug()) {
  1713. return assignedCancelAnimationFrame;
  1714. } else {
  1715. return clearTimeoutWithId;
  1716. }
  1717. }
  1718. function getRequestFn() {
  1719. if (hasMozMismatch) {
  1720. return setTimeoutWithTimestamp;
  1721. } else {
  1722. return queryRequestAnimationFrame();
  1723. }
  1724. }
  1725. function getCancelFn() {
  1726. return queryCancelAnimationFrame();
  1727. }
  1728. function setNativeFn() {
  1729. if (hasMozMismatch) {
  1730. window.requestAnimationFrame = setTimeoutWithTimestamp;
  1731. window.cancelAnimationFrame = clearTimeoutWithId;
  1732. } else {
  1733. window.requestAnimationFrame = queryRequestAnimationFrame();
  1734. window.cancelAnimationFrame = queryCancelAnimationFrame();
  1735. }
  1736. }
  1737. /**
  1738. * The type value "request" singles out firefox 4 - 10 and
  1739. * assigns the setTimeout function if plausible.
  1740. */
  1741. switch (type) {
  1742. case 'request':
  1743. case '':
  1744. func = getRequestFn();
  1745. break;
  1746. case 'cancel':
  1747. func = getCancelFn();
  1748. break;
  1749. case 'native':
  1750. setNativeFn();
  1751. break;
  1752. default:
  1753. throw new Error('RequestFrame parameter is not a type.');
  1754. }
  1755. return func;
  1756. }
  1757. // Default to window as global
  1758. if (typeof window === 'object') {
  1759. window.requestFrame = requestFrame;
  1760. }
  1761. /* global-define */
  1762. }((typeof window === 'undefined' ? {} : window)));
  1763. // Icons
  1764. var Icons = {
  1765. clock: {
  1766. icn: '<svg width="20" height="20" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1024 544v448q0 14-9 23t-23 9h-320q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h224v-352q0-14 9-23t23-9h64q14 0 23 9t9 23zm416 352q0-148-73-273t-198-198-273-73-273 73-198 198-73 273 73 273 198 198 273 73 273-73 198-198 73-273zm224 0q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z" fill="'+ ALARM_YELLOW +'"/></svg>',
  1767. title: 'Режим ожидания'
  1768. },
  1769. exclamination: {
  1770. icn: '<svg width="20" height="20" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1088 1248v224q0 26-19 45t-45 19h-256q-26 0-45-19t-19-45v-224q0-26 19-45t45-19h256q26 0 45 19t19 45zm30-1056l-28 768q-1 26-20.5 45t-45.5 19h-256q-26 0-45.5-19t-20.5-45l-28-768q-1-26 17.5-45t44.5-19h320q26 0 44.5 19t17.5 45z" fill="'+ ALARM_RED +'"/></svg>',
  1771. title: 'Авария'
  1772. },
  1773. normal: {
  1774. icn: '<svg width="20" height="20" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1299 813l-422 422q-19 19-45 19t-45-19l-294-294q-19-19-19-45t19-45l102-102q19-19 45-19t45 19l147 147 275-275q19-19 45-19t45 19l102 102q19 19 19 45t-19 45zm141 83q0-148-73-273t-198-198-273-73-273 73-198 198-73 273 73 273 198 198 273 73 273-73 198-198 73-273zm224 0q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z" fill="'+ ALARM_GREEN +'"/></svg>',
  1775. title: 'Норма'
  1776. },
  1777. shutdown: {
  1778. icn: '<svg width="20" height="20" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1664 896q0 156-61 298t-164 245-245 164-298 61-298-61-245-164-164-245-61-298q0-182 80.5-343t226.5-270q43-32 95.5-25t83.5 50q32 42 24.5 94.5t-49.5 84.5q-98 74-151.5 181t-53.5 228q0 104 40.5 198.5t109.5 163.5 163.5 109.5 198.5 40.5 198.5-40.5 163.5-109.5 109.5-163.5 40.5-198.5q0-121-53.5-228t-151.5-181q-42-32-49.5-84.5t24.5-94.5q31-43 84-50t95 25q146 109 226.5 270t80.5 343zm-640-768v640q0 52-38 90t-90 38-90-38-38-90v-640q0-52 38-90t90-38 90 38 38 90z" fill="'+ ALARM_RED +'"/></svg>',
  1779. title: 'Выключение'
  1780. },
  1781. batteryLow: {
  1782. icn: '<svg width="30" height="20" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1920 576q53 0 90.5 37.5t37.5 90.5v384q0 53-37.5 90.5t-90.5 37.5v160q0 66-47 113t-113 47h-1856q-66 0-113-47t-47-113v-960q0-66 47-113t113-47h1856q66 0 113 47t47 113v160zm0 512v-384h-128v-288q0-14-9-23t-23-9h-1856q-14 0-23 9t-9 23v960q0 14 9 23t23 9h1856q14 0 23-9t9-23v-288h128z" fill="'+ ALARM_RED +'"/></svg>',
  1783. title: 'Низкий уровень заряда'
  1784. },
  1785. batTest: {
  1786. icn: '<svg width="20" height="20" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1024 1408h640v-128h-640v128zm-384-512h1024v-128h-1024v128zm640-512h384v-128h-384v128zm512 832v256q0 26-19 45t-45 19h-1664q-26 0-45-19t-19-45v-256q0-26 19-45t45-19h1664q26 0 45 19t19 45zm0-512v256q0 26-19 45t-45 19h-1664q-26 0-45-19t-19-45v-256q0-26 19-45t45-19h1664q26 0 45 19t19 45zm0-512v256q0 26-19 45t-45 19h-1664q-26 0-45-19t-19-45v-256q0-26 19-45t45-19h1664q26 0 45 19t19 45z" fill="'+ ALARM_YELLOW +'"/></svg>',
  1787. title: 'Тестирование'
  1788. }
  1789. };