$.playable = function(url, settings) {
    var sm = soundManager,
    playable = arguments.callee;
    sm.url = url;
    sm.consoleOnly = window.location.hash.match(/console$/i);
    sm.debugMode = window.location.hash.match(/^#debug/i);
    $.extend(sm.defaultOptions,
    {
        autoStart: false,
        autoNext: true,
        pauseSkip: false,
        playAlone: true,
        doUnload: true,
        css: {
        	playable: 'playable',
            playing: 'playing',
            paused: 'paused'
        },
        onload: function() {
            if (this.readyState == 2)
            playable.next.call(this);
        },
        onplay: function() {
			
			var options = this.options,
			
            current = options.element.removeClass(options.css.paused).addClass(options.css.playing).focus();
			
            if (playable.current && playable.current != current)
            	playable.current.data('playable')[options.pauseSkip ? 'pause': 'stop']();
            if (options.playAlone)
            	playable.current = current;
						
						//var currentSoundID = $('#control-template').parent().find('.playable').attr('id');
						$('.rollover_message').removeClass('hide');
						$('#control-template').parent().find('.rollover_message').addClass('hide');	
							
						$('.module_image').addClass('rollover_image');
						$('.module_rollover').addClass('module_controls');						

						//$('#control-template').parent().find('.playable').attr('id', currentID + ' playing');
						$('#control-template').parent().parent().find('.module_image').removeClass('rollover_image');
						$('#control-template').parent().find('.module_rollover').removeClass('module_controls');
        },
        onstop: function() {
            var options = this.options;
            options.element.removeClass(options.css.playing + ' ' + options.css.paused);
            if (options.doUnload)
            this.unload();						
        },
        onpause: function() {
            var options = this.options;
            options.element.removeClass(options.css.playing).addClass(options.css.paused);
						
						$('#control-template').parent().parent().find('.module_image').addClass('rollover_image');
						$('#control-template').parent().find('.module_rollover').addClass('module_controls');
        },
        onresume: function() {
            this.options.onplay.call(this);
						
						$('#control-template').parent().parent().find('.module_image').removeClass('rollover_image');
						$('#control-template').parent().find('.module_rollover').removeClass('module_controls');
        },
        onfinish: function() {
            var options = this.options;
            if (options.autoNext)
            playable.next.call(this);
            options.onstop.call(this);						

						$('#control-template').addClass('hide');
						$('.rollover_message').removeClass('hide');
        },
				whileplaying: function() {
						var secondsPositionInit = Math.floor(this.position / 1000);
						var secondsPosition = secondsPositionInit % 60;
						secondsPosition = ((secondsPosition <= 9) ? "0" + secondsPosition : secondsPosition );
						
						var minutesPositionInit = Math.floor(secondsPositionInit / 60)
						var minutesPosition = minutesPositionInit % 60
						minutesPosition = ((minutesPosition <= 9) ? "0" + minutesPosition : minutesPosition )
						
						var hoursPositionInit = Math.floor(minutesPositionInit / 60)
						var hoursPosition = hoursPositionInit % 60
						hoursPosition = ((hoursPosition <= 9) ? "0" + hoursPosition : hoursPosition )
						
						var currentLoad = ((this.bytesLoaded / this.bytesTotal) * 100);
						var currentPosition = ((this.position / this.durationEstimate) * 100);
						$('#play_time').html(hoursPosition + ":" + minutesPosition + ":" + secondsPosition);						
						$('#control-template').find('.total_load').width(currentLoad + '%');
						$('#control-template').find('.position').width(currentPosition + '%');		
				}
    },
    settings
    );
    $.extend(playable, {
        count: 0,
        current: null,
        init: function(options) {						
            var self = this,
            options = $.extend(true, {},
            sm.defaultOptions, options);						
            this.addClass(options.css.playable)
            .click(function(event) {
							
                event.preventDefault();
								
								//$('.module_image').not($(this).parent().parent().parent().parent().parent().find('.module_image')).removeClass('hide');						
								$('.module_rollover').not($(this).parent().parent().parent().parent().find('.module_rollover')).addClass('hide');
								
								$(this).parent().parent().parent().parent().parent().after(($('#control-template')));	
								$(this).after($('#play_time'));
													
								var parentWidth = $('#control-template').parent().width();							
	
								$('#control-template').width('100%');	
								$('#control-template').removeClass('hide');
								
								$(this).data('playable').togglePause();					
            })
            .each(function() {												
				$(this).attr('id', 'playable' + playable.count);
                $(this).data('playable', sm.createSound($.extend(
                {
                    id: 'playable' + playable.count++,
                    url: this.href,
                    element: $(this),
                    selector: self.selector
                },
                options
                )));								
            });
            if (options.autoStart)
            self.filter(':first').click();						
        },
        next: function() {
            var options = this.options,
            next = $(options.element).next(options.selector).data('playable');
            if (next && !next.playState)
            next.play();
        }
    }
    );
};


$.fn.elementXLocation = function() 
{
	var curleft = 0;
	var obj = this;
	
	do 
	{
		curleft += obj.attr('offsetLeft');	    
		obj = obj.offsetParent();
	}
	
	while (obj.attr('tagName') != 'BODY');
	return curleft
};

$.fn.playable = function(options) {
    var self = this.is('a[href]') ? this: this.find('a[href]');
    soundManager.onload = function() {
        if (soundManager.canPlayURL(self.attr('href')))
        $.playable.init.call(self, options);
    };
};

$.fn.reloadSM = function(options)
{
	var self = this.is('a[href]') ? this: this.find('a[href]');
  if (soundManager.canPlayURL(self.attr('href')))
  $.playable.init.call(self, options);
}

$(function() {
    /* Simple usage */
    $.playable('/swfs/');
    $('.playable_link').playable(); 
		
		$("#control-template").click(function(e)
		{
			var mouseX = parseInt(e.clientX - $('#control-template').find('.position').elementXLocation());
			var currentLinkElement = $(this).parent().parent().parent().find('.playable')			
			//alert(currentLinkElement.attr('class') +  " " + currentLinkElement.attr('id'))
			var currentSound = soundManager.getSoundById(currentLinkElement.attr('id'));
			
			$('#control-template').find('.position').width(mouseX);						
			var mousePercentage = mouseX / $('#control-template').width()
			var offset = mousePercentage * (currentSound.durationEstimate);
			//alert(mousePercentage + " DDDDDD " + offset);
	  	if (!isNaN(offset)) offset = Math.min(offset, currentSound.duration);
	  	if (!isNaN(offset)) currentSound.setPosition(offset);
		});
		
		//Example configurations 
		//$('.playlist').playable({autoStart: true, autoNext: true, playAlone: true, doUnload: false}); 
		//$('.sampler').playable({autoStart: false, autoNext: false, playAlone: true}); 
		//$('.listen').playable({autoStart: false, autoNext: false, playAlone: true,pauseSkip: true, doUnload: true}); 
});