//moz_extensions.js
//OxCal extensions for Mozilla using XPCOM nsIFile IO Library

// This script sets OSName variable as follows:
// "Windows"    for all versions of Windows
// "MacOS"      for all versions of Macintosh OS
// "Linux"      for all versions of Linux
// "UNIX"       for all other UNIX flavors 
// "Unknown OS" indicates failure to detect the OS

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

function xpcomTest()
{
 if (Components) // XPConnect 'Components' object check.
 try 
 { 
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 }
 catch(e) 
 {
  alert(e+"\n\nIt seems that permissions are set not to allow access to \nthe file system.  You cannot run this program");
  return false;
 };
 return false;
};
xpcomTest();
function xpcomCreateDirectory(filePath)
{
 var permission=0644;
 if (Components) // XPConnect 'Components' object check.
 try 
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

 // Get file component.
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (!file.exists()) 
  {
   if(!confirm('Creating new directory ' + filePath)){return false;};
   file.create(file.DIRECTORY_TYPE, permission);
  };
  return true;
 }
 catch(e) 
 {
  alert(e+"\n\nDirectory: "+filePath);
  return false;
 };
 return false;
};
function xpcomFileDelete(filePath)
{
 if (Components) // XPConnect 'Components' object check.
 try 
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  // Get file component.
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (file.exists()) 
  {
   if(file.isDirectory())
   {
    var a = xpcomReadDirectory(filePath);
    if(!a){return false;};
    if((a.dirs.length==0)&&(a.files.length==0))
    {
     file.remove(true);
     return true;
    }
    else
    {
     alert("Folder not empty");
     return false;
    };
   }
   else
   {
    file.remove(false);
   };
   return true;
  };
 }
 catch(e) 
 {
  alert(e+"\n\nFile: "+filePath);
  return false;
 };
 return false;
};
function xpcomMoveTo(filePath,newPathName,newName)
{
 if (Components) // XPConnect 'Components' object check.
 try 
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  // Get file component.
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (file.exists()) 
  {
   var newpath = 
   Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
   newpath.initWithPath(newPathName);
   if(newpath.exists() && newpath.isDirectory())
   {
    file.moveTo(newpath,newName);
    return true;
   }
   else
   {
    alert("New path does not exist");
   };
  };
 }
 catch(e) 
 {
  alert(e+"\n\nFile: "+filePath);
  return false;
 };
 return false;
};
function xpcomFileWrite(filePath, content) 
{
 var permission=0644;
 if (Components) // XPConnect 'Components' object check.
 try 
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  // Get file component.
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (!file.exists()) 
  {
   file.create(0x00, permission);
  }
  // Write with nsIFileOutputStream.
  var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
  outputStream.init(file, 0x20 | 0x02, permission, null);
  outputStream.write(content, content.length);
  outputStream.flush();
  outputStream.close();
  return true;
 }
 catch(e) 
 {
  alert(e+"\n\nFile: "+filePath);
  return false;
 };
 return false;
}
function xpcomFileRead(filePath) 
{
 if (Components)
 try 
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (!file.exists()) 
  {
   alert('File does not exist');
   return false;
  };
  var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
  inputStream.init(file, 0x01, 00004, null);
  var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
  sInputStream.init(inputStream);
  return sInputStream.read(sInputStream.available());
 }
 catch(e) 
 {
  alert(e+"\n\nFile: "+filePath);
  return false;
 };
 return false;
}
function xpcomLaunchFile(filePath) 
{
 if (Components)
 try 
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (!file.exists()) 
  {
   alert('File does not exist');
   return false;
  };
  file.launch();
  return true;
 }
 catch(e) 
 {
  alert(e+"\n\nFile: "+filePath);
  return false;
 };
 return false;
};
function xpcomRunFile(filePath,args,lock) 
{
 if (Components)
 try 
 {
  if(!args){args=new Array();};
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (!file.exists()) 
  {
   alert('File does not exist');
   return false;
  };
  // create an nsIProcess
  var process = Components.classes["@mozilla.org/process/util;1"]
                        .createInstance(Components.interfaces.nsIProcess);
  process.init(file);

  process.run(lock, args, args.length);  
  return true;
 }
 catch(e) 
 {
  alert(e+"\n\nFile: "+filePath);
  return false;
 };
 return false;
};
function xpcomDirectory(dir)
{
 if (Components)
 try 
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  var dirService = Components.classes["@mozilla.org/file/directory_service;1"].createInstance(Components.interfaces.nsIDirectoryServiceProvider);
  return dirService.getFile(dir,{}).path;
 }
 catch(e) 
 {
  alert(e);
  return false;
 };
 return false;
};
function xpcomReadDirectory(filePath)
{
 var l,i,j,f;
 var a=false;
 if(Components)
 try
 {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath);
  if (!file.exists()) 
  {
   alert('Path "'+filePath+'" not found');
   return false;
  };
  var dirIterator = file.directoryEntries;
  a=new Object;
  a.files=new Array();i=0;
  a.dirs=new Array();j=0;
  while(dirIterator.hasMoreElements())
  {
   f=dirIterator.getNext();
   if(f)
   {
    f.QueryInterface(Components.interfaces.nsIFile);
    if(!f.exists())
    {
     continue;
    };
    if(f.isSymlink())
    {
     continue;
    };
    if(f.isDirectory())
    {
     a.dirs[j]=f.leafName;
     j++;
    }
    else
    {
     if(f.isFile())
     {
      if(f.leafName==".DS_Store")
      {
       continue;
      };
      a.files[i]=f.leafName;
      i++;
     };
    };
   };
  };
  return a;
 }
 catch(e)
 {
  alert(e+"\n\nFile: "+filePath);
  return a;
 };
 return false;
};
function findbin()
{
 var reg = /\//g;
 var bin;
 bin=unescape(document.location.href.split("?")[0]);
 bin=bin.replace("localhost\/","\/");
 bin=bin.replace("Plot.",".");
 bin=bin.replace("Input.",".");
 if(OSName=="Windows")
 {
  bin=bin.replace('file:\/\/\/','').replace(reg,'\\');
  bin=bin.replace('\\oxcal\\OxCal','\\bin\\OxCal');
  bin=bin.replace('.html','Win.exe');
  if(bin.indexOf("OxCalWin.exe")!=-1)
  {
   return bin;
  };
 }
 else
 {
  if(OSName=="MacOS")
  {
   bin=bin.replace('file:\/\/\/','/');
   bin=bin.replace('\/oxcal\/OxCal','\/bin\/OxCal');
   bin=bin.replace('.html','Mac');
   if(bin.indexOf("OxCalMac")!=-1)
   {
    return bin;
   };
  }
  else
  {
   bin=bin.replace('file:\/\/\/','/');
   bin=bin.replace('\/oxcal\/OxCal','\/bin\/OxCal');
   bin=bin.replace('.html','Linux');
   if(bin.indexOf("OxCalLinux")!=-1)
   {
    return bin;
   };
  };
 };
 return "";
};
function setWorkingPath(path)
{
 if(OSName!="Windows")
 {
  if(path.charAt(path.length-1)!="/")
  {
   path+="/";
  };
 }
 else
 {
  if(path.charAt(path.length-1)!="\\")
  {
   path+="\\";
  };
 };
 setCookie("OxCalWorkingPath",path);
 setCookie("OxCalHomePath",path);
 return path;
};
function getHomePath()
{
 var path;
 path=getCookie("OxCalHomePath");
 if(path=="undefined")
 {
  path=xpcomDirectory("Home");
  path=setWorkingPath(path);
  if(xpcomCreateDirectory(path+"OxCal"))
  {
   path=setLocalFileSub(path,"OxCal");
  };
  return setWorkingPath(path);
 };
 return path;
};
function setLocalFileSub(path,dirname)
{
 var els;
 if(dirname=="..")
 {
  if(OSName!="Windows")
  {
   els=path.split("/");
   if(els.length>2)
   {
    els.pop();els.pop();
    path=els.join("/")+"/";
   };
  }
  else
  {
   els=path.split("\\");
   if(els.length>2)
   {
    els.pop();els.pop();
    path=els.join("\\")+"\\";
   };
  };
 }
 else
 {
  if(dirname.indexOf(":")!=-1)
  {
   if(OSName!="Windows")
   {
    path=dirname+"/";
   }
   else
   {
    path=dirname+"\\";
   };
  }
  else
  {
   if(OSName!="Windows")
   {
    path+=dirname+"/";
   }
   else
   {
    path+=dirname+"\\";
   };
  };
 };
 if(path){setCookie("OxCalWorkingPath",path);};
 return path;
};
function setWorkingPathGeneric(name)
{
 if(name=="Home")
 {
  path=getHomePath();
 }
 else
 {
  path=xpcomDirectory(name);
 };
 return setWorkingPath(path);
};
function fullPath(filename)
{
 var path;
 path=getHomePath();
 return path+filename;
};
function localFileRead(filename)
{
 return xpcomFileRead(filename);
};
function localFileWrite(filename,content)
{
 xpcomFileWrite(filename,content);
};
function localFileLaunch(filename)
{
 xpcomLaunchFile(filename);
};
function localOxCalLaunch(filename,lock)
{
 var bin,args;
 bin=findbin();
 args=new Array(filename);
 xpcomRunFile(bin,args,lock);
};
function localOpenOxCal(path)
{
 command=xpcomFileRead(path);
 return true;
};
