// '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 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 = '<a href="history.html">События Контроллера</a>';
  li[1].innerHTML = '<a href="ups_history.html">Состояние ИБП</a>';
  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 {
        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');
  }
}

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 | sms) ) );
}

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);
  }
};
