var attachPlayer;
// a 'var swfPath' must be defined in a dynamically generated script elsewhere on the page.

( function ( $ ) { $( document ).ready( function() { 
    var playerContainerContainer = $( '#all-teachings' );

    var playerError = function( e ) {
    	//alert( e.jPlayer.error.type + ": " + e.jPlayer.error.context + "\n" + e.jPlayer.error.message + "\n" + e.jPlayer.error.hint );
    	if (e.jPlayer.error.type == $.jPlayer.error.URL ) { 
    		e.data.playerContainer.find( e.data.errorSelector ).show();
    	}
    };
    
    /*
     * playerAncestor: the control containing all the sections (which have each player handle and player container)
     * player: the control just for the jQuery jPlayer object
     * playerContainer: the control containing the "player"
     * mp3: the absolute URL of the MP3 to be loaded into the player 
     * playerHandle: the control whose click event will fire the showing/hiding of the playerContainer control
     */
    var initPlayer = function( args ) {
    	args.playerHandle.hide();
	    args.player.jPlayer({
	        ready: function () {
	        	args.player.bind( $.jPlayer.event.error, args, playerError );
		        
	        	if ( args.playerHandle.length > 0 ) {
	        		args.playerHandle.show();
	        		args.playerHandle.click( args, togglePlayer );
	        	}
	        	else {
	            	args.player.jPlayer( 'setMedia', { 'mp3': args.mp3 } );
	                args.player.jPlayer( 'load' );
	        	}
	        },
	        supplied: 'mp3',
	        solution: 'html,flash',
	        swfPath: args.swfPath,
	        volume: .8,
	        cssSelectorAncestor: args.playerContainer.selector,
	        cssSelector: {
        		play: ".jplayer_play",
	        	pause: ".jplayer_pause",
	        	stop: ".jplayer_stop",
	        	seekBar: ".jplayer_load_bar",
	        	playBar: ".jplayer_play_bar",
	        	mute: ".jplayer_volume_min",
	        	volumeBar: ".jplayer_volume_bar",
	        	volumeBarValue: ".jplayer_volume_bar_value",
	        	volumeMax: ".jplayer_volume_max",
	        	currentTime: ".jplayer_play_time",
	        	duration: ".jplayer_total_time"
        	},
	        errorAlerts: false,
	        warningAlerts: false
	    })
	    .jPlayer('onSoundComplete', function() {
	        args.player.jPlayer( 'pause' );
	    });
    };
    
    var togglePlayer = function( e ) {
    	e.data.playerHandle.children( ':not(script)' ).toggle();
    	
    	opening = !( closing = e.data.playerSection.attr( 'section-opened' ) === true.toString() ? true : false );
    	e.data.playerSection.attr( 'section-opened', opening );

    	if ( opening ) {
		    // close other sermons, pausing them
    		otherOpenSections = e.data.playerAncestor.find( '[section-opened="' + true.toString() + '"]' ).filter( ':not(' + e.data.sectionSelector + ')' ); 
    		otherOpenSections.find( e.data.playerHandleSelector ).children( ':not(script)' ).toggle();
    		otherOpenSections.find( e.data.playerContainerSelector ).slideUp( 'fast' );
    		otherOpenSections.attr( 'section-opened', false );
		    e.data.player.jPlayer( 'pauseOthers');

		    loaded = e.data.playerContainer.attr( 'loaded' ) === true.toString() ? true : false;
	    	if ( !loaded ) {
		    	loadPlayer( e.data );
	    	}
		    e.data.playerContainer.slideDown( 'fast' );
	    }
        if ( closing ) {
        	e.data.player.jPlayer( 'pause' );
	    	e.data.playerContainer.slideUp( 'fast' );
        }
    };

    /*
     * player: the div just for the jQuery jPlayer object
     * playerContainer: the control containing the jQuery jPlayer div
     * mp3: the absolute URL of the MP3 to be loaded into the player 
     */
    var loadPlayer = function( args ) {
    	args.player.jPlayer( 'setMedia', { 'mp3': args.mp3 } );
        args.player.jPlayer( 'load' );
        args.player.jPlayer( 'play' );
        args.playerContainer.attr( 'loaded', 'true' );
    };

    /*
     * [ancestorSelector]
     * |-> [sectionSelector]
     *     |-> [playerHandleSelector]
     *     |-> [playerContainerSelector]
     *         |-> [playerSelector]
     *         |-> [errorSelector]
     * mp3: the absolute URL to the MP3 file to attached to the jQuery jPlayer.
     * ancestorSelector: the jQuery selector string for the control that contains all the jPlayers' containers (this selector should work for the one control that contains all the player containers as well as all the player handles)
     * sectionSelector: the jQuery selector string for the control that contains both the player container control and the player handle control
     * playerHandleSelector: the jQuery selector string for each control that's used as handle for showing/hiding its respective jPlayer container 
     * playerContainerSelector: the jQuery selector string for the playerContainer (this selector should work for each one or set of controls that contain each jPlayer in the ancestor control)
     * playerSelector: the jQuery selector string for the empty jQuery jPlayer div to be filled by the jPlayer library (this selector should work for each empty control for the jPlayer objects)
     * errorSelector: the jQuery selector string for the controls in each player container that are shown when a URL error happens.
     * swfPath: the absolute URL to the directory containing the jQuery jPlayer flash file (.swf). 
     */
    attachPlayer = function( args ) {
	    var playerAncestor = $( args.ancestorSelector );
	    var playerSection = playerAncestor.length > 0 ? playerAncestor.find( args.sectionSelector ) : $( args.sectionSelector );
	    var playerContainer = playerSection.length > 0 ? playerSection.find( args.playerContainerSelector ) : $( args.playerContainerSelector );
	    var playerHandle = playerSection.length > 0 ? playerSection.find( args.playerHandleSelector ) : $( args.playerHandleSelector );
	    var player = playerContainer.find( args.playerSelector );
	    
	    initPlayer( $.extend( {}, args, { playerAncestor: playerAncestor, playerSection: playerSection, playerContainer: playerContainer, player: player, playerHandle: playerHandle } ) );
    };
} ); } )( jQuery);

