// Copyright 2005 and onwards Google Inc.
// Author: Ruxandra G. Paun
//
// The JavaScript install file for toolbar, sendtophone and suggest
// applications. Takes care of the install install process at
// toolbar.google.com/firefox/install.html.


var iframe; // iframe for addons.mozilla.org
var thisXpiUrl; // the install .xpi URL
var thisIconUrl; // the install icon URL
var thisXpiName; // the name of the install .xpi 
var timer; // timeout handler for whitelisting when addons is down
var pathToFile; // path from current location to the 
          // googleclient/bar/server/static/firefox/ directory

/**
 * Redirect to tools.google.com for all installs
 */
var url = String(window.location);
var match = url.match(/(.*)www\.google\.com(.*\/install.html)/);
if (match) {
  window.location = match[1]+"tools.google.com"+match[2];
}

/**
 * Called when installation is triggered.
 * If installation successful - opens the "done.html" page,
 * otherwise opens the "error.html" page.
 */
function xpiinstallCallback(url, status) {
  if (status == 0) {	
    // installation succeeded 
    window.location.href='done.html';
  } else {
    // installation failed
    window.location.href='error.html';
  }
}

/**
 * Called when users don't have the latest vesion of Firefox.
 * Uses InstallTrigger to start the install. 
 */
function whitelist() {
  var params = {
    URL: thisXpiUrl,
    IconURL: thisIconUrl,
    toString: function() { return this.URL; }
  };
  var xpis = {};
  xpis[thisXpiName] = params;
  InstallTrigger.install(xpis, xpiinstallCallback);
}	

/**
 * Called when we need to cancel the timeout. Calls clearTimeout.
 */
function clearTimer(event) {
  clearTimeout(timer);
}

/**
 * Checks the user's OS against a list of supported OSes.
 * @param OSList -- array of supported OSes.
 * @returns -- array [boolean (true if supported), OS ('win', 'mac', etc)]
 */
function checkOS(OSList) {
  var returns = [false, navigator.platform];
  if (navigator.platform.toLowerCase().indexOf('win32') == 0) {
    if ((navigator.userAgent.toLowerCase().indexOf('win9') != -1) ||
        (navigator.userAgent.toLowerCase().indexOf('win 9') != -1) ||
        (navigator.userAgent.toLowerCase().indexOf('winnt') != -1)) {
      // Win9X is not supported.
      returns[1] = "Win9X";
    } else {
      returns[1] = "win";
    }
  }
  else if (navigator.platform.toLowerCase().indexOf('mac') == 0) {
    returns[1] = "mac";
  }
  else if (navigator.platform.toLowerCase().indexOf('linux') == 0) {
    returns[1] = "linux";
  }

  for (var i = 0; i < OSList.length; i++) {
    if (OSList[i] == returns[1]) {
      returns[0] = true;
      break;
    }
  }
  return returns;
}

/**
 * Called when addons.mozilla.org is down. Loads an alternate install
 * page into the iframe. Does not have the nice install name and icon
 * for the install prompt.
 */
function addonsDown() {
  // remove the event listener for clearing the timeout.
  iframe.removeEventListener('load', clearTimer, false);
  // Load the alternate install page.
  // Doesn't have the nice name and icon for the install prompt. We pass 
  // the xpi url to the page to trigger the install of the right application.
  iframe.src = thisXpiUrl;
}
	
/**
 * Called when the "Agree and Install" button is clicked. Checks
 * what browser is used. 
 *   - If Firefox 1.0.4+, try installing through
 * addons.mozilla.org. Call addonsDown() if addons is down. 
 *   - If Firefox 1.0 - 1.0.3, whitelist. 
 *   - If other versions of Firefox, ask the user if they want to 
 * download the newest version of Firefox and redirect them to the 
 * Firefox download page if they do or whitelist if not. 
 *   - If any other browser than Firefox, output an error message.
 *   - If an OS list is specified, and the user's OS is not in the list,
 * output an error message
 * 
 * Params:
 *   - @param iframeSrc - src of the iframe on addons.mozilla.org
 *   - @param xpiUrl - the URL of the install xpi
 *   - @param iconUrl - the URL of the install icon
 *   - @param xpiName - the name of the install xpi
 *   - @param wrongBrowserMsg - the error message for a browser other
 * than Firefox.
 *   - @param relativePath - the path to the 
 * googleclient/bar/server/static/firefox/ directory
 *   - @param OSList - an array containing the OSes this extension can be
 * installed on.  'win' = windows 2k+, 'mac' = MacPPC or MacIntel, 'linux' =
 * linux.  If this array is null, all OSes will be allowed.
 */
