var detectableWithVB = false;
var pluginFound = false;
var mediaPlayer = null;
var os = getUserAgent();
var sndtoplay = "";
var sndArray = new Array(1);
var sndIndex = 0;
var player;
var hasWMP64 = false;
var qtVer = 0;
var localIsLLS = false;
var safariVersion = 0;
var isSafari = navigator.userAgent.indexOf('Safari')>0;
if(isSafari)
	safariVersion = getSafariVersion();
	
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1))
{
    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');
    if(window.parent.frames["macapiframe"] != null && window.parent.frames["macapiframe"].document.getElementById("MediaPlayer") != null)
    	document.writeln('hasWMP64 = (top.frames("macapiframe").document.getElementById("MediaPlayer").FileName="")');

    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.write('          qtVer = CInt(Hex(hasQuickTimeChecker.QuickTimeVersion) / 1000000) \n');
    document.writeln('      End If');
    document.writeln('    End If');
    document.writeln('  End If');
    document.writeln('End Function');
    
    document.writeln('</scr' + 'ipt>');
}


if(window.parent.frames["macapiframe"] != null && window.parent.frames["macapiframe"].document.currentMediaPlayer != null)
	mediaPlayer = window.parent.frames["macapiframe"].document.currentMediaPlayer;
else
{
	//The new QuickTime plug-in will not work with IE on windows because of the way the IE 
        //handles <param tags with the innerHTML property. So it will default to Windows Media Player 
	if(canDetectPlugins() && !(os == "Windows" && getSpecificBrowserName() == "Internet Explorer"))
	{
		if(detectQuickTime())
			mediaPlayer = "QuickTime";
		else if(os == "Windows" && detectWindowsMedia())
			mediaPlayer = "WMP";		
		else
			setMediaPlayerToDefault();
	}else
		setMediaPlayerToDefault();
	//store in the macapiframe the type of player being used
	//this session so we don't have to check each time
	if(window.parent.frames["macapiframe"] != null && window.parent.frames["macapiframe"].document.currentMediaPlayer != null)
		window.parent.frames["macapiframe"].document.currentMediaPlayer = mediaPlayer;
}

function setMediaPlayerToDefault()
{
	try
	{
		if(os == "Mac")
			mediaPlayer = "QuickTime";
		else if(os == "Windows")
			mediaPlayer = "WMP";
		else
			mediaPlayer = "JavaApplet"
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.setMediaPlayer()");
	}
}

function initializeSound(isLLS)
{

	setPlayingSound(false);
	localIsLLS = isLLS;

	try
	{
		element = window.ContentFrame.document.getElementById("playSound");
		if(window.ContentFrame.soundEvent.substring(window.ContentFrame.soundEvent.length - 1) == "/")
			window.ContentFrame.soundEvent = "";
                
		if(isLLS)
		{
			if(window.ContentFrame.soundEvent != "" && window.ContentFrame.soundEvent != "<SOUNDEVENT></SOUNDEVENT>")
				window.ContentFrame.document.repeat.src="/als/images/pb/lls/frog.gif";
		}else
		{
			if(window.ContentFrame.soundEvent != "" && soundFlag && window.ContentFrame.soundEvent != "<SOUNDEVENT></SOUNDEVENT>")
			{
				if(window.ContentFrame.document.getElementById("repeat") != null)
					window.ContentFrame.document.repeat.src="/als/images/pb/repeatsound.gif";
				else if(window.ContentFrame.document.getElementById("repeatER") != null)
					window.ContentFrame.document.repeatER.src="/als/images/pb/emergentreader/repeatButton.jpg";
			}else
			{
				if(window.ContentFrame.document.getElementById("repeat") != null)
					window.ContentFrame.document.repeat.src="/als/images/pb/repeatsoundblank.gif";
				else if(window.ContentFrame.document.getElementById("repeatER") != null)
					window.ContentFrame.document.repeatER.src="/als/images/pb/emergentreader/repeatDisabled.jpg";
			}
		}

		if(mediaPlayer == "JavaApplet")
		{
			if((soundFlag || isLLS)  && window.ContentFrame.autoSound && window.ContentFrame.soundEvent != "<SOUNDEVENT></SOUNDEVENT>" && window.ContentFrame.soundEvent != "")
			{
				element.innerHTML = '<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="0" height="0" name="SndApplet" align="middle" vspace="0" hspace="0" codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_3_1_02-win.cab#Version=1,3,1,2"><PARAM name="code" value="SndApplet.class" ><PARAM name="codebase" value="http://204.97.228.48/als/api"><PARAM name="archive" value="sSndApplet.jar"><PARAM name="name" value="SndApplet" ><PARAM name="type" value="application/x-java-applet;jpi-version=1.3.1_02"><PARAM name="scriptable" value="true"><PARAM name="sndPath" value="' + window.ContentFrame.soundEvent + '"><EMBED type="application/x-java-applet;jpi-version=1.3.1_02"  code="SndApplet.class" codebase="http://204.97.228.48/als/api" archive="sSndApplet.jar" NAME = "SndApplet" width=0 height=0 middle=middle vspace=0 hspace=0 sndPath=' + window.ContentFrame.soundEvent + '  scriptable=true pluginspage="http://java.sun.com/j2se/1.3/jre "></EMBED></OBJECT>';
			}
		}else if(mediaPlayer == "QuickTime" || mediaPlayer == "WMP")
		{
			if(soundFlag || isLLS)
			{
				if(window.ContentFrame.autoSound)
				{
					if(window.ContentFrame.document.getElementById("randFeedBack") != null && os == "Mac" &&  navigator.appName.indexOf("Microsoft") != -1)
						return;
					else
						playSound();
				}
			}
			else
			{
				window.ContentFrame.document.repeat.src="/als/images/pb/repeatsoundblank.gif";
			}
		}
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.initializeSound()");
	}
}

