//Prefs
var showresults = 0; // 0 = not at all, 1 = html page, 2 = javascript dialog

// browser check
var vendorName = "Beonex";       // Vendor in UA-string for |samevendorrelease|
var vendorRelease = "0.8"; // first 3 chars of Vendor-Release; dito
var minVer = 20020301;  // ealiest build date (Gecko version) for |sameversion|
var maxVer = 20030301;  // last... dito
var installName = "Beonex Communicator " + vendorRelease;
                     // Primary target release
var installPage = "http://www.beonex.com/communicator/version/0.8/install";
                     // Where the user can get the primary target release
var otherCompatible = " or Mozilla 1.0";
                     // Other compatible Mozillas. Form like ", a, b or c".

// todo
// - restart
// - localizable

////////////////////////////////////////////////////////
// Helper stuff
////////////////////////////////////////////////////////

//Other global vars

var newline;
if (showresults == 1)
  newline = "<br>";
else
  newline = "\n";

var numstatus = 0;
var numxpi = 0;
var gxpi;


function statusCallback(url, status) {
    for (i in gxpi) {
        if ( url.indexOf(gxpi[i]) != -1 ) {
            gxpi[i] = status;
            numstatus++;
            break;
        }
    }

    // if we've gotten all results then display them
    if (numstatus == numxpi)
    {
        var restart = false;

        var textResults = "";
        var textInstructions = "";

        for (i in gxpi)
        {
            textResults += i + ": ";
            switch (status) {
              case 999:
                 restart = true;     // fall-through
              case 0:
                 textResults += "Successful";
                 restart = true; //XXX
                 break;
              case -210:
                 textResults += "Cancelled";
                 break;
              default:
                 textResults += "Error encountered -- "+status;
                 break;
            }
            textResults += newline;
        }
        if (restart)
        {
            textInstructions += "Please restart Communicator.";
            if (isWindows())
              textInstructions += " If you are using Win9x (incl. Windows ME), restart your computer.";
        }

        if (showresults == 0) // don't show
        {
        }
        else if (showresults == 1) // html page
        {
          dlg = window.open("","resultWindow");
          //open(,, "width=400,height=300,scrollbars=yes,resizable=yes"); XXX
          dlg.document.write("<he" + "ad>" +
                             "<tit" + "le>" + "XPInstall Results" +
                             "</tit" + "le>" + "</he" + "ad>");
          dlg.document.write("<bo" + "dy>" + "<h1>Installation Results</h1>");
          dlg.document.write(textResults);
          if (textInstructions != "")
          {
              dlg.document.write("<h1>Instructions</h1>");
              dlg.document.write(textInstructions);
          }
          dlg.document.write("<p><center><f" + "orm name=\"okclose\">" +
                             "<i" + "nput type=button " +
                             "on" + "Click=\"window.close();\" " +
                             "on" + "Command=\"window.close();\" " +
                             "value=\"OK\">" +
                             "</center></f" + "orm>");
          dlg.document.write("</bo" + "dy>");
          dlg.document.close();
        }
        else if (showresults == 2) // dialog
        {
          alert(textResults + newline + textInstructions);
        }
    }
}


function isWindows()
{
  return (navigator.platform.indexOf("Win") == 0);
}
function isLinux()
{
  return (navigator.platform.indexOf("Linux") == 0);
}
function isMac()
{
  return (navigator.platform.indexOf("Mac") != -1);
}
function isBeOS()
{
  //XXX vrfy
  return (navigator.platform.indexOf("BeOS") != -1);
}
function badPlatform()
{
  alert("Platform not recognized");
}


function gotoInstallPage()
{
  document.location.href = installPage;
}


// Will return false silently for non-Mozillas
function installEnabled()
{
  if (typeof InstallTrigger != "object") // non-Mozilla?
    return false;

  if (InstallTrigger.updateEnabled())
    return true;
  else
  {
    alert("Software Installation is disabled in your browser.\n Please enable it first.\n To do that, check Edit|Preferences...|Advanced|Software Installation|Enable software installation.");
    return false;
  }
}

// exclusive: anymozilla, sameversion or samevendorrelease
// security: any of security_*
var anymozilla = 0; // any Mozilla
var sameversion = 1; // this Mozilla release only,
                       // e.g. Mozilla 0.6/Netscape 6.0/Beonex Comm. 0.6
var samevendorrelease = 2; // this vendor release only, e.g. Beonex Comm. 0.6
var security_none = 0; // don't care
var security_xpi = 1; // want to install XPI
var security_theme = 2; // want to install theme/skin
var security_locale = 3; // want to install locale
function browserOK(exclusive, security)
{
  // make sure that older browser don't fail below
  if (typeof InstallTrigger != "object")
  {
    if(window.confirm("This package is intended only for Beonex Communicator, Netscape 6 or Mozilla.\nWould you like to download " + installName + "?"))
      gotoInstallPage();
    return false;
  }

  var securityOK = true;
  if (security == security_xpi)
  {
    if (!installEnabled())
    {
      alert("You must enable installation in Edit|Preferences|Software Installation");
      return false;
    }
  }

  if (exclusive == anymozilla)
  {
    // already checked above
    return securityOK;
  }
  else if (exclusive == sameversion)
  {
    var start = navigator.userAgent.indexOf("Gecko/") + 6;
    var build = parseInt(navigator.userAgent.substring(start, start + 8));
    if (typeof InstallTrigger == "object"
        && build >= minVer && build <= maxVer)
      return securityOK;
    else
    {
      if(window.confirm("This package is intended only for " + installName + otherCompatible + ".\nWould you like to download " + installName + "?"))
        gotoInstallPage();
      return false;
    }
  }
  else if (exclusive == samevendorrelease)
  {
    if (typeof InstallTrigger == "object" && navigator.vendor && navigator.vendor == vendorName && navigator.vendorSub && navigator.vendorSub.substr(0,3) == vendorRelease.substr(0,3))
      return securityOK;
    else
    {
      if(window.confirm("This package is intended for " + installName + " only.\nWould you like to download " + installName + "?"))
        gotoInstallPage();
      return false;
    }
  }
  else
  {
    alert("Fatal error: Bug on Website. Wrong version identifer.");
    return false;
  }
}


