main.js 67 KB

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