function playSound()
{
	try
	{
		//if this function was passed a value, set the soundEvent variable.
		if(soundFlag || localIsLLS)
		{
                        if(localIsLLS && window.ContentFrame.autoSound)
				setPlayingSound(true);

			if(playSound.arguments.length > 0)
				sndtoplay = playSound.arguments[0];
			else
			{
				if(window.ContentFrame.autoSound)
				{
					if(mediaPlayer == "QuickTime")
						sndtoplay = getFirstSoundForQT(window.ContentFrame.soundEvent)
					else 
						sndtoplay = window.ContentFrame.soundEvent;
				}
			}
			if(mediaPlayer == "WMP")
			{
				resetVars();
				var index = sndtoplay.indexOf("|");
				if(index != -1)
					fillArray(sndtoplay);
			}
			if(mediaPlayer == "JavaApplet")
			{
				if(document.applets["SndApplet"] != null && sndtoplay != "")
					document.applets["SndApplet"].playSound(sndtoplay);
				else if(sndtoplay != "")
				{
					element = window.ContentFrame.document.getElementById("playSound");
					element.innerHTML = '<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="0" height="0" name="SndApplet" align="middle" vspace="0" hspace="0" codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_3_1_02-win.cab#Version=1,3,1,2"><PARAM name="code" value="SndApplet.class" ><PARAM name="codebase" value="http://204.97.228.48/als/api"><PARAM name="archive" value="sSndApplet.jar"><PARAM name="name" value="SndApplet" ><PARAM name="type" value="application/x-java-applet;jpi-version=1.3.1_02"><PARAM name="scriptable" value="true"><PARAM name="sndPath" value="' + sndtoplay + '"><EMBED type="application/x-java-applet;jpi-version=1.3.1_02"  code="SndApplet.class" codebase="http://204.97.228.48/als/api" archive="sSndApplet.jar" NAME = "SndApplet" width=0 height=0 middle=middle vspace=0 hspace=0 sndPath=' + sndtoplay + '  scriptable=true pluginspage="http://java.sun.com/j2se/1.3/jre "></EMBED></OBJECT>';
				}
			}else if(mediaPlayer == "QuickTime" || mediaPlayer == "WMP")
				setPlayer();
		}
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.playSound()");
	}
}

function setPlayer()
{
	try
	{
		if(window.parent.frames["macapiframe"] != null)
		{
			if(mediaPlayer == "QuickTime")
				element = window.parent.frames["macapiframe"].document.getElementById("playSound");
			else if(mediaPlayer == "WMP")
				element = window.parent.frames["macapiframe"].document.getElementById("MediaPlayer");
			if(element == null)
				setTimeout('setPlayer()', 25);
			else
			{
				player = element;
				play();
			}
			
		}else
			return;
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.getPlayer()");
	}
	
}

function findQTEnd()
{
	try
	{
		if(window.parent.frames["macapiframe"] != null)
		{
			if(mediaPlayer == "QuickTime")
				element = window.parent.frames["macapiframe"].document.getElementById("QTPlayer");
			if(element == null || element.GetPluginStatus() != "Complete" && element.GetPluginStatus() != null)
				setTimeout('findQTEnd()', 25);
			else
			{
				if(element.GetTime() != element.GetDuration())
					setTimeout('findQTEnd()', 25);
				else if(localIsLLS && window.ContentFrame.autoSound)
					setPlayingSound(false);
			}
		}
		return;
	}catch (e)
	{
		setPlayingSound(false);
	}
}

