
// global html audio player vars
var audioPlayerVars = {
        currentPosition: 0,
        currentDuration: false,
        currentSongIndex: false,
        currentItem: -1,
        playlistElementId: false,
        player: false,
        loaded: false
    };


soundManager.url = '/_swf/'; // directory where SM2 .SWFs live

soundManager.debugMode = false;


whileloading = function ()
{    
	//soundManager._writeDebug('sound '+this.sID+' loading, '+this.bytesLoaded+' of '+this.bytesTotal);	
	
	audioPlayerVars.currentLoaded = this.bytesLoaded; 
	audioPlayerVars.currentTotal  = this.bytesTotal;

	var loadedPercentage =  percentComplete(audioPlayerVars.currentLoaded, audioPlayerVars.currentTotal);
	var totalLoaded      =  document.getElementById("loaded_progress");

	totalLoaded.style.width = loadedPercentage + '%';        
};

whileplaying = function ()
{    
    audioPlayerVars.currentPosition = (this.position / 1000); 
    
    if (this.bytesLoaded == this.bytesTotal)
    {
        audioPlayerVars.currentDuration = (this.duration / 1000);
    }
    else
    {
        audioPlayerVars.currentDuration = (this.durationEstimate / 1000);
    }
        
    // progress bar
    if ($('#' + audioPlayerVars.playlistElementId + ' #played_progress').length > 0)
    {   
        var playedPercentage =  percentComplete(audioPlayerVars.currentPosition, audioPlayerVars.currentDuration);

        $('#' + audioPlayerVars.playlistElementId + ' #played_progress').width(playedPercentage + '%');
    }
    
    // time display
    if ($('#' + audioPlayerVars.playlistElementId + ' #time_elapsed').length > 0)
    {    
        $('#' + audioPlayerVars.playlistElementId + ' #time_elapsed').html(formatTime(audioPlayerVars.currentPosition));
    }
};

soundManager.onload = function() 
{    
	audioPlayerVars.loaded = true;
};



onfinish = function ()
{
    selectNextSong();
};

soundManager.defaultOptions = {
  autoLoad: false,      // enable automatic loading (otherwise .load() will call with .play())
  autoPlay: false,      // enable playing of file ASAP (much faster if "stream" is true)
  multiShot: false,      // let sounds "restart" or "chorus" when played multiple times..
  onid3: null,          // callback function for "ID3 data is added/available"
  onload: null,         // callback function for "load finished"
  onstop: null,         // callback for "user stop"
  onfinish: onfinish,       // callback function for "sound finished playing"
  onbeforefinish: null, // callback for "before sound finished playing (at [time])"
  onbeforefinishtime: 5000,    // offset (milliseconds) from sound end, call beforefinish..
  onbeforefinishcomplete: null,// function to call when said sound finishes playing
  onjustbeforefinish: null,    // callback for [n] msec before end of current sound
  onjustbeforefinishtime: 200, // if unused, set to 0 (or null handler), event will not fire.
  onpause: null,        // callback for "pause"
  onplay: null,         // callback for "play" start
  onresume: null,       // callback for "resume" (pause toggle)
  position: null,       // offset (milliseconds) to seek to within downloaded sound.
  pan: 0,               // "pan" settings, left-to-right, -100 to 100
  stream: true,         // allows playing before entire file has loaded (recommended)
  volume: 100,          // self-explanatory. 0-100, the latter being the max.
  whileloading: whileloading,   // callback function for updating progress (X of Y bytes received)
  whileplaying: whileplaying,   // callback during play (position update)
  isMovieStar: null,    // "MovieStar" MPEG4 audio/video mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
  usePeakData: false,   // enable left/right channel peak (level) data
  useWaveformData:false,// enable sound spectrum (raw waveform data) - WARNING: May set CPUs on fire.
  useEQData: false,     // enable sound EQ (frequency spectrum data) - WARNING: Also CPU-intensive.
  onmetadata: null,     // callback for when video width/height etc. are received
  useVideo: false       // if loading movieStar content, whether to show video
};


function selectCurrentSong(elementId)
{
    if (audioPlayerVars.currentItem < 1 || elementId != audioPlayerVars.playlistElementId)
    {        
        $('#' + elementId + ' a.track_name:first').click();
    }
    else
    {    
        $('#' + audioPlayerVars.playlistElementId + ' #song_' + audioPlayerVars.currentItem + ' a.track_name').click();
    }
    
    return true;
};

function selectNextSong(elementId)
{
    if (elementId !== undefined && elementId != audioPlayerVars.playlistElementId)
    {
        return selectCurrentSong(elementId);
    }

    if ($('#' + audioPlayerVars.playlistElementId + ' #song_' + audioPlayerVars.currentItem).next().length > 0)
    {
        $('#' + audioPlayerVars.playlistElementId + ' #song_' + audioPlayerVars.currentItem).next().find('a.track_name').click();
    }
};

function selectPrevSong(elementId)
{
    if (elementId != audioPlayerVars.playlistElementId)
    {        
        return selectCurrentSong(elementId);
    }

    if ($('#' + audioPlayerVars.playlistElementId + ' #song_' + audioPlayerVars.currentItem).prev().length > 0)
    {        
        $('#' + audioPlayerVars.playlistElementId + ' #song_' + audioPlayerVars.currentItem).prev().find('a.track_name').click();
    }
};