////////////////////////////////////////////////////////////
// main functions
// (You can use the is<Platform>() functions above, too)
////////////////////////////////////////////////////////////

// xpi = Array for InstallTrigger
// exclusive = see above
function startInstall(xpi, exclusive)
{
  if (!browserOK(exclusive, security_xpi))
    return;

  gxpi = xpi;
  for (i in xpi) {
    numxpi++;
  }

  InstallTrigger.install(xpi,statusCallback);
}

// name = name of the theme to install. Is also used to "select" the theme, so
//        it must match exactly the name in the internal manifest.rdf file.
// url = url of the theme to install
// exclusive = see above
function installTheme(name, url, exclusive)
{
  if (!browserOK(exclusive, security_theme))
    return;

  installChrome(InstallTrigger.SKIN, url, name);
}

// args = see installTheme
function installLocale(name, url, exclusive)
{
  if (!browserOK(exclusive, security_locale))
    return;

  installChrome(InstallTrigger.LOCALE, url, name);
}


// genLaunch - Generic Launcher: picks up package URLs and names from document
// and installs thse packages.

// idClass = HTML-Class of package to be installed. This can be chosen freely
//   by you. All packages from HTML elements which have this class will be
//   installed.
//   Use empty string to install all packages.
// exclusive = see above
//
// HTML elements:
// element
//   Currently, only A elements (hyperlinks) are supported. This can easily
//   be changed, if needed.
// id class
//   The class of the HTML element must match |idClass|.
// type class
//   There's also a class for the type. It is mandatory.
//   Possible values:
//     dlWin = XPI for Win32
//     dlMac = XPI for Mac OS
//     dlLinux = XPI for Linux
//     dlBeOS = XPI for BeOS
//     dlAll = XPI for all platforms
//     dlTheme = Theme/Skin (jar)
//     dlLocale = Localization (jar)
//   Only matching packages will be installed, e.g. a Windows machine will not
//   install Linux XPIs.
// |name| attribute
//   XPIs: The name of the package, to be displayed to the user.
//   Themes/Locales: see installTheme/Locale
// |href| attribute
//   url of package to install
//
// Example:
// <a class="dlLinux,java" name="Java RE" href="http://foo/bar-ix.xpi">bla</a>
// <a class="dlLinux,psm" name="PSM" href="http://foo/baz-ix.xpi">bla bla</a>
// <a class="dlWin32,java" name="Java RE" href="http://foo/bar-win.xpi">bla</a>
// <a class="dlWin32,psm" name="PSM" href="http://foo/baz-win.xpi">bla bla</a>
// <div onclick="genLaunch('java',1)>button 1</div>
// <div onclick="genLaunch('',1)>button 2</div>
// If you click on button 1, the Java package for your platform
// will be installed.
// If you click on button 2, both the Java and PSM package for your platform
// will be installed.

function genLaunch(idClass, exclusive)
{
  // Check

  // Make sure, older browsers don't fail below
  //  "Security" check will happen in the specialized install functions.
  if (!browserOK(exclusive, security_none))
    return;


  // Init

  //  For XPI
  var platformClass;
  if (isWindows())
    platformClass = "dlWin32";
  else if (isLinux())
    platformClass = "dlLinux";
  else if (isMac())
    platformClass = "dlMac";
  else if (isBeOS())
    platformClass = "dlBeOS";
  else
  {
    badPlatform();
    return;
  }
  // "dlAll" is OK, too.

  var xpi = new Array();
  var xpi_found = false;
  var theme_name = "";
  var theme_url = "";
  var theme_found = false;
  var locale_name = "";
  var locale_url = "";
  var locale_found = false;


  // Search

  var elems = document.getElementsByTagName("A");
  for (var i = 0; i < elems.length; i++)
  {
    var elem = elems.item(i);
    var attrs = elem.attributes;
    if (attrs)
    {
      var classes = attrs.getNamedItem("class");
      if (classes && classes.nodeValue.indexOf(idClass) != -1)
      {
        var uri; var name;
        var attr_href = attrs.getNamedItem("href");
        var attr_name = attrs.getNamedItem("name");
        if (attr_href && attr_name)
             // some little tricks to avoid try/catch, which breaks 4.x
             // at compilation time, I think
        {
          uri = attr_href.nodeValue;
          name = attr_name.nodeValue;
        }
        if (uri && name)
        {

          if (
              classes.value.indexOf(platformClass) != -1 ||
              classes.value.indexOf("dlAll") != -1
             )
          {
            xpi[name] = uri;
            xpi_found = true;
          }
          if (classes.value.indexOf("dlTheme") != -1)
          {
            theme_name = name;
            theme_url = uri;
            theme_found = true;
          }
          if (classes.value.indexOf("dlLocale") != -1)
          {
            locale_name = name;
            locale_url = uri;
            locale_found = true;
          }
        }
      }
    }
  }


  // Install

  if (xpi_found)
    startInstall(xpi, exclusive);
  if (theme_found)
    installTheme(theme_name, theme_url, exclusive);
  if (locale_found)
    installLocale(locale_name, locale_url, exclusive);
  if (!xpi_found && !theme_found && !locale_found)
    alert("No appropriate packages available");
}

