var browser = -1;
var browserVersion = -1;
var platformInfo = -1;
var isBrowserOnWince = -1;
var unknownPlatform = false;
var versions = {
  win: {
    // Unique platform id.
    id: 'win',
    // The download URL for the installer. The browser is navigated to this URL
    // to begin the download.
    // May be ignored when tagging.
    url: null,
    // Only used on platforms where the installer is a Firefox XPI. This is a URL
    // on mozilla.org that has been configured to redirect to our XPI URL. For
    // details, see: http://code.google.com/p/google-gears/issues/detail?id=339.
    iframeUrl: null,
    // Once the installation is finished, should the browser stay on
    // gears.google.com or should it be redirected elsewhere?
    auto_redirect: true
  },
  linux: {
    id: 'linux',
    url: 'http://dl.google.com/gears/current/gears-linux-opt.xpi',
    iframeUrl: 'http://addons.mozilla.org/google/google_gears_linux.html',
    auto_redirect: false
  },
  mac_firefox: {
    id: 'mac-firefox',
    url: 'http://dl.google.com/gears/current/gears-osx-opt.xpi',
    iframeUrl: 'http://addons.mozilla.org/google/google_gears_osx.html',
    auto_redirect: false
  },
  mac_safari: {
    id: 'mac-safari',
    url: 'http://dl.google.com/gears/current/gears-osx-opt.dmg',
    iframeUrl: null,
    auto_redirect: false
  },
  wince_ie: {
    id: 'wince-ie',
    url: 'http://dl.google.com/gears/current/gears-wince-opt.cab',
    iframeUrl: null,
    auto_redirect: false
  },
  wince_opera: {
    id: 'wince-opera',
    url: 'http://dl.google.com/gears/current/gears-wince-opt-opera.cab',
    iframeUrl: null,
    auto_redirect: false
  },
  android: {
    id: 'android',
    url: null,
    iframeUrl: null,
    auto_redirect: false
  }
};

var installing = false;

function isDefined(type) {
  return (type != 'undefined' && type != 'unknown');
}

function getElementById(element_name) {
  if (isDefined(typeof document.getElementById)) {
    return document.getElementById(element_name);
  } else if(typeof isDefined(document.all)) {
    return document.all[element_name];
  } else {
    alert("Not found: "+ element_name);
    return null;
  }
}

function detectPlatform() {
  // first try to use a param if it is present
  if (window.location.href.indexOf('platform=wince-opera') != -1) {
    platformInfo = versions.wince_opera;
  // This should be wince-ie, but left as-is for backwards compatibility. This
  // must come after the rule for wince-opera.
  } else if (window.location.href.indexOf('platform=wince') != -1) {
    platformInfo = versions.wince_ie;
  } else if (window.location.href.indexOf('platform=mac-firefox') != -1) {
    platformInfo = versions.mac_firefox;
  } else if (window.location.href.indexOf('platform=mac-safari') != -1) {
    platformInfo = versions.mac_safari;
  } else if (window.location.href.indexOf('platform=linux') != -1) {
    platformInfo = versions.linux;
  } else if (window.location.href.indexOf('platform=win') != -1) {
    platformInfo = versions.win;
  } else if (navigator.platform == 'Win32') {
    platformInfo = versions.win;
  } else if (navigator.platform.indexOf('WinCE') > -1 ||
             navigator.platform.indexOf('Pocket PC') > -1 ||
             navigator.platform.indexOf('Windows CE') > -1 ||
             navigator.platform.indexOf('Windows Mobile') > -1) {
    if (navigator.userAgent.indexOf('PPC; Opera Mobi') != -1) {
      platformInfo = versions.wince_opera;
    } else {
      platformInfo = versions.wince_ie;
    }
  } else if (navigator.platform == 'Android') {
    platformInfo = versions.android;
  } else {
    if (/linux/i.test(navigator.platform)) {
      platformInfo = versions.linux;
    } else if (/mac/i.test(navigator.platform)) {
      if (/Safari/i.test(navigator.userAgent)) {
        platformInfo = versions.mac_safari;
      } else {
        platformInfo = versions.mac_firefox;
      }
    } else if (/win/i.test(navigator.platform)) {
      platformInfo = versions.win;
    } else {
      // Default to unknown platform.
      unknownPlatform = true;
    }
  }
  detectBrowser();
  installing = getCookie('installing') == '1';
  removeCookie('installing');
}

