/**
 * @author tompa
 */
var playerListener = new Object();
var player = new Object();

/**
 * Initialisation
 */
playerListener.onInit = function(){
//    console.log("onInit");
    this.position = 0;
};
/**
 * Update
 */
playerListener.onUpdate = function(){
	try {
//        console.log("onUpdate");

        var isPlaying = (this.isPlaying == "true");
        if (isPlaying) {
            $("#player-play").hide();
            $("#player-pause").show();
        } else {
            $("#player-play").show();
            $("#player-pause").hide();
        }

        if (this.duration > 0 && this.position > this.duration - 1000&& this.bytesPercent == 100) {
            player.forward();
        }

        var sec = Math.round(this.position/1000);
        var min = Math.floor(sec/60);
        sec = sec - min * 60;
        if(sec < 10) sec = "0" + sec;
        $("#player-time").html(min + ":" + sec);

        $("#player-progress2").width(Math.round(100 * this.position / this.duration) + "%");
    } catch (e) {
        //console.log(e);
    }
};

player.getFlashObject = function(){
    return document.getElementById("mp3player");
}

player.play = function(){
//    console.log("play");
    if (playerListener.position == 0 || this.force) {
		this.force = false;
        this.getFlashObject().SetVariable("method:setUrl", this.url);
    }
	    
	this.getFlashObject().SetVariable("enabled", "true");
    this.getFlashObject().SetVariable("method:play", "");
}

player.pause = function(){
    this.getFlashObject().SetVariable("method:pause", "");
}

player.stop = function(){
    this.getFlashObject().SetVariable("method:stop", "");
}

player.back = function(){
	var $nxt = $('#playlist .current').prev().children('a');
	if(!$nxt) return;
	this.url = $nxt.attr("href");
	$("#playlist li").removeClass("current");
	$nxt.parent().addClass("current");
	this.stop();
	this.force = true;
	$('#player-info').html($nxt.html());
	this.play();
}

player.forward = function(){
	var $nxt = $('#playlist .current').next().children('a');
	if(!$nxt) return;
	this.url = $nxt.attr("href");
	$("#playlist li").removeClass("current");
	$nxt.parent().addClass("current");
	this.stop();
	this.force = true;
	$('#player-info').html($nxt.html());
	this.play();
}

player.playlist = function(){
	$("#playlist").slideToggle(400);
}

player.setPosition = function(){}
player.setVolume = function(){}
player.url = "mp3/tjm-soh-01-de_naglar_fast_mig_pa_korset.mp3";
player.force = false;

player.initialized = false;

function initMp3Player() {
    if(player.initialized) return;
    player.initialized = true;

	$('#musicplayer .button a').click(function(){		
		eval('player.'+ this.href.split("#")[1] + '()');
		return false;
	});
	$('#playlist a').click(function(){		
		player.stop();
		player.url = this.href;
		player.force = true;
		$("#playlist li").removeClass("current");
		$(this).parent().addClass("current");
		$('#player-info').html($(this).html());
		player.play();
		return false;
	});
}
