if (typeof GGConnectInstall == 'undefined')
	GGConnectInstall = {};

Object.extend(GGConnectInstall, {
	/**
	 * Compare two version strings.
	 *
	 * @param string version1
	 * @param string version2
	 * @return number 0 if the versions are equal, 1 if version1 is higher than
	 *   version2, and -1 if version1 is lower than version2.
	 */
	compareVersions: function(version1, version2) {
	   if (version1 === undefined) {
		  return -1;
	   }
	   if (version2 === undefined) {
		  return 1;
	   }
	   version1 = version1.split('.');
	   version2 = version2.split('.');
	   var length = Math.max(version1.length, version2.length);
	   while (length--) {
		  var v1f = parseFloat(version1.shift()) || 0;
		  var v2f = parseFloat(version2.shift()) || 0;
		  if (v1f > v2f) {
			 return 1;
		  }
		  else if (v1f < v2f) {
			 return -1;
		  }
	   }
	   return 0;
	},

	/**
	 * This method is used to check the install status of the plugin on a client's
	 * computer. It will return true if the plugin is installed and fully upgraded,
	 * or false if it is out of date.
	 *
	 * @param object callbacks Optional object with two keys: install and update, both
	 *   both functions. If specified, the functions will be called as appropriate.
	 * @return bool
	 */
	getCurrentVersion: function(){
		if (this.isIE()) {
			var element = document.createElement('iframe');
			element.style.display = 'none';
			document.body.appendChild(element);
			element = frames[frames.length - 1];
			element.document.open();
			element.document.write([
				'<script language="VBScript">',
					'On error resume next',
					'currentVersion = CreateObject("' + GG.config.plugin.activex.className + '").version',
				 '</script>'
			].join('\n'));
			element.document.close();
			arguments.callee.version = element.currentVersion;

		} else {
			var highest = {};
			var typeRegex = new RegExp('^'+GG.config.plugin.netscape.mimeType+'[\\.\\d]*$');
			var versionRegex = new RegExp('[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+');
			var i = navigator.mimeTypes.length;
			while (i--) {
				var mimeType = navigator.mimeTypes[i];
				if (typeRegex.test(mimeType.type)) {
					var version = versionRegex.exec(mimeType.description)[0];
					if (this.compareVersions(version, highest.version) >= 0) {
						highest.mimeType = mimeType.type;
						highest.version = version;
					}
				}
			}
			arguments.callee.mimeType = highest.mimeType;
			arguments.callee.version = highest.version;
		}
		return arguments.callee.version;
	},
	
	getRequiredVersion: function(){
		if (this.isIE()) {
			return GG.config.plugin.activex.version;
		}
		else {
			return GG.config.plugin.netscape[this.isMac() ? 'versionMac' : 'version'];
		}
	},
	
	isIE: function(){
		return typeof DOMParser == 'undefined' && navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('Win') != -1;
	},
	
	isMac: function(){
		return /Mac/.match(navigator.platform);
	},
	
	check: function(callbacks){
		callbacks = callbacks || {};
		
		var currentVersion = this.getCurrentVersion();
		var requiredVersion = this.getRequiredVersion();
		var checkPlugin = function(){
			if (typeof currentVersion == 'undefined') {
				return 'install';
			}
			if (currentVersion == requiredVersion) {
				return 'installed';
			}
			var a = currentVersion.split('.');
			var b = requiredVersion.split('.');
			for (var i = 0; i < requiredVersion.length; i++) {
				if (typeof a[i] != 'undefined' && parseFloat(a[i]) > parseFloat(b[i])) {
					return 'installed';
				}
			}
			return 'upgrade';
		};
	
		var state = checkPlugin();
		if (state == 'install') {
			if (callbacks.install)
				callbacks.install();
			return false;
		}
		else if (state == 'upgrade') {
			if (callbacks.upgrade)
				callbacks.upgrade();
			return false;
		}
		else {
			return true;
		}
	},
	
	installFirefox: function(options){
		options = options || {};
		var params = {
			'InstantAction.com Game Launcher': {
				URL: GG.config.plugin.urls.xpi,
				IconURL: '/images/plugin/plugin.png',
				toString: function(){ return this.URL; }
			}
		};
		var i = 0;
		var interval = setInterval(function(){
			var authorized = InstallTrigger.install(params, function(url, status){
				if (status != 0) {
					if (options.onError) {
						options.onError(status);
					}
				}
				else if (options.onComplete) {
					options.onComplete();
				}
			});
			if (authorized) {
				if (options.onAuthorized) {
					options.onAuthorized();
				}
				clearInterval(interval);
			}
			else if (i == 0) {
				if (options.onUnauthorized) {
					options.onUnauthorized();
				}
			}
			i++;
		}, 250);
	},

	installIE: function(options){
		var element = document.getElementById('ggconnect_install_container');
		element.innerHTML = '<object id="ggconnect_install" classid="' + GG.config.plugin.activex.classId + '" codebase="' + GG.config.plugin.urls.cab + '#version=' + GG.config.plugin.activex.version.replace(/\./g,',') + '" width="1" height="1"></object>';
		var interval = setInterval(function(){
			if (typeof document.ggconnect_install.version != 'undefined') {
				clearInterval(interval);
				if (options.onComplete) {
					options.onComplete();
				}
			}
		}, 250);
	}
});

Object.extend(GGConnectInstall, {
	downloadInstaller: function(pkg, browser){
		this.setInstallCookie(browser);
		this.logAndRedirect('download', GG.config.plugin.urls[pkg]);
	},
	
	getCookieDomain: function(){
		return window.location.host.replace(/www(.login)?/g, '');
	},
	
	log: function(name, options){
		options = options || {};
		if (name && name == 'prompt') {
			this.setLogTrackingPostPluginCookie();
			new Ajax.Request('/account/logtrackingpreplugin');
		}
		//} else if (name && name == 'install') {
		//	this.setLogTrackingPostPluginCookie();
		//}
		var url = [
			'/logplugin' + name,
			GG.util.BrowserDetect.OS,
			GG.util.BrowserDetect.browser,
			GG.util.BrowserDetect.version
		];
		if (options.log) {
			url = url.concat(options.log);
		}
		url = url.join('/');
		return new Ajax.Request(url, options);
	},
	
	logAndRedirect: function(name, url){
		return this.log(name, {
			onComplete: function(){
				window.location = url;
			}
		});
	},
	
	setInstallCookie: function(browser){
		var expires = new Date();
		expires.setTime(expires.getTime() + 30 * 24 * 60 * 60 * 1000);
		document.cookie = 'pluginInstall=' + browser + '; expires=' + expires.toGMTString() + '; domain=' + this.getCookieDomain() + '; path=/';
	},
	
	setStatusCookie: function(){
		var pluginStatus = 'installed';
		GGConnectInstall.check({
			install: function(){ pluginStatus = 'install'; },
			upgrade: function(){ pluginStatus = 'upgrade'; }
		});
		document.cookie = 'pluginStatus=' + pluginStatus + '; domain=' + this.getCookieDomain() + '; path=/';
	},

	//set cookie here, then check/delete cookie later, once persistent.global.plugin.id available
	setLogTrackingPostPluginCookie: function(){
		var expires = new Date();
		expires.setTime(expires.getTime() + 30 * 24 * 60 * 60 * 1000);
		document.cookie = 'IALogPostPlugin=true; expires=' + expires.toGMTString() + '; domain=' + this.getCookieDomain() + '; path=/';
	}

});