function play()
{
	try
	{
		if(mediaPlayer == "QuickTime")
		{
			if(sndtoplay != "" && sndtoplay != "<SOUNDEVENT></SOUNDEVENT>")
			{
				if(isSafari && safariVersion >= 312)
				{
					qPlayer=window.parent.frames["macapiframe"].document.getElementById("QTPlayer");
					if(qPlayer != null && window.ContentFrame.qtattributes.length == 0)
					{
						try
						{
							qPlayer.SetURL(sndtoplay);
							qPlayer.Play();
						}catch(a)
						{
							player.innerHTML = '<EMBED id="QTPlayer" name="QTPlayer" SRC="' + sndtoplay + '" width="200" enablejavascript="true" height="200" controller="true" pluginspage="http://www.apple.com/quicktime/download/"autoplay="true"></EMBED>';
						}
					}else
						player.innerHTML = '<EMBED id="QTPlayer" name="QTPlayer" SRC="' + sndtoplay + '" width="200" enablejavascript="true" height="200" controller="true" pluginspage="http://www.apple.com/quicktime/download/"autoplay="true" ' +  window.ContentFrame.qtattributes + ' ></EMBED>';
				}else if(getSpecificBrowserName() == 'Mozilla')
					player.innerHTML = '<EMBED id="QTPlayer" name="QTPlayer" SRC="' + sndtoplay + '" width="200" enablejavascript="true" height="200" controller="true" pluginspage="http://www.apple.com/quicktime/download/"autoplay="true" ' +  window.ContentFrame.qtattributes + ' ></EMBED>';
				else
					player.innerHTML = '<OBJECT id="QTPlayer" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab"><PARAM name="src" value="' + sndtoplay + '"><PARAM name="height" value="2"><PARAM name="width" value="2"><PARAM name="controller" value="true"><PARAM name="pluginspage" value="http://www.apple.com/quicktime/download/"><PARAM name="enablejavascript" value="true"><PARAM name="height" value="200"><PARAM name="width" value="200"><PARAM name="autoplay" value="true">' + window.ContentFrame.qtparams + '<EMBED id="QTPlayer" SRC="' + sndtoplay + '" width="200" enablejavascript="true" height="200" controller="true" pluginspage="http://www.apple.com/quicktime/download/"autoplay="true" ' +  window.ContentFrame.qtattributes + ' ></EMBED></OBJECT>';
				findQTEnd();
			}
		}else if(mediaPlayer == "WMP")
		{
			if(sndtoplay != "" && sndtoplay != "<SOUNDEVENT></SOUNDEVENT>")
			{
				if(sndArray.length < 2)
				{
					player.Open(sndtoplay)
					playWMP();
				}else
					playPlayList();
			}

		}
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.play()");
	}	

}

function playWMP()
{
	try
	{
		if(player != null)
		{
			if(player.OpenState == 6)
			{
				try
				{
					player.play();
				}catch(e)
				{
					//It seems that a error is thrown here when right before the sound is played the user
					//clicks the next, previous, or stop button. Just ignore the error for trying to play
					//the sound because we don't want to play the sound anyway because they are leaving the
					//page.
				}
			}else
				setTimeout('playWMP()', 25);
		}
		
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.playWMP()");
	}
}

function playPlayList()
{
	try
	{
		if(sndArray.length > 1)
		{
			if(sndArray.length > sndIndex)
			{
				player.Open(sndArray[sndIndex])
				playWMP();
				sndIndex++;
			}
		}
		if(localIsLLS && window.ContentFrame.autoSound)
			setPlayingSound(false);
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.playPlayList()");
	}
}

function audioEnded()
{
	try
	{
		if(mediaPlayer == "WMP")
			playPlayList()
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.audioEnded()");
	}
}

function resetVars()
{
	try
	{
		sndArray = new Array(1);
		sndIndex = 0;
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.retsetVars()");
	}
}

function disableSound()
{
	try
	{
		if(mediaPlayer == "JavaApplet")
		{
			if(document.applets["SndApplet"])
				document.applets["SndApplet"].stop();
		}else if(mediaPlayer == "QuickTime")
		{
			if(window.parent.frames["macapiframe"] != null)
			{
				qPlayer=window.parent.frames["macapiframe"].document.getElementById("QTPlayer");
				try
				{
					qPlayer.Stop()
				}catch(e)
				{}
				if(!isSafari)
				{
					element=window.parent.frames["macapiframe"].document.getElementById("playSound");
					element.innerHTML = "&nbsp;";
				}
			}
		}else if(mediaPlayer == "WMP")
		{
			if(player != null && player.playState != undefined && player.openState != undefined)
				player.stop();
		}
		
	}catch (e)
 	{
 		errorHandler(e.message, "" ,"" , e.name, "alssounds.disableSound()");
	}
}

