| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101 | 
function $(id) {return document.getElementById(id);}// ############### Mobile Device ################if (window.screen.width < 769) {  $('nav').style.display = 'none';}$('menu-icon').onclick = function(){  $('nav').style.display = $('nav').style.display == 'none' ? 'block' : 'none';};//########## Main Page Alert Handler ############// fadeIn animation special for alertsfunction fadeIns(el){  el.style.opacity = 0;  (function fade() {    var val = parseFloat(el.style.opacity);    if (((val += 0.03) > 1) !== true) {      el.style.opacity = val;      var request = window.requestFrame('request');      request(fade);    }  })();}var ac          = $('AC'),  dc            = $('DC'),  in_freq       = $('in_freq'),  out_freq      = $('out_freq'),  pwr           = $('pwr'),  bat_rem_cap       = $('bat_rem_cap'),  inner_temp    = $('inner_temp'),  battimeleft   = $('bat_time_left'),  // alarm         = $('alarm'),  sPower        = $('sPower'),  sBattery      = $('sBattery');var battempCtrlChecked;function dataFadeIn(){  var x = [    ac,    dc,    in_freq,    out_freq,    pwr,    bat_rem_cap,    inner_temp,    battimeleft,    sPower,    sBattery  ];  for (var i = 0; i < x.length; i++){    fadeIns(x[i]);  }}// Alarm colorsvar ALARM_RED    = '#ff5050',  ALARM_YELLOW = '#f0ad4e',  ALARM_GREEN  = '#33cc00';//########## Settings Inform Boxes ############function HTMLcreate(htmlStr) {  var frag = document.createDocumentFragment(),    temp = document.createElement('div');  temp.innerHTML = htmlStr;  while (temp.firstChild) {    frag.appendChild(temp.firstChild);  }  return frag;}// fade in animationfunction fadeIn(el, display){  el.style.opacity = 0;  el.style.display = display || 'block';  (function fade() {    var val = parseFloat(el.style.opacity);    if (((val += 0.05) > 1) !== true) {      el.style.opacity = val;      var request = window.requestFrame('request');      request(fade);    }  })();}//########## Settings Form ############function formValidation(){  var read_community,write_community,managerIP,managerIP2,managerIP3,managerIP4,managerIP5,    ups_cell_min, ups_cell_max,    ipaddr, gw, mask, di_name1, di_name2/*, ntpservip*/;  read_community  = $('read_community');  write_community = $('write_community');  managerIP       = $('managerIP');  managerIP2      = $('managerIP2');  managerIP3      = $('managerIP3');  managerIP4      = $('managerIP4');  managerIP5      = $('managerIP5');  ipaddr          = $('ipaddr');  gw              = $('gw');  mask            = $('mask');  ups_cell_min    = +$('ups_cell_min').children[0].value;  ups_cell_max    = +$('ups_cell_max').children[0].value;  di_name1        = $('di_name1');  di_name2        = $('di_name2');  // ntpservip          = $('ntpservip');  var flag = true;  if (!$('dhcp').checked) {    if(!ValidateIPaddress(ipaddr, ' IP-адрес устройства')) flag = false;    if(!ValidateIPaddress(gw,     ' IP-адрес шлюза')) flag = false;    if(!ValidateIPaddress(mask,   'а Маска подсети')) flag = false;  }  if(ups_cell_min > ups_cell_max) {    var warn = document.createElement('li');    warn.innerHTML = 'Минимальное напряжение на ячейке не может быть больше максимального!';    $('validation-box').appendChild(warn);    flag = false;  }  if(!ValidateIPaddress(managerIP, ' Сервер SNMP 1')) flag = false;  if(!ValidateAlphanumericPlus(read_community, 'Read Community')) flag = false;  if(!ValidateAlphanumericPlus(write_community, 'Write Community')) flag = false;  if(!ValidateIPaddress(managerIP2, ' Сервер SNMP 2')) flag = false;  if(!ValidateIPaddress(managerIP3, ' Сервер SNMP 3')) flag = false;  if(!ValidateIPaddress(managerIP4, ' Сервер SNMP 4')) flag = false;  if(!ValidateIPaddress(managerIP5, ' Сервер SNMP 5')) flag = false;  if(!ValidateAlphanumericMax(di_name1, ' "Название дискретного входа 1"')) flag = false;  if(!ValidateAlphanumericMax(di_name2, ' "Название дискретного входа 2"')) flag = false;  if ($('ntp-inp') && !$('ntp-inp').disabled) {    if(!ValidateIPaddress($('ntp-inp'), ' IP адрес NTP сервера')) flag = false;  }  return flag;}function ValidateIPaddress(ipaddress, z) {  var warn = document.createElement('li');  warn.innerHTML = 'Неправильно задан' + z + '!';  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)) {    return true;  }  $('validation-box').appendChild(warn);  return false;}function ValidateNumber(n, z) {  var warn = document.createElement('li');  warn.innerHTML = 'Неправильно задан' + z + '!';  if(/^-?[\d.]+(?:e-?\d+)?$/.test(n.value)) {    return true;  }  $('validation-box').appendChild(warn);  return false;}function ValidateAlphanumeric(uadd, z) {  var warn = document.createElement('li');  var letter = /^[0-9a-zA-Z]+$/;  warn.innerHTML = 'Поле ' + z + ' может содержать только латинские буквы и цифры';  if (letter.test(uadd.value)) {return true;}  $('validation-box').appendChild(warn);  return false;}function ValidateAlphanumericPlus(uadd, z) {  var warn = document.createElement('li');  var letter = /^[0-9a-zA-Z\-_]+$/;  warn.innerHTML = 'Поле ' + z + ' может содержать только латинские буквы, цифры и символы -_';  if (letter.test(uadd.value)) {return true;}  $('validation-box').appendChild(warn);  return false;}function ValidateAlphanumericMax(uadd, z) {  var warn = document.createElement('li');  var letter = /^[0-9a-zA-Z.,/-_*#()[\]+=;:'"@!^%&?|${}`~<>]+$/;  warn.innerHTML = 'Поле ' + z + ' может содержать только латинские буквы, цифры и символы .,/-_*#()[]+=;:\'"@!^%&?|${}`~<>';  if (letter.test(uadd.value)) {return true;}  $('validation-box').appendChild(warn);  return false;}function validateUpload(oForm) {  var file = oForm.elements.datafile.files[0];  var fnmreg = /^.{1,}\.crt$/g;  if (file && fnmreg.test(file.name) ) {    upload(file);  } else {    alert('Файл сертификата не указан или не валиден!');  }  return false;}function submitForms() {  if (confirm('Вы уверены что хотите применить настройки?')) {    if ($('ntp-inp')) {      $('ntpservip').options[3].value = $('ntp-inp').value;    }    if (formValidation()) {      $('form1').submit();    }    else{      $('validation-box').style.display = 'block';    }  }}function upload(file) {  var fl = new FormData();  fl.append('file', file);  var xhr = new XMLHttpRequest();  xhr.open('POST', '/srv_crt_upload.cgi', true);  // обработчик для закачки  xhr.upload.onprogress = function(event) {    var progress = Math.floor((event.loaded / event.total) * 100);    console.log(progress + '%');  };  xhr.onload = xhr.onerror = function() {    if (this.status == 200) {      if (+xhr.responseText == '1') {        alert('Успешно');        window.location.reload();      } else {        alert('Ошибка установки сертификата');      }    } else {      alert('Ошибка ' + this.status);    }  };  xhr.send(fl);}function checkPWD(){  // $('checkUpdatePass').style.display = 'none';  $('count-wrap').style.display = 'block';  $('countdown').style.display = 'block';  countdown();}function checkChangePWD(){  var user = $('changePasswordUser').value;  var oldpass = $('oldpwd').value;  var newpass = $('newpwd').value;  var newpassrepeat = $('newpwdrepeat').value;  var letter = /^[0-9a-zA-Z.,/\\\-_*#()[\]+:'"@!^%&?|${}`~<>]+$/;  if (oldpass.length === 0 || newpass.length === 0 || newpassrepeat.length === 0){    alert('Поля не заполнены!');  } else if (newpass !== newpassrepeat){    alert('Поля с новым паролем не совпадают!');    $('oldpwd').value = '';    $('newpwd').value = '';    $('newpwdrepeat').value = '';  } else if (user === ''){    alert('Не выбран пользователь для которого необходимо сменить пароль!');  } else {    if (letter.test(oldpass) && letter.test(newpass) && letter.test(newpassrepeat)) {      loadXMLDoc('changepwd.cgi?username=' + encodeURIComponent(user) + '&oldpass=' + encodeURIComponent(oldpass) + '&newpass=' + encodeURIComponent(newpass), 'GET', function(){        alert(this.responseText);        window.location.reload();      });    } else {      alert('Пароль задан неправильно');      $('oldpwd').value = '';      $('newpwd').value = '';      $('newpwdrepeat').value = '';    }  }}function timesetType(el) {  if (el.selectedIndex === 0) {    $('ntpservip_l').className += ' hidden';    $('ntpservip').className += ' hidden';    $('ntpservip').setAttribute('disabled', 'disabled');    if ($('ntp-inp')) {      $('ntp-inp').className += ' hidden';      $('ntp-inp').setAttribute('disabled', 'disabled');    }    $('lastsynctime_l').className += ' hidden';    $('lastsynctime').className += ' hidden';    // -----------------    $('date_l').className = 'col span_1_of_2';    $('date').className = 'form-control';    $('time_l').className = 'col span_1_of_2';    $('time').className = 'form-control';    $('date').removeAttribute('disabled');    $('time').removeAttribute('disabled');  } else {    $('ntpservip_l').className = 'col span_1_of_2';    $('ntpservip').className = 'form-control';    $('ntpservip').removeAttribute('disabled');    if ($('ntp-inp')) {      $('ntp-inp').className = 'form-control';      $('ntp-inp').removeAttribute('disabled');    }    $('lastsynctime_l').className = 'col span_1_of_2';    $('lastsynctime').className = 'form-control';    // -------------    $('date_l').className += ' hidden';    $('date').className += ' hidden';    $('time_l').className += ' hidden';    $('time').className += ' hidden';    $('date').setAttribute('disabled', 'disabled');    $('time').setAttribute('disabled', 'disabled');  }}function countdown(rel) {  var countDown = 10;  setInterval(function () {    if (countDown == 1 && rel === true) {      location.reload(true);    }    else if (countDown == 1 && rel !== true){      window.location.href = 'http:' + window.location.origin.substring(window.location.protocol.length);    }    if (countDown > 0){countDown--;}    $('count-number').innerHTML = countDown;    return countDown;  }, 1000);}function dhcpState() {  if ($('dhcp').checked) {    $('ipaddr').setAttribute('disabled', 'disabled');    $('gw').setAttribute('disabled', 'disabled');    $('mask').setAttribute('disabled', 'disabled');  } else {    $('ipaddr').removeAttribute('disabled');    $('gw').removeAttribute('disabled');    $('mask').removeAttribute('disabled');  }}//########## Info Form Validation ############function infoValidation(){  var sysname, owner, sysLocation,comment;  sysname  = $('sysname').value,  owner    = $('owner').value,  sysLocation = $('sysLocation').value,  comment  = $('comment').value;  var flag = true;  if(!ValidateAlphanumeric2(sysname, 'Название устройства')){flag = false;}  if(!ValidateAlphanumeric2(owner, 'Владелец')){flag = false;}  if(!ValidateAlphanumeric2(sysLocation, 'Местоположение')){flag = false;}  if(!ValidateAlphanumeric2(comment, 'Комментарии')){flag = false;}  return flag;}function ValidateAlphanumeric2(uadd, z) {  var warn = document.createElement('li');  // var letter = /^[0-9a-zA-Z]+[^\u0430-\u044f\u0410-\u042f\u0451\u0401\?]+$/m;  var letter = /^[0-9a-zA-Z.,/\-_*#()[\]+=;:'"@!^%&?|${}`~<>]+$/m;  warn.innerHTML = 'Поле ' + z + ' может содержать только латинские буквы, цифры и символы .,/-_*#()[]+=;:\'"@!^%&?|${}`~<>';  if (letter.test(uadd) || !uadd) {    return true;  }  $('validation-box').appendChild(warn);  return false;}function submitInfo() {  if (confirm('Вы уверены что хотите применить изменения?')) {    if (infoValidation()) {      $('SNMPinfo').submit();      // loadXMLDoc('info.cgi?owner='+ $('owner').value + '&sysLocation='+ $('location').value + '&comment='+ decodeURIComponent($('comment').value), 'GET', function(){      //   console.log('Сохранено');      // });    }    else {      $('validation-box').style.display = 'block';    }  }}function getJSON(url, successHandler, errorHandler) {  var xhr;  xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP');  xhr.open('GET', url, true);  xhr.onreadystatechange = function () {    var status;    var data;    if (xhr.readyState == 4) {      status = xhr.status;      if (status == 200) {        data = JSON.parse(xhr.responseText);        successHandler(data);      } else {        errorHandler(status);      }    }  };  xhr.send();}function updatepage(){  var loc = location.pathname.slice(1, -5);  switch(loc){  case 'settings':    setTimeout(settingsGET, 1000);    break;  case 'history':    getPage($('currentpage').value);    break;  }}function getCGI(url) {  var xmlhttp;  var q;  if (url == 'reset.cgi') {    q = confirm('Вы уверены что хотите сбросить в заводские настройки?');  }  if (url == 'reboot.cgi') {    q = confirm('Вы уверены что хотите перезагрузить устройство?');  }  if (url == 'update.cgi') {    q = confirm('Вы уверены что хотите обновить прошивку устройства?');  }  if (q) {    if (window.XMLHttpRequest) {      xmlhttp = new XMLHttpRequest();    } else {      xmlhttp = new window.ActiveXObject('Microsoft.XMLHTTP');    }    // xmlhttp.onreadystatechange = true;    xmlhttp.open('GET', url, true);    xmlhttp.send();    return true;  }  // else {alert(a);}}function Alarm(bitmask, num) {  // Bit mask format DEC <NUMBER>  var answ = (bitmask & (1 << num)) >> num;  return answ;}function setIcons(containerID, icnName) {  $(containerID).innerHTML ='';  var icons = typeof icnName === 'string' ? [icnName] : icnName;  for (var i = 0; i < icons.length; i++) {    var icnContainer = document.createElement('i');    icnContainer.innerHTML = Icons[icons[i]]['icn'];    icnContainer.style.paddingLeft = '10px';    icnContainer.title = Icons[icons[i]]['title'];    $(containerID).appendChild(icnContainer);  }}function paramsRefresh() {  getJSON('getJson.cgi'+'?'+Math.random(), function (data) {    var alrm   = +data.u_alarm;    var ma     = +data.m_alarm;    var pstate = [];    var bstate = [];    var ups_bypass = Alarm(alrm, 5),      ups_alarm    = Alarm(alrm, 4) || Alarm(alrm, 7),      ups_standby  = Alarm(alrm, 3),      ups_shutdown = Alarm(alrm, 1),      bat_low      = Alarm(alrm, 6),      bat_test     = Alarm(alrm, 2);    // PPS    $('AC').innerHTML         = parseFloat(data.AC) + ' В';    $('AC').style.color       = Alarm(alrm, 7) ? ALARM_RED : ALARM_GREEN;    $('DC').innerHTML         = parseFloat(data.DC) + ' В';    $('DC').style.color       = Alarm(ma, 7) ? ALARM_RED : ALARM_GREEN;    $('in_freq').innerHTML    = parseFloat(data.in_freq) + ' Гц';    $('in_freq').style.color  = Alarm(alrm, 7) ? ALARM_RED : ALARM_GREEN;    $('out_freq').innerHTML   = parseFloat(data.out_freq) + ' Гц';    $('out_freq').style.color = Alarm(ma, 7) ? ALARM_RED : ALARM_GREEN;    $('pwr').innerHTML        = parseFloat(data.pwr) + ' %';    $('pwr').style.color      = Alarm(ma, 0) ? ALARM_RED : ALARM_GREEN;    $('pmode').innerHTML      = ups_bypass ? 'Bypass' : 'Boost or Buck';    // State    ups_alarm ? pstate.push('exclamination') : pstate.push('normal');    // ups_standby ? pstate.push('clock') : null;    ups_shutdown ? pstate.push('shutdown') : null;    !Alarm(ma, 3) && !bat_low ? bstate.push('normal') : null;    Alarm(ma, 3) ? bstate.push('exclamination') : null;    bat_low ? bstate.push('batteryLow') : null;    bat_test ? bstate.push('batTest') : null;    setIcons('pstate_icons', pstate);    setIcons('bstate_icons', bstate);    // ACB    $('bat_rem_cap').innerHTML      = parseFloat(data.bat_rem_cap) + ' %';    $('bat_rem_cap').style.color    = bat_low ? ALARM_RED : ALARM_GREEN;    $('inner_temp').innerHTML   = parseFloat(data.inner_temp).toString() === 'NaN' ? data.inner_temp : parseFloat(data.inner_temp) + ' °C';    $('inner_temp').style.color = Alarm(ma, 1) || Alarm(ma, 8) ? ALARM_RED : ALARM_GREEN;    $('bat_time_left').innerHTML = parseFloat(data.bat_time_left) + ' мин';    $('bat_time_left').style.color    = bat_low ? ALARM_RED : ALARM_GREEN;    $('case_temp').innerHTML   = parseFloat(data.case_temp).toString() === 'NaN' ? data.case_temp : parseFloat(data.case_temp) + ' °C';    $('case_temp').style.color = Alarm(ma, 9) || Alarm(ma, 10) ? ALARM_RED : ALARM_GREEN;    // Inputs    $('di_name1').innerHTML = data.di_name1;    $('di1').innerHTML   = +data.di1 ? 'Разомкнут' : 'Замкнут';    $('di1').style.color = Alarm(ma, 4) ? ALARM_RED : ALARM_GREEN;    $('di_name2').innerHTML = data.di_name2;    $('di2').innerHTML   = +data.di2 ? 'Разомкнут' : 'Замкнут';    $('di2').style.color = Alarm(ma, 5) ? ALARM_RED : ALARM_GREEN;    // checkState();    window.setCookie('netsettings_changed', data.netsettings_changed);    window.setCookie('device-error', Alarm(ma, 2));    checkNotify();    setTimeout(paramsRefresh, 1000);  }, function (status) {    if (status !== 0){      alert('Не удалось получить данные.');      setTimeout(paramsRefresh, 15000);    }  });}var mint;//########## History ############var ctrl_inputs = [  'h_param_',  'h_event_',  'h_datetime_'];function getPage(pn){  getJSON('history.cgi?page=' + pn, function(data){    $('history_data').textContent = '';    var n = data.page;    $('currentpage').value = pn;    $('pagelimit').innerHTML = data.pages;    for (var i in n){      var tr = document.createElement('tr');      for (var num = 0; num < ctrl_inputs.length; num++) {        var td = document.createElement('td');        td.innerHTML = n[i].split(';')[num];        td.id = ctrl_inputs[num] + i;        tr.appendChild(td);      }      $('history_data').appendChild(tr);    }    window.setCookie('netsettings_changed', data.netsettings_changed);    checkNotify();    clearTimeout(mint);    mint = setTimeout(history_dataref, 5000);  }, function(){    $('table').display = 'none';    $('content').innerHTML =      '<h1>Журнал событий</h1>'+      '<div class="panel panel-default">'+        '<div class="panel-heading">Ошибка</div>'+        '<p style="text-align: center;">Данные отсутствуют.</p>'+      '</div>';  });}function history_dataref() {  var pn = parseInt($('currentpage').value);  getJSON('history.cgi?page=' + pn, function(data) {    var p = data.page;    for (var j in p) {      for (var num = 0; num < ctrl_inputs.length; num++) {        $(ctrl_inputs[num] + j).innerHTML = p[j].split(';')[num];      }      $('pagelimit').innerHTML = data.pages;    }    clearTimeout(mint);    mint = setTimeout(history_dataref, 5000);  });}function nextPage(){  var next = parseInt($('currentpage').value);  if (next < parseInt($('pagelimit').textContent)) {    next = next + 1;    getPage(next);  }}function prevPage(){  var prev = parseInt($('currentpage').value);  if (prev != 1) {    prev = prev - 1;    getPage(prev);  }}//########## UPS History ############var ups_inputs = [  { id: 'h_inputv_',  unit: ' В',  parse: 'float' },  { id: 'h_inputfv_', unit: ' В',  parse: 'float' },  { id: 'h_outputv_', unit: ' В',  parse: 'float' },  { id: 'h_outputc_', unit: '%',   parse: 'float' },  { id: 'h_inputf_',  unit: ' Гц', parse: 'float' },  { id: 'h_batv_',    unit: ' В',  parse: 'float' },  { id: 'h_temp_',    unit: ' °C', parse: 'float' },  { id: 'h_status_',  unit: '',    parse: 'string' },  { id: 'h_time_',    unit: '',    parse: 'string' }];function getUPSPage(pn){  getJSON('ups_history.cgi?page=' + pn, function(data){    $('history_data').textContent = '';    var n = data.page;    $('currentpage').value = pn;    $('pagelimit').innerHTML = data.pages;    for (var i in n){      var tr = document.createElement('tr');      for (var num = 0; num < ups_inputs.length; num++) {        var td = document.createElement('td');        td.innerHTML = ups_inputs[num].parse === 'float' ? parseFloat(n[i].split(';')[num]) + ups_inputs[num].unit : n[i].split(';')[num] + ups_inputs[num].unit;        td.id = ups_inputs[num].id + i;        tr.appendChild(td);      }      $('history_data').appendChild(tr);    }    window.setCookie('netsettings_changed', data.netsettings_changed);    checkNotify();    clearTimeout(mint);    mint = setTimeout(ups_history_dataref, 5000);  }, function(){    $('table').display = 'none';    $('content').innerHTML =      '<h1>Журнал событий</h1>'+      '<div class="panel panel-default">'+        '<div class="panel-heading">Ошибка</div>'+        '<p style="text-align: center;">Данные отсутствуют.</p>'+      '</div>';  });}function ups_history_dataref() {  var pn = parseInt($('currentpage').value);  getJSON('ups_history.cgi?page=' + pn, function(data) {    var p = data.page;    for (var j in p) {      for (var num = 0; num < ups_inputs.length; num++) {        $(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;      }      $('pagelimit').innerHTML = data.pages;    }    clearTimeout(mint);    mint = setTimeout(ups_history_dataref, 5000);  });}function nextUPSPage(){  var next = parseInt($('currentpage').value);  if (next < parseInt($('pagelimit').textContent)) {    next = next + 1;    getUPSPage(next);  }}function prevUPSPage(){  var prev = parseInt($('currentpage').value);  if (prev != 1) {    prev = prev - 1;    getUPSPage(prev);  }}function utf8_decode (s) {  var bb = '', c = 0;  for (var i = 0; i < s.length; i++) {    c = s.charCodeAt(i);    if (c > 127) {      if (c > 1024) {        if (c == 1025) {          c = 1016;        } else if (c == 1105) {          c = 1032;        }        bb += String.fromCharCode(c - 848);      }    } else {      bb += s.charAt(i);    }  }  return bb;}function msieversion() {  var ua = window.navigator.userAgent;  var msie = ua.indexOf('MSIE ');  if (msie != -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) /*If IE, return version number*/ return true;  return false;}function blobLoad(requestUrl, fileName, buttonID){  if(isMobile.iOS()){    alert('На данном устройстве сохранение не доступно.');    return false;  }  var old = $(buttonID).children[0].textContent;  var pgFlag = 'Обработка';  var pgFlagLen = pgFlag.length;  var d = new Date();  var fName;  if (fileName === 'settings.dat') {    fName = fileName;  } else {    fName = d.getDate()+'_'+(d.getMonth()+1)+'_'+d.getHours()+d.getMinutes() + '_' + fileName;  }  var xhr = new XMLHttpRequest();  var fURL = requestUrl.split('.').pop() == 'cgi' ? requestUrl+'?' : requestUrl+'&';  xhr.open('GET', fURL+'_='+ new Date().getTime());  xhr.responseType = 'blob';  $(buttonID).setAttribute('disabled', 'disabled');  xhr.addEventListener('load', function(){    $(buttonID).children[1].style.width = 0;    $(buttonID).children[0].textContent = old;    $(buttonID).removeAttribute('disabled');  });  xhr.onload = function(){    if (this.status === 200) {      var blob = this.response;      if(msieversion()){        if (window.navigator.msSaveOrOpenBlob) {          window.navigator.msSaveOrOpenBlob(blob, fName);        } else {          var IEwindow = window.open(requestUrl);        }      } else {        var objectUrl = URL.createObjectURL(blob);        var uri = objectUrl;        var link = document.createElement('a');        link.href = uri;        link.style = 'visibility:hidden';        link.download = fName;        document.body.appendChild(link);        link.click();        document.body.removeChild(link);      }    }  };  xhr.onprogress = function(event) {    $(buttonID).children[0].textContent = parseInt((event.loaded / event.total) * 100) + '%';    $(buttonID).children[1].style.width = parseInt((event.loaded / event.total) * 100) + '%';  };  xhr.send();}var isMobile = {  Android: function() {    return navigator.userAgent.match(/Android/i);  },  BlackBerry: function() {    return navigator.userAgent.match(/BlackBerry/i);  },  iOS: function() {    return navigator.userAgent.match(/iPhone|iPad|iPod/i);  },  Opera: function() {    return navigator.userAgent.match(/Opera Mini/i);  },  Windows: function() {    return navigator.userAgent.match(/IEMobile/i);  },  any: function() {    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());  }};function checkOther(ele) {  if (ele.selectedIndex == 3) {    var newInput = document.createElement('input');    newInput.type = 'text';    newInput.className = 'form-control';    newInput.id = 'ntp-inp';    newInput.value = ntpservipValue;    newInput.style.marginTop = '10px';    ele.parentNode.insertBefore(newInput, ele.nextSibling);  }  else if ($('ntp-inp')) {    var d = $('ntp-inp');    ele.parentNode.removeChild(d);  }}// ################################################################################function fillTempRange(id, min, max) {  var obj = $(id);  for (var i = min; i <= max; i++) {    var opt = document.createElement('option');    opt.value = i;    opt.text = i;    obj.appendChild(opt);  }}function pgwState() {  if (!$('pgw_en').checked) {    $('pgw_port').children[0].setAttribute('disabled', 'disabled');    $('pgw_baud').setAttribute('disabled', 'disabled');    $('pgw_par').setAttribute('disabled', 'disabled');    $('pgw_ndata').setAttribute('disabled', 'disabled');    $('pgw_nstop').setAttribute('disabled', 'disabled');  } else {    $('pgw_port').children[0].removeAttribute('disabled');    $('pgw_baud').removeAttribute('disabled');    $('pgw_par').removeAttribute('disabled');    $('pgw_ndata').removeAttribute('disabled');    $('pgw_nstop').removeAttribute('disabled');  }}function changeNData(e) {  var num = e.id.split('_')[0];  if (e.value == 'no') {    $(num+'_ndata').value = '8';    $(num+'_ndata').children[0].disabled = true;  } else {    $(num+'_ndata').children[0].disabled = false;  }}function tsChange() {  var selects = ['type_ts1', 'type_ts2'];  for (var s in selects) {    var obj = $(selects[s]);    for (var j = 1; j < obj.options.length; j++) {      if (obj.options[j].value != obj.value && obj.options[j].value !== 0) {        obj.options[j].disabled = false;        if (obj.options[j].value == $(selects[0]).value)          obj.options[j].disabled = true;        if (obj.options[j].value == $(selects[1]).value)          obj.options[j].disabled = true;      } else {        obj.options[j].disabled = false;      }    }  }}function settingsGET(){  getJSON('settings.cgi', function(data) {    //SNMP params    $('managerIP').value = data.managerIP;    $('read_community').value = data.read_community;    $('write_community').value = data.write_community;    $('managerIP2').value = data.managerIP2;    $('managerIP3').value = data.managerIP3;    $('managerIP4').value = data.managerIP4;    $('managerIP5').value = data.managerIP5;    $('di_name1').value = data.di_name1;    $('di1').value = +data.di1;    $('di_name2').value = data.di_name2;    $('di2').value = +data.di2;    $('type_ts1').value = +data.type_ts1;    $('type_ts2').value = +data.type_ts2;    // Network params    $('ipaddr').value   = data.ipaddr;    $('gw').value       = data.gw;    $('mask').value     = data.mask;    $('dhcp').checked   = data.dhcp;    // Alarms    fillTempRange('temp_high', 40, 80);    fillTempRange('temp_low', -40, 0);    fillTempRange('case_temp_high', 40, 80);    fillTempRange('case_temp_low', -40, 0);    fillTempRange('mainvolt_low', 110, 200);    fillTempRange('mainvolt_high', 220, 250);    $('temp_high').value = data.temp_high;    $('temp_low').value = data.temp_low;    $('case_temp_high').value = data.case_temp_high;    $('case_temp_low').value = data.case_temp_low;    ups_cell_min = new SpinBox('ups_cell_min', {      'value': data.ups_cell_min,      'name':'ups_cell_min',      'minimum':0,      'maximum':3.0,      'decimals':2,      'step':0.01    });    ups_cell_max = new SpinBox('ups_cell_max', {      'value': data.ups_cell_max,      'name':'ups_cell_max',      'minimum':0,      'maximum':3.0,      'decimals':2,      'step':0.01    });    temp_hist = new SpinBox('temp_hist', {      'name':'temp_hist','minimum':0.5,'maximum':2.0,'step':0.1,'decimals':1, 'value': data.temp_hist    });    case_temp_hist = new SpinBox('case_temp_hist', {      'name':'case_temp_hist','minimum':0.5,'maximum':2.0,'step':0.1,'decimals':1, 'value': data.case_temp_hist    });    $('mainvolt_low').value = data.mainvolt_low;    $('mainvolt_high').value = data.mainvolt_high;    mainvolt_hist = new SpinBox('mainvolt_hist', {      'name':'mainvolt_hist','minimum':10,'maximum':30,'step':1, 'value': data.mainvolt_hist    });    // PGW params    $('pgw_en').checked = data.pgw_en;    // $('pgw_port').value = data.pgw_port;    pgw_port = new SpinBox('pgw_port',      {        'value': data.pgw_port,        'name':'pgw_port',        'minimum':1,        'maximum':65535,        'step':1      }    );    $('pgw_baud').value = data.pgw_baud;    $('pgw_par').value = data.pgw_par;    $('pgw_ndata').value = data.pgw_ndata;    $('pgw_nstop').value = data.pgw_nstop;    changeNData($('pgw_par'));    tsChange();    // DateTime    if (data.ntpservip != $('ntpservip').options[0].value &&        data.ntpservip != $('ntpservip').options[1].value &&        data.ntpservip != $('ntpservip').options[2].value )    {      var newInput                       = document.createElement('input');      newInput.type                      = 'text';      newInput.className                 = 'form-control';      newInput.id                        = 'ntp-inp';      newInput.style.marginTop           = '10px';      $('ntpservip').options[3].selected = 'selected';      $('ntpservip').options[3].value    = data.ntpservip;      $('ntpservip').parentNode.insertBefore(newInput, $('ntpservip').nextSibling);      window.ntpservipValue        = data.ntpservip;      newInput.value        = window.ntpservipValue;    } else {      window.ntpservipValue        = data.ntpservip;      $('ntpservip').value  = window.ntpservipValue;    }    $('utc').value          = data.utc;    $('date').value         = data.date;    $('time').value         = data.time;    $('lastsynctime').value = data.lastsynctime;    $('ntp').value          = data.ntp;    dhcpState();    pgwState();    timesetType($('ntp'));    window.setCookie('netsettings_changed', data.netsettings_changed);    checkNotify();  }, function() {    alert('Не удалось получить данные.');  });}function batTest(options) {  this.options = (options ? options : {});  if (this.options.time) {    if (typeof this.options.time !== 'number' && this.options.time > 99) {      return alert('Ошибка заданного времени');    }  }  var str = '';  for (var option in options) {    str += option + '=' + options[option] + '&';  }  str = str.slice(0, -1);  var url = 'bat_test.cgi';  loadXMLDoc(url + '?' + str, 'GET', function(){    this.responseText ? alert(this.responseText) : null;  });}function UPSPowerOff(options) {  this.options = (options ? options : {});  if (typeof this.options.after !== 'number' && this.options.after > 9999) {    return alert('Ошибка заданного времени отключения');  }  var str = '';  for (var option in options) {    str += option + '=' + options[option] + '&';  }  str = str.slice(0, -1);  var url = 'ups_power.cgi';  loadXMLDoc(url + '?' + str, 'GET', function(){    this.responseText ? alert(this.responseText) : null;  });}var apply_settings = new NotificationBox('apply-settings',  {    'message': 'Внимание, для применения сетевых настроек необходимо их подтвердить. Иначе они будут сброшены в течении 10 минут.',    'bgcolor':'#ffcc00',    'textcolor': '#333',    'url': 'confirm.cgi',    'show': window.getCookie('role') < 2  });var device_error = new NotificationBox('device-error',  {    'message': 'Внимание, связь с ИБП не установлена!',    'bgcolor':'#ec0035',    'textcolor': '#fff'  });// ################################################################################function infoGet() {  getJSON('info.cgi', function(data) {    // Cotroller Info    $('uptime').innerHTML    = data.uptime;    $('model').innerHTML     = data.model;    $('prodate').innerHTML   = data.prodate;    $('fwversion').innerHTML = data.fwversion;    $('macaddr').innerHTML   = data.macaddr;    $('serno').innerHTML     = data.serno;    $('ups_fwversion').innerHTML = data.ups_fwversion;    $('ups_sn').innerHTML        = data.ups_sn;    $('ups_model').innerHTML     = data.ups_model;    var info_labels = {      sysname: ['Название устройства', data.sysname,     19],      owner:   ['Владелец',            data.owner,       49],      sysLocation:['Местоположение',   data.sysLocation, 109],      comment: ['Комментарии',         data.comment,     109]    };    for (var i in info_labels) {      var row = document.createElement('tr');      var label = document.createElement('td');      label.innerHTML = info_labels[i][0];      var val = document.createElement('td');      val.id = i+'_wr';      if (getCookie('role') <= 1) {        var inp = document.createElement('input');        inp.type = 'text';        inp.id = i;        inp.name = i;        inp.className = 'form-control';        inp.maxLength = info_labels[i][2];        inp.value = info_labels[i][1];        val.appendChild(inp);      } else {        val.innerHTML = info_labels[i][1];      }      row.appendChild(label);      row.appendChild(val);      $('ctrl_info').appendChild(row);    }    if (getCookie('role') <= 1) {      var sbmt = document.createElement('button');      sbmt.className = 'btn btn-primary-inverted';      sbmt.type = 'button';      sbmt.setAttribute('onclick', 'submitInfo(); return false;');      sbmt.innerHTML = 'Сохранить';      $('SNMPinfo').appendChild(sbmt);    }    window.setCookie('netsettings_changed', data.netsettings_changed);    checkNotify();  }, function() {    alert('Не удалось получить данные.');  });}// ################################################################################/*SpinBox.jsImplements a spin box interface for a text fieldCreated by Stephen Morley - http://code.stephenmorley.org/ - and released underthe terms of the CC0 1.0 Universal legal code:http://creativecommons.org/publicdomain/zero/1.0/legalcode*//* Creates a spin box. The parameter is: * * container - either the DOM node to contain the spin box or the ID of the node * options   - an object containing various parameters; this optional parameter *             defaults to the empty object * * The options object may contain the following keys: * * className - a class name to apply to the container; the class name with the *             suffixes 'Up' and 'Down' will be applied to the up and down *             buttons. The default value is 'spinBox'. * value     - the initial value for the spin box. The default is 0 (subject to *             restrictions on the minimum and maximum value) if the input *             element did not already exist, or the existing value if the input *             element did already exist. * step      - the value by which to increment or decrement the value. The *             default value is 1. * minimum   - the minimum allowed value. The default is not to have a minimum *             value. * maximum   - the maximum allowed value. The default is not to have a maximum *             value. * decimals  - the number of decimal places allowed. The default is 0. * name      - input name attribute. * * Note that the minimum, maximum, and decimal places restrictions are enforced * for values set by the spin box, but a value outside of these restrictions may * be typed by the user. */function SpinBox(container, options) {  // fetch the DOM node if a string was supplied  if (typeof container == 'string') {    container = document.getElementById(container);    container.innerHTML = '';  }  // store the options and set the default values  this.options = (options ? options : {});  if (!('className' in this.options)) this.options.className = 'spinBox';  if (!('step'      in this.options)) this.options.step      = 1;  if (!('decimals'  in this.options)) this.options.decimals  = 0;  // check whether the input field should be created  var inputs = container.getElementsByTagName('input');  if (inputs.length === 0) {    // create the input node    this.input = document.createElement('input');    this.input.setAttribute('minimum', this.options.minimum);    this.input.setAttribute('maximum', this.options.maximum);    this.setValue('value' in this.options ? this.options.value : 0);    this.setName('name'   in this.options ? this.options.name : '');    container.appendChild(this.input);  } else {    // store a reference to the input node    this.input = inputs[0];    this.setValue(this.options.value ? this.options.value : this.input.value);  }  // create the up button  var upButton = document.createElement('span');  upButton.appendChild(document.createElement('span'));  upButton.innerHTML = '+';  container.appendChild(upButton);  // create the down button  var downButton = document.createElement('span');  downButton.appendChild(document.createElement('span'));  downButton.innerHTML = '-';  container.appendChild(downButton);  // apply the classes  container.className += ' ' + this.options.className;  upButton.className = this.options.className + 'Up';  downButton.className = this.options.className + 'Down';  // add the listeners  this.addEventListener(this.input, 'mousewheel',     this.handleMouseWheel, [], true);  this.addEventListener(this.input, 'DOMMouseScroll', this.handleMouseWheel, [], true);  this.addEventListener(this.input, 'keydown',        this.handleKeyDown, [], true);  this.addEventListener(this.input, 'keypress',       this.handleKeyPress, [], true);  this.addEventListener(this.input, 'keyup',          this.stop);  this.addEventListener(this.input, 'blur',           this.loseFocus);  this.addEventListener(upButton,   'mousedown',      this.start, [true]);  this.addEventListener(upButton,   'mouseup',        this.stop);  this.addEventListener(upButton,   'mouseout',       this.stop);  this.addEventListener(downButton, 'mousedown',      this.start, [false]);  this.addEventListener(downButton, 'mouseup',        this.stop);  this.addEventListener(downButton, 'mouseout',       this.stop);}/* Returns the current value. This will be a number, or the value NaN if the * current contents of the input field do not start with a valid number. */SpinBox.prototype.getValue = function () {  // parse and return the value  return parseFloat(this.input.value);};SpinBox.prototype.loseFocus = function () {  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);  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);};SpinBox.prototype.setName = function (name) {  // asign input name  this.input.name = name;};/* Sets the value. Restrictions on the minimum and maximum value are enforced. * The parameter is: * * value - the value */SpinBox.prototype.setValue = function (value) {  // ensure the value is within the permitted range  if ('minimum' in this.options) value = Math.max(this.options.minimum, value);  if ('maximum' in this.options) value = Math.min(this.options.maximum, value);  // store the sign  var sign = (value < 0 ? '-' : '');  value = Math.abs(value);  // determine the multiplier for rounding  var multiplier = Math.pow(10, this.options.decimals);  // split the value in to integer and fractional parts  value = Math.round(value * multiplier);  var integer = (value - value % multiplier) / multiplier;  var fractional = '' + value % multiplier;  // add leading zeros to the fractional part  while (fractional.length < this.options.decimals) {    fractional = '0' + fractional;  }  // set the value  this.input.value =      sign + integer + (this.options.decimals > 0 ? '.' + fractional : '');  // check whether the browser can dispatch events  if ('dispatchEvent' in this.input){    // create the event    try{      var event = new Event('change', {bubbles : true, cancelable : true});    }catch (e){      var event = document.createEvent('Event');      event.initEvent('change', true, true);    }    // dispatch the event    this.input.dispatchEvent(event);  }};/* Adds an event listener to a node. The event listener is bound to the current * value of 'this'. The parameters are: * * node         - the node * event        - the event name * listener     - the listener functions * parameters   - an array of additional parameters to pass to the listener; *                these are placed after the event parameter * allowDefault - true if the default action should not be prevented */SpinBox.prototype.addEventListener = function (node, event, listener, parameters, allowDefault) {  // store a reference to the 'this' object  var thisObject = this;  // create the bound listener  function boundListener(e) {    // get the event if it is not supplied    if (!e) e = window.event;    // call the listener    listener.apply(thisObject, [e].concat(parameters));    // prevent the default action if necessary    if (!allowDefault) {      if (e.preventDefault) {        e.preventDefault();      } else {        e.returnValue = false;      }    }  }  // add the event listener  if (node.addEventListener) {    node.addEventListener(event, boundListener, false);  } else {    node.attachEvent('on' + event, boundListener);  }};/* Handles a mouse wheel event by updating the value if the field is active. The * parameter is: * * e - the event object */SpinBox.prototype.handleMouseWheel = function (e) {  // check whether the field is active  if (document.activeElement == this.input) {    // update the value    if (e.wheelDelta) {      this.start(e, e.wheelDelta > 1);    } else if (e.detail) {      this.start(e, e.detail < 1);    }    this.stop();    // prevent the default action    if (e.preventDefault) {      e.preventDefault();    } else {      e.returnValue = false;    }  }};/* Handles a key down event by starting updating if appropriate. The parameter * is: * * e - the event object */SpinBox.prototype.handleKeyDown = function (e) {  // if the up or down keys were pressed, start updating  if (e.keyCode == 38) this.start(e, true);  if (e.keyCode == 40) this.start(e, false);};/* Handles a key press event by filtering out invalid characters. The parameter * is: * * e - the event object */SpinBox.prototype.handleKeyPress = function (e) {  // determine the character code  var charCode = ('charCode' in e ? e.charCode : e.keyCode);  // allow special key presses  if (charCode === 0 || e.altKey || e.ctrlKey || e.metaKey) return;  // allow a minus sign if the value can be negative  if (charCode == 45 && (!('minimum' in this.options) || this.options.minimum < 0)) {    return;  }  // allow a decimal point if the value may contain decimals  if (charCode == 46 && this.options.decimals > 0) return;  // allow digits  if (charCode >= 48 && charCode <= 57) return;  // prevent the default action  if (e.preventDefault) {    e.preventDefault();  } else {    e.returnValue = false;  }};/* Starts updating the value. The parameters are: * * e  - the event object * up - true to increment the value, false to decrement the value */SpinBox.prototype.start = function (e, up) {  // if the field is disabled or we are already updating, return immediately  if (this.input.disabled || 'timeout' in this) return;  // set the update step  this.updateStep = (up ? this.options.step : -this.options.step);  // initialise the timeout delay  this.timeoutDelay = 500;  // update the value  this.update();};// Stops update the value.SpinBox.prototype.stop = function () {  // clear the timeout if it exists  if ('timeout' in this) {    window.clearTimeout(this.timeout);    delete this.timeout;  }};// Updates the value.SpinBox.prototype.update = function () {  // determine the current value  var value = parseFloat(this.input.value);  if (isNaN(value)) value = 0;  // update the value  this.setValue(value + this.updateStep);  // reduce the delay  this.timeoutDelay = Math.max(20, Math.floor(this.timeoutDelay * 0.9));  // call this function again  var thisObject = this;  this.timeout = window.setTimeout(function () { thisObject.update(); }, this.timeoutDelay);};/*  This code is from Dynamic Web Coding at dyn-web.com  Copyright 2009-12 by Sharon Paine  See Terms of Use at www.dyn-web.com/business/terms.php  regarding conditions under which you may use this code.  This notice must be retained in the code as is!*/// DYN_WEB is namespace used for code from dyn-web.com// replacing previous use of dw_ prefix for object namesvar DYN_WEB = DYN_WEB || {};DYN_WEB.Event = {  add: document.addEventListener ? function (obj, etype, fp, cap) {    cap = cap || false;    obj.addEventListener(etype, fp, cap);  } : function (obj, etype, fp) {    obj.attachEvent('on' + etype, fp);  },  remove: document.removeEventListener ? function (obj, etype, fp, cap) {    cap = cap || false;    obj.removeEventListener(etype, fp, cap);  } : function (obj, etype, fp) {    obj.detachEvent('on' + etype, fp);  },  DOMit: function (e) {    e = e ? e : window.event;    if (!e.target) e.target = e.srcElement;    if (!e.preventDefault) e.preventDefault = function () {      e.returnValue = false;      return false;    };    if (!e.stopPropagation) e.stopPropagation = function () {      e.cancelBubble = true;    };    return e;  },  getTarget: function (e) {    e = dw_Event.DOMit(e);    var tgt = e.target;    if (tgt.nodeType != 1) tgt = tgt.parentNode;    return tgt;  }};DYN_WEB.Cookie = {  set: function (name, value, days, path, domain, secure) {    var date, expires;    if (typeof days == 'number') {      date = new Date();      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));      expires = date.toGMTString();    }    document.cookie = name + '=' + encodeURIComponent(value) + (      (expires) ? '; expires=' + expires : ''      ) + (      (path) ? '; path=' + path : ''      ) + (      (domain) ? '; domain=' + domain : ''      ) + (      (secure) ? '; secure' : '');  },  get: function (name) {    var c, cookies = document.cookie.split(/;\s/g);    for (var i = 0; cookies[i]; i++) {      c = cookies[i];      if (c.indexOf(name + '=') === 0) {        return decodeURIComponent(c.slice(name.length + 1, c.length));      }    }    return null;  },  del: function (name, path, domain) {    if (dw_Cookie.get(name)) {      document.cookie = name + '=' + (        (path) ? '; path=' + path : ''        ) + (        (domain) ? '; domain=' + domain : ''        ) + '; expires=Thu, 01-Jan-70 00:00:01 GMT';    }  }};if (!DYN_WEB.Util) {  DYN_WEB.Util = {    // add props of Obj2 to Obj1    augment: function (Obj1, Obj2) {      var prop;      for (prop in Obj2) {        if (Obj2.hasOwnProperty(prop) && !Obj1[prop]) {          Obj1[prop] = Obj2[prop];        }      }    },    $: function (id) {      return document.getElementById(id);    }  };}DYN_WEB.Tabs = (function () {  // obj holds props: id, useCookies, etc.  function Constr(obj) {    this.useCookies = obj.useCookies;    this.before_hide = obj.before_hide || function () {};    this.on_activate = obj.on_activate || function () {};    this.on_init = obj.on_init || function () {};    Constr.col[obj.id] = this;    Constr.init(obj.id);  }  Constr.col = {};  Constr.prototype = {    current: null // id of currently active pane  };  return Constr;})();(function () {  var Ut = DYN_WEB.Util,    Ev = DYN_WEB.Event,    Cookie = DYN_WEB.Cookie,    Tabs = DYN_WEB.Tabs;  Ut.augment(Tabs, {    // static props/methods for DYN_WEB.Tabs    setup: function () {      var obj, settings = [];      if (Tabs.hasBrowserSupport()) {        for (var i = 0; obj = arguments[i]; i++) {          if (obj.css) {            Ut.writeStyleSheet(obj.css);          }          settings[i] = obj; // save to pass to constructor onload        }        Ev.add(window, 'load', function () {          for (var i = 0; settings[i]; i++) {            new Tabs(settings[i]);          }        });      }    },    hasBrowserSupport: function () {      if (document.getElementById && document.getElementsByTagName && typeof decodeURI !== 'undefined' && (document.addEventListener || document.attachEvent)) {        return true;      }      return false;    },    init: function (tabsetId) {      var _this = Tabs.col[tabsetId],        links = Tabs.getTabs(tabsetId),        // code uses hash in tab links but tabs can also link to other pages        // so compare current location to link's href        loc = Ut.getURLtoHash(location),        lnk, pg, paneId, pane, sel, dflt, cur, c, q, hash;      q = Ut.getValueFromQueryString(tabsetId);      if (_this.useCookies) {        c = Tabs.checkCookie(tabsetId);      }      // tab in query string or cookie?      sel = q ? q : c ? c : null;      // add ids and event handlers to links ...      for (var i = 0; lnk = links[i]; i++) {        paneId = '', pane = ''; // reset        pg = Ut.getURLtoHash(lnk);        hash = Ut.getHash(lnk);        if (lnk.hash && (loc == pg)) { // has hash and points to current page          paneId = hash;          lnk.id = tabsetId + '__' + paneId; // double underscore between        }        // if tab associated with tabpane, set up onclick fn        if (paneId) {          try {            pane = Ut.$(paneId);          } catch (err) { // showClicked fn throws          }          // first tab/pane is default          if (!dflt) {            dflt = paneId;          }          // if set active in markup, hold as current          if (pane && Ut.hasClass(lnk, 'activeTab') && Ut.hasClass(pane, 'activePane')) {            _this.current = cur = paneId;          }          // to pass paneId, tabsetId to showClicked...          Ev.add(lnk, 'click', function (paneId, tabsetId) {            return function (e) {              Tabs.showClicked(e, paneId, tabsetId);            };          }(paneId, tabsetId));        }      }      // check if tab and pane for sel      if (sel && (lnk = Ut.$(tabsetId + '__' + sel)) && (pane = Ut.$(sel))) {        if (cur && cur !== sel) {          Tabs.hideCurrent(tabsetId, cur);        }        Ut.addClass(lnk, 'activeTab');        Ut.addClass(pane, 'activePane');        _this.current = sel;      } else if (!cur && dflt) {        Ut.addClass(Ut.$(tabsetId + '__' + dflt), 'activeTab');        Ut.addClass(Ut.$(dflt), 'activePane');        _this.current = dflt;      }      _this.on_init();    },    getTabs: function (id) {      var set = Ut.$(id),        list, links;      if (!set) {        throw new Error('No element matching tabset id found.');        return [];      }      list = Ut.getElementsByClassName('tabnavs', 'ul', set);      if (list.length === 0) {        throw new Error('No tabnavs were found in the tabset.');        return [];      }      links = list[0].getElementsByTagName('a');      return links;    },    showClicked: function (e, paneId, tabsetId) {      var tabId = tabsetId + '__' + paneId;      var _this = Tabs.col[tabsetId];      _this.before_hide(tabId, paneId, tabsetId);      Tabs.hideCurrent(tabsetId, _this.current);      Ut.addClass(Ut.$(tabId), 'activeTab');      try {        Ut.addClass(Ut.$(paneId), 'activePane');      } catch (err) {        throw new Error('showClicked can\'t find pane associated with tab. Check tab hash and pane id.');        return false;      }      _this.current = paneId;      if (_this.useCookies) {        Tabs.setCookie(tabsetId, paneId);      }      _this.on_activate(tabId, paneId, tabsetId);      if (e) {        Ev.DOMit(e);        e.preventDefault();      }      return false;    },    hideCurrent: function (tabsetId, cur) {      var tab = Ut.$(tabsetId + '__' + cur),        pane = Ut.$(cur);      Ut.removeClass(tab, 'activeTab');      Ut.removeClass(pane, 'activePane');    },    checkCookie: function (tabsetId) {      var c, cookies, tab_cookies = Cookie.get('dw_Tabs');      if (tab_cookies) {        cookies = tab_cookies.split(',');        for (var i = 0; cookies[i]; i++) {          c = cookies[i];          if (c.indexOf(tabsetId + ':') === 0) {            return decodeURI(c.slice(tabsetId.length + 1, c.length));          }        }      }      return null;    },    setCookie: function (tabsetId, paneId) {      // format for cookies (multiple tabsets supported): dw_Tabs=tabsetId:paneId,tabsetId:paneId;      var new_tab_cookies = '',        cookies,        tab_cookies = Cookie.get('dw_Tabs');      if (tab_cookies) {        cookies = tab_cookies.split(',');        for (var i = 0; cookies[i]; i++) {          if (cookies[i].indexOf(tabsetId + ':') === 0) {            cookies[i] = tabsetId + ':' + paneId;            new_tab_cookies = cookies.join(',');            break;          }        }        if (!new_tab_cookies) { // if no match for this tabsetId          new_tab_cookies = tab_cookies + ',' + tabsetId + ':' + paneId;        }      } else { // no dw_Tabs set yet        new_tab_cookies = tabsetId + ':' + paneId;      }      Cookie.set('dw_Tabs', new_tab_cookies, null, '/');    }  });})();// util(function () {  var Ut = DYN_WEB.Util;  // add methods to DYN_WEB.Util  Ut.augment(Ut, {    trim: function (str) {      if (String.prototype.trim) {        return str.trim(); // ECMAScript 5      } else {        var re = /^\s+|\s+$/g;        return str.replace(re, '');      }    },    normalizeString: function (str) {      var re = /\s\s+/g;      return Ut.trim(str).replace(re, ' ');    },    hasClass: function (el, cl) {      var re = new RegExp('\\b' + cl + '\\b', 'i');      if (re.test(el.className)) {        return true;      }      return false;    },    addClass: function (el, cl) {      if (!Ut.hasClass(el, cl)) {        el.className = Ut.trim(el.className + ' ' + cl);      }    },    removeClass: function (el, cl) {      el.className = Ut.normalizeString(el.className.replace(cl, ' '));    },    getElementsByClassName: function (sClass, sTag, oCont) {      oCont = oCont ? oCont : document;      if (oCont.getElementsByClassName) {        return oCont.getElementsByClassName(sClass); // html5      } else {        sTag = sTag || '*';        var result = [],          re = new RegExp('\\b' + sClass + '\\b', 'i'),          list = oCont.getElementsByTagName(sTag);        for (var i = 0; list[i]; i++) {          if (re.test(list[i].className)) result.push(list[i]);        }        return result;      }    },    // obj: link or window.location    getValueFromQueryString: function (name, obj) {      obj = obj ? obj : window.location;      var pairs, set;      if (obj.search && obj.search.indexOf(name != -1)) {        pairs = obj.search.slice(1).split('&'); // name/value pairs        for (var i = 0; pairs[i]; i++) {          set = pairs[i].split('='); // Check each pair for match on name          if (set[0] == name && set[1]) {            return set[1];          }        }      }      return '';    },    getURLtoHash: function (obj) {      obj = obj ? obj : window.location;      var href = obj.href,        pt = href.indexOf('#'),        url = (pt != -1) ? href.slice(0, pt) : href; // remove hash from href      return url;    },    getHash: function (obj) {      obj = obj ? obj : window.location;      var hash = '';      if (obj.hash) { // some browsers say true if just #, some '' (ff)        hash = obj.hash.slice(1);      }      return hash;    },    // Alternate functions are available that use DOM methods instead of document.write    writeStyleSheet: function (file, bScreen) {      var screen = (bScreen !== false) ? '" media="screen" />\n' : '"/>\n';      document.write('\n<link rel="stylesheet" href="' + file + screen);    },    // used to set min-height (as on dyn-web home page)    writeStyleRule: function (rule, bScreen) {      var screen = (bScreen !== false) ? ' media="screen">' : '>';      document.write('\n<style type="text/css"' + screen + rule + '</style>');    }  });})();(function (window) {/** * @param  {String} type - request | cancel | native. * @return {Function} Timing function. */  function requestFrame(type) {    // The only vendor prefixes required.    var vendors = ['moz', 'webkit'],      // Disassembled timing function abbreviations.      aF = 'AnimationFrame',      rqAF = 'Request' + aF,      // Final assigned functions.      assignedRequestAnimationFrame,      assignedCancelAnimationFrame,      // Initial time of the timing lapse.      previousTime = 0,      mozRAF = window.mozRequestAnimationFrame,      mozCAF = window.mozCancelAnimationFrame,      // Checks for firefox 4 - 10 function pair mismatch.      hasMozMismatch = mozRAF && !mozCAF,      func;    // Date.now polyfill, mainly for legacy IE versions.    if (!Date.now) {      Date.now = function() {        return new Date().getTime();      };    }  /**   * hasIOS6RequestAnimationFrameBug.   * @See {@Link https://gist.github.com/julienetie/86ac394ec41f1271ff0a}   * - for Commentary.   * @Copyright 2015 - Julien Etienne.   * @License: MIT.   */    function hasIOS6RequestAnimationFrameBug() {      var webkitRAF = window.webkitRequestAnimationFrame,        rAF = window.requestAnimationFrame,        // CSS/ Device with max for iOS6 Devices.        hasMobileDeviceWidth = screen.width <= 768 ? true : false,        // Only supports webkit prefixed requestAnimtionFrane.        requiresWebkitprefix = !(webkitRAF && rAF),        // iOS6 webkit browsers don't support performance now.        hasNoNavigationTiming = window.performance ? false : true,        iOS6Notice = 'setTimeout is being used as a substitiue for' +        'requestAnimationFrame due to a bug within iOS 6 builds',        hasIOS6Bug = requiresWebkitprefix && hasMobileDeviceWidth &&        hasNoNavigationTiming;      function bugCheckresults(timingFnA, timingFnB, notice) {        if (timingFnA || timingFnB) {          console.warn(notice);          return true;        } else {          return false;        }      }      function displayResults() {        if (hasIOS6Bug) {          return bugCheckresults(webkitRAF, rAF, iOS6Notice);        } else {          return false;        }      }      return displayResults();    }    /**     * Native clearTimeout function.     * @return {Function}     */    function clearTimeoutWithId(id) {      clearTimeout(id);    }    /**     * Based on a polyfill by Erik, introduced by Paul Irish &     * further improved by Darius Bacon.     * @see  {@link http://www.paulirish.com/2011/     * requestanimationframe-for-smart-animating}     * @see  {@link https://github.com/darius/requestAnimationFrame/blob/     * master/requestAnimationFrame.js}     * @callback {Number} Timestamp.     * @return {Function} setTimeout Function.     */    function setTimeoutWithTimestamp(callback) {      var immediateTime = Date.now(),        lapsedTime = Math.max(previousTime + 16, immediateTime);      return setTimeout(function() {        callback(previousTime = lapsedTime);      },          lapsedTime - immediateTime);    }      /**       * Queries the native function, prefixed function       * or use the setTimeoutWithTimestamp function.       * @return {Function}       */    function queryRequestAnimationFrame() {      if (Array.prototype.filter) {        assignedRequestAnimationFrame = window['request' + aF] ||          window[vendors.filter(function(vendor) {            if (window[vendor + rqAF] !== undefined)              return vendor;          }) + rqAF] || setTimeoutWithTimestamp;      } else {        return setTimeoutWithTimestamp;      }      if (!hasIOS6RequestAnimationFrameBug()) {        return assignedRequestAnimationFrame;      } else {        return setTimeoutWithTimestamp;      }    }    /**     * Queries the native function, prefixed function     * or use the clearTimeoutWithId function.     * @return {Function}     */    function queryCancelAnimationFrame() {      var cancellationNames = [];      if (Array.prototype.map) {        vendors.map(function(vendor) {          return ['Cancel', 'CancelRequest'].map(            function(cancellationNamePrefix) {              cancellationNames.push(vendor +                  cancellationNamePrefix + aF);            });        });      } else {        return clearTimeoutWithId;      }      /**       * Checks for the prefixed cancelAnimationFrame implementation.       * @param  {Array} prefixedNames - An array of the prefixed names.       * @param  {Number} i - Iteration start point.       * @return {Function} prefixed cancelAnimationFrame function.       */      function prefixedCancelAnimationFrame(prefixedNames, i) {        var cancellationFunction;        for (; i < prefixedNames.length; i++) {          if (window[prefixedNames[i]]) {            cancellationFunction = window[prefixedNames[i]];            break;          }        }        return cancellationFunction;      }      // Use truthly function      assignedCancelAnimationFrame = window['cancel' + aF] ||          prefixedCancelAnimationFrame(cancellationNames, 0) ||          clearTimeoutWithId;      // Check for iOS 6 bug      if (!hasIOS6RequestAnimationFrameBug()) {        return assignedCancelAnimationFrame;      } else {        return clearTimeoutWithId;      }    }    function getRequestFn() {      if (hasMozMismatch) {        return setTimeoutWithTimestamp;      } else {        return queryRequestAnimationFrame();      }    }    function getCancelFn() {      return queryCancelAnimationFrame();    }    function setNativeFn() {      if (hasMozMismatch) {        window.requestAnimationFrame = setTimeoutWithTimestamp;        window.cancelAnimationFrame = clearTimeoutWithId;      } else {        window.requestAnimationFrame = queryRequestAnimationFrame();        window.cancelAnimationFrame = queryCancelAnimationFrame();      }    }      /**       * The type value "request" singles out firefox 4 - 10 and       * assigns the setTimeout function if plausible.       */    switch (type) {    case 'request':    case '':      func = getRequestFn();      break;    case 'cancel':      func = getCancelFn();      break;    case 'native':      setNativeFn();      break;    default:      throw new Error('RequestFrame parameter is not a type.');    }    return func;  }  // Default to window as global  if (typeof window === 'object') {    window.requestFrame = requestFrame;  }  /* global-define */}((typeof window === 'undefined' ? {} : window)));// Iconsvar Icons = {  clock: {    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>',    title: 'Режим ожидания'  },  exclamination: {    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>',    title: 'Авария'  },  normal: {    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>',    title: 'Норма'  },  shutdown: {    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>',    title: 'Выключение'  },  batteryLow: {    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>',    title: 'Низкий уровень заряда'  },  batTest: {    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>',    title: 'Тестирование'  }};
 |