/* ---------------------------------------------------------------------------------------------------------
Cool Javascript MP3 Playback in Web Page with Custom Controls
Version 1.2b By Jeff Baker, Created October 12, 2007 Copyright 2007 by Jeff Baker, www.seabreezecomputers.com
   --------------------------------------------------------------------------------------------------------- */
var ObjPlayer = null;
var TimerVolume; // for volume timer
var TimerTrackTime; // for Track time display timer
var TimerFastReverse; // used for FastReverse in media player
var FadeOut = 0; // 0 = no Fade out when stopping or changing TrackList
                  // change to FadeOut = 1 for Fade volume between TrackList or you can use the Fade out button
//var TrackList = new Array("Images/LaSerenissima64Low.mp3"); // will hold the playlist of TrackList
var TrackList = new Array("Images/NewSound.mp3");
var Browser = GetBrowserType();
var CurrentTrack = 0;
var TrackTitle = "NA";
var TrackArtist = "NA";
var TrackRate = 1;
var TrackTime = "NA";
var TrackDuration = "NA";
var TrackStatus = "NA";
var TrackScale = "NA";          // used for quicktime
var TrackBufferState = "NA";  // used for media player

// Make a DIV to hold the player and place it off the screen so that we don't see it
document.write("<DIV ID='SoundPlayer' style='position:absolute;left:-1000px;top:-1000px'></DIV>");
InitSoundControl();

function InitSoundControl()
{
    ObjPlayer = document.getElementById('SoundPlayer');
	if (ObjPlayer == null || ObjPlayer == undefined)
	{
		setTimeout('InitSoundControl()', 500);
	}
}

function TrackLoad(SourceFile)
{
    if (Browser == "MSIE" || Browser == "Netscape")
    {
        ObjPlayer.innerHTML = 
            "<object "
                + "id='sound' " 
                + "classid = 'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6' "
                + "codebase = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701' "
                + "standby = 'Loading Microsoft® Windows® Media Player components...' "  
                + "type = 'application/x-oleobject width='160' height='144'> "                
                + "<param name = 'url' value='" + SourceFile + "'\/> "      
                + "<param name = 'volume' value='100' \/>"            
                + "<embed "
                    + "type='application/x-mplayer2' " 
                    + "src='" + SourceFile + "' " 
                    + "classid = 'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6' "
                    + "pluginspage = 'http://www.microsoft.com/Windows/MediaPlayer/' "
                    + "url = '" + SourceFile + "' " 
                    + "volume = '100' width = '160' height='144'> "               
                + "<\/embed>"
            + "<\/object>";
    }
    else // if Safari or Firefox, then Load Quicktime controls
    {
        ObjPlayer.innerHTML = '<object '
+ 'classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" '
+ 'width="160" height="144" id="sound"'
+ 'style="position:absolute;left:-1000px;top:-1000px"'
+ 'codebase="http://www.apple.com/qtactivex/qtplugin.cab">'
+ '<param name="SRC" value="'+SourceFile+'">'
+ '<param name="AUTOPLAY" value="true">'
+ '<param name="CONTROLLER" value="false">'
+ '<param name="VOLUME" value="100">'
+ '<param name="ENABLEJAVASCRIPT" value="true">'
+ '<param name="TYPE" value="audio/wav">'
+ '<embed classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"'
+ 'name="sound"'
+ 'id="sound"'
+ 'src="'+SourceFile+'"'
+ 'pluginspage="http://www.apple.com/quicktime/download/"'
+ 'volume="100"'
+ 'enablejavascript="true" '
+ 'type="audio/wav" '
+ 'height="16" '
+ 'width="200"'
+ 'style="position:absolute;left:-1000px;top:-1000px"'
+ 'autostart="true"'
+ '> </embed>'
+ '</object>'   ;    
         
//            "<object "
//                + "id = 'sound' " 
//                + "name = 'sound' "
//                + "classid = 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' "
//                + "width = '160' height = '144' "
//                + "style = 'position:absolute;left:-1000px;top:-1000px' "
//                + "codebase = 'http://www.apple.com/qtactivex/qtplugin.cab'> "
//                + "<param name = 'AUTOPLAY' value = 'true' \/>"
//                + "<param name = 'CONTROLLER' value = 'false' \/>"
//                + "<param name = 'VOLUME' value = '100' \/>"
//                + "<param name = 'ENABLEJAVASCRIPT' value = 'true' \/>"
//                + "<param name = 'TYPE' value = 'audio/wav' \/>"
//                + "<param name = 'SRC' value = '" + SourceFile + "' \/>"
//                + "<embed "
//                    + "src = '" + SourceFile + "'" 
//                    + "classid = 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B'" 
//                    + "pluginspage = 'http://www.apple.com/quicktime/download/'"
//                    + "volume = '100'" 
//                    + "enablejavascript = 'true' "
//                    + "type = 'audio/wav' "
//                    + "height = '16' "
//                    + "width = '200'"
//                    + "style = 'position:absolute;left:-1000px;top:-1000px'"
//                    + "autostart = 'true'>"
//                + "</embed>"
//            + "</object>";
//    
    }
}

