function usrReq(url, req, get, data, callback) {
  var method, xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
	if(this.readyState == 4){
      if(this.status == 200) {
	    callback(this.response, this.status);
      }else if(this.status == 0){
	    /* chyba spojenia */
		callback(this.response, this.status);
	  }else{
	    callback(this.response, this.status);
	  }
	}
  };
  if(get == 1){
	method = "GET";
  }else{
    method = "POST";
  }
  xhttp.open(method, url+req, true);
  xhttp.withCredentials = true;
  if(get == 1){
	xhttp.send();
  }else{
    xhttp.send(data);
  }
}

var baseurl = sessionStorage.getItem("baseUrl");
var url = sessionStorage.getItem("api");

function TheoryForm(){
  OpenModalUrl("Teória", "max-content", "768px", "theory.html", function(){});
}

function TasksForm(){
  OpenModalUrl("Úlohy", "max-content", "768px", "tasks.html", function(){});
}

function ManualForm(){
  OpenModalUrl("Manuál", "max-content", "768px", "manual.html", function(){});
}

function LoginForm(){
  OpenModalUrl("Prihlásenie", "500px", "", baseurl+"/modals/login.html", function(){});
}

function Login(){
  var info = document.getElementById("info");
  var email = document.getElementById("email");
  var pass = document.getElementById("pass");
  var data = '["'+email.value+'", "'+pass.value+'"]';
  var err = 0;
  
  if(email.value.length == 0){
	email.classList.add("invalid");
	info.innerHTML = "Vyplnte e-mail";
	err++;
  }else{
	email.classList.remove("invalid");	  
  }
  
  if(pass.value.length == 0){
	pass.classList.add("invalid");
	info.innerHTML = "Vyplnte heslo"; 
	err++; 
  }else{
	pass.classList.remove("invalid");	  
  }
  
  if(err == 2){
	info.innerHTML = "Vyplnte údaje"; 
  }  
  
  if(err == 0){  
    usrReq(url, "/user/login", 0, data, function(arg, status){ 
	  if(status == 200){
	    usrReq(url, "/user/info", 1, "", function(arg, status){ 
		  if(status == 200){
	  	    sessionStorage.setItem("user", arg);
	  	    location.reload();		
		  }
  	    });
	  }else if(status == 403){
		var resp = JSON.parse(arg);
	    info.innerHTML = resp.message;
	  }else if(status == 0){
	    info.innerHTML = "Chyba spojenia !";
	  }
    });
  }
}

function Logout(){
  usrReq(url, "/user/logout", 0, "", function(arg, status){ 
	if(status == 200){
	  sessionStorage.setItem("user", "not");
	  location.reload();		
	}
  });
}

/* ------------------------------------------- */
function PassChangeForm(){
  OpenModalUrl("Zmena hesla", "500px", "", baseurl+"/modals/passchange.html", function(){});
}

function PassChange(){
  var info = document.getElementById("info");
  var actpass = document.getElementById("actpass");
  var newpass = document.getElementById("newpass");	
  var newpass2 = document.getElementById("newpass2");
  var err = 0;
  
  if(actpass.value.length == 0){
	actpass.classList.add("invalid");
	info.innerHTML = "Vyplnte heslo";
	err++;
  }else{
	actpass.classList.remove("invalid");	  
  }
  
  if(newpass.value.length == 0){
	newpass.classList.add("invalid");
	info.innerHTML = "Vyplnte heslo"; 
	err++; 
  }else{
	newpass.classList.remove("invalid");	  
  }
  
  if(newpass.value.length < 8){
	newpass.classList.add("invalid");
	info.innerHTML = "Minimálna dĺžka 8 znakov"; 
	err++; 
  }else{
	newpass.classList.remove("invalid");	  
  }
  
  if(newpass.value != newpass2.value){
	newpass2.classList.add("invalid");
	info.innerHTML = "Heslá sa nezhodujú"; 
	err++; 
  }else{
	newpass2.classList.remove("invalid");	  
  }

  if(err == 0){
	var data = '["'+actpass.value+'", "'+newpass.value+'", "'+newpass2.value+'"]';    
    usrReq(url, "/user/password", 0, data, function(arg, status){ 
	  if(status == 200){
	    info.innerHTML = "Heslo zmenené";
		actpass.value = "";
		newpass.value = "";
		newpass2.value = "";
	  }else if(status == 403){
		var resp = JSON.parse(arg);
	    info.innerHTML = resp.message;
	  }else if(status == 0){
	    info.innerHTML = "Chyba spojenia !";
	  }
    });
  }
}

