var browser = -1;
var browserId = 0;
var browserVersion = -1;
var platformInfo = -1;
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.
    url: 'http://dl.google.com/tag/gears/GoogleGearsSetup.exe',
    // 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: {
    id: 'mac',
    url: 'http://dl.google.com/gears/current/gears-osx-opt.xpi',
    iframeUrl: 'http://addons.mozilla.org/google/google_gears_osx.html',
    auto_redirect: false
  },
  wince: {
    id: 'wince',
    url: 'http://dl.google.com/gears/current/gears-wince-opt.cab',
    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') != -1) {
    platformInfo = versions.wince;
  } else if (window.location.href.indexOf('platform=mac') != -1) {
    platformInfo = versions.mac;
  } 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 == 'WinCE') {
    platformInfo = versions.wince;
  } else {
    if (/linux/i.test(navigator.platform)) {
      platformInfo = versions.linux;
    } else if (/mac/i.test(navigator.platform)) {
      platformInfo = versions.mac;
    } else {
      //default to Windows
     platformInfo = versions.win;
    }
  }
  detectBrowser();
  installing = getCookie('installing') == '1';
  removeCookie('installing');
}

function detectBrowser() {
  if (navigator.userAgent.indexOf("Opera")!=-1) {
    browser = "Opera";
  } else if (navigator.userAgent.indexOf("Firefox")!=-1) {
    browser = "Firefox";
    browserId = 3;
  } 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";
      browserId = 4;
    } 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";
      browserId = 2;
    }
  } else if (navigator.userAgent.indexOf("Safari")!=-1) {
    browser = "Safari";
  }
  if (browser != -1) {
    index = navigator.userAgent.indexOf(browser);
    if (browser.indexOf("Safari") >= 0) {
      browserVersion = parseFloat(navigator.userAgent.substring(index - 4, index -1));
    } 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) {
      node.innerText = node.textContent = text;
    }
  }
}

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

function setAppContent() {
  if (getQueryParam('action') == 'install' ||
      getQueryParam('action') == 'upgrade') {
    putParamText('app-name', 'name');
    putParamText('app-message', 'message');
    putParamImage('app-icon', 'icon_src');
    getElementById('app-action').style.display = 'block';
    getElementById('no-app-action').style.display = 'none';
  } else {
    getElementById('app-action').style.display = 'none';
    getElementById('no-app-action').style.display = 'block';
  }

  if (window.google && google.gears && !getQueryParam('platform')) {
    if (getQueryParam('action') == 'upgrade') {
      getElementById('upgrade').style.display = 'block';
      getElementById('upgrade-version').innerHTML =
          google.gears.factory.getBuildInfo();
    } else {
      getElementById('is-installed').style.display = 'block';
      getElementById('is-installed-version').innerHTML =
          google.gears.factory.getBuildInfo();
    }
  } else {
    if (getQueryParam('platform') ||
        browser == "Firefox" && browserVersion >= 1.5 || 
        browser == "MSIE" && browserVersion >= 6 || 
        browser == "IEMobile" && browserVersion >= 4) {
      getElementById("is-not-installed").style.display = "block";
      getElementById("is-not-installed-text-" + platformInfo.id).style.display = "block";
    } else {
      getElementById("is-not-supported").style.display = "block";
    }
  }
  getElementById("platform-details-" + platformInfo.id).style.display = "block";
  getElementById("right-pane").style.display = "block";
}

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

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

// Create a random number containing four hexadecimal digits.
function getFourCharId() {
  var possibleValues = 0x10000;
  var number = Math.floor(Math.random() * possibleValues);
  var str = number.toString(16);
  while (str.length < 4) {
    str = "0" + str;
  }
  return str.toUpperCase();
}

// The IID must be in the form of a GUID.
function getLocalIid() {
  var localIidPrefix = '14159265';
  return '{' + localIidPrefix + '-' +
    getFourCharId() + '-' +
    getFourCharId() + '-' +
    getFourCharId() + '-' +
    getFourCharId() + getFourCharId() + getFourCharId() + '}';
}

function initIid() {
  var currentIid = getCookie('iid');
  if (currentIid) {
    setIid(currentIid);
  } else {
    setIid(getLocalIid());
  }
}

function setIid(new_iid) {
  iid = new_iid;
  setCookie('iid', iid, null);
}

function getIid() {
  return iid;
}

var iid;

/**
 *  Ajax namespaced-object.
 */
var ajaxObject = {};

ajaxObject.READY_STATE_UNINITIALIZED = 0;
ajaxObject.READY_STATE_LOADING = 1;
ajaxObject.READY_STATE_LOADED = 2;
ajaxObject.READY_STATE_INTERACTIVE = 3;
ajaxObject.READY_STATE_COMPLETE = 4;


/**
 *  Content loader object for cross-browser requests
 */
ajaxObject.ContentLoader = function(url, onload, onerror, method, 
                                params, contentType) {
  this.req = null;
  this.url = url;
  this.onload_ = (onload) ? onload : this.defaultLoad;
  this.onerror_ = (onerror) ? onerror : this.defaultError;
  this.loadDoc(this.url, method, params, contentType);
};

ajaxObject.ContentLoader.prototype = {
  loadDoc : function(url, method, params, contentType) {
    method = method || "GET";

    if (!contentType && method == "POST") {
      contentType = 'application/x-www-form-urlencoded';
    }
    if (window.XMLHttpRequest) {
      this.req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      this.req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (this.req) {
      try {
        var loader = this;
        this.req.onreadystatechange = function() {
          loader.onReadyState.call(loader);
        };
        this.req.open(method, url, true);
        if (contentType) {
          this.req.setRequestHeader('Content-Type', contentType);
        }
        // TODO: make this header argument-driven?
        this.req.setRequestHeader("If-Modified-Since",
                                  "Sat, 1 Jan 2000 00:00:00 GMT");
        this.req.send(params);
      } catch (err) {
        var msg;
        if (err instanceof Error) {
          msg = err.message;
        } else {
          msg = err;
        }
        this.onerror_(msg, url);
      }
    }
  },

  onReadyState : function() {
    var req = this.req;
    var ready = req.readyState;
    if (ready == ajaxObject.READY_STATE_COMPLETE) {
      var httpStatus = req.status;
      if (httpStatus == 200 || httpStatus == 0) {
        this.onload_();
      } else {
        this.onerror_("unexpected HTTP status " + httpStatus, this.url);
      }
    }
  },

  defaultError : function(msg, url) {
    // Do nothing.
  },
  
  defaultLoad : function() {
    // Do nothing.
  }
};