function check(iframeSrc,
               xpiUrl,
               iconUrl,
               xpiName,
               wrongBrowserMsg,
               relativePath,
               OSList) {
  // check the os
  if (OSList != null) {
    results = checkOS(OSList);
    if (results[0] == false) {
      // not supported
      alert("Your operating system(" + results[1] + ") is not supported.");
      return false;
    } else {
      iframeSrc = iframeSrc.replace("%OS%", results[1]);
      xpiUrl = xpiUrl.replace("%OS%", results[1]);
    }
  }

  // set the global variables for the install xpi URL, icon URl and xpi name
  thisXpiUrl = xpiUrl;
  thisIconUrl = iconUrl;
  thisXpiName = xpiName;
  pathToFile = relativePath;

  if (checkBrowser(xpiUrl,'iframe')) {   // Check browsers for iframe install
    iframe = document.createElement('IFRAME');
    iframe.style.visibility = "hidden";
    iframe.width = iframe.height = 0;
    document.body.appendChild(iframe);
    timer = setTimeout('addonsDown()', 3000);
    iframe.addEventListener('load', clearTimer, false);
    iframe.src = iframeSrc;
  } else if (checkBrowser(xpiUrl,'whitelist')) {	// Check browsers for whitelist install
		whitelist();
  } else if (navigator.userAgent.match(/Firefox/)) {
    if (confirm("You are using an unsupported version of Firefox.  " + 
		"Would you like to get the latest version?")) {
      // User wants to download newest Firefox
      window.location.href = "http://www.mozilla.org/products/firefox/";
    } else {
      // User wants to try and download the xpi with this version of firefox.
      whitelist();
    }
  } else {
    // This browser isn't Firefox.
    if (confirm(wrongBrowserMsg)) 
      window.location.href = "http://www.mozilla.org/products/firefox/";
  }
  return false; // don't post the form
}

/**
 * Called when a new window for showing either a screenshot or opening
 * the agreement terms in a printer-friendly version is needed. Opens
 * a new, resizable, scrollable window with @param newHtml as the window
 * html, @param windowName as the window name, @param windowWidth as the
 * window width, and @param windowHeight as the window height.
 */
function newwin(newHtml, windowName, windowWidth, windowHeight) {
  oWindow = window.open(newHtml, windowName, 'width=' + windowWidth + 
			', height=' + windowHeight + ', resizable=yes, ' +
			'scrollbars=yes, toolbar=no, directories=no, ' +
			'status=no, menubar=no'); 
  oWindow.focus();
}

/**
 * Called by check to determine allowable Firefox versions per extension.
 * Params:
 *   - @param xpiUrl - Url of xpi
 *   - @param installType - Type of installation to check, 'iframe' or 'whitelist'
 */
function checkBrowser(xpiUrl,installType) {
  var valid = false;
  switch(installType) {
  //If iframe install is requested for newer versions of Firefox
  case 'iframe':
    // Allow Firefox/BonEcho 1.5+		
    if (xpiUrl.match("google-toolbar") ||
        xpiUrl.match("google-sendtophone") ||
        xpiUrl.match("google-webcomments") ||
	xpiUrl.match("google-browsersync") ||
        xpiUrl.match("GoogleGadgetPluginFirefox")) {
      var match = navigator.userAgent.match(/(Firefox|BonEcho)\/([\d\.]+)/);
      valid = match && parseFloat(match[2]) >= 1.5;
    }
    else {  //Default check for all other extensions 1.0.4, 1.1-5
      if (navigator.userAgent.match(/Firefox\/1\.0\.[4-9]/) ||
          navigator.userAgent.match(/Firefox\/1\.[1-5]/)) { 
        valid = true;
      }
    }
    return valid;
    break;
  //If whitelist install is requested for older versions of Firefox
  case 'whitelist':
    if (xpiUrl.match("google-toolbar")) {  //No whitelist option for Toolbar
      valid = false;
    }
    else {  //Default check for all other extensions
      if (navigator.userAgent.match(/Firefox\/1\.0/)) {
        valid = true;
      }
    }
    return valid;
    break;
  }
}