function getFirstSoundForQT(soundString)
{
	try
	{
		var index = soundString.indexOf("|");
		if(index != -1)
			soundString = soundString.substring(0, index);
		return soundString;
	}catch (e)
 	{
 		errorHandler(e.message, "" ,"" , e.name, "alssounds.getFirstSoundForQT()");
	}
}

function fillArray(multipleSounds)
{
	try
	{
		var index = 0;
		var done = false;
		var begin = 0
		var end
		var len = multipleSounds.length

		while(!done)
		{
			end = multipleSounds.indexOf("|", begin);
			if(end > -1)
			{
				sndArray[index] = multipleSounds.substring(begin, end);
				begin = end + 1;
			}else if(begin < len)
			{
				sndArray[index] = multipleSounds.substring(begin, len);
				begin = len
			}else
				done = true;
			index++;
		}
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.fillArray()");
	}
}

function redirectCheck(pluginFound, redirectURL, redirectIfFound)
{
	try
	{
		// check for redirection
		if( redirectURL && ((pluginFound && redirectIfFound) ||	(!pluginFound && !redirectIfFound)) )
		{
			// go away
			window.location = redirectURL;
			return pluginFound;
		}else
			return pluginFound;
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.redirectCheck()");
	}
}

function canDetectPlugins()
{
	try
	{
		if(detectableWithVB || (navigator.plugins && navigator.plugins.length > 0))
			return true;
		else
			return false;
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.canDetectPlugins()");
	}
}

function detectFlash(redirectURL, redirectIfFound)
{
	try
	{
		pluginFound = detectPlugin('Shockwave','Flash');
		// if not found, try to detect with VisualBasic
		if(!pluginFound && detectableWithVB)
			pluginFound = detectActiveXControl('ShockwaveFlash.ShockwaveFlash.1');

		return redirectCheck(pluginFound, redirectURL, redirectIfFound);
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.detectFlash()");
	}
}

function detectDirector(redirectURL, redirectIfFound)
{
	try
	{
		pluginFound = detectPlugin('Shockwave','Director');
		// if not found, try to detect with VisualBasic
		if(!pluginFound && detectableWithVB)
			pluginFound = detectActiveXControl('SWCtl.SWCtl.1');

		return redirectCheck(pluginFound, redirectURL, redirectIfFound);
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.detectDirector()");
	}
}

function detectQuickTime(redirectURL, redirectIfFound)
{
	try
	{
		pluginFound = detectPlugin('QuickTime');
		// if not found, try to detect with VisualBasic
		if(!pluginFound && detectableWithVB)
			pluginFound = detectQuickTimeActiveXControl();
		if(pluginFound && qtVer < 5)
			return false;
		return redirectCheck(pluginFound, redirectURL, redirectIfFound);
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.detectQuickTime()");
	}
}

function detectReal(redirectURL, redirectIfFound)
{
	try
	{
		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);
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.detectReal()");
	}
}

function detectWindowsMedia(redirectURL, redirectIfFound)
{
	try
	{
		pluginFound = detectPlugin('Windows Media');
		// if not found, try to detect with VisualBasic
		if(!pluginFound && detectableWithVB)
			pluginFound = detectActiveXControl('MediaPlayer.MediaPlayer.1');
		//return false if they have the WMP plug-in but it's not at least ver 6.4
		if(getBrowserName() == "Internet Explorer")
		{
			if(pluginFound && !hasWMP64)
				return false
		}

		return redirectCheck(pluginFound, redirectURL, redirectIfFound);
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.detectWindowsMedia()");
	}
}

function detectPlugin()
{
      try
      {
	    // 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
			try
			{
				if (navigator.plugins[pluginsArrayCounter].name.indexOf("QuickTime") > -1) 
					qtVer = parseFloat(navigator.plugins[pluginsArrayCounter].name.substring(18));
			}catch(e)
			{
				return false;
			}
			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;
	}catch (e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.detectPlugin()");
	}
}

function alssoundIsLoaded()
{
	return true;
}

function getSafariVersion()
{
	try
	{
		var version = 0;
		var verStr = navigator.appVersion
		var index = verStr.indexOf("Safari/")
		if(index > -1)
		{
			var index2 = verStr.indexOf(".", index)
			version = verStr.substring(index + 7, index2)
		}
		return version;
	}catch(e)
	{
		errorHandler(e.message, "" ,"" , e.name, "alssounds.getSafariVersion()");
	}
	
}
