function js_sync() {
  if (Module.js_fs_synching)
    return;
  Module.js_fs_synching = true;
  FS.syncfs(function (err) {
    console.log("syncFS result:");
    console.log(err);
    Module.js_fs_synching = false;
  });
}
function js_pick_file(fn) {
    var input = document.createElement('input');
    input.type = 'file';
    
    input.onchange = function(e) { 
      // getting a hold of the file reference
      var file = e.target.files[0]; 
  
      // setting up the reader
      var reader = new FileReader();
      reader.readAsArrayBuffer(file);
      //reader.readAsText(file,'UTF-8');
      // here we tell the reader what to do when it's done reading...
      reader.onload = function(readerEvent) {
        console.log("reader.onload " + file.name);
        var content = new Uint8Array(readerEvent.target.result); // this is the content!
        console.log( content );
        FS.writeFile("/" + file.name, content);
        Module.TaskCallback_open_call(fn, "/" + file.name);
        Module.TaskCallback_open_delete(fn);
      }
    }
    
    input.click();
}
function js_pick_file_save(path, name, fn) {
  jspath = Module.UtilityGetString(path);
  jsname = Module.UtilityGetString(name);
  console.log("js_pick_file_save");
  console.log(jspath);
  file = FS.readFile(jspath);
  blob = new Blob([file]);
  console.log(file);

  // IE hack;
  // see: http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
  if (window.navigator.msSaveOrOpenBlob)
  {
    window.navigator.msSaveBlob(blob, jsname);
  }
  else
  {
    var a = window.document.createElement("a");
    a.href = window.URL.createObjectURL(blob, {type: "application/octet-stream"});
    a.download = jsname;
    document.body.appendChild(a);
    // IE: "Access is denied"; 
    // see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
    a.click();
    document.body.removeChild(a);
  }

  Module.TaskCallback_save_call(fn, true);
  Module.TaskCallback_save_delete(fn);
}

mergeInto(LibraryManager.library, {
  js_sync: js_sync,
  js_pick_file: js_pick_file,
  js_pick_file_save: js_pick_file_save,
});