/* -------------------------------------------------------- */
var userdataedit = 0;
var userdata = {};

function ProfilForm(){
  OpenModalUrl("Profil", "500px", "", baseurl+"/modals/profil.html", function(){
	userdataedit = 0;
    GetUserData();
  });
}

function GetUserData(){
  var info = document.getElementById("info");
  usrReq(url, "/user/data", 1, "", function(arg, status){ 
	if(status == 200){
	  var resp = JSON.parse(arg);
	  userdata = resp;
	}else if(status == 403){
	  var resp = JSON.parse(arg);
	  info.innerHTML = resp.message; 
	}else if(status == 0){
	  info.innerHTML = "Chyba spojenia !";
	}
	
	UserDataRef();
  });	
}

function UserDataRef(){
  var fname = document.getElementById("fname");
  var lname = document.getElementById("lname");
  var year = document.getElementById("year");	
  var study = document.getElementById("study");
  var ifname = document.getElementById("ifname");
  var ilname = document.getElementById("ilname");
  var iyear = document.getElementById("iyear");	
  var istudy = document.getElementById("istudy");
  var fnamed = document.getElementById("fnamed");
  var lnamed = document.getElementById("lnamed");
  var yeard = document.getElementById("yeard");	
  var studyd = document.getElementById("studyd");
  var subbtn = document.getElementById("subbtn");
  
  var user = sessionStorage.getItem("user");
  var en = false;

  if(user) {
    try {
      user = JSON.parse(user);
    } catch(e) {}
  }
  
  
  en = user.datachange;
  if(en == true){
    subbtn.disabled = false;
  }else{
	subbtn.disabled = true;  
  }
  
  if(userdataedit){
	fnamed.classList.add("hide");
	lnamed.classList.add("hide");
	yeard.classList.add("hide");
	studyd.classList.add("hide");
	ifname.classList.remove("hide");
	ilname.classList.remove("hide");
	iyear.classList.remove("hide");
	istudy.classList.remove("hide");
	
	subbtn.innerHTML = "Uložiť";
	ifname.value = userdata.fname;
	ilname.value = userdata.lname;
	iyear.value = userdata.year;
	istudy.value = userdata.study;
  }else{
	fnamed.classList.remove("hide");
	lnamed.classList.remove("hide");
	yeard.classList.remove("hide");
	studyd.classList.remove("hide");
	ifname.classList.add("hide");
	ilname.classList.add("hide");
	iyear.classList.add("hide");
	istudy.classList.add("hide");
	
	subbtn.innerHTML = "Upraviť";
	fname.innerHTML = userdata.fname;
	lname.innerHTML = userdata.lname;
	year.innerHTML = userdata.year+".";
	study.innerHTML = userdata.study;
  }
}

function UserDataChange(){
  var ifname = document.getElementById("ifname");
  var ilname = document.getElementById("ilname");
  var iyear = document.getElementById("iyear");	
  var istudy = document.getElementById("istudy");
  var info = document.getElementById("info");
  
  var fname = userdata.fname;
  var lname = userdata.lname;
  var year = userdata.year;
  var study = userdata.study;
  
  if(userdataedit){
	var err = 0;
	
    if(Number(iyear.value) > 0 && Number(iyear.value) <= 5){
	  iyear.classList.remove("invalid");	
    }else{
	  iyear.classList.add("invalid");
	  info.innerHTML = "Rozsah od 1 do 5";
	  err++; 
    }
	
	if(fname == ifname.value && lname == ilname.value && year == iyear.value && study == istudy.value){
	  userdataedit = 0;
	  UserDataRef();	
	}else{
	  
	var data = '["'+ifname.value+'", "'+ilname.value+'", "'+iyear.value+'", "'+istudy.value+'"]';
	
	if(err == 0){
	  usrReq(url, "/user/data", 0, data, function(arg, status){ 
	    if(status == 200){
		  setTimeout(GetUserData(), 350);
		  userdataedit = 0;
		  info.innerHTML = "";
		  UserDataRef();
	    }else if(status == 403){
	      var resp = JSON.parse(arg);
	      info.innerHTML = resp.message; 
	    }else if(status == 0){
	      info.innerHTML = "Chyba spojenia !";
	    }
      });
	}
	}
  }else{
	userdataedit = 1;
	UserDataRef();
  }
}

