// 'use strict';
if (!getCookie('role') && !getCookie('id') && window.location.pathname != '/login.html'){
  window.location.href = '/login.html';
}
if(!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(what, i) {
    i = i || 0;
    var L = this.length;
    while (i < L) {
      if(this[i] === what) return i;
      ++i;
    }
    return -1;
  };
}
function setMainActive(loc){
  var set = '';
  if (typeof(loc) == 'object') {
    for (var i = 0; i < loc.length; i++){
      if (window.location.pathname == loc[i]){
        set = 'active';
      }
    }
    return set;
  } else {
    if (window.location.pathname == loc){
      return 'active';
    } else {
      return '';
    }
  }
}
function createMainNavigation() {
  var nav = [
    {name: 'Параметры', link: 'index.html', child:['/index.html', '/'], access: 2},
    {name: 'Настройки', link: 'settings.html', child: '/settings.html', access: 1},
    {name: 'Уведомления', link: 'snmp.html', child: '/snmp.html', access: 1},
    {name: 'Информация', link: 'info.html', child: '/info.html', access: 2},
    {name: 'Журнал', link: 'history.html', child: ['/history.html', '/ups_history.html'], access: 2}
  ];
  for (var i = 0; i < nav.length; i++) {
    var el = document.createElement('a');
    el.innerHTML = nav[i].name;
    el.href = nav[i].link;
    el.className = setMainActive(nav[i].child);
    var ls = document.createElement('li');
    ls.appendChild(el);
    if (+getCookie('role') > nav[i].access){
      ls.style.display = 'none';
    }
    $('nav').appendChild(ls);
  }
}
function createSubNavigation(){
  var subnav = document.createElement('div');
  subnav.className = 'subnav';
  var ul = document.createElement('ul');
  ul.className = 'nav navbar-nav';
  subnav.appendChild(ul);
  var li = [document.createElement('li'), document.createElement('li')];
  li[0].innerHTML = 'События Контроллера';
  li[1].innerHTML = 'Состояние ИБП';
  if(window.location.pathname == '/history.html') {
    li[0].className = 'active';
  } else if (window.location.pathname == '/ups_history.html') {
    li[1].className = 'active';
  }
  ul.appendChild(li[0]);
  ul.appendChild(li[1]);
  $('subnavf').appendChild(subnav);
}
function $(id) {return document.getElementById(id);}
var timeout;
function clockinit(timeS) {
  clearInterval(timeout);
  customClock(timeS);
  timeout = setInterval(customClock, 1000);
}
var customClock = (function() {
  var timeDiff;
  function addZ(n) {
    return (n < 10? '0' : '') + n;
  }
  function formatTime(d) {
    //Format 'dd.mm.yyyy hh:mm:ss'
    return addZ(d.getDate()) + '.' +
           addZ(d.getMonth() + 1) + '.' +
           d.getFullYear() + ' ' +
           addZ(d.getHours()) + ':' +
           addZ(d.getMinutes()) + ':' +
           addZ(d.getSeconds());
  }
  return function (s) {
    var now = new Date();
    var then;
    // Get the time difference if first run
    if (s) {
      document.getElementById('clockbox').style.opacity = '1';
      then = new Date(now);
      //Set time in mileseconds and reset OS timezone
      then.setTime( parseInt(s) * 1000 + (then.getTimezoneOffset()*60000));
      timeDiff = now - then;
    }
    now = new Date(now - timeDiff);
    if(document.getElementById('clockbox') ){
      document.getElementById('clockbox').innerHTML = formatTime(now);
    }
  };
}());
window.onload = function(){
  if (window.location.pathname !== '/login.html' && getCookie('auth') !== '0'){
    var navId = document.getElementById('nav');
    var li = document.createElement('li');
    var logout = document.createElement('a');
    logout.href = 'javascript:void(0);';
    logout.innerHTML = 'Выход (' + getCookie('uname') + ')';
    logout.onclick = logOut;
    li.id = 'logout';
    li.className = 'logout';
    li.appendChild(logout);
    navId.appendChild(li);
  }
};
function logOut() {
  loadXMLDoc('logout.cgi'+'?'+Math.random(), 'GET', function(){
    deleteCookie('role');
    deleteCookie('id');
    window.location.href = '/login.html';
  });
  return false;
}
function loadXMLDoc(url, method, callback, body) {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new window.ActiveXObject('Microsoft.XMLHTTP');
  }
  xmlhttp.open(method, url, true);
  xmlhttp.setRequestHeader('Content-Type', 'application/json');
  var status;
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4) {
      status = xmlhttp.status;
      if (status == 200) {
        pwdIsCorrect = xmlhttp.responseText;
        if (typeof callback == 'function') {
          callback.apply(xmlhttp);
        }
      } else if (status == 401) {
        alert('Request failed with status code 401');
        window.location.reload();
      } else {
        console.log('Error');
      }
    }
  };
  xmlhttp.send(body);
}
function addSort(page){
  var sortButton = document.getElementsByClassName('sortable');
  for (var i = 0; i < sortButton.length; i++) {
    sortButton[i].addEventListener('click', function(){
      var name = this.getAttribute('sort');
      var direction = this.getAttribute('direction');
      switch(page){
      case 'alarms':
        var target = location.hash.split('#')[1];
        getAlarms(target, name, direction);
        break;
      case 'dryinputs':
        getDryInputs(name, direction);
        break;
      case 'relais':
        getRelais(name, direction);
        break;
      }
      if(direction == 1){
        this.setAttribute('direction', '-1');
      } else {
        this.setAttribute('direction', '1');
      }
    });
  }
}
function getCookie(name){
  var strCookie, arrCookie;
  strCookie = document.cookie,
  arrCookie = strCookie.split('; ');
  for (var i = 0; i < arrCookie.length; i++){
    var arr = arrCookie[i].split('=');
    if (arr[0] == name) return unescape(arr[1]);
  }
  return '';
}
function setCookie(name,value,expirehours){
  var cookieString = name + '=' + escape(value);
  if (expirehours > 0) {
    var date = new Date();
    date.setTime(date.getTime() + expirehours * 3600 * 1000);
    cookieString = cookieString + '; expires=' + date.toGMTString();
  }
  document.cookie = cookieString;
}
function deleteCookie(name) {
  document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
function getJSON(url, successHandler, errorHandler) {
  var xhr;
  xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP');
  var fURL = url.split('.').pop() == 'cgi' ? url+'?' : url+'&';
  xhr.open('GET', fURL+'_=' + new Date().getTime(), true);
  xhr.onreadystatechange = function () {
    var status, data;
    if (xhr.readyState == 4) {
      status = xhr.status;
      if (status == 200) {
        data = JSON.parse(xhr.responseText);
        successHandler(data);
      } else {
        errorHandler(status);
      }
    }
  };
  xhr.send();
}
function checkNotify() {
  ( getCookie('netsettings_changed')  == 'true' ) ? apply_settings.init() : apply_settings.close();
  ( getCookie('device-error') == '1' )            ? device_error.init()   : device_error.close();
}
function getParam(e,x) {
  switch (x) {
  case 0:
    return (e.snmp === 'true');
  case 1:
    return (e.sms === 'true');
  case 2:
    return (e.email === 'true');
  }
}
var snmpArray = [];
function snmpPush(e){
  var index = snmpArray.indexOf(e);
  if (index !== -1) {
    snmpArray.splice(index, 1);
  } else {
    snmpArray.push(e);
  }
  if (snmpArray.length > 0){
    $('sa').style.height = 'auto';
    $('sa').style.opacity = 1;
    $('sa_length').textContent = snmpArray.length;
  } else {
    $('sa').style.height = 0;
    $('sa').style.opacity = 0;
  }
  checkAllStates();
}
function rowsToSubmit(array){
  var rows = [];
  for (var i = 0; i < array.length; i++) {
    var parent = $(array[i]).parentNode.parentNode;
    array[i];
    var index = rows.indexOf(parent.id);
    if (index !== -1) {
      rows[index] = parent.id;
    } else {
      rows.push(parent.id);
    }
  }
  return rows;
}
function createSNMP(id){
  getJSON('snmp.cgi', function(data) {
    $(id).innerHTML = '';
    for (var i = 0; i < data.params.length; i++) {
      var param = data.params[i];
      var param_row = document.createElement('tr');
      param_row.id = param.name;
      var param_name = document.createElement('td');
      param_name.textContent = param.label;
      param_row.appendChild(param_name);
      for (var x = 0; x < 1; x++) {
        var cb_td = document.createElement('td');
        var cb_input = document.createElement('input');
        cb_input.type = 'checkbox';
        cb_input.checked = getParam(param,x);
        cb_input.id = 'cb'+x+param.name;
        cb_input.className = 'checkbox';
        cb_input.setAttribute('onchange', 'snmpPush(this.id)');
        cb_td.appendChild(cb_input);
        param_row.appendChild(cb_td);
      }
      var param_snmp = document.createElement('td');
      $(id).appendChild(param_row);
    }
    utcParam = data.utc;
    // clockinit(data.utm);
    checkAllStates();
    setCookie('netsettings_changed', data.netsettings_changed);
    setCookie('profilaction_changed', data.profilaction_changed);
    setCookie('need_confirm', data.need_confirm);
    checkNotify();
  }, function(error){});
}
function snmpSaSubmit(){
  var url = 'snmp.cgi?';
  var string = '';
  for (var i = 0; i < rowsToSubmit(snmpArray).length; i++) {
    if(i == rowsToSubmit(snmpArray).length-1) {
      string+= $(rowsToSubmit(snmpArray)[i]).id + '=' + arrayToBitMask(rowsToSubmit(snmpArray)[i]);
    } else {
      string+= $(rowsToSubmit(snmpArray)[i]).id + '=' + arrayToBitMask(rowsToSubmit(snmpArray)[i]) + '&';
    }
  }
  if (string){
    loadXMLDoc( url + string, 'GET', updatepage);
  } else {
    updatepage();
  }
  $('sa').style.height = 0;
  $('sa').style.opacity = 0;
  snmpArray = [];
  return false;
}
function snmpChangeCancel(){
  updatepage();
  $('sa').style.height = 0;
  $('sa').style.opacity = 0;
  snmpArray = [];
}
function checkAll(e,id){
  var rows = $('snmp_list').getElementsByTagName('tr');
  if ($(id).checked && !$(id).indeterminate){
    for (var i = 0; i < rows.length; i++) {
      var input = rows[i].children[e].getElementsByTagName('input')[0];
      if (!input.checked) {
        input.checked = true;
        snmpPush(input.id);
      }
    }
  } else if (!$(id).checked && !$(id).indeterminate) {
    for (var i = 0; i < rows.length; i++) {
      var input = rows[i].children[e].getElementsByTagName('input')[0];
      input.checked = false;
      snmpPush(input.id);
    }
  } else if ($(id).checked) {
    for (var i = 0; i < rows.length; i++) {
      var input = rows[i].children[e].getElementsByTagName('input')[0];
      input.checked = true;
      snmpPush(input.id);
    }
  }
}
function checkAllStates(){
  allCheckboxStates(1,'cb_snmp');
  // allCheckboxStates(2,'cb_sms');
  // allCheckboxStates(3,'cb_email');
}
function allCheckboxStates(e,id){
  var rows = $('snmp_list').getElementsByTagName('tr');
  var c = [];
  var nc = [];
  for (var i = 0; i < rows.length; i++) {
    var input = rows[i].children[e].getElementsByTagName('input')[0];
    if (input.checked){
      c.push(input.id);
    } else {
      nc.push(input.id);
    }
  }
  if (c.length && nc.length) {
    $(id).checked = false;
    $(id).indeterminate = true;
  } else if (c.length == rows.length) {
    $(id).checked = true;
    $(id).indeterminate = false;
  } else {
    $(id).checked = false;
    $(id).indeterminate = false;
  }
}
function decimalToBinary(decimal) {
  return (decimal >>> 0).toString(2);
}
function binaryToDecimal(binaryString) {
  return parseInt(binaryString, 2);
}
function cbToBit(id, n){
  var bit = $(id).checked ? 1 : 0;
  return bit << n;
}
function arrayToBitMask(id){
  // var parent = $(id).id;
  var snmp = cbToBit('cb0'+id, 0);
  // var sms = cbToBit('cb1'+id, 1);
  // var email = cbToBit('cb2'+id, 2);
  return binaryToDecimal( decimalToBinary( (snmp) ) );
}
function NotificationBox (id, options) {
  this.id = id;
  this.options = (options ? options : {});
  if(! ('message' in this.options)) this.options.message = 'NotificationBox: Hello World!';
  if(! ('bgcolor' in this.options)) this.options.bgcolor = '#009966';
  if(! ('textcolor' in this.options)) this.options.textcolor = '#fff';
  if(! ('show' in this.options)) this.options.show = true;
  if(! ('url' in this.options)) this.options.url = false;
}
NotificationBox.prototype.init = function(){
  if (!$(this.id)) {
    if (this.options.show) {
      var maindiv = document.createElement('div');
      maindiv.id = this.id;
      maindiv.className = 'notify-box';
      maindiv.style.backgroundColor = this.options.bgcolor;
      maindiv.style.color = this.options.textcolor;
      var string  = document.createElement('p');
      string.textContent = this.options.message;
      maindiv.appendChild(string);
      if (this.options.url) {
        var confirm = document.createElement('button');
        confirm.className = 'btn btn-danger-inverted';
        confirm.textContent = 'Подтвердить';
        confirm.setAttribute('onclick', 'loadXMLDoc(\''+ this.options.url +'\',\'GET\', updatepage)');
        maindiv.appendChild(confirm);
      }
      if (this.options.cancelButton) {
        var cancel = document.createElement('button');
        cancel.className = 'btn btn-warning-inverted';
        cancel.style.marginLeft = '5px';
        cancel.textContent = 'Отмена';
        cancel.setAttribute('onclick', 'loadXMLDoc(\''+ this.options.cancelUrl +'\',\'GET\', updatepage)');
        maindiv.appendChild(cancel);
      }
      document.body.insertBefore(maindiv, document.body.childNodes[0]);
      fadeIn($(this.id));
    }
  }
};
NotificationBox.prototype.close = function(){
  if ($(this.id) ){
    var set = $(this.id);
    document.body.removeChild(set);
  }
};