PageRenderTime 96ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/files/anythingslider/1.7/jquery.anythingslider.video.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 367 lines | 257 code | 24 blank | 86 comment | 62 complexity | c32473ddf655e33f49afb3252a79b144 MD5 | raw file
  1. /*
  2. * AnythingSlider Video Controller 1.0 beta for AnythingSlider v1.6+
  3. * By Rob Garrison (aka Mottie & Fudgey)
  4. * Dual licensed under the MIT and GPL licenses.
  5. */
  6. (function($) {
  7. $.fn.anythingSliderVideo = function(options){
  8. //Set the default values, use comma to separate the settings, example:
  9. var defaults = {
  10. videoID : 'asvideo' // id prefix
  11. };
  12. return this.each(function(){
  13. // make sure a AnythingSlider is attached
  14. var video, tmp, service, sel, base = $(this).data('AnythingSlider');
  15. if (!base) { return; }
  16. video = base.video = {};
  17. video.options = $.extend({}, defaults, options);
  18. // check if SWFObject is loaded
  19. video.hasSwfo = (typeof(swfobject) !== 'undefined' && swfobject.hasOwnProperty('embedSWF') && typeof(swfobject.embedSWF) === 'function') ? true : false;
  20. video.list = {};
  21. video.hasVid = false;
  22. video.hasEmbed = false;
  23. video.services = $.fn.anythingSliderVideo.services;
  24. video.len = 0; // used to add a unique ID to videos "asvideo#"
  25. video.hasEmbedCount = 0;
  26. video.hasiframeCount = 0;
  27. video.$items = base.$items.filter(':not(.cloned)');
  28. // find and save all known videos
  29. for (service in video.services) {
  30. if (typeof(service) === 'string') {
  31. sel = video.services[service].selector;
  32. video.$items.find(sel).each(function(){
  33. tmp = $(this);
  34. // save panel and video selector in the list
  35. tmp.attr('id', video.options.videoID + video.len);
  36. video.list[video.len] = {
  37. id : video.options.videoID + video.len++,
  38. panel : tmp.closest('.panel')[0],
  39. service : service,
  40. selector : sel,
  41. status : -1 // YouTube uses -1 to mean the video is unstarted
  42. };
  43. video.hasVid = true;
  44. if (sel.match('embed|object')) {
  45. video.hasEmbed = true;
  46. video.hasEmbedCount++;
  47. } else if (sel.match('iframe')) {
  48. video.hasiframeCount++;
  49. }
  50. });
  51. }
  52. }
  53. // Initialize each video, as needed
  54. $.each(video.list, function(i,s){
  55. // s.id = ID, s.panel = slider panel (DOM), s.selector = 'jQuery selector'
  56. var tmp, $tar, vidsrc, opts,
  57. $vid = $(s.panel).find(s.selector),
  58. service = video.services[s.service],
  59. api = service.initAPI || '';
  60. // Initialize embeded video javascript api using SWFObject, if loaded
  61. if (video.hasEmbed && video.hasSwfo && s.selector.match('embed|object')) {
  62. $vid.each(function(){
  63. // Older IE doesn't have an object - just make sure we are wrapping the correct element
  64. $tar = ($(this).parent()[0].tagName === 'OBJECT') ? $(this).parent() : $(this);
  65. vidsrc = ($tar[0].tagName === 'EMBED') ? $tar.attr('src') : $tar.find('embed').attr('src') || $tar.children().filter('[name=movie]').attr('value');
  66. opts = $.extend(true, {}, {
  67. flashvars : null,
  68. params : { allowScriptAccess: 'always', wmode : base.options.addWmodeToObject, allowfullscreen : true },
  69. attr : { 'class' : $tar.attr('class'), 'style' : $tar.attr('style'), 'data-url' : vidsrc }
  70. }, service.embedOpts);
  71. $tar.wrap('<div id="' + s.id + '"></div>');
  72. // use SWFObject if it exists, it replaces the wrapper with the object/embed
  73. swfobject.embedSWF(vidsrc + (api === '' ? '': api + s.id), s.id,
  74. $tar.attr('width'), $tar.attr('height'), '10', null,
  75. opts.flashvars, opts.params, opts.attr, function(){
  76. // run init code if it exists
  77. if (service.hasOwnProperty('init')) {
  78. video.list[i].player = service.init(base, s.id, i);
  79. }
  80. if (i >= video.hasEmbedCount) {
  81. base.$el.trigger('swf_completed', base); // swf callback
  82. }
  83. }
  84. );
  85. });
  86. } else if (s.selector.match('iframe')) {
  87. $vid.each(function(i,v){
  88. vidsrc = $(this).attr('src');
  89. tmp = (vidsrc.match(/\?/g) ? '' : '?') + '&wmode=' + base.options.addWmodeToObject; // string connector & wmode
  90. $(this).attr('src', function(i,r){ return r + tmp + (api === '' ? '': api + s.id); });
  91. });
  92. }
  93. });
  94. // Returns URL parameter; url: http://www.somesite.com?name=hello&id=11111
  95. // Original code from Netlobo.com (http://www.netlobo.com/url_query_string_javascript.html)
  96. video.gup = function(n,s){
  97. n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
  98. var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s || window.location.href);
  99. return (p===null) ? "" : p[1];
  100. };
  101. // postMessage to iframe - http://benalman.com/projects/jquery-postmessage-plugin/ (FOR IE7)
  102. video.postMsg = function(data, vid){
  103. var $vid = $('#' + vid);
  104. if ($vid.length){
  105. $vid[0].contentWindow.postMessage(data, $vid.attr('src').split('?')[0]);
  106. }
  107. };
  108. // receive message from iframe
  109. video.message = function(e){
  110. if (e.data) {
  111. if (/infoDelivery/g.test(e.data)) { return; } // ignore youtube video loading spam
  112. var data = $.parseJSON(e.data);
  113. $.each(video.list, function(i,s){
  114. if (video.services[video.list[i].service].hasOwnProperty('message')) {
  115. video.services[video.list[i].service].message(base, data);
  116. }
  117. });
  118. }
  119. };
  120. // toDO = 'cont', 'pause' or 'isPlaying'
  121. video.control = function(toDo){
  122. var i,
  123. s = video.list,
  124. slide = (toDo === 'pause') ? base.$lastPage[0] : base.$currentPage[0],
  125. isPlaying = false;
  126. for (i=0; i < video.len; i++){
  127. if (s[i].panel === slide && video.services[s[i].service].hasOwnProperty(toDo)){
  128. isPlaying = video.services[s[i].service][toDo](base, s[i].id, i);
  129. }
  130. }
  131. return isPlaying;
  132. };
  133. // iframe event listener
  134. if (video.hasiframeCount){
  135. if (window.addEventListener){
  136. window.addEventListener('message', video.message, false);
  137. } else { // IE
  138. window.attachEvent('onmessage', video.message, false);
  139. }
  140. }
  141. // bind to events
  142. base.$el
  143. .bind('slide_init', function(){
  144. video.control('pause');
  145. })
  146. .bind('slide_complete', function(){
  147. video.control('cont');
  148. });
  149. base.options.isVideoPlaying = function(){ return video.control('isPlaying'); };
  150. });
  151. };
  152. /* Each video service is set up as follows
  153. * service-name : {
  154. * // initialization
  155. * selector : 'object[data-url*=service], embed[src*=service]', // required: jQuery selector used to find the video ('video' or 'iframe[src*=service]' are other examples)
  156. * initAPI : 'string added to the URL to initialize the API', // optional: the string must end with a parameter pointing to the video id (e.g. "&player_id=")
  157. * embedOpts : { flashvars: {}, params: {}, attr: {} }, // optional: add any required flashvars, parameters or attributes to initialize the API
  158. * // video startup functions
  159. * init : function(base, vid, index){ }, // optional: include any additional initialization code here; function called AFTER the embeded video is added using SWFObject
  160. * // required functions
  161. * cont : function(base, vid, index){ }, // required: continue play if video was previously played
  162. * pause : function(base, vid, index){ }, // required: pause ALL videos
  163. * message : function(base, data){ }, // required for iframe: process data received from iframe and update the video status for the "isPlaying" function
  164. * isPlaying : function(base, vid, index){ } // required: return true if video is playing and return false if not playing (paused or ended)
  165. * }
  166. *
  167. * Function variables
  168. * base (object) = plugin base, all video values/functions are stored in base.video
  169. * vid (string) is the ID of the video: vid = "asvideo1"; so jQuery needs a "#" in front... "#" + videoID option default ("asvideo") + index (e.g. "1"); each video matching a service will have a unquie vid
  170. * index (number) is the unique video number from the vid (starts from zero)
  171. *
  172. * var list = base.video.list[index]; list will contain:
  173. * list.id = vid
  174. * list.service = service name (e.g. 'video', 'vimeo1', 'vimeo2', etc)
  175. * list.selector = 'jQuery selector' (e.g. 'video', 'object[data-url*=vimeo]', 'iframe[src*=vimeo]', etc)
  176. * list.panel = AnythingSlider panel DOM object. So you can target the video using $(list[index].panel).find(list[index].service) or $('#' + vid)
  177. * list.status = video status, updated by the iframe event listeners added in the video service "ready" function; see examples below
  178. */
  179. $.fn.anythingSliderVideo.services = {
  180. // *** HTML5 video ***
  181. video : {
  182. selector : 'video',
  183. cont : function(base, vid, index){
  184. var $vid = $('#' + vid);
  185. if ($vid.length && $vid[0].paused && $vid[0].currentTime > 0 && !$vid[0].ended) {
  186. $vid[0].play();
  187. }
  188. },
  189. pause : function(base, vid){
  190. // pause ALL videos on the page
  191. $('video').each(function(){
  192. if (typeof(this.pause) !== 'undefined') { this.pause(); } // throws an error in older ie without this
  193. });
  194. },
  195. isPlaying : function(base, vid, index){
  196. var $vid = $('#' + vid);
  197. // media.paused seems to be the only way to determine if a video is playing
  198. return ($vid.length && typeof($vid[0].pause) !== 'undefined' && !$vid[0].paused && !$vid[0].ended) ? true : false;
  199. }
  200. },
  201. // *** Vimeo iframe *** isolated demo: http://jsfiddle.net/Mottie/GxwEX/
  202. vimeo1 : {
  203. selector : 'iframe[src*=vimeo]',
  204. initAPI : '&api=1&player_id=', // video ID added to the end
  205. cont : function(base, vid, index){
  206. if (base.video.list[index].status === 'pause'){
  207. // Commands sent to the iframe originally had "JSON.stringify" applied to them,
  208. // but not all browsers support this, so it's just as easy to wrap it in quotes.
  209. base.video.postMsg('{"method":"play"}', vid);
  210. }
  211. },
  212. pause : function(base, vid){
  213. // pause ALL videos on the page
  214. $('iframe[src*=vimeo]').each(function(){
  215. base.video.postMsg('{"method":"pause"}', this.id);
  216. });
  217. },
  218. message : function(base, data){
  219. // *** VIMEO *** iframe uses data.player_id
  220. var index, vid = data.player_id || ''; // vid = data.player_id (unique to vimeo)
  221. if (vid !== ''){
  222. index = vid.replace(base.video.options.videoID, '');
  223. if (data.event === 'ready') {
  224. // Vimeo ready, add additional event listeners for video status
  225. base.video.postMsg('{"method":"addEventListener","value":"play"}', vid);
  226. base.video.postMsg('{"method":"addEventListener","value":"pause"}', vid);
  227. base.video.postMsg('{"method":"addEventListener","value":"finish"}', vid);
  228. }
  229. // update current status - vimeo puts it in data.event
  230. if (base.video.list[index]) { base.video.list[index].status = data.event; }
  231. }
  232. },
  233. isPlaying : function(base, vid, index){
  234. return (base.video.list[index].status === 'play') ? true : false;
  235. }
  236. },
  237. // *** Embeded Vimeo ***
  238. // SWFObject adds the url to the object data
  239. // using param as a selector, the script above looks for the parent if it sees "param"
  240. vimeo2 : {
  241. selector : 'object[data-url*=vimeo], embed[src*=vimeo]',
  242. embedOpts : { flashvars : { api : 1 } },
  243. cont : function(base, vid, index) {
  244. var $vid = $('#' + vid);
  245. // continue video if previously played & not finished (api_finish doesn't seem to exist) - duration can be a decimal number, so subtract it and look at the difference (2 seconds here)
  246. if (typeof($vid[0].api_play) === 'function' && $vid[0].api_paused() && $vid[0].api_getCurrentTime() !== 0 && ($vid[0].api_getDuration() - $vid[0].api_getCurrentTime()) > 2) {
  247. $vid[0].api_play();
  248. }
  249. },
  250. pause : function(base, vid){
  251. // find ALL videos and pause them, just in case
  252. $('object[data-url*=vimeo], embed[src*=vimeo]').each(function(){
  253. var el = (this.tagName === 'EMBED') ? $(this).parent()[0] : this;
  254. if (typeof(el.api_pause) === 'function') {
  255. el.api_pause();
  256. }
  257. });
  258. },
  259. isPlaying : function(base, vid, index){
  260. var $vid = $('#' + vid);
  261. return (typeof($vid[0].api_paused) === 'function' && !$vid[0].api_paused()) ? true : false;
  262. }
  263. },
  264. // *** iframe YouTube *** isolated demo: http://jsfiddle.net/Mottie/qk5MY/
  265. youtube1 : {
  266. selector : 'iframe[src*=youtube]',
  267. // "iv_load_policy=3" should turn off annotations on init, but doesn't seem to
  268. initAPI : '&iv_load_policy=3&enablejsapi=1&playerapiid=',
  269. cont : function(base, vid, index){
  270. if (base.video.list[index].status === 2){
  271. base.video.postMsg('{"event":"command","func":"playVideo"}', vid);
  272. }
  273. },
  274. pause : function(base, vid, index){
  275. // pause ALL videos on the page - in IE, pausing a video means it will continue when next seen =(
  276. $('iframe[src*=youtube]').each(function(){
  277. // if (this.id !== vid || (this.id === vid && base.video.list[index].status >= 0)) { // trying to fix the continue video problem; this only breaks it
  278. base.video.postMsg('{"event":"command","func":"pauseVideo"}', vid);
  279. // }
  280. });
  281. },
  282. message : function(base, data){
  283. if (data.event === 'infoDelivery') { return; } // ignore youtube video loading spam
  284. // *** YouTube *** iframe returns an embeded url (data.info.videoUrl) but no video id...
  285. if (data.info && data.info.videoUrl) {
  286. // figure out vid for youtube
  287. // data.info.videoURL = http://www.youtube.com/watch?v=###########&feature=player_embedded
  288. var url = base.video.gup('v', data.info.videoUrl), // end up with ###########, now find it
  289. vid = $('iframe[src*=' + url + ']')[0].id,
  290. index = vid.replace(base.video.options.videoID, '');
  291. // YouTube ready, add additional event listeners for video status. BUT this never fires off =(
  292. // Fixing this may solve the continue problem
  293. if (data.event === 'onReady') {
  294. base.video.postMsg('{"event":"listening","func":"onStateChange"}', vid); // **** FIX: NEED TO DETERMINE VID ***
  295. }
  296. // Update status, so the "isPlaying" function can access it
  297. if (data.event === 'onStateChange' && base.video.list[index]) {
  298. // update list with current status; data.state = YouTube
  299. base.video.list[index].status = data.state;
  300. }
  301. }
  302. },
  303. isPlaying : function(base, vid, index){
  304. var status = base.video.list[index].status;
  305. // state: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
  306. return (status === 1 || status > 2) ? true : false;
  307. }
  308. },
  309. // *** Embeded YouTube ***
  310. // include embed for IE; SWFObject adds the url to the object data attribute
  311. youtube2 : {
  312. selector : 'object[data-url*=youtube], embed[src*=youtube]',
  313. initAPI : '&iv_load_policy=3&enablejsapi=1&version=3&playerapiid=', // video ID added to the end
  314. // YouTube - player states: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
  315. cont : function(base, vid, index) {
  316. var $vid = $('#' + vid);
  317. // continue video if previously played and not cued
  318. if ($vid.length && typeof($vid[0].getPlayerState) === 'function' && $vid[0].getPlayerState() > 0) {
  319. $vid[0].playVideo();
  320. }
  321. },
  322. pause : function(base, vid){
  323. // find ALL videos and pause them, just in case
  324. $('object[data-url*=youtube], embed[src*=youtube]').each(function(){
  325. var el = (this.tagName === 'EMBED') ? $(this).parent()[0] : this;
  326. // player states: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
  327. if (typeof(el.getPlayerState) === 'function' && el.getPlayerState() > 0) {
  328. // pause video if not autoplaying (if already initialized)
  329. el.pauseVideo();
  330. }
  331. });
  332. },
  333. isPlaying : function(base, vid){
  334. var $vid = $('#' + vid);
  335. return (typeof($vid[0].getPlayerState) === 'function' && ($vid[0].getPlayerState() === 1 || $vid[0].getPlayerState() > 2)) ? true : false;
  336. }
  337. }
  338. };
  339. })(jQuery);
  340. // Initialize video extension automatically
  341. jQuery(window).load(function(){
  342. jQuery('.anythingBase').anythingSliderVideo();
  343. });