/* -------------------------------------------------------- */
var offset = 0;
var rescnt = 0;
var totalrescnt = 0;

function ReservationsForm(){
  OpenModalUrl("Rezervácie", "768px", "675px", baseurl+"/modals/reservations.html", function(){
	LoadReservations(offset, function(){
      PrevNextRef();
    });  
  });
}

function PrevNextRef(){ 
  if((totalrescnt-offset)>8){
	document.getElementById("next").disabled = false;  
  }else{
	document.getElementById("next").disabled = true;
  }
  if(offset > 0){
	document.getElementById("prev").disabled = false; 
  }else{
	document.getElementById("prev").disabled = true; 
  }	
  document.getElementById("delconf").innerHTML = "";
}

function ResPrev(){
  if(offset > 0){
	if((offset-8) < 0){
	  offset = 0;
	}else{
	  offset = offset -8;
	}
	LoadReservations(offset, function(){
	  PrevNextRef();
	});  
  }
}

function ResNext(){
  if((totalrescnt-offset)>8){
 	offset = offset + 8;
  	LoadReservations(offset, function(){
	  PrevNextRef();
	});
  }
}

function LoadReservations(offset, callback){
  usrReq(url, "/reservations/user/"+offset, 1, "", function(arg, status){ 
	if(status == 200){
	  var resp = JSON.parse(arg);
	  totalrescnt = resp.count;
	  var list = resp.list;
	  rescnt = resp.list.length;
	  var now = Date.now();
	  
	  var table = "<tr><th>Názov pracoviska</th><th>Začiatok</th><th>Koniec</th><th></th></tr>";
	  for (i = 0; i < list.length; i++) {
		  
	    var start = new Date(list[i].start*1000);
	    var starth = "0" + start.getHours();
	    var startm = "0" + start.getMinutes();
	    var startdt = starth.substr(-2)+":"+startm.substr(-2)+" "+start.getDate()+"."+(start.getMonth()+1)+"."+start.getFullYear();;

	    var end = new Date(list[i].end*1000);
	    var endh = "0" + end.getHours();
	    var endm = "0" + end.getMinutes();
	    var enddt = endh.substr(-2)+":"+endm.substr(-2)+" "+end.getDate()+"."+(end.getMonth()+1)+"."+end.getFullYear();;		  
		  
	    table += "<tr><td>";
	    table += list[i].appname;
	    table += "</td><td>";
	    table += startdt;
	    table += "</td><td>";
	    table += enddt;
		table += "</td><td>";
		if(start > now){
		  table += "<span class='del' onclick='DelResConf(this," + list[i].id + ")'>&#128931;</span>";
		}
	    table += "</td></tr>";
	  }
	  
	  document.getElementById("reslist").innerHTML = table;
	}	
	callback();
  });
}

function DelResConf(row, id){
  var selected = document.querySelectorAll(".selected");
  for (i = 0; i < selected.length; i++) {
	selected[i].classList.remove("selected");
  }	
  var srow = row.parentNode.parentNode;
  document.getElementById("delconf").innerHTML = "Odstrániť rezerváciu ? <button onclick='DelConf("+id+",1)'>Áno</button><button onclick='DelConf(0, 0)'>Nie</button>";
  srow.classList.add("selected");
}

function DelConf(id, opt){
  if(opt == 1){
	usrReq(url, "/reservations/delete/"+id, 0, "", function(arg, status){ 
	  if(status == 200){
		LoadReservations(offset, function(){
		  document.getElementById("delconf").innerHTML = "";
		});  
	  }else if(status == 403 || status == 400){
	   	var resp = JSON.parse(arg);
	    document.getElementById("delconf").innerHTML = resp.message;
	  }else if(status == 0){
	  document.getElementById("delconf").innerHTML = "Chyba spojenia !";
	  }	  
    });
  }else if(opt == 0){
	document.getElementById("delconf").innerHTML = "";
	
	var selected = document.querySelectorAll(".selected");
	for (i = 0; i < selected.length; i++) {
	  selected[i].classList.remove("selected");
	}
  }
  
}

