main.js 67 KB

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