$(window).load(function(){
	var playItem = 0;
	var urlPlaying ='';
	var timePlaying=0;
	var myPlayList=[];

	// Local copy of jQuery selectors, for performance.
	var jpPlayTime = $("#jplayer_play_time");
	var jpTotalTime = $("#jplayer_total_time");
	var jp = $("#jquery_jplayer");

	$("#jquery_jplayer").jPlayer({
		swfPath:'site/assets/js/jPlayer',
		volume:100,
		ready: function() {
			initPlayList();
			playListInit(true);
			initState();
			$('ul.jp-controls li.jp-play').click(function(){
				saveState('play');
			});
			$('ul.jp-controls li.jp-pause').click(function(){
				saveState('stop');
			});
			// show player
			$('#player h1').hide();
			$('div.jp-progress').add('div.jp-interface').add('#jplayer_playlist').show();
			// if youtube, stop playing
			if ($('.article .embed')) {
				$("#jquery_jplayer").jPlayer("stop");
			}
		}
	})
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime.text($.jPlayer.convertTime(playedTime));
		// jpTotalTime.text($.jPlayer.convertTime(totalTime));
		savePlayerTime();
	})
	.jPlayer("onSoundComplete", function() {
		var rnd=playItem;
		while (rnd==playItem) {rnd=Math.ceil(Math.random()*myPlayList.length)-1}
		playListChange(rnd);
		// else {
		// 	playListNext();
		// }
	});

	// buttons

	$("#jplayer_previous").click( function() {
		playListPrev();
		return false;
	});

	$("#jplayer_next").click( function() {
		playListNext();
		return false;
	});

	// playlist

	function initPlayList() {
		// was there allready something playing?
		urlPlaying=getCookie('url');
		if (urlPlaying!='') {
			var item=$('#jplayer_playlist ul li.mp3[mp3='+urlPlaying+']');
			if (item.length>0) {
				playItem=$('#jplayer_playlist ul li.mp3').index(item);
				timePlaying=getCookie('time');
			}
			else {
				urlPlaying='';
			}
		}
		// init list
		var i=0;
		$('#jplayer_playlist ul li.mp3').each(function(){
			var txt=$(this).children('a').html();
			if (txt!=undefined) {
				$(this).html('<span class="bullit">&bull;</span>'+txt);
				$(this).data( "index", i ).click(function(){
					var index = $(this).data('index');
					if (playItem != index) {
						playListChange( index );
					} else {
						$("#jquery_jplayer").jPlayer("play");
					}
				});
				myPlayList.push({mp3:$(this).attr('mp3'), ogg:'', name:$(this).attr('name'), project:$(this).attr('project')});
				i++;
			}
		});
		// rnd start
		if (urlPlaying=='') {
			var rnd=Math.ceil(Math.random()*myPlayList.length)-1;
			playListChange(rnd);
		}
	}

	function playListInit(autoplay) {
		if(autoplay) {
			playListChange( playItem );
		} else {
			playListConfig( playItem );
		}
	}

	function playListConfig( index ) {
		$("#jplayer_playlist_item_"+playItem).removeClass("jplayer_playlist_current");
		var currItem=$("#jplayer_playlist_item_"+index);
		$(currItem).addClass("jplayer_playlist_current");
		playItem = index;
		$("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3, myPlayList[playItem].ogg);
		var uri=$(currItem).attr('uri');
		var project=$(currItem).attr('project');
		var title=$(currItem).attr('name');
		$('#jplayer_playing_title').html('<a class="projectLink" href="'+uri+'">'+project+'</a><br/><span class="title">'+title+'</span>');
	}

	function playListChange( index ) {
		playListConfig( index );
		$("#jquery_jplayer").jPlayer("play");
	}

	function playListNext() {
		var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
		playListChange( index );
	}

	function playListPrev() {
		var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
		playListChange( index );
	}
	
	// state
	
	function initState() {
		if (urlPlaying!='') {
			$("#jquery_jplayer").jPlayer('playHeadTime',timePlaying);
		}
		var playState=getCookie('playState');
		if (playState=='') playState='play';
		$("#jquery_jplayer").jPlayer(playState);
	}
	function saveState(playState) {
		if (playState==undefined) playState='stop';
		if ($("#jquery_jplayer").data('diag.isPlaying')) playState='play';
		setCookie('playState',playState);
	}

	function savePlayerTime() {
		setCookie('url',$(jp).jPlayer('getData','diag.src'));
		setCookie('time',$(jp).jPlayer('getData','diag.playedTime'));
	}
		
});

// Coockie functions

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function getCookie(c_name) {
	if (document.cookie.length>0)   {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1) {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
	return "";
}

// // YouTube Player
// function onYouTubePlayerReady() {
// 	console.log('Ready');
// 	var youtube=$('.embed object:first');
// 	console.log(youtube);
// 	if (youtube) {
// 		youtube.stopVideo();
// 	}
// 	
// }
