// initialize global variables
var detectableWithVB = false;
var pluginFound = false;

// Here we write out the VBScript block for MSIE Windows
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) {
	
	// document.writeln('<p>######## userAgent IE</p>');

    document.writeln('<script language="VBscript">');

    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');

    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('\'and the following function handles QuickTime');
    document.writeln('Function detectQuickTimeActiveXControl()');
    document.writeln('  on error resume next');
    document.writeln('  detectQuickTimeActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('    detectQuickTimeActiveXControl = False');
    document.writeln('    hasQuickTimeChecker = false');
    document.writeln('    Set hasQuickTimeChecker = CreateObject("QuickTimeCheckObject.QuickTimeCheck.1")');
    document.writeln('    If IsObject(hasQuickTimeChecker) Then');
    document.writeln('      If hasQuickTimeChecker.IsQuickTimeAvailable(0) Then ');
    document.writeln('        detectQuickTimeActiveXControl = True');
    document.writeln('      End If');
    document.writeln('    End If');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('</scr' + 'ipt>');
}
// else { 	document.writeln('<p>######## userAgent NOT IE</p>'); }


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
		// 2010-08-04 JS added code:
		this.hasQuickTime = false;
		this.hasFlash = false;
		this.hasWMV = false;
		// alert("canDetectPlugins(): " + canDetectPlugins());
		if (canDetectPlugins())
		{
			this.hasQuickTime = detectQuickTime();
			this.hasFlash = detectFlash();
			this.hasWMV = detectWindowsMedia();
			// alert("hasQuickTime (): " + this.hasQuickTime);
/*
	tr("Supports QuickTime:",detectQuickTime());
	tr("","");
	tr("Supports Shockwave for Director:", detectDirector() );
	tr("Supports Shockwave Flash:", detectFlash() );
	tr("Supports RealPlayer:", detectReal() );
	tr("Supports Windows Media Player:", detectWindowsMedia() );			
*/		

		}
		else {
			// couldn't check the original way; e.g. in CrossOver virtual machine on Mac 
			//  - doesn't have VB script; at least not the VM tested
			// alert("didn't check plugins...!!!"); 
			
			//var version = getFlashVersion();//.split(',').shift();
			var infoStr = getFlashVersionFull();//.split(',').shift();
			var version = infoStr.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]
			var mainversion = version.split(',').shift();
			if (mainversion > 0) {
				this.hasFlash = true;
//				document.writeln("<p>Flash main version is <b>" + mainversion + "</b> (<i>"+infoStr+"</i>)</p>");
			}
//			else {
//				document.writeln("<p class=\"SI_NOTE\"><b>No flash detected</b></p>");
//			}

		}
		
		// Windows Media stuff; added 2010-08-05
		var $$ = PluginDetect;
		var WMP = $$.isMinVersion('WindowsMediaPlayer', '0');
		this.WMP_Enabled = (WMP >= 0);
		this.WMP_Version = $$.getVersion('WindowsMediaPlayer');
		this.WMP_Scriptable = (WMP == 1);
		var minVersion = "7,0,0,0";
		this.WMP_Min700 = ($$.isMinVersion('WindowsMediaPlayer', minVersion));
		/*
			1:    document.write('Windows Media Player ' + minVersion + ' or higher is installed and enabled<br>')
			0: 
			   	// Browsers do not reveal the WinMediaPlayer version in their navigator array,
   				// they only show whether the plugin is installed or not. It is thus the user's 
   				// responsibility to make sure that their Media Player is up to date.
   				document.write('Windows Media Player installed but version is unknown.');
			-1:
			    if (PluginDetect.isMinVersion('WindowsMediaPlayer', '0') >= 0)
    			  document.write('Windows Media Player installed but version is < ' + minVersion + '<br>');
  				else document.write('Windows Media Player not installed/enabled<br>');
			-2:
			   // ActiveX is disabled
			   document.write('Please enable ActiveX in Internet Explorer so that we can detect your plugins<br>');
			*:
				document.write('Windows Media Player installed but version is unknown...')
		*/

	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();


/* ##### */

function goURL(daURL) {
    // if the browser can do it, use replace to preserve back button
    if(javascriptVersion1_1) {
	window.location.replace(daURL);
    } else {
	window.location = daURL;
    }
    return;
}

function redirectCheck(pluginFound, redirectURL, redirectIfFound) {
    // check for redirection
    if( redirectURL && ((pluginFound && redirectIfFound) || 
	(!pluginFound && !redirectIfFound)) ) {
	// go away
	goURL(redirectURL);
	return pluginFound;
    } else {
	// stay here and return result of plugin detection
	return pluginFound;
    }	
}