/* ------------------------------------------------ */
// RespListRefresh ?
var nameslst, idslst, limits;

function ResAddForm(){
  OpenModalUrl("Rezervácie", "768px", "", baseurl+"/modals/reservation_add.html", function(){
	GetAppList(function(ids, names){
	  var labninput = document.getElementById("labname");  
	  nameslst = names;
	  idslst = ids;
      autocomplete(labninput, names);
	
	  var date = new Date();
	  var dd = date.getDate();
	  var mm = date.getMonth()+1;
	  if(dd<10){ dd='0'+dd; } 
	  if(mm<10){ mm='0'+mm; } 
	  document.getElementById("day").setAttribute("min", date.getFullYear()+'-'+mm+'-'+dd);
	  document.getElementById("resadd").disabled = true;
	  labninput.addEventListener("change", CheckLabName);
    });   
  });
}

function ResAdd(){
  var labninput = document.getElementById("labname");
  var dayinput = document.getElementById("day");
  var startinput = document.getElementById("tstart");
  var endinput = document.getElementById("tend");	
  
  for (var i = 0; i < nameslst.length; i++) {
    if (nameslst[i].toUpperCase() == labninput.value.toUpperCase()){ break; }
  }	
  
  var data = JSON.stringify({start:dayinput.value+" "+startinput.value, end:dayinput.value+" "+endinput.value});
     
  usrReq(url, "/reservations/add/"+idslst[i], 0, data, function(arg, status){ 
	if(status == 200){
	  CheckLabDay();
	}else if(status == 403 || status == 400){
	  var err = JSON.parse(arg);
	  document.getElementById("resinf").innerHTML = err.message;
	}else if(status == 0){
	  document.getElementById("resinf").innerHTML = "Chyba spojenia !";
	}
  });
  
}

function CheckLabDayTimeEnd(){
  var startinput = document.getElementById("tstart");
  var endinput = document.getElementById("tend");
  document.getElementById("resinf").innerHTML = "";

  var s = startinput.value.split(":");
  var sval = Number(s[0])*60+Number(s[1]);
  var maxend = (sval + Number(limits[0]));
  var e = endinput.value.split(":");
  var val = Number(e[0])*60+Number(e[1]);
   
  if(endinput.value != "" && val <= maxend && val > sval && val != sval){
	endinput.classList.add("active");
	endinput.classList.remove("invalid");
	document.getElementById("resadd").disabled = false;
  }else{
	if(val > maxend || val < sval || val == sval){
	  endinput.classList.add("invalid");
	}else{
	  endinput.classList.remove("invalid");
	}
    endinput.classList.remove("active");
	document.getElementById("resadd").disabled = true;
  }  
}

