]> khamidou — GitHub mirrors - popcorn-js.git/commitdiff
[#280] Wrapper coded, unit tests written
authorstevenaw <sweerdenburg@gmail.com>
Tue, 8 Mar 2011 02:57:15 +0000 (21:57 -0500)
committerstevenaw <sweerdenburg@gmail.com>
Tue, 8 Mar 2011 02:57:15 +0000 (21:57 -0500)
players/vimeo/froogaloop.min.js [new file with mode: 0644]
players/vimeo/popcorn.vimeo.html [new file with mode: 0644]
players/vimeo/popcorn.vimeo.js [new file with mode: 0644]
players/vimeo/popcorn.vimeo.unit.html [new file with mode: 0644]
players/vimeo/popcorn.vimeo.unit.js [new file with mode: 0644]
popcorn.js

diff --git a/players/vimeo/froogaloop.min.js b/players/vimeo/froogaloop.min.js
new file mode 100644 (file)
index 0000000..f911b71
--- /dev/null
@@ -0,0 +1,5 @@
+var Froogaloop=function(){var e={hasWindowEvent:false,PLAYER_DOMAIN:"",eventCallbacks:{},iframe_pattern:/player\.(([a-zA-Z0-9_\.]+)\.)?vimeo(ws)?\.com\/video\/([0-9]+)/i},j=function(b){b||(b=document.getElementsByTagName("iframe"));for(var a,c=0,f=b.length,g;c<f;c++){a=b[c];if(g=e.iframe_pattern.test(a.getAttribute("src"))){a.api=h.api;a.get=h.get;a.addEvent=h.addEvent}}},h={api:function(b,a){i(b,a,this)},get:function(b,a){k(b,a,this.id!=""?this.id:null);i(b,null,this)},addEvent:function(b,a){k(b,
+a,this.id!=""?this.id:null);b!="onLoad"&&i("api_addEventListener",[b,a.name],this);if(e.hasWindowEvent)return false;e.PLAYER_DOMAIN=d.getDomainFromUrl(this.getAttribute("src"));window.addEventListener?window.addEventListener("message",l,false):window.attachEvent("onmessage",l,false);e.hasWindowEvent=true}},i=function(b,a,c){if(!c.contentWindow.postMessage)return false;if(a===undefined||a===null)a="";var f=c.getAttribute("src").split("?")[0];b=d.serialize({method:b,params:a,id:c.getAttribute("id")});
+c.contentWindow.postMessage(b,f)},k=function(b,a,c){if(c){e.eventCallbacks[c]||(e.eventCallbacks[c]={});e.eventCallbacks[c][b]=a}else e.eventCallbacks[b]=a},l=function(b){if(b.origin!=e.PLAYER_DOMAIN)return false;var a=d.unserialize(b.data);b=a.params?a.params.split('"').join("").split(","):"";a=a.method;var c=b[b.length-1];if(c=="")c=null;if(a=c?e.eventCallbacks[c][a]:e.eventCallbacks[a])b.length>0?a.apply(null,b):a.call()},d={r20:/%20/g,isArray:function(b){return Object.prototype.toString.call(b)===
+"[object Array]"},isFunction:function(b){return Object.prototype.toString.call(b)==="[object Function]"},unserialize:function(b){if(!b)return false;var a={};b=b.split("&");for(var c,f,g=0;g<b.length;g++){c=unescape(b[g].split("=")[0]);f=unescape(b[g].split("=")[1]);if(f.indexOf("=")>-1)f=d.unserialize(f);a[c]=f}return a},s:false,serialize:function(b){d.s=[];for(var a in b)d.buildParams(a,b[a]);return d.s.join("&").replace(d.r20,"+")},buildParams:function(b,a){var c=0;if(d.isArray(a)){for(;c<a.length;c++)a[c]=
+encodeURIComponent(a[c]);d.addToParam(encodeURIComponent(b),a.join(","))}else d.addToParam(encodeURIComponent(b),encodeURIComponent(a))},addToParam:function(b,a){a=d.isFunction(a)?a():a;d.s[d.s.length]=b+"="+a},getDomainFromUrl:function(b){b=b.split("/");for(var a="",c=0;c<b.length;c++){if(c<3)a+=b[c];else break;if(c<2)a+="/"}return a}};j();return{init:j}}();
\ No newline at end of file
diff --git a/players/vimeo/popcorn.vimeo.html b/players/vimeo/popcorn.vimeo.html
new file mode 100644 (file)
index 0000000..507f223
--- /dev/null
@@ -0,0 +1,149 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>Popcorn Vimeo Player Example</title>
+        <style>
+            iframe{
+                display:block;
+                border:0;
+            }
+            body > div {
+                width: 100%;
+                float: left;
+                overflow: hidden;
+            }
+            div div {
+                margin-bottom:20px;
+            }
+
+            .api_output {
+                float:right;
+                padding-left: 20px;
+            }
+        </style>
+        
+        
+        <script src="../../popcorn.js"></script>
+        <script type="text/javascript" src="popcorn.vimeo.js"></script>
+        <script src="../../plugins/footnote/popcorn.footnote.js"></script>
+        
+        <script type="text/javascript">
+            // Called as onload function
+            // Set up interface controls
+            VimeoEmbedLoaded = function( player ) {
+                var loop = 0,
+                    volume = 1;
+                
+                // Hook up custom controls
+                // Single play/pause buttons
+                document.getElementById( "btnPlay" ).addEventListener( "click", function(e) {
+                  player.play();
+                }, false);
+                
+                document.getElementById( "btnPause" ).addEventListener( "click", function(e) {
+                    player.pause();
+                }, false);
+                
+                //Seek
+                document.getElementById( "btnSeek" ).addEventListener( "click", function() {
+                  player.currentTime( 30 );
+                }, false);
+
+                // Loop
+                document.getElementById( "btnLoop" ).addEventListener( "click", function() {
+                  loop = loop === "loop" ? "" : "loop";
+                  player.loop( loop );
+                }, false);
+
+                // Volume
+                document.getElementById( "btnVolume" ).addEventListener( "click", function() {
+                  volume = volume === 1 ? 0.5 : 1;
+                  player.volume( volume );
+                }, false);
+                
+                // Mute
+                document.getElementById( "btnMute" ).addEventListener( "click", function() {
+                  player.volume( 0 );
+                }, false);
+                
+                // Hook into player events
+                // Timeupdate, as the video plays
+                player.listen( "timeupdate", function() {
+                  document.getElementById( "player_time" ).innerHTML = player.currentTime();
+                });
+                
+                // When the volume changes
+                player.listen( "volumechange", function() {
+                  document.getElementById( "player_vol" ).innerHTML = player.volume();
+                });
+                
+                // When the video duration changes
+                player.listen( "durationchange", function() {
+                  document.getElementById( "player_duration" ).innerHTML = player.duration();
+                });
+                
+                // When the meddia ready state changes
+                player.listen( "readystatechange", function() {
+                  document.getElementById( "player_state" ).innerHTML = player.readyState();
+                });
+                
+                // Output some initial UI values so we caan see what the player is doing
+                document.getElementById( "player_time" ).innerHTML = player.currentTime();
+                document.getElementById( "player_vol" ).innerHTML = player.volume();
+            };
+
+            //On document ready
+            document.addEventListener( "DOMContentLoaded", function() {
+              var player = Popcorn.vimeo( "player_1", "http://vimeo.com/11127501" )
+                    .footnote({
+                      start: 5, // seconds
+                      end: 40, // seconds
+                      text: 'The video is "RiP: A Remix Manifesto", by Brett Gaylor',
+                      target: 'footnotediv'
+                    })
+                    .listen( "load", function() {
+                      VimeoEmbedLoaded( player );
+                    })
+                    .listen( "loadstart", function() {
+                      document.getElementById( "player_load" ).innerHTML = "Started";
+                    });
+            }, false);
+        </script>
+    </head>
+    <body>
+        <div>
+           <div style="float:right;">
+            <h3>Description</h3>
+            <p>
+              This demo will showcase how a Vimeo flash video can be integrated into Popcorn. This  is done by making the flash video masquerade as HTML 5 video.<br />
+              Due to the Flash security model, this demo must be  run from a web server<br />
+              From 5 to 40 seconds, the footnote 'The video is "RiP: A Remix Manifesto", by Brett Gaylor' will appear below 'Footnote Area'.
+            <hr >
+              Vimeo does not support their player to be chromeless (hidden controls), but custsom controls have been developed and tied into their player.<br />
+              Clicking play/pause or seeking in either the video or via custsom controls will cause the other to update.<br />
+              Clicking on the embed option in the Vimeo player while the video is playing will cause the video to pause and custom controls to update.<br />
+              The vimeo video can be specified in the HTML source by giving the vimeo web site url (http://vimeo.com/VIDEOID) to either the VimeoEngine or as the iframe src attribute.<br/>
+            </p>
+            <br />
+            <br />
+            <br />
+            <div id="footnotediv" width="50%" height="50%">
+              <strong>Footnote Area</strong><br />
+            </div>
+          </div>
+          <iframe id="player_1" width="500" height="281" frameborder="0"></iframe>
+          <button class="simple" id="btnPlay">Play</button>
+          <button class="simple" id="btnPause">Pause</button>
+          <button class="seek" id="btnSeek">Seek to 30</button>
+          <button class="loop" id="btnLoop">Toggle Loop</button>
+          <button class="volume" id="btnVolume">Toggle Volume</button>
+          <button class="volume" id="btnMute">Mute</button>
+          <div>
+            Current Time (s): <span id="player_time"></span>
+            <br />Video Duration (s): <span id="player_duration"></span>
+            <br />Volume (0-1): <span id="player_vol"></span>
+            <br />Load Status: <span id="player_load">Not Started</span>
+          </div>
+        </div>
+    </body>
+</html>
\ No newline at end of file
diff --git a/players/vimeo/popcorn.vimeo.js b/players/vimeo/popcorn.vimeo.js
new file mode 100644 (file)
index 0000000..2ac1b29
--- /dev/null
@@ -0,0 +1,478 @@
+// Popcorn Vimeo Player Wrapper
+( function( Popcorn ) {
+  /**
+  * Vimeo wrapper for Popcorn.
+  * This player adds enables Popcorn.js to handle Vimeo videos. It does so by masking an embedded Vimeo video iframe
+  * as a video and implementing the HTML5 Media Element interface.
+  *
+  * To use this plug-in, include the Vimeo JavaScript API Froogaloop in the parent HTML page as well as the embedded Vimeo iframe:
+  *
+  *   <script src="https://github.com/downloads/vimeo/froogaloop/froogaloop.v1.0.min.js"></script>
+  *
+  * You can specify the video in three ways:
+  *  1. Use the embed code supplied by Vimeo, and pass the iframe id into a new Popcorn.VimeoEngine object
+  *
+  *    <iframe id="player_1" src="http://player.vimeo.com/video/11127501?js_api=1&js_swf_id=player_1" width="500" height="281" frameborder="0"></iframe>
+  *    <script type="text/javascript">
+  *      document.addEventListener("DOMContentLoaded", function() {
+  *        var player = Popcorn.vimeo( "player_1" );
+  *      }, false);
+  *    </script>
+  *
+  *  2. Use an empty iframe and give both the iframe id and the web url when creating a new Popcorn.VimeoEngine
+  *
+  *    <iframe id="player_1" width="500" height="281" frameborder="0"></iframe>
+  *    <script type="text/javascript">
+  *      document.addEventListener("DOMContentLoaded", function() {
+  *        var player = Popcorn.vimeo( "player_1", "http://vimeo.com/11127501" );
+  *      }, false);
+  *    </script>
+  *
+  *  3. Set the iframe's src attribute to the vimeo video's web url, and pass the id when creating a new Popcorn.VimeoEngine
+  *
+  *    <iframe id="player_1" src="http://vimeo.com/11127501" width="500" height="281" frameborder="0"></iframe>
+  *    <script type="text/javascript">
+  *      document.addEventListener("DOMContentLoaded", function() {
+  *        var player = Popcorn.vimeo( "player_1" );
+  *      }, false);
+  *    </script>
+  *
+  * Due to Vimeo's API, certain events must be subscribed to at different times, and some not at all.
+  * These events are completely custom-implemented and may be subscribed to at any time:
+  *   durationchange
+  *   load
+  *   loadstart
+  *   play
+  *   readystatechange
+  *   volumechange
+  *
+  * These events are related to player functionality and must be subscribed to during or after the load event:
+  *   abort
+  *   emptied
+  *   ended
+  *   pause
+  *   playing
+  *   progress
+  *   seeked
+  *   timeupdate
+  *
+  * These events are not supported:
+  *   canplay
+  *   canplaythrough
+  *   error
+  *   loadeddata
+  *   loadedmetadata
+  *   ratechange
+  *   seeking
+  *   stalled
+  *   suspend
+  *   waiting
+  *
+  * Due to Vimeo's API, some attributes are be supported while others are not.
+  * Supported media attributes:
+  *   autoplay ( via Popcorn )
+  *   currentTime ( get only, set by calling setCurrentTime() )
+  *   duration ( get only )
+  *   ended ( get only )
+  *   initialTime ( get only, always 0 )
+  *   loop ( get only, set by calling setLoop() )
+  *   muted ( get only, set by calling setVolume(0) )
+  *   paused ( get only )
+  *   readyState ( get only )
+  *   src ( get only )
+  *   volume ( get only, set by calling setVolume() )
+  *
+  *   load() function
+  *
+  * Unsupported media attributes:
+  *   buffered
+  *   defaultPlaybackRate
+  *   networkState
+  *   playbackRate
+  *   played
+  *   preload
+  *   seekable
+  *   seeking
+  *   startOffsetTime
+  */
+  
+  // base object for DOM-related behaviour like events
+  var LikeADOM = function ( owner ) {
+    var evts = {};
+    var makeHandler = function( evtName ) {
+      if ( !evts[evtName] ) {
+        evts[evtName] = [];
+        
+        // Create a wrapper function to all registered listeners
+        this["on"+evtName] = function() {
+          Popcorn.forEach( evts[evtName], function( fn ) {
+            if ( fn ) {
+              fn.call( owner );
+            }
+          });
+        }
+      }
+    };
+    
+    return {
+      addEventListener: function( evtName, fn, doFire ) {
+        evtName = evtName.toLowerCase();
+        
+        makeHandler.call( this, evtName );
+        evts[evtName].push( fn );
+        
+        if ( doFire ) {
+          dispatchEvent( evtName );
+        }
+        
+        return fn;
+      },
+      // Add many listeners for a single event
+      // Takes an event name and array of functions
+      addEventListeners: function( evtName, events ) {
+        evtName = evtName.toLowerCase();
+        
+        makeHandler.call( this, evtName );
+        evts[evtName] = evts[evtName].concat( events );
+      },
+      removeEventListener: function( evtName, fn ) {
+        var evtArray = this.getEventListeners( evtName ),
+            i,
+            l;
+        
+        // Find and remove from events array
+        for ( i = 0, l = evtArray.length; i < l; i++) {
+          if ( evtArray[i] === fn ) {
+            var removed = evtArray[i];
+            evtArray[i] = 0;
+            return removed;
+          }
+        }
+      },
+      getEventListeners: function( evtName ) {
+        if( evtName ) {
+          return evts[ evtName.toLowerCase() ] || [];
+        } else {
+          return evts;
+        }
+      },
+      dispatchEvent: function( evt ) {        
+        // If event object was passed in, toString will yield event type as string (timeupdate)
+        // If a string, toString() will return the string itself (timeupdate)
+        var evt = "on"+evt.toString().toLowerCase();
+        this[evt] && this[evt]();
+      }
+    };
+  };
+  
+  Popcorn.vimeo = function( mediaId, list ) {
+    return new Popcorn.vimeo.init( mediaId, list );
+  };
+  
+  // A constructor, but we need to wrap it to allow for "static" functions
+  Popcorn.vimeo.init = (function() {
+    var rPlayerUri = /^http:\/\/player\.vimeo\.com\/video\/[\d]+/i,
+        rWebUrl = /vimeo\.com\/[\d]+/,
+        registry = [],
+        hasAPILoaded = false;
+        
+    // Source file is from https://github.com/vimeo/froogaloop/blob/master/froogaloop.min.js
+    // HTTPS seems to have some difficulties with getScript, so store locally
+    Popcorn.getScript( "./froogaloop.min.js", function() {
+      var i,
+          l = registry.length;
+          
+      hasAPILoaded = true;
+      for( i=0; i<l; i++ ) {
+        registry[i].addEventListener.transferToHandler.call( registry[i] );
+      }
+    });
+    
+    // Extract the numeric video id from container uri: 'http://player.vimeo.com/video/11127501' or 'http://player.vimeo.com/video/4282282'
+    // Expect id to be a valid 32/64-bit unsigned integer
+    // Returns string, empty string if could not match
+    function extractIdFromUri( uri ) {
+      var matches = uri.match( rPlayerUri );
+      return matches ? matches[0].substr(30) : "";
+    };
+    
+    // Extract the numeric video id from url: 'http://vimeo.com/11127501' or simply 'vimeo.com/4282282'
+    // Ignores protocol and subdomain, but one would expecct it to be http://www.vimeo.com/#######
+    // Expect id to be a valid 32/64-bit unsigned integer
+    // Returns string, empty string if could not match
+    function extractIdFromUrl( url ) {
+      var matches = url.match( rWebUrl );
+      return matches ? matches[0].substr(10) : "";
+    };
+  
+    // If container id is not supplied, assumed to be same as player id
+    var ctor = function ( containerId, videoUrl ) {
+      if ( !containerId ) {
+        throw "Must supply an id!";
+      }
+      
+      var vidId,
+          that = this;
+      
+      this.swfObj = document.getElementById( containerId ),
+      this.addEventFn,
+      this.evtHolder,
+      this.popped,
+      this.autoplay,
+      this.readyState = 0,
+      this.objVars;
+          
+      if ( !this.swfObj ) {
+        throw "Invalid id, could not find it!";
+      }
+      
+      this.evtHolder = new LikeADOM( this );
+      this.autoplay = this.swfObj.autoplay;
+      
+      // Tracking variables for the video player
+      // Better to store them here than on the DOM
+      this.objVars = {
+        paused: true,
+        duration: -1,
+        ended: 0,
+        currentTime: -1,
+        volume: 1,
+        loop: 0,
+        initialTime: 0,
+        played: 0,
+      };
+      
+      // Try and get a video id from a vimeo site url
+      // Try either from ctor param or from iframe itself
+      if( videoUrl ) {
+        vidId = extractIdFromUrl( videoUrl );
+      } else {
+        vidId = extractIdFromUrl( this.swfObj.src )
+      }
+      
+      // If was able to gete a video id
+      if ( vidId ) {
+        // Set iframe source to vimeo player and id
+        // Note that speccifying a web url will over-write any src attribute already on the iframe
+        this.swfObj.src = "http://player.vimeo.com/video/"+vidId+"?js_api=1&js_swf_id="+containerId;
+      }
+      
+      registry.push( this );
+      
+      if( hasAPILoaded ) {
+        Froogaloop.init( [ this.swfObj ] );
+      } else {
+        // API not ready, temporarily hold events here, will be transfered over shortly
+        // This is in case an object is instantiated and played around with before the Vimeo API is ready
+        this.addEventListener = (function() {
+          // Make a lightweight collection
+          var evts = {},
+              retFn;
+              
+          retFn = function( evt, fn ) {
+              evt = evt.toLowerCase();
+              
+              if ( !evts[evt] ) {
+                evts[evt] = [];
+              }
+              
+              evts[evt].push( fn );
+            }
+            
+          retFn.transferToHandler = function() {
+            Froogaloop.init( [ this.swfObj ] );
+            
+            // No need to keep caching events, now we can connect them to the API directly!
+            this.addEventListener = Popcorn.vimeo.prototype.addEventListener;
+            
+            Popcorn.forEach( evts, function( evtArray, evtName ) {
+              // Must call once on own to link up event to Froogaloop events
+              // Splice off first callback to setup link
+              that.addEventListener( evtName, evtArray.splice( 0, 1 )[0] );
+              
+              // Splice call above modified the array. Link rest up quickly
+              that.evtHolder.addEventListeners( evtName, evtArray );
+            });
+            
+            // GC Function
+            retFn = null;
+          };
+          
+          return retFn;
+        })();
+      }
+      
+      // Set up listeners to internally track state as needed
+      this.addEventListener( "load", function() {
+        var loadingFn;
+        
+        that.swfObj.get( "api_getDuration", function( duration ) {
+          that.objVars.duration = duration;
+          that.evtHolder.dispatchEvent( "durationchange" );
+        });
+        
+        // Chain events and calls together so that this.currentTime reflects the current time of the video
+        // Done by Getting the Current Time while the video plays
+        that.swfObj.addEvent( "onProgress", function() {
+          that.swfObj.get( "api_getCurrentTime", function( time ) {
+            that.objVars.currentTime = parseFloat( time );
+            that.evtHolder.dispatchEvent( "timeupdate" );
+          });
+        });
+        
+        // Add pause listener to keep track of playing state
+        that.addEventListener( "pause", function() {
+          that.objVars.paused = true;
+        });
+        
+        // Add play listener to keep track of playing state
+        that.addEventListener( "playing", function() {
+          that.objVars.paused = false;
+          that.objVars.ended = 0;
+        });
+        
+        // Add ended listener to keep track of playing state
+        that.addEventListener( "ended", function() {
+          if ( that.objVars.loop !== "loop" ) {
+            that.objVars.paused = true;
+            that.objVars.ended = 1;
+          }
+        });
+        
+        // Add progress listener to keep track of ready state
+        loadingFn = that.addEventListener( "progress", function() {
+          that.readyState = 3;
+          that.evtHolder.dispatchEvent( "readystatechange" );
+          that.evtHolder.removeEventListener( "progress", loadingFn );
+        });
+      });
+    
+      // 'this' is a video wrapper, so put into Popcorn and return the result
+      this.popped = Popcorn( this );      
+      return this.popped;
+    }
+    return ctor;
+  })();
+  
+  Popcorn.vimeo.init.prototype = Popcorn.vimeo.prototype;
+  
+  // Sequence object prototype
+  Popcorn.extend( Popcorn.vimeo.prototype, {
+    // Do everything as functions instead of get/set
+    loop: function( val ) {
+      if ( !val ) {
+        return this.objVars.loop;
+      }
+      
+      this.objVars.loop = val;
+      var isLoop = val === "loop" ? 1 : 0;
+      // HTML convention says to loop if value is 'loop'
+      this.swfObj.api('api_setLoop', isLoop );
+    },
+    // Set the volume as a value between 0 and 1
+    volume: function( val ) {
+      if ( !val && val !== 0 ) {
+        return this.objVars.volume;
+      }
+      
+      // Normalize in case outside range of expected values
+      if ( val < 0 ) {
+        val = -val;
+      }
+      
+      if ( val > 1 ) {
+        val %= 1;
+      }
+      
+      // HTML video expects to be 0.0 -> 1.0, Vimeo expects 0-100
+      this.objVars.volume = val;
+      this.swfObj.api( "api_setVolume", val*100 );
+      this.evtHolder.dispatchEvent( "volumechange" );
+    },
+    // Seeks the video
+    currentTime: function ( time ) {
+      if ( !time && time !== 0 ) {
+        return this.objVars.currentTime;
+      }
+      
+      this.objVars.currentTime = time;
+      this.objVars.ended = time < this.objVars.duration;
+      this.swfObj.api( "api_seekTo", time );
+      
+      // Fire events for seeking and time change
+      this.evtHolder.dispatchEvent( "seeked" );
+      this.evtHolder.dispatchEvent( "timeupdate" );
+    },
+    // Play the video
+    play: function() {
+      if ( !this.objVars.played ) {
+        this.objVars.played = 1;
+        this.evtHolder.dispatchEvent( "loadstart" );
+      }
+      
+      this.evtHolder.dispatchEvent( "play" );
+      this.swfObj.api( "api_play" );
+    },
+    // Pauses the video
+    pause: function() {
+      this.swfObj.api( "api_pause" );
+    },
+    duration: function() {
+      return this.objVars.duration;
+    },
+    muted: function() {
+      return this.objVars.volume === 0;
+    },
+    // Force loading by playing the player. Pause afterwards
+    load: function() {
+      this.play();
+      this.pause();
+    },
+    unload: function() {
+      this.pause();
+      
+      this.swfObj.api( "api_unload" );
+      this.evtHolder.dispatchEvent( "abort" );
+      this.evtHolder.dispatchEvent( "emptied" );
+    },
+    // Hook an event listener for the player event into internal event system
+    // Stick to HTML conventions of add event listener and keep lowercase, without prependinng "on"
+    addEventListener: function( evt, fn ) {
+      var playerEvt,
+          that = this;
+      
+      evt = evt.toLowerCase();
+      
+      // If it's an HTML media event supported by player, map
+      if ( evt === "seeked" ) {
+        playerEvt = "onSeek";
+      } else if ( evt === "timeupdate" ) {
+        playerEvt = "onProgress";
+      } else if ( evt === "progress" ) {
+        playerEvt = "onLoading";
+      } else if ( evt === "ended" ) {
+        playerEvt = "onFinish";
+      } else if ( evt === "playing" ) {
+        playerEvt = "onPlay";
+      } else if ( evt === "pause" || evt === "load" ) {
+        // Direct mapping, CamelCase the event name as vimeo API expects
+        playerEvt = "on"+evt[0].toUpperCase() + evt.substr(1);
+      }
+      
+      // Vimeo only stores 1 callback per event
+      // Have vimeo call internal collection of callbacks
+      this.evtHolder.addEventListener( evt, fn, false );
+      
+      // Link manual event structure with Vimeo's if not already
+      // Do not link for 'timeupdate'
+      if( evt !== "timeupdate" && playerEvt && this.evtHolder.getEventListeners( evt ).length === 1 ) {
+        this.swfObj.addEvent( playerEvt, function() {
+          that.evtHolder.dispatchEvent( evt );
+        });
+      }
+    },
+    removeEventListener: function( evtName, fn ) {
+      return this.evtHolder.removeEventListener( evtName, fn );
+    }
+  });
+})( Popcorn );
\ No newline at end of file
diff --git a/players/vimeo/popcorn.vimeo.unit.html b/players/vimeo/popcorn.vimeo.unit.html
new file mode 100644 (file)
index 0000000..7be1d61
--- /dev/null
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>Popcorn API</title>
+  <link rel="stylesheet" href="../../test/qunit/qunit.css" type="text/css" media="screen">
+  <script src="../../test/qunit/qunit.js"></script>
+  <!-- 
+    do not move - this must be called immediately prior to 
+    popcorn-api-draft.js
+  -->
+  
+  <script src="../../popcorn.js"></script>
+  
+  <script src="popcorn.vimeo.unit.js"></script>
+  <script src="popcorn.vimeo.js"></script>
+  
+</head>
+<body>
+  <h1 id="qunit-header">Popcorn Vimeo Player Plugin</h1>
+  <h2 id="qunit-banner"></h2>
+  <div id="qunit-testrunner-toolbar"></div>
+  <h2 id="qunit-userAgent"></h2>
+  <ol id="qunit-tests"></ol>
+  <div id="qunit-fixture">  </div>
+  
+  <iframe id="player_1" width="500" height="281" frameborder="0" ></iframe>
+</body>
+</html>
diff --git a/players/vimeo/popcorn.vimeo.unit.js b/players/vimeo/popcorn.vimeo.unit.js
new file mode 100644 (file)
index 0000000..471e0fd
--- /dev/null
@@ -0,0 +1,149 @@
+test("Popcorn Vimeo Plugin", function () {
+  function makeHandler( evtName ) {
+    return( function() {
+      var count = 0;
+      return function() {
+        count++;
+        
+        if ( count === 1 ) {
+          ok( true, "Event '"+evtName+"' is supported" );
+          plus();
+        }
+      }
+    })();
+  }
+  
+  function plus() {
+    if ( ++count === expects ) {
+      start();
+    }
+  }
+  
+  var popped = Popcorn.vimeo( "player_1", "http://vimeo.com/11127501" ),
+      expects = 21,
+      playCount = 0,
+      pauseCount = 0,
+      count = 0,
+      events = {
+        "durationchange": makeHandler( "durationchange" ),
+        "play": makeHandler( "play" ),
+        "loadstart": function() {
+          (makeHandler( "loadstart" ))();
+          this.play();
+        },
+        "readystatechange": makeHandler( "readystatechange" ),
+        "volumechange": (function() {
+          var timesCalled = 0;
+          
+          return function() {
+            timesCalled++;
+            
+            if (timesCalled === 1) {
+              ok( true, "Volume changed event works" );
+              plus();
+              
+              equals( popped.volume(), 0, "Volume correctly set" );
+              plus();
+              
+              ok( popped.video.muted(), "Muted set when player volume 0" );
+              plus();
+              
+              popped.volume( 1 );
+            } else if ( timesCalled === 2 ) {
+              ok( !popped.video.muted(), "Unmuted when volume not 0" );
+              plus();
+              
+              popped.exec( 4, function() {
+                popped.video.unload();
+              });
+            }
+          };
+        })(),
+        "emptied": makeHandler( "emptied" ),
+        "ended": 0,
+        "pause": (function() {
+          var timesCalled = 0;
+          
+          return function() {
+            timesCalled++;
+            
+            if ( timesCalled === 1 ) {
+              ok( true, "Pause event works" );
+              plus();
+              ok( popped.video.objVars.paused, "Pause attribute set" );
+              plus();
+              popped.play();
+            }
+          };
+        })(),
+        "playing": (function() {
+          var timesCalled = 0;
+          
+          return function() {
+            timesCalled++;
+            
+            if ( timesCalled === 1 ) {
+              ok( true, "Play event works" );
+              plus();
+              
+              ok( true, "Video autoplay attribute works" );
+              plus();
+              
+              ok( !popped.video.objVars.paused, "Player paused attribute not set" );
+              plus();
+              
+              popped.exec( 5, function() {
+                popped.currentTime( 0 );
+                popped.pause();
+              });
+            } else if ( timesCalled === 2 ) {
+              ok( true, "Popcorn play function works" );
+              plus();
+              popped.volume( 0 );
+            }
+          };
+        })(),
+        "progress": makeHandler( "progress" ),
+        "seeked": makeHandler( "seeked" ),
+        "timeupdate": makeHandler( "timeupdate" )
+      };
+  
+  expect( expects );
+  
+  stop( 20000 );
+  
+  ok( "vimeo" in Popcorn, "Vimeo is a method of Popcorn" );
+  plus();
+  
+  equals( popped.video.objVars.initialTime, 0, "Player initial time is 0" );
+  plus();
+  
+  Popcorn.plugin( "timingTest", {
+    start: function ( event, options ) {
+      ok( true, "Popcorn plugin started" );
+      plus();
+    },
+    end: function ( event, options ) {
+      ok( true, "Popcorn plugin stopped" );
+      plus();
+    }
+  });
+  
+  popped.timingTest({
+    start: 3, // seconds
+    end: 4, // seconds
+  });
+  
+  popped.listen( "load", function() {
+    ok ( this.video.swfObj.id === popped.video.swfObj.id, "Correctly kept track of 'this'" );
+    plus();
+    
+    Popcorn.forEach( events, function( fn, evtName ) {
+      fn && popped.listen( evtName, fn );
+    });
+    
+    // Queue load
+    // Load event will play when beginning to load
+    popped.load();
+  });
+});
index 17d20e3bed8cea1c427fb6d41c094a0a5e75fa00..4bb3a53ba906ec0834c4c053e32752d3d892c1cc 100644 (file)
       }
 
 
-      matches = rIdExp.exec( entity );
-
-      if ( matches.length && matches[2]  ) {
-        elem = document.getElementById(matches[2]);
-      }
+      if ( (typeof entity) == "string" ) {
+        matches = rIdExp.exec( entity );
 
+        if ( matches.length && matches[2]  ) {
+          elem = document.getElementById(matches[2]);
+        }
 
-      this.video = elem ? elem : null;
+        this.video = elem ? elem : null;
+      } else if ( entity instanceof Object ) {
+        this.video = entity;
+      }
 
       this.data = {
         history: [],
                 tracksByEnd    = tracks.byEnd,
                 tracksByStart  = tracks.byStart;
 
+
+            if (typeof currentTime === "function") {
+              currentTime = this.currentTime();
+            }
+
             // Playbar advancing
             if ( previousTime < currentTime ) {
 
         }
       };
 
-      isReady( this );
+      if ( this.video ) {
+        isReady( this );
+      }
 
       return this;
     }
 
         ret[ name ] = function( arg ) {
 
-          if ( typeof this.video[name] === "function" ) {
-            this.video[ name ]();
-
-            return this;
-          }
-
+          var isFunc = typeof this.video[name] === "function";
 
           if ( arg !== false && arg !== null && typeof arg !== "undefined" ) {
 
-            this.video[ name ] = arg;
+            if ( isFunc ) {
+              this.video[ name ](arg);
+            } else {
+              this.video[ name ] = arg;
+            }
 
             return this;
           }
 
+          if ( isFunc ) {
+            return this.video[ name ]();
+          }
+
           return this.video[ name ];
         };
       });
 
 
       settings.ajax.open( settings.type, settings.url, settings.async );
-      settings.ajax.send( settings.data = null ? null : settings.data );
+      settings.ajax.send( settings.data || null );
 
       return Popcorn.xhr.httpData( settings );
     }
   }, false );
 
 })(window, window.document);
+