main.js 65 KB

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