function CheckLabDayTime(){
  var startinput = document.getElementById("tstart");
  var endinput = document.getElementById("tend");
  document.getElementById("resinf").innerHTML = "";

//  var maxtime = (24*60 - Number(limits[0]));
  var maxtime = (24*60 - 2);
  var v = startinput.value.split(":");
  var val = Number(v[0])*60+Number(v[1]);
  CheckLabDayTimeEnd();
  
  var dayinput = document.getElementById("day");
  var today = new Date().setHours(0,0,0,0);
  var t, vd = dayinput.value.split("-");
  var vald = new Date(vd[0],vd[1]-1,vd[2]).getTime();
  
  //if today, cant set start time in past 
  if(today == vald){
	today = new Date();
	today.setMinutes(today.getMinutes() + 1);
	var smm = today.getHours();
	var emm = today.getMinutes();
	var valm = Number(today.getHours())*60+Number(today.getMinutes());
	if(smm<10){ smm='0'+smm; }
	if(emm<10){ emm='0'+emm; }
	startinput.setAttribute("min", smm+":"+emm);

	if(val >= valm){ t = 1; }else{ t = 0; }
  }else{
	startinput.setAttribute("min", " "); 	
	t = 1;
  }
	
  if(startinput.value != "" && val <= maxtime && t){
	startinput.classList.add("active");
	startinput.classList.remove("invalid")

	var maxend = (val + Number(limits[0]));
	if(maxend >= 1440){ maxend=1439; }
    var hrs = Math.floor((maxend % (60 * 24)) / (60));
    var mins = Math.floor((maxend % (60)) );
	if(hrs<10){ hrs='0'+hrs; }
	if(mins<10){ mins='0'+mins; }
	endinput.setAttribute("max", hrs+":"+mins);
	
	maxend = (val + 1);
    hrs = Math.floor((maxend % (60 * 24)) / (60));
    mins = Math.floor((maxend % (60)) );
	if(hrs<10){ hrs='0'+hrs; }
	if(mins<10){ mins='0'+mins; }
	endinput.setAttribute("min", hrs+":"+mins);
	
	endinput.addEventListener("change", CheckLabDayTimeEnd);
  }else{
	if(val > maxtime || !t){
	  startinput.classList.add("invalid");
	}else{
	  startinput.classList.remove("invalid");
	}
    startinput.classList.remove("active");
	endinput.setAttribute("class", "");
	endinput.addEventListener("change", CheckLabDayTimeEnd);
	document.getElementById("resadd").disabled = true;
  }
}

function CheckLabDay(){
  var labninput = document.getElementById("labname");
  var dayinput = document.getElementById("day");
  var startinput = document.getElementById("tstart");
  var endinput = document.getElementById("tend");
  
  for (var i = 0; i < nameslst.length; i++) {
    if (nameslst[i].toUpperCase() == labninput.value.toUpperCase()){ break; }
  }	
  
  document.getElementById("resinf").innerHTML = "";
  document.getElementById("restmlist").innerHTML = "";
  var today = new Date().setHours(0,0,0,0);
  var v = dayinput.value.split("-");
  var val = new Date(v[0],v[1]-1,v[2]).getTime();
  var maxdate = new Date();
  maxdate.setDate(maxdate.getDate() + Number(limits[3]));

  if(dayinput.value != "" && val >= today && val < maxdate.getTime()){
    GetAppDayRes(idslst[i], dayinput.value, function(resp){
	  var list = "";
	  for (var i = 0; i < resp.length; i++) {
	    var startd = new Date(resp[i].start*1000);
	    var endd = new Date(resp[i].end*1000);
	    var smm = startd.getMinutes();
	    var emm = endd.getMinutes();
	    if(smm<10){ smm='0'+smm; }
	    if(emm<10){ emm='0'+emm; }
	
	    list += '<div class="timeres">';
	    list += startd.getHours()+":"+smm;
	    list += " - ";
	    list += endd.getHours()+":"+emm;
	    list += "</div>";
	  }
	document.getElementById("restmlist").innerHTML = list;
	dayinput.classList.add("active");
	
//	var maxtime = (24*60 - Number(limits[0]));
	var maxtime = (24*60 - 2);
	var hrs = Math.floor((maxtime % (60 * 24)) / (60));
	var mins = Math.floor((maxtime % (60)) );
   	startinput.setAttribute("max", hrs+":"+mins);
	
	//if today, cant set start time in past 
	if(today == val){
	  today = new Date();
	  today.setMinutes(today.getMinutes() + 1);
	  smm = today.getHours();
	  emm = today.getMinutes();
	  if(smm<10){ smm='0'+smm; }
	  if(emm<10){ emm='0'+emm; }

	  startinput.setAttribute("min", smm+":"+emm); 
	}else{
	  startinput.setAttribute("min", " "); 	
	}
   
	startinput.disabled = false;
    endinput.disabled = false;
	startinput.addEventListener("focusout", CheckLabDayTime);
  });
  }else{
	if(val >= today || val < maxdate.getTime()){
	  dayinput.classList.add("invalid");
	}else{
	  dayinput.classList.remove("invalid");
	}
	startinput.removeEventListener("focusout", CheckLabDayTime);
    dayinput.classList.remove("active");
	startinput.disabled = true;
    endinput.disabled = true;
	startinput.setAttribute("class", "");
	endinput.setAttribute("class", "");
	startinput.value = startinput.defaultValue;
	endinput.value = endinput.defaultValue;
	document.getElementById("resadd").disabled = true;
  }
}