function TrackPlay()
{
	// Wait if either ObjPlayer is not created Or ObjPlayer Created but has something playing in it
	if (ObjPlayer == null || ObjPlayer.innerHTML != "")
	{
		setTimeout('TrackPlay()', 500);
	}
	else
	{
		TrackLoad(TrackList[CurrentTrack]);
    }
}

function TrackStop()
{
	if (document.sound)
	{
	    // Call stop function if available in quicktime player
	    if (typeof document.sound.Stop == "function")
	    {
		    document.sound.Stop();
	    }
	    
	    // Call stop function if available in Media player
	    if (typeof document.sound.controls == "object")
	    {
		    document.sound.controls.stop();
	    }
	}
	//clearTimeout(GetTrackDetails);    // Stop getting track info
	ObjPlayer.innerHTML = "";           // Wipe out contents of player DIV
}

function TrackPause()
{
	if (ObjPlayer.innerHTML == "") return;
	if (Browser == "MSIE" || Browser == "Netscape")
    { 	
	    if (document.sound.controls)
	    {
	        document.sound.controls.pause();
	        return;
	    }
    }
    else // If Firefox or Safari then use Quicktime Stop (Pause)	
    {
	    // Check to see if Stop is a function, If not then return, So far Safari does not support Stop
	    if (typeof document.embeds["sound"].Stop == "function")
	    {
	        document.embeds["sound"].Stop();
            return;
	    }
    }
    alert("This browser does not support pause control.");
}

function TrackResume()
{
	if (ObjPlayer.innerHTML == "") return;
	if (Browser == "MSIE" || Browser == "Netscape")
    { 	
	    if (document.sound.controls)
	    {
	        document.sound.controls.play();
	        return;
	    }
    }
    else // If Firefox or Safari then use Quicktime Stop (Pause)	
    {
	    // Check to see if Stop is a function, If not then return, So far Safari does not support Stop
	    if (typeof document.embeds["sound"].Stop == "function")
	    {
	        document.embeds["sound"].Play();
            return;
	    }
    }
    alert("This browser does not support pause control.");
}

function GoToPrevTrack()
{
	if (ObjPlayer.innerHTML != "") StopTrack(); // stop the current Track if playing
	if (TrackList.length > 0)
	{ 
	    CurrentTrack = ((CurrentTrack < 1) ? TrackList.length - 1 : CurrentTrack - 1);
	    PlayTrack(TrackList[CurrentTrack]);
    }
}

function GoToNextTrack(Direction)
{
	if (ObjPlayer.innerHTML != "") StopTrack(); // stop the current Track if playing
	if (TrackList.length > 0)
	{ 
	    CurrentTrack = ((CurrentTrack > TrackList.length - 1) ? 0 : CurrentTrack + 1);
	    PlayTrack(TrackList[CurrentTrack]);
    }
}

// functions to be checked later on
function shuffle()
{
	//Array elements now scrambled
	TrackList.sort(function() { return 0.5 - Math.random() }); 
	NextTrack(true);
}