function detectBrowser() {
  if (navigator.userAgent.indexOf("PPC; Opera Mobi")!=-1) {
    // On WinCE, the Opera Mobile UA is
    // Opera/9.51 Beta (Microsoft Windows; PPC; Opera Mobi/250; U; en) Presto/<major>.<minor>.<maintenance>
    // We need to check for PPC to detect only the WinCE version of Opera
    // Mobile, not the Symbian version.
    browser = "OperaMobile";
  } else if (navigator.userAgent.indexOf("Opera")!=-1) {
    browser = "Opera";
  } else if (navigator.userAgent.indexOf("Firefox")!=-1) {
    browser = "Firefox";
  } else if (navigator.userAgent.indexOf("MSIE")!=-1) {
    if (navigator.userAgent.indexOf("Windows CE")!=-1) {
      // As of Windows Mobile 5, the UA always contains 'Windows CE'
      browser = "IEMobile";
    } else if ((navigator.userAgent.indexOf("PPC")==-1) &&
               (navigator.userAgent.indexOf("Smartphone")==-1)) {
      // The UA reports 'MSIE' but none of 'Windows CE', 'PPC' or
      // 'Smartphone'. So it must be IE for desktop.
      browser = "MSIE";
    }
  } else if (navigator.userAgent.indexOf("Android") != -1) {
    browser = "Android";
  } else if (navigator.userAgent.indexOf("Safari")!=-1) {
    browser = "Safari";
  }
  if (browser != -1) {
    isBrowserOnWince = (browser == "IEMobile" || browser == "OperaMobile");
    index = navigator.userAgent.indexOf(browser);
    if (browser.indexOf("Safari") >= 0) {
      browserVersion =
          parseFloat(navigator.userAgent.substring(index - 4, index -1));
    } else if (browser.indexOf("OperaMobile") >= 0) {
      // The first publicly released Gears-compatible Opera Mobile binary was
      // version 9.51 Beta with build 'Presto/2.1.0'. It was released in Opera
      // Labs.
      var prestoString = 'Presto/';
      var ua = navigator.userAgent;
      // If the user agent string doesn't include 'Presto', the build is too
      // old.
      if (ua.indexOf(prestoString) != -1) {
        // The Presto build number has the format <major>.<minor>.<maintenance>,
        // with no limit on the value of each element. For now, we assume that
        // each is limited to 99, though we may have to revisit this.
        var majorIndex = ua.indexOf(prestoString) + prestoString.length;
        var minorIndex = ua.indexOf('.', majorIndex) + 1;
        var maintenanceIndex = ua.indexOf('.', minorIndex) + 1;
        browserVersion =
            10000 * parseInt(ua.substring(majorIndex, minorIndex - 1)) +
            100 * parseInt(ua.substring(minorIndex, maintenanceIndex - 1)) +
            1 * parseInt(ua.substring(maintenanceIndex));
      }
    } else if (browser.indexOf("IEMobile") >= 0) {
      // For version calculation, we still look at the "MSIE" string.
      browserTemp = "MSIE";
      index = navigator.userAgent.indexOf(browserTemp);      
      browserVersion = parseFloat(navigator.userAgent.substring(
          index + browserTemp.length + 1, index + browserTemp.length + 4));
    } else {
      browserVersion = parseFloat(navigator.userAgent.substring(
          index + browser.length + 1, index + browser.length + 4));
    }    
  }
}

function setCookie(name, value, expireMinutes) {
  var exdate = new Date;
  exdate.setMinutes(exdate.getMinutes() + expireMinutes);
  document.cookie = name + '=' + escape(value) +
      (expireMinutes == null ? '' : ';expires=' + exdate.toGMTString());
}

function getCookie(name) {
  if (document.cookie) {
    var start = document.cookie.indexOf(name + '=');
    // Check that 'name' exists and that it's an actual variable
    if (((start != -1)) && 
        ((start == 0) || (document.cookie.substring(start-2, start-1) == ';'))) {
      start = start + name.length + 1;
      var end = document.cookie.indexOf(';', start);
      if (end == -1) {
        end = document.cookie.length;
      }
      return unescape(document.cookie.substring(start, end));
    } 
  }
  return '';
}

function removeCookie(name) {
  setCookie(name, '', 0);
}

function detectCookieSupport() {
  setCookie('test', '1', 1);
  var supportsCookies = getCookie('test') == '1';
  removeCookie('test');
  return supportsCookies;
}

function getQueryParam(name) {
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  var results = regex.exec(window.location.href);
  return results && decodeURIComponent(results[1]);
}

function putParamText(nodeId, paramName) {
  var text = getQueryParam(paramName);
  if (text) {
    if (text.length > 150) {
      text = text.substring(0, 150)
    }
    var node = getElementById(nodeId);
    if (node) {
      setText(node, text);
    }
  }
}

