jQuery( function( $ ) {
	'use strict';

	function addWidthClass( elem ) {
		var elWidth;
		elem = $( elem );
		elWidth = elem.width();
		if ( 600 < elWidth ) {
			elem.addClass( 'expanded' );
		}
	}

	// Get rid of the floating time span
	$( '.mejs-time-total' ).unbind( 'mouseenter' );

	initPlayers();

	function initPlayers() {
		$( 'audio.rogers-audio-player-player' ).each(function() {
			// Checks if player has been instantiated.
			if(typeof $(this).data().mediaelementplayer === 'undefined'){
				$( this ).mediaelementplayer( {
					features: ['progress','current', 'duration','playpause'],
					audioWidth: '100%',
					audioHeight: 12,
					startVolume: 1,
					pauseOtherPlayers: true,
					success: function( playerElem ) {
						var parentElem = $( playerElem ).parents( '.rogers-audio-main-wrapper' );
						addEvents( playerElem, parentElem );
					}
				} );
			}
		} );
		// This applies to wordpress audio shortcodes.
		$( 'audio' ).each(function() {
			if(typeof $(this).data().mediaelementplayer === 'undefined'){
				$( this ).mediaelementplayer();
			}
		} );
	}

	function addEvents( playerElem, parentElem ) {
		var $element = $( parentElem );
		window.audioPlayer = playerElem;

		$element.each( function() {
			addWidthClass( this );
			$( this ).addClass( 'done-loading' );
		});

		$( playerElem ).on('play', function() {
			$( '.rogers-audio-play-button', $element ).css( 'display', 'none' );
			$( '.rogers-audio-pause-button', $element ).css( 'display', 'inline-block' );
    	});

    	$( playerElem ).on('pause', function() {
			$( '.rogers-audio-pause-button', $element ).css( 'display', 'none' );
			$( '.rogers-audio-play-button', $element ).css( 'display', 'inline-block' );
    	});

		$( '.rogers-audio-body .text-links .copy-link', $element ).on( 'click', function() {
			var input = $( this ).siblings( 'input[type=\'text\']' );
			input.select();
			document.execCommand( 'copy' );
		} );

		$( '.rogers-audio-body .text-links input[type=\'text\']', $element ).focus(function() {
			$( this ).select();
			document.execCommand( 'copy' );
		} );

		$( '.rogers-audio-body .share-overlay .share-close', $element ).on( 'click', function() {
			$( '.rogers-audio-body', $element ).removeClass( 'overlay' );
		} );

		$( '.rogers-audio-body a.actions-share', $element ).on( 'click', function( e ) {
			e.preventDefault();
			$( '.rogers-audio-body', $element ).addClass( 'overlay' );
		} );

	}
		window.addEventListener('dynamic-audio-player', initPlayers, false);

} );
