var Playlist = function(instance, defil, playlist) {
	var self		= this;

	this.scroll		= false;
	this.defil		= defil;
	this.instance	= instance;
	this.playlist	= playlist;
	this.options	= {
		ready: function () {
			self.displayPlaylist();			
			self.playlistInit(true);
		},
		ended: function (event) {
			self.playlistNext();
		},
		swfPath: urlSite + "medias/swf/",
		supplied: "mp3"
	};
	this.current	= 0;
	
	this.cssId = {
		jPlayer: "playerMP3_",
		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-previous").click(function() {
		self.playlistPrev();
		$(this).blur();
		return false;
	});

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

};

Playlist.prototype = {
	displayPlaylist: function() {
		var self = this;
		$(this.cssSelector.playlist + " ul").empty();
		for (i=0; i < this.playlist.length; i++) {
			var listItem = (i === this.playlist.length-1) ? "<li class='jp-playlist-last Din'" : "<li class='Din'";
			listItem += " id='" + this.cssId.playlist + this.instance + "_item_" + i +"'>"+ this.playlist[i].name +"</li>";
			$(this.cssSelector.playlist + " ul").append(listItem);
		}
	},
	playlistInit: function(autoplay) {
		if(autoplay) {
			this.playlistChange(this.current);
		} else {
			this.playlistConfig(this.current);
		} 
	},
	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]);
		this.playlistScroll();
	},
	playlistChange: function(index) {
		this.playlistConfig(index);
		$(this.cssSelector.jPlayer).jPlayer("play");
	},
	playlistNext: function() {
		var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
		this.playlistChange(index);
	},
	playlistPrev: function() {
		var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;
		this.playlistChange(index);
	},
	playlistScroll: function() {
		if(this.scroll===false) {
			this.scroll = true;
			$(this.cssSelector.playlist + " ul").liScroll({travelocity: this.defil});
			Cufon.refresh();
		}
		else {
			var saveUl	= $(this.cssSelector.playlist + ' .mask').html();
			$(this.cssSelector.playlist).html(saveUl);
			Cufon.refresh();
			$(this.cssSelector.playlist + " ul").attr('style','');
			$(this.cssSelector.playlist + " ul").liScroll({travelocity: this.defil});
		}
	}
};
