// by Jan den Besten 2011

// Start the player
$(document).ready(function() {
	
	$('#player h1').hide();
	
	var audioPlaylist = new Playlist("1", {
		ready: function() {
			audioPlaylist.fillPlaylist();
			var start=$("#jp_interface_1").attr('start');
			if (start=='') start='play';
			// if youtube, don't start mp3s
			if ($('.embed').length>0) {
				start='stop';
			}
			audioPlaylist.playlistInit(start);
			$('#player').css({color:'#FFE200'});	
		},
		ended: function() {
			var end=$("#jp_interface_1").attr('end');
			if (end=='random')
				audioPlaylist.playlistShuffle();
			if (end=='next')
				audioPlaylist.playlistNext();
		},
		play: function() {
			$(this).jPlayer("pauseOthers");
		},
		swfPath: "site/assets/js/jplayer",
		supplied: "mp3"
	});
});



// Playlist Object
var Playlist = function(instance, options) {
		var self = this;
		this.instance = instance; // String: To associate specific HTML with this playlist
		this.playlist = []; // Array of Objects: The playlist
		this.options = options; // Object: The jPlayer constructor options for this playlist
		this.current = 0;
		this.time = 0;
		this.init = false;
		this.state = '';

		this.cssId = {
			jPlayer: "jquery_jplayer_",
			interface: "jp_interface_",
			playlist: "jp_playlist_"
		};
		this.cssSelector = {};
		$.each(this.cssId, function(entity, id) {
			self.cssSelector[entity] = "#" + id + self.instance;
		});
		if(!this.options.cssSelectorAncestor) {
			this.options.cssSelectorAncestor = this.cssSelector.interface;
		}
		$(this.cssSelector.jPlayer).jPlayer(this.options);

		$(this.cssSelector.interface + " .jp-prev").click(function() {
			self.playlistPrev();
			$(this).blur();
			return false;
		});
		$(this.cssSelector.interface + " .jp-next").click(function() {
			self.playlistNext();
			$(this).blur();
			return false;
		});
	};

	Playlist.prototype = {
		fillPlaylist: function() {
			var self = this;
			this.playlist=[];
			$(this.cssSelector.playlist + " ul li.mp3").each(function(){
				var item=$(this).children("a:first");
				self.playlist.push({mp3:$(item).attr('mp3'), ogg:'', name:$(item).attr('title'), artist:$(item).attr('artist')});
			});
			for (i=0; i < this.playlist.length; i++) {
				// Associate playlist items with their media
				$(this.cssSelector.playlist + "_item_" + i).data("index", i).click(function() {
					var index = $(this).data("index");
					if(self.current !== index) {
						self.playlistChange(index);
					} else {
						this.time=0;
						$(self.cssSelector.jPlayer).jPlayer("play",this.time);
					}
					return false;
				});
			}
		},
		playlistInit: function(autoplay) {
			if (! this.init) {
				this.init = true;
				// init jPlayer events
				var self = this;
				$(this.cssSelector.jPlayer).bind($.jPlayer.event.timeupdate, function(event){
					self.savePlayerState(event.jPlayer.status.src, event.jPlayer.status.currentTime, event.jPlayer.status.paused);
				}).bind($.jPlayer.event.play, function(event){
					self.savePlayerState(event.jPlayer.status.src, event.jPlayer.status.currentTime, event.jPlayer.status.paused);
				}).bind($.jPlayer.event.pause, function(event){
					self.savePlayerState(event.jPlayer.status.src, event.jPlayer.status.currentTime, event.jPlayer.status.paused);
				}).bind($.jPlayer.event.error, function(event){
					alert('jPlayer ERROR');
				});

				if (autoplay=='auto') {
					var getState=self.getPlayerState();
					autoplay='play';
					if (getState.state=='stop') autoplay=getState.state;
					if (getState.url!='') {
						var index='#'+$(this.cssSelector.playlist + " ul li a:[mp3="+getState.url+"]").attr('id');
						index=index.replace(this.cssSelector.playlist+"_item_","");
						if (index>0 && index<this.playlist.length)
							this.current=index;
					}
					else {
						this.current=this.getRandomIndex();
					}
					if (getState.time!='') {
						this.time=Number(getState.time);
					}
				}
				// console.log(autoplay,this.time);
				switch (autoplay) {
					case 'stop':
						this.playlistConfig(this.current);
						break;
					case 'random':
						this.playlistShuffle();
						autoplay='play';
						break;
					case 'play':
					default:
						this.playlistChange(this.current,this.time);
						break;
				}
				this.state=autoplay;
				
				// react on losing or getting focus
				$(window).blur(function(){
					var blurState=self.state;
					var blurTime=self.time;
					var blurPaused=(blurState=='stop')?true:false;
					$(self.cssSelector.jPlayer).jPlayer("stop");
					self.savePlayerState('',blurTime,blurPaused);
					// console.log('blur:'+self.state+self.time);
				}).focus(function(){
					// console.log('focus:'+self.state+self.time);
					$(self.cssSelector.jPlayer).jPlayer(self.state, self.time);
				});

			}
		},
		playlistConfig: function(index) {
			$(this.cssSelector.playlist + "_item_" + this.current).removeClass("jp-playlist-current").parent().removeClass("jp-playlist-current");
			$(this.cssSelector.playlist + "_item_" + index).addClass("jp-playlist-current").parent().addClass("jp-playlist-current");
			this.current = index;
			$(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
			// set Artist & Title
			var artist=$(this.cssSelector.playlist + "_item_" + this.current).attr('artist');
			var uri=artist.replace(/ /ig,'_');
			var title=$(this.cssSelector.playlist + "_item_" + this.current).attr('title');
			$(this.cssSelector.interface + ' .jp_current_artist').html('<a href="'+uri+'">'+artist+"</a>");
			$(this.cssSelector.interface + ' .jp_current_title').html(title);
		},
		playlistChange: function(index,time) {
			this.playlistConfig(index);
			if (typeof time!='undefined') {
				this.time=time;
				// console.log(this.time);
			}
			$(this.cssSelector.jPlayer).jPlayer("play",this.time);
		},
		getRandomIndex: function() {
			var index=this.current;
			if (this.playlist.length>1) {
				while (index==this.current) {index=Math.ceil(Math.random()*this.playlist.length)-1};
			}
			return index;
		},
		playlistShuffle: function() {
			this.time = 0;
			this.playlistChange(this.getRandomIndex());
		},
		playlistNext: function() {
			var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
			this.time = 0;
			this.playlistChange(index);
		},
		playlistPrev: function() {
			var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;
			this.time = 0;
			this.playlistChange(index);
		},
		getPlayerState: function() {
			var player=(this.cssSelector.jPlayer).replace(/#/,'');
			var state=getCookie(player+'_state');
			var url=getCookie(player+'_url');
			var time=getCookie(player+'_time');
			// console.log("GET:",state,url,time);
			return {state:state,url:url,time:time};
		},
		savePlayerState: function(url,time,paused) {
			this.state=(paused)?'stop':'play';
			this.time=time;
			// console.log("SAVE:",this.state,url,time);
			var player=(this.cssSelector.jPlayer).replace(/#/,'');
			if (url!='') setCookie(player+'_url',url);
			setCookie(player+'_time',time);
			setCookie(player+'_state',this.state);
		}
	};


// 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 "";
}
