main.js 63 KB

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