function canDetectPlugins() {
    if( detectableWithVB || (navigator.plugins && navigator.plugins.length > 0) ) {
	return true;
    } else {
	return false;
    }
}

function detectFlash(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('Shockwave','Flash'); 
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('ShockwaveFlash.ShockwaveFlash.1');
    }
    // check for redirection
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectDirector(redirectURL, redirectIfFound) { 
    pluginFound = detectPlugin('Shockwave','Director'); 
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('SWCtl.SWCtl.1');
    }
    // check for redirection
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectQuickTime(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('QuickTime');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectQuickTimeActiveXControl();
    }
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectReal(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('RealPlayer');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = (detectActiveXControl('rmocx.RealPlayer G2 Control') ||
		       detectActiveXControl('RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)') ||
		       detectActiveXControl('RealVideo.RealVideo(tm) ActiveX Control (32-bit)'));
    }	
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectWindowsMedia(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('Windows Media');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('MediaPlayer.MediaPlayer.1');
    }
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectPlugin() {
    // allow for multiple checks in a single pass
    var daPlugins = detectPlugin.arguments;
    // consider pluginFound to be false until proven true
    var pluginFound = false;
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) {
	var pluginsArrayLength = navigator.plugins.length;
	// for each plugin...
	for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
	    // loop through all desired names and check each against the current plugin name
	    var numFound = 0;
	    for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
		// if desired plugin name is found in either plugin name or description
		if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) || 
		    (navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
		    // this name was found
		    numFound++;
		}   
	    }
	    // now that we have checked all the required names against this one plugin,
	    // if the number we found matches the total number provided then we were successful
	    if(numFound == daPlugins.length) {
		pluginFound = true;
		// if we've found the plugin, we can stop looking through at the rest of the plugins
		break;
	    }
	}
    }
    return pluginFound;
} // detectPlugin


/* ######################## */

function getFlashVersion(){
  // ie
  try {
    try {
      // avoid fp6 minor version lookup issues
      // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
      try { axo.AllowScriptAccess = 'always'; }
      catch(e) { return '6,0,0'; }
    } catch(e) {}
    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
  // other browsers
  } catch(e) {
    try {
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
      }
    } catch(e) {}
  }
  return '0,0,0';
}


function getFlashVersionFull(){
  // ie
  try {
    try {
      // avoid fp6 minor version lookup issues
      // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
      try { axo.AllowScriptAccess = 'always'; }
      catch(e) { return '6,0,0'; }
    } catch(e) {}
    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');//.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
  // other browsers
  } catch(e) {
    try {
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description;//.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
      }
    } catch(e) {}
  }
  return '0,0,0';
}

// 2010-08-06 12:30

function BrowserDetect_getEnvData()
{
	res = "";
	res += 'BrowserDetect: : ' + BrowserDetect.OS + ', ';
	res += BrowserDetect.browser + ', ' + BrowserDetect.version;
	res += "\n";
	res += 'QuickTime: ' + BrowserDetect.hasQuickTime;
	res += "\n";
	res += 'Flash: ' + BrowserDetect.hasFlash + ", " + getFlashVersion();
	res += "\n";
	res += 'WMW: ' + BrowserDetect.hasWMV;
	if (BrowserDetect.hasWMV) {
		res += ", enabled:" + BrowserDetect.WMP_Enabled;
		res += ", version:" + BrowserDetect.WMP_Version;
		res += ", scriptable:" + BrowserDetect.WMP_Scriptable;
	}
	res += "\n";
    if (navigator.plugins && navigator.plugins.length > 0) 
	{
		var pluginsArrayLength = navigator.plugins.length;
		// for each plugin...
		for (pluginsArrayCounter=0; 
			pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) 
		{
			res += "#" + pluginsArrayCounter + ":";
			res += navigator.plugins[pluginsArrayCounter].name ;
			res += ' "' + navigator.plugins[pluginsArrayCounter].description + '"';
			res += "\n";
		}
	}
	
	res += "appVer:" + navigator.appVersion;
	res += "\n";
	if ((navigator.userAgent.indexOf("Opera/5") == -1) &&
	    (navigator.userAgent.indexOf("Opera/4") == -1))
	{
		res += "Screen: " + screen.width + 'x' + screen.height + ' pixels ';
	}
	else 
	{
		res += "Screen: Unknown";
	}
	res += "\n";
	return (res);
} // BrowserDetect_getEnvData()
