// Copyright 2008 Google Inc.  All Rights Reserved.

function clk(err, detail, cv) {
  if (document.images) {
    var u = '/maps/gen_204?source=ge_err_pg'
        + '&err=' + encodeURIComponent(err ? err : '')
        + '&cv=' + encodeURIComponent(cv ? cv : '')
        + '&detail=' + encodeURIComponent(detail ? detail : '');
    (new Image()).src = u;
  }
}

function setInstallLinks() {
  var url = "";
  if (window.google.earth.isOneClickAvailable()) {
    if (3 == window.google.earth.getBrowserId()) {
      // Work around Firefox 3 issue by delaying install after setup.
      url = 'javascript:setTimeout(window.google.earth.installViaOneClick,1000);void(0);';
    } else {
      url = 'javascript:window.google.earth.installViaOneClick();void(0);';
    }
  } else {
    url = 'javascript:window.google.earth.installViaStub();void(0);';
  }
  var alist = document.getElementsByName('install');
  for (var i = 0; i < alist.length; i++) {
    alist[i].href = url;
  }
}

function init() {
  window.google.earth.doOneClickSetup();
  setInstallLinks();

  // Decode URL params.
  var params = {};
  var paramstring = document.location.hash.replace(/(^#)/,'');
  var pairs = paramstring.split('&');
  for (var i = 0; i < pairs.length; i++) {
    var p = pairs[i].split('=');
    params[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
  }

  var textElem = document.getElementById('text_default');

  // If 'error' is defined, try to show the corresponding info section.
  var error = params['error'];
  if (error) {
    // We alias some groups of errors to the same message.
    var alias = error;
    var aliases = {
      'ERR_INVALID_DIV': 'ERR_CREATE_PLUGIN',
      'ERR_NO_AVAILABLE_ID': 'ERR_CREATE_PLUGIN',
      'ERR_EARTH_CONNECT_TIMEOUT': 'ERR_BRIDGE',
      'ERR_CREATE_CONNECT_MUTEX': 'ERR_CREATE_EARTH'
    };
    if (aliases[error]) {
      alias = aliases[error];
    }
    var elem = document.getElementById('text_' + alias);
    if (elem) {
      textElem = elem;
    }
  }

  // Show default error info.
  textElem.style.display = '';

  // Enable installer div if necessary
  if (textElem.className.indexOf('show_installer') >= 0) {
    document.getElementById('installer').style.display = '';
  }

  // Log.
  var detail = params['detail'];
  detail = detail ? detail : '';
  var cv = '';
  var pieces = detail.split(',');
  detail = pieces[0];
  if (pieces[1]) {
    var vpieces = pieces[1].split(':');
    if (vpieces[0] == 'pluginversion') {
      cv = vpieces[1];
    }
  }
  clk(error, detail, cv);

  function doCheckInstalledLoop() {
    navigator.plugins.refresh(false);
    if (google.earth.isInstalled()) {
      document.location.hash = 'error=SUCCESS_RECENT_INSTALL';
      window.location.reload(false);
    } else {
      setTimeout(doCheckInstalledLoop, 2000);
    }
  }

  try {
    if (google.earth.isSupported() && !google.earth.isInstalled()) {
      doCheckInstalledLoop();
    }
  } catch (err) {
  }
}
