var cookie_options = { path: '/', expires: 1 };
var playItem = 0;
var cookie_timeslap = 0;
var autoplay = false;
var path = '/images/items/';
var suff = '.mp3';

function isHTML5() {
    return (document.createElement("video")!= null);
}

$(".songs li a").click(function() {
    var title = $(this).attr("title");
    var data = $(this).attr("name");
    playTrack(title, data);
});

$("#jPlayer").jPlayer({
	swfPath: "../js/",
	ready: function() {
		playListConfig(0);
	},
	oggSupport: false,
	volume: 100,
	nativeSupport: false
})
.jPlayer("onSoundComplete", function() {
	playListNext();
});

function playListConfig( index ) {  
	
	playItem = $.cookie("cookie_playitem");
	
	if (playItem == null || playItem == "-1"){
			playItem = index;   
	} else {
        cookie_timeslap = $.cookie("cookie_timeslap");
        $.cookie("cookie_playitem", "-1", cookie_options);
        autoplay = true;
    }
    preparePlay();
}

function getTrack(data) {
    var d = data.split(/_/);
    return path + d[0] + "/" + d[1] + suff;
}

function preparePlay() {
    playItem = parseInt(playItem);
    var item = myPlayList[playItem];
    $(".mp3-player .now-playing span").html(item.name);
    $("#jPlayer").jPlayer("setFile", getTrack(item.data), item.ogg);
    if (autoplay) doPlay();
}

function doPlay() {
    //alert('playing');
    $("#jPlayer").jPlayer("playHeadTime", cookie_timeslap);
}

function playTrack(title, data) {
    $(".mp3-player .now-playing span").html(title);
    $("#jPlayer").jPlayer("setFile", getTrack(data), "").jPlayer("play");
    return false;
}

function playListChange(index) {
    cookie_timeslap = 0;
	playListConfig( index );
	$("#jPlayer").jPlayer("play");
}  
function playListNext() {
	var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
	playListChange( index );
	$(".now-playing span").css("left", "0");
}
function playListPrev() {
	var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
	playListChange( index );
	$(".now-playing span").css("left", "0");
}

$("#jplayer_previous").click( function() {
	playListPrev();
	return false;
});
$("#jplayer_next").click( function() {
	playListNext(); 
	return false;
});
$("#jplayer_volume_min").click(function(){
	$(this).css("display", "none");
	$("#jplayer_volume_max").css("display", "block");
	return false;
});
$("#jplayer_volume_max").click(function(){
	$(this).css("display", "none");
	$("#jplayer_volume_min").css("display", "block");
	return false;
});

$(window).unload(function(){             
	var cookie_timeslap_value = "";  
	var cookie_playitem_value = playItem;

	if ($("#jPlayer").jPlayer("getData", "diag.isPlaying")){
		cookie_timeslap_value = $("#jPlayer").jPlayer("getData", "diag.playedTime");
		$.cookie("cookie_timeslap", cookie_timeslap_value, cookie_options);
		$.cookie("cookie_playitem", cookie_playitem_value, cookie_options);		
	}
	
});

