summaryrefslogtreecommitdiff
blob: e9f31ba8a7a2829d3c5647e056f815fb263a0556 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
( function( $ ) {

	/**
	 * A function to help debouncing.
	 */
	var debounce = function( func, wait ) {

		var timeout, args, context, timestamp;

		return function() {

			context = this;
			args = [].slice.call( arguments, 0 );
			timestamp = new Date();

			var later = function() {

				var last = ( new Date() ) - timestamp;

				if ( last < wait ) {
					timeout = setTimeout( later, wait - last );
				} else {
					timeout = null;
					func.apply( context, args );
				}

			};

			if ( ! timeout ) {
				timeout = setTimeout( later, wait );
			}

		};

	};

	/**
	 * A function to resize videos.
	 */
	function responsive_videos() {
		
		$( '.jetpack-video-wrapper' ).find( 'embed, iframe, object' ).each( function() {
			var video_element, video_width, video_height, video_ratio, video_wrapper, video_margin, container_width;

			video_element = $( this );
			video_margin = 0;

			if ( video_element.parents( '.jetpack-video-wrapper' ).prev( 'p' ).css( 'text-align' ) === 'center' ) {
				video_margin = '0 auto';
			}

			if ( ! video_element.attr( 'data-ratio' ) ) {
				video_element
					.attr( 'data-ratio', this.height / this.width )
					.attr( 'data-width', this.width )
					.attr( 'data-height', this.height )
					.css( {
						'display' : 'block',
						'margin'  : video_margin
					} );
			}

			video_width     = video_element.attr( 'data-width' );
			video_height    = video_element.attr( 'data-height' );
			video_ratio     = video_element.attr( 'data-ratio' );
			video_wrapper   = video_element.parent();
			container_width = video_wrapper.width();

			if ( video_ratio === 'Infinity' ) {
				video_width = '100%';
			}

			video_element
				.removeAttr( 'height' )
				.removeAttr( 'width' );

			if ( video_width > container_width ) {
				video_element
					.width( container_width )
					.height( container_width * video_ratio );
			} else {
				video_element
					.width( video_width )
					.height( video_height );
			}

		} );

	}

	/**
	 * Load responsive_videos().
	 * Trigger resize to make sure responsive_videos() is loaded after IS.
	 */
	$( window ).load( responsive_videos ).resize( debounce( responsive_videos, 100 ) ).trigger( 'resize' );
	$( document ).on( 'post-load', responsive_videos );

} )( jQuery );