/*
 *	Macht aus einem übergebenen Link zu einer MP3 Datei einen coolen Player
 *	Version 2
 */
var Counter = 0;
var mp3playerDefaults = {
			autoLoad: false,
			wrap: '<div class="mp3player"></div>',
			play: '<a class="control play">PLAY</a>',
			pause: '<a class="control pause">PAUSE</a>',
			time: '<a class="control time"></a>',
			
			onFinish: function() {
				//irgendwas ausführen
			},
			onLoad: function() {}
		};

(function($) {
	
	jQuery.fn.mp3player = function(options) {
		
		
		
		var opts = jQuery.extend(mp3playerDefaults, options);
		
		return this.each(function() {
			var mp3href = $(this).attr('href');			
			var thisSound = '';
			var $player = '';
			
				
			var content = '<div class="left"></div><div class="content">';
			content = content + opts.play;
			content = content + opts.pause;
			content = content + '<a class="title">'+$(this).text()+'</a>';
			content = content + opts.time;
			content = content + '</div><div class="right"></div>';
			
			$player = $(opts.wrap);
			
			
			soundManager.onready(function() {
				Counter++;
				thisSound = soundManager.createSound({
						id: 'mp3-'+Counter,
						url: mp3href,
						autoLoad: opts.autoLoad,
						onid3: function() {
							if(opts.autoLoad) {
								$player.find('.title').text(this.id3.songname);
							}
						},
						onload: function() {
							opts.onLoad.player = $player;
							opts.onLoad.call();
						},
						whileplaying: function() {
							$player.find('.time').text(format_time(this.durationEstimate-this.position));
						},
						onplay: function() {
							$player.addClass('playing');
						},
						onfinish: function() {
							$player.removeClass('playing');
							$player.find('.time').text('');
							opts.onFinish.call();
						},
						onpause: function() {
							$player.addClass('pause').removeClass('playing');
						},
						onresume: function() {
							$player.removeClass('pause').addClass('playing');
						}
					});
			});
			
			$player
				.attr('rel', $(this).attr('href'))
				.html(content)
				.find('.play').click(function() {
					thisSound.play();
				}).end()
				.find('.pause').click(function() {
					if(thisSound.paused)
						thisSound.play();
					else
						thisSound.pause();
				});
				
			$(this).after($player).hide();
		});
	}
	
})(jQuery);


function format_time(ms) {
	minutes = new String(Math.floor(ms / (1000*60)));
	seconds = new String(Math.floor((ms-(minutes*60*1000)) / 1000));
	
	minutes = minutes.length == 1 ? '0'+minutes : minutes;
	seconds = seconds.length == 1 ? '0'+seconds : seconds;
	return minutes+':'+seconds;
}

