main.js 73 KB

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