(function($) {

	// Speed
	$.extend(mejs.MepDefaults, {

		speeds: ['2.00', '1.50', '1.25', '1.00', '0.75'],

		defaultSpeed: '1.00',
		
		speedChar: 'x'

	});

	$.extend(MediaElementPlayer.prototype, {

		buildspeed: function(player, controls, layers, media) {
			var t = this;

			if (t.media.pluginType == 'native') {
				var 
					speedButton = null,
					speedSelector = null,
					playbackSpeed = null,
					inputId = null,
					html = '<div class="mejs-button mejs-speed-button">' + 
								'<button type="button">' + t.options.defaultSpeed + t.options.speedChar + '</button>' + 
								'<div class="mejs-speed-selector">' + 
								'<ul>';
				
				if ($.inArray(t.options.defaultSpeed, t.options.speeds) === -1) {
					t.options.speeds.push(t.options.defaultSpeed);
				}

				t.options.speeds.sort(function(a, b) {
					return parseFloat(b) - parseFloat(a);
				});

				for (var i = 0, il = t.options.speeds.length; i<il; i++) {
					inputId = t.id + '-speed-' + t.options.speeds[i];
					html += '<li>' + 
								'<input type="radio" name="speed" ' + 
											'value="' + t.options.speeds[i] + '" ' + 
											'id="' + inputId + '" ' +
											(t.options.speeds[i] == t.options.defaultSpeed ? ' checked' : '') + 
											' />' +
								'<label for="' + inputId + '" ' +
											(t.options.speeds[i] == t.options.defaultSpeed ? ' class="mejs-speed-selected"' : '') +
											'>' + t.options.speeds[i] + t.options.speedChar + '</label>' + 
							'</li>';
				}
				html += '</ul></div></div>';

				speedButton = $(html).appendTo(controls);
				speedSelector = speedButton.find('.mejs-speed-selector');				

				playbackspeed = t.options.defaultSpeed;

				speedSelector
					.on('click', 'input[type="radio"]', function() {
						var newSpeed = $(this).attr('value');
						playbackspeed = newSpeed;
						media.playbackRate = parseFloat(newSpeed);
						speedButton.find('button').html(newSpeed + t.options.speedChar);
						speedButton.find('.mejs-speed-selected').removeClass('mejs-speed-selected');
						speedButton.find('input[type="radio"]:checked').next().addClass('mejs-speed-selected');
					});

				speedSelector
					.height(
						speedButton.find('.mejs-speed-selector ul').outerHeight(true) + 
						speedButton.find('.mejs-speed-translations').outerHeight(true))
					.css('top', (-1 * speedSelector.height()) + 'px');
			}
		}
	});

})(mejs.$);
