function mp3Ready()
{
	mp3 = swfobject.getObjectById("mp3player"); 
	if (mp3 != null) {
		mp3.init(BASEPATH);
		
		setTimeout(function() { mp3Play(); }, 3000);
	}
}

var progressIntervalID;	
var trackProgress = 0; /* percent */
var trackLength = 0; /* ms */
var trackTitle = "";
var soundVolume = 0.70;
var isPlaying = false;
var userPausedOnce = false;

function mp3tdlProgress(percent, playing)
{
	if ((percent > 10) && (!playing) && (!userPausedOnce)) // start playing at 10%
		mp3Play();
		
	$("#download-progress").css("width", percent + "%");
}

function mp3tProgress()
{
	if (isPlaying) {
		var pos = mp3.position();	
		trackProgress = pos;
		$("#track-progress").css("width", pos + "%");
		
		if (pos == 100) {
			isPlaying = false;
			checkPlayPauseButton();	
		}
	}
}

function mp3OnPlay(title, length)
{
	trackTitle = title;
	trackLength = length;
	
	$("#mp3-track-id").html(title);
	isPlaying = true;
	checkPlayPauseButton()
}

function mp3Play(pos)
{
	if (pos != undefined) {
		mp3.search(pos);
	}
	else
		mp3.doPlay();
		
	mp3SetVolume(soundVolume);
	progressIntervalID = setInterval(mp3tProgress, 500);
	checkPlayPauseButton()
}

function mp3Pause()
{
	userPausedOnce = true;
	isPlaying = false;
	clearInterval(progressIntervalID);
	mp3.pause();
	checkPlayPauseButton()
}		

function mp3Next()
{
	mp3.next();
	isPlaying = true;
	checkPlayPauseButton()
}

function mp3Prev()
{
	if (trackProgress > 2)
		mp3Play(0);
	else
		mp3.previous();
		
	isPlaying = true;
	checkPlayPauseButton()
}

function mp3SetVolume(volume)
{
	mp3.volume(volume);	
}

function mp3ChangeVolume(value)
{
	soundVolume += value;
	
	if (soundVolume > 1)
		soundVolume = 1;
	else if (soundVolume < 0)
		soundVolume = 0;	
		
	mp3SetVolume(soundVolume);
}

function checkPlayPauseButton()
{
	if (isPlaying) {
		$("#play-pause").removeClass("play").addClass("pause");	
	} else {
		$("#play-pause").removeClass("pause").addClass("play");	
	}
}

function mp3PlayPause()
{
	if (isPlaying)
		mp3Pause();
	else
		mp3Play();	
}

$(document).ready(function(e) {	
	$("#mp3-progress-bar").click(function(e) {
		var x = e.pageX - this.offsetLeft;
		var pos = Math.round((x / parseInt($(this).css("width"))) * 100);
		mp3Play(pos);
	});
});
