/*
 * m2list3
 *
 * a jquery-based plugin implementation of a player
 *
 * @author sergio salvatore (sergio.salvatore@sonymusic.com)
 * @author tim nilson (tim.nilson@sonymusic.com)
 *
 * @version 1.0
 */
;(function($) {

  $.fn.extend({
		m2player: function(options) {

			var defaults = {
				'playTime': 30000
			}

	    var opts = $.extend({}, defaults, options);

			// create new objects for each of the things we'd like to have suggestions for
	    return this.each(function() {
				new $.M2Player(this, opts)
	    });
		}
	});
	
	$.M2Player = function(button, options) {
		
		function start_playing(play_button) {
			
			stop_playing();
		
			$button = $(play_button);
			
			mp3url = $('span.url', $button).html();
			animation_target = $('span.animate', $button).html();

			if (animation_target) {

				// set the z-index of the thing we want to animate behind to be in front
				$(animation_target, $button).css('z-index', 2);

				// check to see if we've already wrapped the element -- if not, wrap it it an additional relatively-positioned
				// div that will hold both the thing we want to animate behind, and the expanding play bar itself
				if ($button.find('~ div.play_wrapper').length == 0) {
					$(animation_target, $button).wrap('<div class="play_wrapper"></div>').parent().append('<div class="play_animation">&nbsp;</div>')
				} 

				// find the play animation bar, set it's z-index to be behind the element (text) and animate the expanding width
				$button.find('~ div.play_wrapper').find('.play_animation').css('z-index', 1).animate({width: '100%'}, options.playTime, "linear", function() { 
					$(this).fadeOut(1500, function() { $(this).css('width', 0); });

					// I'd like to just call stop_playing here, but that's not working reliably...
					$('#sony_sampler')[0].stop_sample();
					$button.removeClass('stop').addClass('play').unbind().click( function() { start_playing(this) } );
				});
			}

			// start playing the audio
			$('#sony_sampler')[0].play_sample(mp3url);

			// Change the classes to show a 'stop' button now that we're playing
			$button.removeClass('play').addClass('stop');
			
			// clobber the onclick action to be stop now...
			$button.unbind().click( function () { stop_playing() } );
			
		}
		
		function stop_playing() {
			// Change the classes to show a 'stop' button now that we're playing

			$('div.play_animation').each(function() {
				$(this).stop().fadeOut(300, function() { $(this).css('width', 0); });
			});
			
			// stop the audio
			$('#sony_sampler')[0].stop_sample();
			
			$('div.stop').removeClass('stop').addClass('play').unbind().click( function() { start_playing(this) } );
		}
		
		$(button).unbind().click(function () {
			start_playing(this);
		});
		
	}
	
	
})(jQuery);