function showstatus() {
  var form = document.forms["upload"];
  var file = "";
  // console.log("showstatus()");
  if (file == "") try { file = form.elements["file"].value }      catch(e) {}
  if (file == "") try { file = form.elements["directory"].value } catch(e) {}
  if (file == "") return false;
  window.open(
    '/fup?showstatus=$RANDOM$',
    'fup_status',
    'width=700,height=500'
  );
  return true;
}

function showfileupload(types) {
  document.getElementById("uploadselect").innerHTML = 
    '<input type="file" accept="'+types+'" id="select" name="file" onchange="showfile()">\n'+
    '<b id="filename"></b> <a id="filesize"></a>\n';
  document.getElementById('select').click();
}

function showfile() {
  var form = document.forms["upload"];
  var size = form.file.files[0].size;
  form.elements["filesize"].value = size;
  // alert(size + " bytes");
  size = size.toString();
  size = size.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1,");
  document.getElementById("filesize").innerHTML = size + " bytes";
  document.getElementById("submit").innerHTML = 
    '<input type="submit" value="upload" id="upload">';
  // showstatus();
  // document.getElementById('upload').click();
}

function showdirectoryupload() {
  // alert("showdirectoryupload()");
  if (navigator.userAgent.indexOf("Chrome/") < 0) {
    alert("directory upload is only possible with Google Chrome");
    return false;
  }
  document.getElementById("uploadselect").innerHTML = 
    '<input type="file" id="select" name="directory" onchange="showdirectory(event)" webkitdirectory>\n'+
    '<b id="dirname"></b> <a id="dirsize"></a>\n';
  document.getElementById('select').click();
}

function showdirectory(e) {
  var files = e.target.files;
  var path = files[0].webkitRelativePath;
  var dir = path.split("/");
  var size = 0;
  document.getElementById("dirname").innerHTML = dir[0]+"/";
  for (let i=0; i<files.length; i++) { size += files[i].size }
  document.forms["upload"].elements["filesize"].value = size;
  document.getElementById("dirsize").innerHTML = Math.floor(size/1048576)+" MB";
  document.getElementById("submit").innerHTML = 
    '<input type="submit" value="upload" id="upload">';
  document.getElementById('upload').click();
  showstatus();
}