function setText(element, text) {
  if (isDefined(typeof element.innerText)) {
    element.innerText = text;
  } else if (isDefined(typeof element.textContent)) {
    element.textContent = text;    
  } else {
    throw new Error('Failed to set text');
  }
}

function putParamImage(nodeId, paramName) {
  var src = getQueryParam(paramName);
  if (src) {
    var node = getElementById(nodeId);
    if (node) {
      node.src = src;
    }      
  }
}

function setAppContent() {
  // We do not support 'install' or 'upgrade'
  // functionality on the Android browser. Gears
  // is already installed and cannot be manually
  // upgraded.
  if ((getQueryParam('action') == 'install' ||
      getQueryParam('action') == 'upgrade') &&
      browser != "Android") {
    if (isBrowserOnWince) {
      if (getQueryParam('name')) {
        putParamText('app-name-winmo', 'name');
        getElementById('app-name-winmo').innerHTML += '<br>';
      }
      putParamText('app-message-winmo', 'message');
      if (getQueryParam('icon_src')) {
        putParamImage('app-icon-winmo', 'icon_src');
        getElementById('app-icon-winmo').style.display = 'block';
      }
      getElementById('app-action-winmo').style.display = 'block';
      getElementById('gears-message-winmo').style.display = 'block';
    } else {
      putParamText('app-name', 'name');
      putParamText('app-message', 'message');
      putParamImage('app-icon', 'icon_src');
      getElementById('app-action').style.display = 'block';
    }
  } else {
    getElementById('no-app-action').style.display = 'block';
  }

  if (window.google && google.gears && !getQueryParam('platform')) {
    // Check for the Android browser, which is a special case, since
    // Gears cannot be manually upgraded.
    if (getQueryParam('action') == 'upgrade' && browser != "Android") {
      getElementById('upgrade').style.display = 'block';
      getElementById('upgrade-version').innerHTML =
          google.gears.factory.getBuildInfo();
    } else {
      getElementById('is-installed').style.display = 'block';
      var buildInfo = google.gears.factory.getBuildInfo();
      if (browser == "Android") {
        // If we are on the Android browser and the Gears build info
        // reports 'unknown_os', set the OS name to Android.
        // Unfortunately, Gears 0.4.13.1 and Gears 0.4.23.0 both
        // report 'unknown_os'. This has been fixed in later versions.
        if (buildInfo.indexOf('unknown_os') != -1) {
          buildInfo = buildInfo.replace("unknown_os", "android");
        }
        // Hide the reinstall section
        getElementById('is-installed-reinstall').style.display = 'none';
      }
      getElementById('is-installed-version').innerHTML = buildInfo;
    }
  } else {
    var supportedBrowserVersion =
        browser == "Firefox" && browserVersion >= 1.5 || 
        browser == "MSIE" && browserVersion >= 6 || 
        browser == "IEMobile" && browserVersion >= 4 ||
        browser == "OperaMobile" && browserVersion >= 20100 ||
        browser == "Safari" && browserVersion >= 1;
    if (unknownPlatform) {
      supportedBrowserVersion = null;
    }
    if (getQueryParam('platform') || supportedBrowserVersion) {
      getElementById("is-not-installed").style.display = "block";
      // If we're on WinCE, show links to the ToS and PP (rather than the
      // platform string) to allow a direct install. If we're on any other
      // platform, show the platform string, even if this 'XXX for Windows
      // Mobile', (as specified by the platform query param), to allow a
      // download of a WinCE CAB on other platforms.
      if (isBrowserOnWince) {
        getElementById("install-wince-directly").style.display = "block";
      } else {
        getElementById(
            "is-not-installed-text-" + platformInfo.id).style.display = "block";
      }
    } else {
      getElementById("is-not-supported").style.display = "block";
    }
  }

  if (!unknownPlatform) {
    getElementById("platform-details-" + platformInfo.id).style.display = "block";
  }
  getElementById("right-pane").style.display = "block";

  if (!isBrowserOnWince) {
    getElementById("supported-platforms").style.display = "block";
  }

}

function goToNextAndOverrideSearch(baseUrl, searchSuffix) {
  setCookie('installing', '1', 10);
  window.location.href = baseUrl + searchSuffix;
}

function goToNext(baseUrl) {
  goToNextAndOverrideSearch(baseUrl, window.location.search);
}

function install() {
  if (isBrowserOnWince ) {
    goToNext('download.html');
  } else {
    goToNext('terms.html');
  }
  return false;
}