function volume(Direction)
{
	var CurrentVolume;
	
	// if a Track is not playing then just return
	if (ObjPlayer.innerHTML == '') return;

	// if IE or Netscape then Media Player Volume Controls
	if (Browser == "MSIE" || Browser == "Netscape")
    { 
	    if (!document.sound.settings)
	    {
		    alert('This browser does not support volume control.');
		    return;
	    }
	    CurrentVolume = document.sound.settings.volume;
	    if (Direction == 1 || Direction == 5) // left or down
	    {	
		    document.sound.settings.volume = CurrentVolume - 10;
		    if (Direction == 1)
		    {
			    TimerVolume = setTimeout('volume(' + Direction + ')', 100);
	        }
	    }
	    else if (Direction == 2) // right or up
	    {
		    document.sound.settings.volume = CurrentVolume+10;
		    TimerVolume = setTimeout('volume(' + Direction + ')', 100);
	    }
	    else if (Direction == 3) // stop changing volume
	    {
		    clearTimeout(TimerVolume);
	    }
    }
    else // if Firefox or Safari then Quicktime volume controls
    {
	    // Check if GetVolume is a function; If not, return, So far Safari does not support GetVolume
	    if (typeof document.embeds['sound'].GetVolume != "function")
	    {
		    alert("This browser does not support volume control.");
		    return;
	    }
	    CurrentVolume = document.embeds['sound'].GetVolume();
	    if (Direction == 1 || Direction == 5) // left or down
	    {	
		    //document.sound.settings.volume = CurrentVolume-10;
		    document.embeds['sound'].SetVolume(CurrentVolume - 10);
		    if (Direction == 1) 
		    {
			    TimerVolume = setTimeout('volume(' + Direction + ')', 100);
		    }
	    }
	    else if (Direction == 2) // right or up
	    {
		    document.embeds['sound'].SetVolume(CurrentVolume + 10);
		    TimerVolume = setTimeout('volume(' + Direction + ')', 100);
	    }
	    else if (Direction == 3) // stop changing volume
	    {
		    clearTimeout(TimerVolume);
	    }
    	
    }	
	return CurrentVolume;
}

function GetTrack()
{
    TrackTitle = "NA";
    TrackArtist = "NA";
    TrackRate = 1;
    TrackTime = "NA";
    TrackDuration = "NA";
    TrackStatus = "NA";
    TrackScale = "NA";          // used for quicktime
    TrackBufferState = "NA";  // used for media player
    
	var mins;           // used for quicktime
	var secs;           // used for quicktime
	
    if (ObjPlayer.innerHTML != "")
	{
	    // if IE or Netscape then Media Player 
	    if (Browser == "MSIE" || Browser == "Netscape")
	    {
		    TrackStatus = document.sound.playState;
		    TrackBufferState = document.sound.network.bufferingProgress; // 3 = playing; 1 = stopped
		    TrackTime = document.sound.controls.currentPositionString;
		    TrackDuration = document.sound.currentMedia.durationString;
	        TrackTitle = document.sound.currentMedia.getItemInfo('Title');
	        TrackArtist = document.sound.currentMedia.getItemInfo('Author');
	    }	
	    else  // Firefox or Safari
	    {
    	    TrackStatus = document.embeds['sound'].GetPluginStatus();
	        TrackTime = document.embeds['sound'].GetTime();
	        TrackDuration = document.embeds['sound'].GetDuration();
	        TrackScale = document.embeds['sound'].GetTimeScale();
	        TrackTime = Math.floor(TrackTime*(1/TrackScale));           // convert to seconds
	        TrackDuration = Math.floor(TrackDuration*(1/TrackScale));   // converts to seconds
	        // convert seconds into mm:ss
	        mins = Math.floor(TrackTime / 60);
	        secs = TrackTime - (mins * 60);	
	        TrackTime = mins + ':' + secs;
	        mins = Math.floor(TrackDuration / 60);
	        secs = TrackDuration - (mins * 60);	
	        TrackDuration = mins + ':' + secs;
    	    
		    /* Quicktime has a problem of not being able to Load the Track name and artist until most of the Track is
		    loaded, so if Track_title == null for a while in such cases */
		    TrackTitle = document.sound.GetUserData('©nam');
		    TrackArtist = document.sound.GetUserData('©ART');	
	    }
	}
    return {
                Title: TrackTitle,  
                Artist: TrackArtist, 
                Rate: TrackRate, 
                Time: TrackTime, 
                Duration: TrackDuration, 
                Status: TrackStatus, 
                Scale: TrackScale, 
                BufferState: TrackBufferState
            };
}

