var browser = -1;
var browserVersion = -1;
var platformInfo = null;
var isBrowserOnWince = false;
var macFirefox = {
  url: 'http://dl.google.com/gears/current/gears-osx-opt.xpi',
  iframeUrl: 'http://addons.mozilla.org/google/google_gears_osx.html'
};
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.
    MSIE: {
      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
    },
    Firefox: {
      url: null,
      iframeUrl: null
    },
    // No install on Chrome

    // 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',
    Firefox: {
      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: {
    id: 'mac',
    Firefox: macFirefox,
    Safari: {
      url: 'http://dl.google.com/gears/current/gears-osx-opt.dmg',
      iframeUrl: null
    },
    auto_redirect: false
  },
  macSnowLeopard: {
    id: 'macSnowLeopard',
    Firefox: macFirefox,
    auto_redirect: false
  },
  wince: {
    id: 'wince',
    IEMobile: {
      url: 'http://dl.google.com/gears/current/gears-wince-opt.cab',
      iframeUrl: null
    },
    OperaMobile: {
      url: 'http://dl.google.com/gears/current/gears-wince-opt-opera.cab',
      iframeUrl: null
    },
    auto_redirect: false
  },
  android: {
    id: 'android',
    // No install on Android
    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 detectForcedPlatform() {
  // The platform can be forced with a query param.
  if (window.location.href.indexOf('platform=wince') != -1) {
    return versions.wince;
  } else if (window.location.href.indexOf('platform=macSnowLeopard') != -1) {
    return versions.macSnowLeopard;
  } else if (window.location.href.indexOf('platform=mac') != -1) {
    return versions.mac;
  } else if (window.location.href.indexOf('platform=linux') != -1) {
    return versions.linux;
  } else if (window.location.href.indexOf('platform=win') != -1) {
    return versions.win;
  } else if (window.location.href.indexOf('platform=android') != -1) {
    return versions.android;
  }
}

function detectPlatform() {
  if (navigator.platform.indexOf('WinCE') > -1 ||
      navigator.platform.indexOf('Pocket PC') > -1 ||
      navigator.platform.indexOf('Windows CE') > -1 ||
      navigator.platform.indexOf('Windows Mobile') > -1) {
    platformInfo = versions.wince;
  } 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)) {
    // Version digits may be separated with either '.' or '_'.
    var str = new String(/Mac OS X 10[\._][0-9]*/.exec(navigator.userAgent));
    str = str.replace('_', '.');
    var version = parseFloat(str.substr(9));
    if (version == 10.4 || version == 10.5) {
      platformInfo = versions.mac;
    } else if (version == 10.6) {
      platformInfo = versions.macSnowLeopard;
    }
  } else if (/win/i.test(navigator.platform)) {
    platformInfo = versions.win;
  }
  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("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("Chrome") != -1) {
    // Must come before detection for Safari.
    browser = "Chrome"
  } 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) {
      var str = new String(/Version\/[0-9]*.[0-9]*/.exec(navigator.userAgent));
      browserVersion = parseFloat(str.substring(8));
    } 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';
  }

  var displayedPlatform = platformInfo;

  var forcedPlatform = detectForcedPlatform();
  if (forcedPlatform) {
    displayedPlatform = forcedPlatform;
  }

  if (window.google && google.gears && displayedPlatform == platformInfo) {
    // Gears is installed and we're displaying the host platform.

    // Check for Android and Chrome, which are special cases, since
    // Gears cannot be manually upgraded.
    if (getQueryParam('action') == 'upgrade' &&
        browser != "Android" &&
        browser != "Chrome") {
      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" && buildInfo.indexOf('unknown_os') != -1) {
        // 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.
        buildInfo = buildInfo.replace("unknown_os", "android");
      }
      if (browser == "Android" || browser == "Chrome") {
        // Hide the reinstall section
        getElementById('is-installed-reinstall').style.display = 'none';
      }
      getElementById('is-installed-version').innerHTML = buildInfo;
    }
  } else {
    // Gears is not installed on the platform we're displaying.
    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 (isBrowserOnWince && displayedPlatform == platformInfo) {
      getElementById("install-wince-directly").style.display = "block";
    } else {
      if (displayedPlatform) {
        getElementById(
          "is-not-installed-text-" + displayedPlatform.id).style.display = "block";
      } else {
        getElementById("is-not-installed-text-unknown").style.display = "block";
      }
    }

    if (displayedPlatform == platformInfo) {
      // On Android and Chrome, where manual install/upgrade is not supported,
      // if Gears is not already installed we always fail the 'supported
      // browser' check.
      var supportedBrowserVersion =
          browser == "Firefox" && browserVersion >= 1.5 ||
          browser == "MSIE" && browserVersion >= 6 ||
          browser == "IEMobile" && browserVersion >= 4 ||
          browser == "OperaMobile" && browserVersion >= 20100 ||
          browser == "Safari" && browserVersion >= 3.1;
      if (!displayedPlatform || !displayedPlatform[browser]) {
        supportedBrowserVersion = null;
      }

      if (supportedBrowserVersion) {
        getElementById("install-button").style.display = "block";
      } else {
        getElementById("is-not-supported").style.display = "block";
      }
    }
  }

  if (displayedPlatform) {
    getElementById("platform-details-" + displayedPlatform.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;
}