function CheckLabName(){
  var labninput = document.getElementById("labname");
  var dayinput = document.getElementById("day");
  var startinput = document.getElementById("tstart");
  var endinput = document.getElementById("tend");

  document.getElementById("resinfo").innerHTML = "";
  document.getElementById("restmlist").innerHTML = "";
  document.getElementById("resadd").disabled = true;
  dayinput.value = dayinput.defaultValue;
  dayinput.classList.remove("active");
  dayinput.classList.remove("invalid");
  startinput.disabled = true;
  endinput.disabled = true;
  
  for (var i = 0; i < nameslst.length; i++) {
	if (nameslst[i].toUpperCase() == labninput.value.toUpperCase()) {
	  GetAppInfo(idslst[i], function(resp){
		limits = resp.limits.split(",");
		var maxdate = new Date();
		maxdate.setDate(maxdate.getDate() + Number(limits[3]));
		
		var dd = maxdate.getDate();
		var mm = maxdate.getMonth()+1;
		if(dd<10){ dd='0'+dd; } 
		if(mm<10){ mm='0'+mm; } 
		dayinput.setAttribute("max", maxdate.getFullYear()+'-'+mm+'-'+dd);
		
		labninput.classList.add("active");
		document.getElementById("resinfo").innerHTML = "Maximálny počet na deň: "+limits[1]+"<br />Maximálny celkový počet na pracovisko: "+limits[2];
		
		dayinput.disabled = false;
		dayinput.addEventListener("change", CheckLabDay);
	  });
	}else{
	  dayinput.disabled = true;
	  dayinput.removeEventListener("change", CheckLabDay);
	  labninput.classList.remove("active");
	  startinput.value = startinput.defaultValue;
	  endinput.value = endinput.defaultValue;
	  startinput.setAttribute("class", "");
	  endinput.setAttribute("class", "");
	}
  }
}

function GetAppList(callback){
  usrReq(url, "/reservations/applist", 1, "", function(arg, status){ 
	if(status == 200){
	  var resp = JSON.parse(arg);
	  var ids = [];
	  var names = []; 
	  
	  for(var i = 0; i < resp.length; i++) {
  		ids.push(resp[i].appid);
		names.push(resp[i].appname);
	  }
	  callback(ids, names);
	}else if(status == 0){
	  document.getElementById("resinf").innerHTML = "Chyba spojenia !";
	}
  });
}

function GetAppInfo(appid, callback){
  usrReq(url, "/app/info/"+appid, 1, "", function(arg, status){ 
	if(status == 200){
	  var resp = JSON.parse(arg);
	  callback(resp);
	}else if(status == 0){
	  document.getElementById("resinf").innerHTML = "Chyba spojenia !";
	}
  });
}

function GetAppDayRes(appid, date, callback){
  usrReq(url, "/reservations/app/"+appid+"/"+date, 1, "", function(arg, status){ 
	if(status == 200){
	  var resp = JSON.parse(arg);
	  callback(resp);
	}else if(status == 0){
	  document.getElementById("resinf").innerHTML = "Chyba spojenia !";
	}
  });
}

/* ----------------------------------------------- */
function autocomplete(inp, arr) {
  var currentFocus;
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      closeAllLists();
	  
      if (!val) { return false; }
      currentFocus = -1;

      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");

      this.parentNode.appendChild(a);

      for (i = 0; i < arr.length; i++) {
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          b = document.createElement("DIV");
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          b.addEventListener("click", function(e) {
              inp.value = this.getElementsByTagName("input")[0].value;
		      CheckLabName(); //check
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });

  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) { //down
        currentFocus++;
        addActive(x);
      } else if (e.keyCode == 38) { //up
        currentFocus--;
        addActive(x);
      } else if (e.keyCode == 13) { //enter
        e.preventDefault();
        if (currentFocus > -1) {
          if (x) x[currentFocus].click();
        }
      }
  });
  
  function addActive(x) {
    if (!x) return false;

    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);

    x[currentFocus].classList.add("autocomplete-active");
  }
  
  function removeActive(x) {
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }

  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
  });
}
/* ----------------------------------------------------- */