(function( $ ) {

var sm = soundManager;

$.widget( "ui.player", {

    options: {
        prev: '.prev',
        playPause: '.play-pause',
        next: '.next',
        progress: '.progress'
    },

    _init: function() {
        var self = this,
            $progress = this.element.find( this.options.progress ),
            $playPause = this.element.find( this.options.playPause ),
            $next = this.element.find( this.options.next ),
            $prev = this.element.find( this.options.prev ),
            isSliding = false,
            currentSound = null,
            currentRecipeItem = null,

            // Update loading progress on each whileLoading event from sound manager.
            whileLoadingHandler = function() {
                $progress.progressbar(
                    'option',
                    'value',
                    currentSound.bytesLoaded / currentSound.bytesTotal * 100 );
            },

            // Update slider position on each whilePlaying event from sound manager, unless the user is dragging the slider.
            whilePlayingHandler = function() {
                var duration = currentSound.loaded ? currentSound.duration : currentSound.durationEstimate;
    
                isSliding || $progress.slider( 'option', 'value', currentSound.position / duration * 100 );
            },

            // Update play/pause icon and label depending on play state
            playPauseHandler = function() {
                var options;
               if( this.playState ) {
                    if( this.paused ) {
						options = {
							label: "Play",
							icons: {
								primary: "ui-icon-play"
							},
							text:true
						};
                    }
                    else {
						 options = {
							label: "Pause",
							icons: {
								primary: "ui-icon-pause"
							},
							text:true
						};
                    }
                }
                else {
					options = {
						label: "Play",
						icons: {
							primary: "ui-icon-play"
						},
                        text:true
					};
                }
				$playPause.button( "option", options );
            },

            onReadyHandler = function() {
                sm.stopAll();
                if( currentRecipeItem ) {
                    self._playRecipeItem( currentRecipeItem );
                }
            };

        sm.enabled ? onReadyHandler() : sm.onready(onReadyHandler);

        self._playRecipeItem = function (item) {
            if (!sm.enabled) {
                return;
            }

            sm.stopAll();

            self.element.trigger('recipeItemChanged.player', [item]);

            if (item) {
                currentSound = sm.createSound({
                    id: item.song.id,
                    url: item.song.songResource.url
                });

                currentSound.play({
                    whileloading: whileLoadingHandler,
                    whileplaying: whilePlayingHandler,
                    onplay: playPauseHandler,
                    onresume: playPauseHandler,
                    onpause: playPauseHandler,
                    onstop: playPauseHandler,
                    onfinish: function () {
                        $next.trigger('click');
                        playPauseHandler.apply(this, []);
                    }
                });

                $playPause.button( 'enable' );
                $progress.slider( 'enable' );
                $prev.button( item.prev ? 'enable' : 'disable' );
                $next.button( item.next ? 'enable' : 'disable' );
            }
            else {
                $playPause.button( 'disable' );
                $progress.slider( 'disable' );
                $prev.button( 'disable' );
                $next.button( 'disable' );
            }

            currentRecipeItem = item;
        };
            

        $progress.slider({
            disabled: true,
            range: 'min',
            value: 0,
            min: 0,
            max: 100,
            start: function( event, ui ) {
                isSliding = true;
            },
            stop: function( event, ui ) {
                var position;

                if( !currentSound ) {
                    this.slider( 'value', 0 );
                    return;
                }

                // Calculate the new sound position based on slider value
                if( currentSound.loaded ) {
                    position = ui.value * currentSound.duration / 100;
                }
                else {
                    position = ui.value * currentSound.durationEstimate / 100;
                }

                // If the calculated position is further along in the sound than has yet
                // been downloaded, use the max available position.
                if( position > currentSound.duration ) {
                    position = currentSound.duration - 250;
                }

                currentSound.setPosition( position );
                isSliding = false;
            }
        })
        .progressbar({
            value: 0
        });

        $playPause.button({
            icons: { primary: 'ui-icon-play' },
            text: true,
            disabled: true
        })
        .click( function() {
            currentSound.togglePause();
        });

        $next.button({
            label: "Skip",
            text: true,
            disabled: true
        })
        .click(function () {
            var nextItem;

            if (currentRecipeItem && currentRecipeItem.next) {
                nextItem = currentRecipeItem.next();
                if (nextItem) {
                    $.when(nextItem).then(function (item) {
                        self._playRecipeItem(item);
                    });
                }
            }
        });

        $prev.button({
            label: "Back",            
            text: true,
            disabled: true
        })
        .click( function() {
            var prevItem;

            // If we're after the first 3 seconds of the current song, rewind
            // to the beginning.  If we're within the first 3 seconds, switch
            // to the previous song.
            if( currentSound && currentSound.position > 3000 ) {
                currentSound.setPosition( 0 );
            }
            else {
                if (currentRecipeItem && currentRecipeItem.prev) {
                    prevItem = currentRecipeItem.prev();
                    if (prevItem) {
                        $.when(prevItem).then(function (item) {
                            self._playRecipeItem(item);
                        });
                    }
                }
            }
        });
    },

    playRecipeItem: function( recipeItem ) {
        this._playRecipeItem( recipeItem );
    }

});

})( jQuery );