function FastForward()
{
	// if Track is stopped then just return
	if (ObjPlayer.innerHTML == '') return;
	
	// Note: Only WMV and ASF files can go backwards with -.5 to -5
	// if IE or Netscape then Media Player 
	if (Browser == "MSIE" || Browser == "Netscape")
	{	
	    if (document.sound.settings.isAvailable('Rate'))
	    {
		    TrackRate = parseFloat(document.sound.settings.rate);
		    TrackRate = (((TrackRate == 1) || (TrackRate == 2)) ? TrackRate + 1 : 1);
		    document.sound.settings.rate = TrackRate;    
	    }
	    else
	    {	
		    alert("This browser does not support fast forward.");
	    }
	}
	else // Firefox so quicktime
	{
		if (typeof document.sound.GetVolume != 'function')
		{
		    alert('This browser does not support fast forward.');
		    return ; // done 
		}
		TrackRate = document.sound.GetRate() + 1;
	    TrackRate = (((TrackRate < 1) || (TrackRate > 3)) ? 1 : TrackRate);
		document.sound.SetRate(TrackRate);
	}
}

function FastReverse(rewinding)
{
	var current_pos;
	clearTimeout(TimerFastReverse);
	// Note: Only WMV and ASF files can go backwards with -.5 to -5
	// in Media Player.  So instead of using controls.fastReverse
	// or settings.rate for reverse, I use controls.currentPosition
	// and make it go back two seconds.
	// var rewinding is used for media player with the setTimeout
	// because there is not a real rewind with MP3s in WMP
	
	// if Track is stopped then just return
	if (ObjPlayer.innerHTML == '') return;
	
	// if IE or Netscape then Media Player 
	if (Browser == "MSIE" || Browser == "Netscape")
	{
	    current_pos = document.sound.controls.currentPosition;
	    if (document.getElementById('speed').innerHTML == '1X' && rewinding != 1)
		    TrackRate = -2;
	    else if (document.getElementById('speed').innerHTML == '-2X' && rewinding != 1)
		    TrackRate = -3;
	    else if (rewinding != 1)
		    TrackRate = 1;
	    else 
		    TrackRate = parseFloat(document.getElementById('speed').innerHTML);

	    current_pos = current_pos + TrackRate;
		if (TrackRate < 1)
		{	
		    document.sound.controls.currentPosition = current_pos;
		    TimerFastReverse = setTimeout('FastReverse(1);', 1000);
		}
	}
	else // Firefox so quicktime
	{
		if (typeof document.sound.GetVolume != 'function')
		{
			alert('This browser does not support rewind.');
		    return ; // done 
		}
		TrackRate = document.sound.GetRate();
		if (TrackRate == 1)
			TrackRate = -2;
		else if (TrackRate == -2)
			TrackRate = -3;
		else
			TrackRate = 1;
	
		document.sound.SetRate(TrackRate);
	}
	
	document.getElementById('speed').innerHTML = TrackRate
		+ 'X';
	
}

//Verified Functions
function GetBrowserType()
{
	var BrowserName = navigator.userAgent;
	// Check for Opera first; B'Cos agent variable has MSIE for Opera also. 
	if (BrowserName.indexOf("Opera")!= -1)          BrowserName = "Opera";
	else if (BrowserName.indexOf("Firefox")!= -1)   BrowserName = "Firefox";
	else if (BrowserName.indexOf("MSIE")!= -1)      BrowserName = "MSIE";
	else if (BrowserName.indexOf("Netscape")!= -1)  BrowserName = "Netscape";
	else if (BrowserName.indexOf("Safari")!= -1)    BrowserName = "Safari";
	return BrowserName;
}