// ALL Players
soundManager.onerror = function() 
{
    /*
    var browser = browserDetect();
    
     window.setTimeout(
        function() 
        { 
            $.post('http://www.purevolume.com/_test/_new_player/errors.php', {
                                                                      v: '2.1',
                                                                      version: getFlashVersion(), 
                                                                      browserVer: browser.version,
                                                                      browserOS: browser.OS,
                                                                      browser: browser.browser,
                                                                      errors: 'they are ' + jsErrors
                                                                      });
        }, 5000);
    */
    soundManager.reboot();
};


function clearPreviousSong()
{
    // stop all songs
    soundManager.stopAll();
    
    if (audioPlayerVars.currentItem != -1)
    {
        //alert(audioPlayerVars.player.sID +  ' ' +  audioPlayerVars.player.bytesTotal);
    
        soundManager.destroySound(audioPlayerVars.currentItem); 
    }
    

    // reset all variables
    audioPlayerVars.currentItem       = -1;
    audioPlayerVars.playlistElementId = false;
    audioPlayerVars.currentPosition   = 0; 
    audioPlayerVars.currentDuration   = false;
    audioPlayerVars.player            = false;
    
    // reset all icons
    $('.paused').removeClass('paused');
    $('.playlist_pause_button').removeClass('playlist_pause_button');

};

function waitForLoaded(js)
{
    if (audioPlayerVars.loaded == true)
    {
        return true;
    }

    else
    {    
        // wait a second
        setTimeout(js, 1000);
        
        return false;
    }
};

// choose song to play
function selectSong(id, elementId)
{    
    var js = "selectSong('" + id + "', '" + elementId + "');";
    
    if (waitForLoaded(js) == false)
    {
        return false;
    }

    // if we have a new song, instaniate it
    if (audioPlayerVars.currentItem != id)
    {
        clearPreviousSong();
    
        audioPlayerVars.currentItem       = id;
        audioPlayerVars.playlistElementId = elementId;
                
        soundManager.createSound({id: audioPlayerVars.currentItem});
            
        audioPlayerVars.player = soundManager.getSoundById(id);
                
        soundManager.authorizeSong(id, false);
                
        $('#' + audioPlayerVars.playlistElementId + ' #song_' + id).show();
                
        $('#' + audioPlayerVars.playlistElementId + ' #play_button').addClass('paused');
        $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' .playlist_play_button').addClass('playlist_pause_button');
        
        var artistName = $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' #track_meta_artist_name').html();
        var albumName  = $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' #track_meta_album_name').html();
        var songName   = $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' #track_meta_song_name').html();
        var albumLink  = $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' #track_meta_album_link').html();
        var albumImage = $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' #track_meta_album_image').html();
        var artistLink = $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' #track_meta_artist_link').html();
        
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container').show();
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_album_link').attr('href', albumLink);
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_album_image').attr('src', albumImage);
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_artist_name').html(artistName);
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_artist_name').attr('href', artistLink);
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_album_name').html(albumName);
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_album_name').attr('href', albumLink);
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_song_name').html(songName);
        $('#' + audioPlayerVars.playlistElementId + ' #track_meta_container #track_meta_song_name').attr('href', artistLink);
        
        //alert('selectSong id=' + id + ' ,elementId=' + elementId);
    }
    
    // if this is the current song, toggle play / pause
    else
    {
    
        if (audioPlayerVars.player.readyState != 1 && audioPlayerVars.player.readyState != 3)
        {
           return false;
        }
    
        else if (audioPlayerVars.player.paused) 
    	{ 		
            $('#' + audioPlayerVars.playlistElementId + ' #play_button').addClass('paused');
            $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' .playlist_play_button').addClass('playlist_pause_button');
    	        
    	}
    	else
    	{
            $('#' + audioPlayerVars.playlistElementId + ' #play_button').removeClass('paused');		
            $('#' + audioPlayerVars.playlistElementId + ' #song_' + id + ' .playlist_play_button').removeClass('playlist_pause_button');
    	}
        
        
        
        audioPlayerVars.player.togglePause();
    }
};


// skip to the part of the song the user has selected
function seek(x)
{
    //alert('seek');

    if (audioPlayerVars.currentDuration == false)
    {
        return false;
    }

    var totalWidth = $('#' + audioPlayerVars.playlistElementId + ' div#total_progress').width();
    var containerX = $('#' + audioPlayerVars.playlistElementId + ' div#total_progress').offset().left;
    var percentage = (x - containerX) / totalWidth;

    var position   = audioPlayerVars.currentDuration * 1000 * percentage;

    //alert('x: ' + x + ' currentDuration: ' + currentDuration + ' percentage: ' + percentage);

    audioPlayerVars.player.setPosition(position); 
};


// calculate the percentage we've gone through
function percentComplete(position, duration)
{
    return (position / duration) * 100;
};



function playSong(id, newUrl)
{
    //alert('trying to play id: ' + id + ' url: ' + newUrl);

	// play & override sound object with new URL
	audioPlayerVars.player.play({id: id, url: newUrl});	
};


function formatTime(time)
{
	var sec = Math.round(time % 60);

	if (sec < 10)
	{
		sec = "0" + sec;
	}
	
	var min = Math.floor(time / 60);

	return min + ":" + sec;
};

// show next X results in the playlist
function showNext(elementIdentifier, amount, viewMoreLink)
{	
	amount = $(elementIdentifier + ':visible').length + amount;
	
	$(elementIdentifier + ':lt(' + amount + ')').show();
	
	// if no more results, hide the View More button
	if ($(elementIdentifier + ':hidden').length < 1)
	{
		$(viewMoreLink).hide();
	}
};