main.js 64 KB

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