popcorn-js/popcorn.js

1997 строки
56 KiB
JavaScript
Исходник Обычный вид История

(function(global, document) {
2010-12-04 23:54:38 +03:00
// Popcorn.js does not support archaic browsers
if ( !document.addEventListener ) {
global.Popcorn = {
isSupported: false
};
2012-01-05 21:05:34 +04:00
var methods = ( "removeInstance addInstance getInstanceById removeInstanceById " +
"forEach extend effects error guid sizeOf isArray nop position disable enable destroy" +
2011-09-07 00:21:57 +04:00
"addTrackEvent removeTrackEvent getTrackEvents getTrackEvent getLastTrackEventId " +
"timeUpdate plugin removePlugin compose effect xhr getJSONP getScript" ).split(/\s+/);
while ( methods.length ) {
2011-09-07 00:21:57 +04:00
global.Popcorn[ methods.shift() ] = function() {};
}
return;
}
2011-02-14 21:38:50 +03:00
var
AP = Array.prototype,
OP = Object.prototype,
forEach = AP.forEach,
slice = AP.slice,
hasOwn = OP.hasOwnProperty,
toString = OP.toString,
2010-12-04 23:54:38 +03:00
// Copy global Popcorn (may not exist)
_Popcorn = global.Popcorn,
2011-03-18 18:33:05 +03:00
// Ready fn cache
2011-02-14 21:38:50 +03:00
readyStack = [],
readyBound = false,
readyFired = false,
2011-02-14 21:38:50 +03:00
// Non-public internal data object
internal = {
events: {
hash: {},
apis: {}
}
},
2010-12-04 23:54:38 +03:00
// Non-public `requestAnimFrame`
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimFrame = (function(){
return global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function( callback, element ) {
global.setTimeout( callback, 16 );
};
}()),
// Non-public `getKeys`, return an object's keys as an array
getKeys = function( obj ) {
return Object.keys ? Object.keys( obj ) : (function( obj ) {
var item,
list = [];
for ( item in obj ) {
if ( hasOwn.call( obj, item ) ) {
list.push( item );
}
}
return list;
})( obj );
},
2011-03-18 18:33:05 +03:00
// Declare constructor
2011-02-14 21:38:50 +03:00
// Returns an instance object.
Popcorn = function( entity, options ) {
2010-12-06 01:37:33 +03:00
// Return new Popcorn object
return new Popcorn.p.init( entity, options || null );
2010-12-04 23:54:38 +03:00
};
// Popcorn API version, automatically inserted via build system.
2011-09-23 19:24:30 +04:00
Popcorn.version = "@VERSION";
// Boolean flag allowing a client to determine if Popcorn can be supported
Popcorn.isSupported = true;
// Instance caching
2011-02-02 01:52:07 +03:00
Popcorn.instances = [];
2011-02-14 21:38:50 +03:00
// Declare a shortcut (Popcorn.p) to and a definition of
// the new prototype for our Popcorn constructor
2010-12-04 23:54:38 +03:00
Popcorn.p = Popcorn.prototype = {
init: function( entity, options ) {
2010-12-04 23:54:38 +03:00
2012-01-06 20:15:08 +04:00
var matches,
self = this;
2011-02-14 21:38:50 +03:00
// Supports Popcorn(function () { /../ })
// Originally proposed by Daniel Brooks
2011-02-14 21:38:50 +03:00
2010-12-20 18:01:13 +03:00
if ( typeof entity === "function" ) {
2011-02-14 21:38:50 +03:00
// If document ready has already fired
if ( document.readyState === "complete" ) {
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
entity( document, Popcorn );
2011-02-14 21:38:50 +03:00
return;
}
2011-03-18 18:33:05 +03:00
// Add `entity` fn to ready stack
readyStack.push( entity );
// This process should happen once per page load
if ( !readyBound ) {
// set readyBound flag
readyBound = true;
2011-05-17 04:57:04 +04:00
var DOMContentLoaded = function() {
2011-02-14 21:38:50 +03:00
readyFired = true;
2011-02-14 21:38:50 +03:00
2011-03-18 18:33:05 +03:00
// Remove global DOM ready listener
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// Execute all ready function in the stack
2011-05-17 04:57:04 +04:00
for ( var i = 0, readyStackLength = readyStack.length; i < readyStackLength; i++ ) {
2011-05-17 04:57:04 +04:00
readyStack[ i ].call( document, Popcorn );
2010-12-04 23:54:38 +03:00
}
// GC readyStack
2011-02-14 21:38:50 +03:00
readyStack = null;
};
2011-03-18 18:33:05 +03:00
// Register global DOM ready listener
2011-05-17 04:57:04 +04:00
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
}
2011-02-14 21:38:50 +03:00
return;
2010-12-20 18:01:13 +03:00
}
2011-02-14 21:38:50 +03:00
2012-03-22 23:15:22 +04:00
if ( typeof entity === "string" ) {
try {
matches = document.querySelector( entity );
2012-03-22 23:30:42 +04:00
} catch( e ) {
throw new Error( "Popcorn.js Error: Invalid media element selector: " + entity );
}
}
2011-03-24 17:09:20 +03:00
// Get media element by id or object reference
this.media = matches || entity;
2011-02-14 21:38:50 +03:00
2011-03-24 17:09:20 +03:00
// Create an audio or video element property reference
2011-05-09 04:21:48 +04:00
this[ ( this.media.nodeName && this.media.nodeName.toLowerCase() ) || "video" ] = this.media;
2011-03-24 17:09:20 +03:00
2011-03-18 18:33:05 +03:00
// Register new instance
Popcorn.instances.push( this );
2011-02-14 21:38:50 +03:00
this.options = options || {};
this.isDestroyed = false;
2010-12-04 23:54:38 +03:00
this.data = {
// data structure of all
2012-03-18 05:33:13 +04:00
running: {
cue: []
2012-03-18 05:33:13 +04:00
},
2011-11-01 21:48:37 +04:00
// Executed by either timeupdate event or in rAF loop
timeUpdate: Popcorn.nop,
// Allows disabling a plugin per instance
2012-03-18 05:33:13 +04:00
disabled: {},
// Stores DOM event queues by type
2010-12-04 23:54:38 +03:00
events: {},
// Stores Special event hooks data
hooks: {},
// Store track event history data
history: [],
// Stores ad-hoc state related data]
state: {
volume: this.media.volume
},
// Store track event object references by trackId
trackRefs: {},
// Playback track event queues
trackEvents: {
2011-02-16 00:55:52 +03:00
byStart: [{
2011-02-16 00:55:52 +03:00
start: -1,
end: -1
}],
2011-07-21 00:15:04 +04:00
byEnd: [{
2011-02-16 00:55:52 +03:00
start: -1,
end: -1
}],
animating: [],
2010-12-07 19:15:30 +03:00
startIndex: 0,
2011-07-21 00:15:04 +04:00
endIndex: 0,
previousUpdateTime: -1
2010-12-07 19:15:30 +03:00
}
2010-12-04 23:54:38 +03:00
};
2011-02-14 21:38:50 +03:00
2012-01-06 00:21:13 +04:00
// function to fire when video is ready
2012-01-06 20:15:08 +04:00
var isReady = function() {
// chrome bug: http://code.google.com/p/chromium/issues/detail?id=119598
// it is possible the video's time is less than 0
// this has the potential to call track events more than once, when they should not
// start: 0, end: 1 will start, end, start again, when it should just start
// just setting it to 0 if it is below 0 fixes this issue
if ( self.media.currentTime < 0 ) {
self.media.currentTime = 0;
}
2012-01-06 20:15:08 +04:00
self.media.removeEventListener( "loadeddata", isReady, false );
2010-12-10 19:53:47 +03:00
2012-03-20 21:17:30 +04:00
var duration, videoDurationPlus,
runningPlugins, runningPlugin, rpLength, rpNatives;
2012-01-06 00:21:13 +04:00
// Adding padding to the front and end of the arrays
// this is so we do not fall off either end
2012-01-06 20:15:08 +04:00
duration = self.media.duration;
2010-12-10 19:53:47 +03:00
2012-01-06 00:21:13 +04:00
// Check for no duration info (NaN)
videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1;
2011-02-16 20:06:45 +03:00
2012-01-06 20:15:08 +04:00
Popcorn.addTrackEvent( self, {
2012-01-06 00:21:13 +04:00
start: videoDurationPlus,
end: videoDurationPlus
});
2011-02-14 21:38:50 +03:00
2012-01-06 20:15:08 +04:00
if ( self.options.frameAnimation ) {
2012-03-18 05:33:13 +04:00
2012-01-06 00:21:13 +04:00
// if Popcorn is created with frameAnimation option set to true,
// requestAnimFrame is used instead of "timeupdate" media event.
// This is for greater frame time accuracy, theoretically up to
// 60 frames per second as opposed to ~4 ( ~every 15-250ms)
2012-01-06 20:15:08 +04:00
self.data.timeUpdate = function () {
2010-12-10 02:18:12 +03:00
2012-01-06 20:15:08 +04:00
Popcorn.timeUpdate( self, {} );
2012-03-18 05:33:13 +04:00
// fire frame for each enabled active plugin of every type
Popcorn.forEach( Popcorn.manifest, function( key, val ) {
runningPlugins = self.data.running[ val ];
2012-03-18 05:33:13 +04:00
// ensure there are running plugins on this type on this instance
if ( runningPlugins ) {
2012-03-20 21:17:30 +04:00
rpLength = runningPlugins.length;
for ( var i = 0; i < rpLength; i++ ) {
2012-03-18 05:33:13 +04:00
2012-03-20 21:17:30 +04:00
runningPlugin = runningPlugins[ i ];
rpNatives = runningPlugin._natives;
rpNatives && rpNatives.frame &&
rpNatives.frame.call( self, {}, runningPlugin, self.currentTime() );
2012-03-18 05:33:13 +04:00
}
}
});
self.emit( "timeupdate" );
2012-01-06 20:15:08 +04:00
!self.isDestroyed && requestAnimFrame( self.data.timeUpdate );
2012-01-06 00:21:13 +04:00
};
2012-01-06 20:15:08 +04:00
!self.isDestroyed && requestAnimFrame( self.data.timeUpdate );
2012-01-06 00:21:13 +04:00
} else {
2012-01-06 20:15:08 +04:00
self.data.timeUpdate = function( event ) {
Popcorn.timeUpdate( self, event );
2012-01-06 00:21:13 +04:00
};
2012-01-06 20:15:08 +04:00
if ( !self.isDestroyed ) {
self.media.addEventListener( "timeupdate", self.data.timeUpdate, false );
}
2010-12-07 19:15:30 +03:00
}
2010-12-10 02:18:12 +03:00
};
2010-12-10 19:53:47 +03:00
Object.defineProperty( this, "error", {
get: function() {
2012-05-08 00:38:55 +04:00
return self.media.error;
}
});
2012-05-08 00:38:55 +04:00
2012-01-06 20:15:08 +04:00
if ( self.media.readyState >= 2 ) {
2012-01-06 00:21:13 +04:00
2012-01-06 20:15:08 +04:00
isReady();
2012-01-06 00:21:13 +04:00
} else {
2012-01-06 20:15:08 +04:00
self.media.addEventListener( "loadeddata", isReady, false );
2012-01-06 00:21:13 +04:00
}
2010-12-10 02:18:12 +03:00
2010-12-04 23:54:38 +03:00
return this;
}
};
// Extend constructor prototype to instance prototype
2011-03-18 18:33:05 +03:00
// Allows chaining methods to instances
2010-12-04 23:54:38 +03:00
Popcorn.p.init.prototype = Popcorn.p;
Popcorn.forEach = function( obj, fn, context ) {
if ( !obj || !fn ) {
return {};
}
context = context || this;
2011-06-17 17:51:17 +04:00
2011-06-17 19:20:07 +04:00
var key, len;
2011-06-17 17:51:17 +04:00
2010-12-04 23:54:38 +03:00
// Use native whenever possible
if ( forEach && obj.forEach === forEach ) {
2011-05-17 04:57:04 +04:00
return obj.forEach( fn, context );
2011-02-14 21:38:50 +03:00
}
2010-12-04 23:54:38 +03:00
if ( toString.call( obj ) === "[object NodeList]" ) {
2011-06-17 17:51:17 +04:00
for ( key = 0, len = obj.length; key < len; key++ ) {
fn.call( context, obj[ key ], key, obj );
}
return obj;
}
2011-06-17 17:51:17 +04:00
for ( key in obj ) {
2011-05-17 04:57:04 +04:00
if ( hasOwn.call( obj, key ) ) {
fn.call( context, obj[ key ], key, obj );
2011-02-14 21:38:50 +03:00
}
}
2010-12-04 23:54:38 +03:00
return obj;
2011-02-14 21:38:50 +03:00
};
2010-12-04 23:54:38 +03:00
Popcorn.extend = function( obj ) {
2011-05-17 04:57:04 +04:00
var dest = obj, src = slice.call( arguments, 1 );
2010-12-04 23:54:38 +03:00
Popcorn.forEach( src, function( copy ) {
for ( var prop in copy ) {
2011-05-17 04:57:04 +04:00
dest[ prop ] = copy[ prop ];
2010-12-04 23:54:38 +03:00
}
});
2011-05-17 04:57:04 +04:00
2011-02-14 21:38:50 +03:00
return dest;
2010-12-04 23:54:38 +03:00
};
2010-12-10 19:53:47 +03:00
2010-12-04 23:54:38 +03:00
// A Few reusable utils, memoized onto Popcorn
Popcorn.extend( Popcorn, {
noConflict: function( deep ) {
if ( deep ) {
global.Popcorn = _Popcorn;
}
return Popcorn;
},
error: function( msg ) {
throw new Error( msg );
},
guid: function( prefix ) {
Popcorn.guid.counter++;
2011-03-18 18:33:05 +03:00
return ( prefix ? prefix : "" ) + ( +new Date() + Popcorn.guid.counter );
2011-02-14 21:38:50 +03:00
},
2011-05-17 06:56:43 +04:00
sizeOf: function( obj ) {
2010-12-04 23:54:38 +03:00
var size = 0;
2011-05-17 04:57:04 +04:00
for ( var prop in obj ) {
size++;
2010-12-04 23:54:38 +03:00
}
return size;
2011-02-14 21:38:50 +03:00
},
isArray: Array.isArray || function( array ) {
return toString.call( array ) === "[object Array]";
2011-05-17 04:57:04 +04:00
},
2011-04-22 01:37:04 +04:00
2011-05-17 04:57:04 +04:00
nop: function() {},
2011-04-22 01:37:04 +04:00
position: function( elem ) {
var clientRect = elem.getBoundingClientRect(),
2011-05-17 06:56:43 +04:00
bounds = {},
2011-04-22 01:37:04 +04:00
doc = elem.ownerDocument,
docElem = document.documentElement,
body = document.body,
clientTop, clientLeft, scrollTop, scrollLeft, top, left;
// Determine correct clientTop/Left
2011-05-17 06:56:43 +04:00
clientTop = docElem.clientTop || body.clientTop || 0;
2011-04-22 01:37:04 +04:00
clientLeft = docElem.clientLeft || body.clientLeft || 0;
// Determine correct scrollTop/Left
2011-05-17 06:56:43 +04:00
scrollTop = ( global.pageYOffset && docElem.scrollTop || body.scrollTop );
2011-04-22 01:37:04 +04:00
scrollLeft = ( global.pageXOffset && docElem.scrollLeft || body.scrollLeft );
// Temp top/left
2011-05-17 06:56:43 +04:00
top = Math.ceil( clientRect.top + scrollTop - clientTop );
2011-04-22 01:37:04 +04:00
left = Math.ceil( clientRect.left + scrollLeft - clientLeft );
for ( var p in clientRect ) {
bounds[ p ] = Math.round( clientRect[ p ] );
}
return Popcorn.extend({}, bounds, { top: top, left: left });
},
disable: function( instance, plugin ) {
2012-03-18 05:33:13 +04:00
if ( !instance.data.disabled[ plugin ] ) {
2012-03-18 05:33:13 +04:00
instance.data.disabled[ plugin ] = true;
2012-03-18 05:33:13 +04:00
for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) {
2012-03-18 05:33:13 +04:00
event = instance.data.running[ plugin ][ i ];
event._natives.end.call( instance, null, event );
}
}
return instance;
},
enable: function( instance, plugin ) {
2012-03-18 05:33:13 +04:00
if ( instance.data.disabled[ plugin ] ) {
2012-03-18 05:33:13 +04:00
instance.data.disabled[ plugin ] = false;
2012-03-18 05:33:13 +04:00
for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) {
2012-03-18 05:33:13 +04:00
event = instance.data.running[ plugin ][ i ];
event._natives.start.call( instance, null, event );
}
}
return instance;
},
destroy: function( instance ) {
var events = instance.data.events,
singleEvent, item, fn, plugin;
// Iterate through all events and remove them
for ( item in events ) {
singleEvent = events[ item ];
for ( fn in singleEvent ) {
delete singleEvent[ fn ];
}
events[ item ] = null;
}
// remove all plugins off the given instance
for ( plugin in Popcorn.registryByName ) {
Popcorn.removePlugin( instance, plugin );
}
if ( !instance.isDestroyed ) {
instance.data.timeUpdate && instance.media.removeEventListener( "timeupdate", instance.data.timeUpdate, false );
instance.isDestroyed = true;
}
2011-04-22 01:37:04 +04:00
}
2011-02-14 21:38:50 +03:00
});
2011-03-18 18:33:05 +03:00
// Memoized GUID Counter
2011-05-17 04:57:04 +04:00
Popcorn.guid.counter = 1;
2011-02-14 21:38:50 +03:00
2011-03-18 18:33:05 +03:00
// Factory to implement getters, setters and controllers
// as Popcorn instance methods. The IIFE will create and return
// an object with defined methods
2011-05-17 06:56:43 +04:00
Popcorn.extend(Popcorn.p, (function() {
2011-02-14 21:38:50 +03:00
var methods = "load play pause currentTime playbackRate volume duration preload playbackRate " +
"autoplay loop controls muted buffered readyState seeking paused played seekable ended",
2010-12-04 23:54:38 +03:00
ret = {};
2011-02-14 21:38:50 +03:00
2010-12-04 23:54:38 +03:00
// Build methods, store in object that is returned and passed to extend
2011-05-17 04:57:04 +04:00
Popcorn.forEach( methods.split( /\s+/g ), function( name ) {
2011-02-14 21:38:50 +03:00
2010-12-04 23:54:38 +03:00
ret[ name ] = function( arg ) {
var previous;
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
if ( typeof this.media[ name ] === "function" ) {
// Support for shorthanded play(n)/pause(n) jump to currentTime
// If arg is not null or undefined and called by one of the
// allowed shorthandable methods, then set the currentTime
// Supports time as seconds or SMPTE
if ( arg != null && /play|pause/.test( name ) ) {
this.media.currentTime = Popcorn.util.toSeconds( arg );
}
2011-03-24 17:09:20 +03:00
this.media[ name ]();
2011-02-14 21:38:50 +03:00
2010-12-04 23:54:38 +03:00
return this;
}
2011-02-14 21:38:50 +03:00
2011-07-23 02:21:35 +04:00
if ( arg != null ) {
// Capture the current value of the attribute property
previous = this.media[ name ];
2011-02-14 21:38:50 +03:00
// Set the attribute property with the new value
2011-03-24 17:09:20 +03:00
this.media[ name ] = arg;
2011-02-14 21:38:50 +03:00
// If the new value is not the same as the old value
// emit an "attrchanged event"
if ( previous !== arg ) {
this.emit( "attrchange", {
attribute: name,
previousValue: previous,
currentValue: arg
});
}
2010-12-04 23:54:38 +03:00
return this;
}
2011-02-14 21:38:50 +03:00
2011-03-24 17:09:20 +03:00
return this.media[ name ];
2010-12-04 23:54:38 +03:00
};
});
2011-02-14 21:38:50 +03:00
2010-12-04 23:54:38 +03:00
return ret;
2011-02-14 21:38:50 +03:00
2010-12-04 23:54:38 +03:00
})()
);
2011-02-14 21:38:50 +03:00
Popcorn.forEach( "enable disable".split(" "), function( method ) {
Popcorn.p[ method ] = function( plugin ) {
return Popcorn[ method ]( this, plugin );
};
});
2010-12-04 23:54:38 +03:00
Popcorn.extend(Popcorn.p, {
2011-02-14 21:38:50 +03:00
2011-03-18 18:33:05 +03:00
// Rounded currentTime
2011-05-17 04:57:04 +04:00
roundTime: function() {
2011-03-24 17:09:20 +03:00
return -~this.media.currentTime;
},
2011-03-18 18:33:05 +03:00
// Attach an event to a single point in time
2011-05-17 04:57:04 +04:00
exec: function( time, fn ) {
2011-02-14 21:38:50 +03:00
2011-03-18 18:33:05 +03:00
// Creating a one second track event with an empty end
Popcorn.addTrackEvent( this, {
start: time,
end: time + 1,
_running: false,
_natives: {
2011-02-23 21:19:23 +03:00
start: fn || Popcorn.nop,
end: Popcorn.nop,
type: "cue"
}
});
2010-12-06 00:07:39 +03:00
return this;
},
// Mute the calling media, optionally toggle
mute: function( toggle ) {
2011-08-23 22:06:58 +04:00
var event = toggle == null || toggle === true ? "muted" : "unmuted";
// If `toggle` is explicitly `false`,
// unmute the media and restore the volume level
if ( event === "unmuted" ) {
this.media.muted = false;
this.media.volume = this.data.state.volume;
}
// If `toggle` is either null or undefined,
// save the current volume and mute the media element
if ( event === "muted" ) {
this.data.state.volume = this.media.volume;
this.media.muted = true;
}
// Trigger either muted|unmuted event
this.emit( event );
return this;
},
// Convenience method, unmute the calling media
unmute: function( toggle ) {
return this.mute( toggle == null ? false : !toggle );
},
// Get the client bounding box of an instance element
position: function() {
2011-04-22 01:37:04 +04:00
return Popcorn.position( this.media );
},
// Toggle a plugin's playback behaviour (on or off) per instance
toggle: function( plugin ) {
2012-03-18 05:33:13 +04:00
return Popcorn[ this.data.disabled[ plugin ] ? "enable" : "disable" ]( this, plugin );
},
// Set default values for plugin options objects per instance
defaults: function( plugin, defaults ) {
// If an array of default configurations is provided,
// iterate and apply each to this instance
if ( Popcorn.isArray( plugin ) ) {
Popcorn.forEach( plugin, function( obj ) {
for ( var name in obj ) {
this.defaults( name, obj[ name ] );
}
}, this );
return this;
}
if ( !this.options.defaults ) {
this.options.defaults = {};
}
if ( !this.options.defaults[ plugin ] ) {
this.options.defaults[ plugin ] = {};
}
Popcorn.extend( this.options.defaults[ plugin ], defaults );
return this;
2010-12-04 23:54:38 +03:00
}
});
Popcorn.Events = {
UIEvents: "blur focus focusin focusout load resize scroll unload",
2011-02-14 21:38:50 +03:00
MouseEvents: "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave click dblclick",
2012-05-08 00:38:55 +04:00
Events: "loadstart progress suspend emptied stalled play pause error " +
2011-05-17 04:57:04 +04:00
"loadedmetadata loadeddata waiting playing canplay canplaythrough " +
"seeking seeked timeupdate ended ratechange durationchange volumechange"
};
2011-02-14 21:38:50 +03:00
Popcorn.Events.Natives = Popcorn.Events.UIEvents + " " +
2011-05-17 04:57:04 +04:00
Popcorn.Events.MouseEvents + " " +
Popcorn.Events.Events;
2011-02-14 21:38:50 +03:00
internal.events.apiTypes = [ "UIEvents", "MouseEvents", "Events" ];
// Privately compile events table at load time
(function( events, data ) {
2011-02-14 21:38:50 +03:00
var apis = internal.events.apiTypes,
eventsList = events.Natives.split( /\s+/g ),
idx = 0, len = eventsList.length, prop;
2011-02-14 21:38:50 +03:00
for( ; idx < len; idx++ ) {
data.hash[ eventsList[idx] ] = true;
}
apis.forEach(function( val, idx ) {
data.apis[ val ] = {};
var apiEvents = events[ val ].split( /\s+/g ),
len = apiEvents.length,
k = 0;
for ( ; k < len; k++ ) {
data.apis[ val ][ apiEvents[ k ] ] = true;
}
});
})( Popcorn.Events, internal.events );
Popcorn.events = {
2011-02-14 21:38:50 +03:00
isNative: function( type ) {
return !!internal.events.hash[ type ];
2011-02-14 21:38:50 +03:00
},
getInterface: function( type ) {
2011-02-14 21:38:50 +03:00
if ( !Popcorn.events.isNative( type ) ) {
return false;
}
2011-02-14 21:38:50 +03:00
var eventApi = internal.events,
apis = eventApi.apiTypes,
apihash = eventApi.apis,
idx = 0, len = apis.length, api, tmp;
for ( ; idx < len; idx++ ) {
tmp = apis[ idx ];
if ( apihash[ tmp ][ type ] ) {
api = tmp;
break;
}
}
return api;
2011-02-14 21:38:50 +03:00
},
2011-03-18 18:33:05 +03:00
// Compile all native events to single array
2011-05-17 04:57:04 +04:00
all: Popcorn.Events.Natives.split( /\s+/g ),
2011-03-18 18:33:05 +03:00
// Defines all Event handling static functions
2010-12-04 23:54:38 +03:00
fn: {
2011-05-17 04:57:04 +04:00
trigger: function( type, data ) {
2011-02-14 21:38:50 +03:00
var eventInterface, evt;
2010-12-04 23:54:38 +03:00
// setup checks for custom event system
2011-03-18 18:33:05 +03:00
if ( this.data.events[ type ] && Popcorn.sizeOf( this.data.events[ type ] ) ) {
2011-02-14 21:38:50 +03:00
eventInterface = Popcorn.events.getInterface( type );
2011-02-14 21:38:50 +03:00
if ( eventInterface ) {
2011-02-14 21:38:50 +03:00
evt = document.createEvent( eventInterface );
evt.initEvent( type, true, true, global, 1 );
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
this.media.dispatchEvent( evt );
2011-02-14 21:38:50 +03:00
return this;
2011-02-14 21:38:50 +03:00
}
2011-02-14 21:38:50 +03:00
// Custom events
2011-05-17 04:57:04 +04:00
Popcorn.forEach( this.data.events[ type ], function( obj, key ) {
2010-12-04 23:54:38 +03:00
obj.call( this, data );
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
}, this );
2011-02-14 21:38:50 +03:00
2010-12-04 23:54:38 +03:00
}
2011-02-14 21:38:50 +03:00
return this;
2011-02-14 21:38:50 +03:00
},
2011-05-17 04:57:04 +04:00
listen: function( type, fn ) {
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
var self = this,
hasEvents = true,
eventHook = Popcorn.events.hooks[ type ],
origType = type,
tmp;
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
2010-12-04 23:54:38 +03:00
hasEvents = false;
}
2011-02-14 21:38:50 +03:00
// Check and setup event hooks
if ( eventHook ) {
// Execute hook add method if defined
if ( eventHook.add ) {
eventHook.add.call( this, {}, fn );
}
// Reassign event type to our piggyback event type if defined
if ( eventHook.bind ) {
type = eventHook.bind;
}
// Reassign handler if defined
if ( eventHook.handler ) {
tmp = fn;
fn = function wrapper( event ) {
eventHook.handler.call( self, event, tmp );
};
}
// assume the piggy back event is registered
hasEvents = true;
// Setup event registry entry
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
// Toggle if the previous assumption was untrue
hasEvents = false;
}
}
// Register event and handler
2011-03-18 18:33:05 +03:00
this.data.events[ type ][ fn.name || ( fn.toString() + Popcorn.guid() ) ] = fn;
2011-02-14 21:38:50 +03:00
// only attach one event of any type
if ( !hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) {
2010-12-04 23:54:38 +03:00
2011-03-24 17:09:20 +03:00
this.media.addEventListener( type, function( event ) {
2011-02-14 21:38:50 +03:00
2011-05-17 06:56:43 +04:00
Popcorn.forEach( self.data.events[ type ], function( obj, key ) {
2010-12-06 00:07:39 +03:00
if ( typeof obj === "function" ) {
2011-05-17 04:57:04 +04:00
obj.call( self, event );
2010-12-06 00:07:39 +03:00
}
2010-12-04 23:54:38 +03:00
});
2011-02-14 21:38:50 +03:00
}, false);
2010-12-04 23:54:38 +03:00
}
return this;
2011-02-14 21:38:50 +03:00
},
2010-12-06 00:07:39 +03:00
unlisten: function( type, fn ) {
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
if ( this.data.events[ type ] && this.data.events[ type ][ fn ] ) {
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
delete this.data.events[ type ][ fn ];
2011-02-14 21:38:50 +03:00
2010-12-06 00:07:39 +03:00
return this;
}
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
this.data.events[ type ] = null;
return this;
2010-12-04 23:54:38 +03:00
}
},
hooks: {
canplayall: {
bind: "canplaythrough",
add: function( event, callback ) {
var state = false;
if ( this.media.readyState ) {
callback.call( this, event );
state = true;
}
this.data.hooks.canplayall = {
fired: state
};
},
// declare special handling instructions
handler: function canplayall( event, callback ) {
if ( !this.data.hooks.canplayall.fired ) {
// trigger original user callback once
callback.call( this, event );
this.data.hooks.canplayall.fired = true;
}
}
}
2010-12-04 23:54:38 +03:00
}
};
2011-02-14 21:38:50 +03:00
2011-03-18 18:33:05 +03:00
// Extend Popcorn.events.fns (listen, unlisten, trigger) to all Popcorn instances
// Extend aliases (on, off, emit)
Popcorn.forEach( [ [ "trigger", "emit" ], [ "listen", "on" ], [ "unlisten", "off" ] ], function( key ) {
Popcorn.p[ key[ 0 ] ] = Popcorn.p[ key[ 1 ] ] = Popcorn.events.fn[ key[ 0 ] ];
2011-02-14 21:38:50 +03:00
});
// Internal Only - Adds track events to the instance object
2010-12-16 21:44:19 +03:00
Popcorn.addTrackEvent = function( obj, track ) {
2011-02-14 21:38:50 +03:00
// Determine if this track has default options set for it
// If so, apply them to the track object
if ( track && track._natives && track._natives.type &&
( obj.options.defaults && obj.options.defaults[ track._natives.type ] ) ) {
track = Popcorn.extend( {}, obj.options.defaults[ track._natives.type ], track );
}
if ( track._natives ) {
2011-03-18 18:33:05 +03:00
// Supports user defined track event id
track._id = !track.id ? Popcorn.guid( track._natives.type ) : track.id;
2010-12-16 21:44:19 +03:00
// Push track event ids into the history
2011-02-14 21:38:50 +03:00
obj.data.history.push( track._id );
2010-12-16 21:44:19 +03:00
}
2011-02-14 21:38:50 +03:00
track.start = Popcorn.util.toSeconds( track.start, obj.options.framerate );
2011-05-17 04:57:04 +04:00
track.end = Popcorn.util.toSeconds( track.end, obj.options.framerate );
2011-03-18 18:33:05 +03:00
// Store this definition in an array sorted by times
var byStart = obj.data.trackEvents.byStart,
byEnd = obj.data.trackEvents.byEnd,
2012-03-18 05:33:13 +04:00
startIndex, endIndex;
for ( startIndex = byStart.length - 1; startIndex >= 0; startIndex-- ) {
if ( track.start >= byStart[ startIndex ].start ) {
byStart.splice( startIndex + 1, 0, track );
2011-05-11 21:41:50 +04:00
break;
}
}
for ( endIndex = byEnd.length - 1; endIndex >= 0; endIndex-- ) {
if ( track.end > byEnd[ endIndex ].end ) {
byEnd.splice( endIndex + 1, 0, track );
2011-05-11 21:41:50 +04:00
break;
}
}
// Display track event immediately if it's enabled and current
2012-03-18 05:33:13 +04:00
if ( track.end > obj.media.currentTime &&
track.start <= obj.media.currentTime ) {
2012-03-18 05:33:13 +04:00
track._running = true;
obj.data.running[ track._natives.type ].push( track );
2012-03-18 05:33:13 +04:00
if ( !obj.data.disabled[ track._natives.type ] ) {
2012-03-18 05:33:13 +04:00
track._natives.start.call( obj, null, track );
}
}
// update startIndex and endIndex
if ( startIndex <= obj.data.trackEvents.startIndex &&
track.start <= obj.data.trackEvents.previousUpdateTime ) {
obj.data.trackEvents.startIndex++;
}
if ( endIndex <= obj.data.trackEvents.endIndex &&
track.end < obj.data.trackEvents.previousUpdateTime ) {
obj.data.trackEvents.endIndex++;
}
this.timeUpdate( obj, null, true );
2010-12-16 21:44:19 +03:00
// Store references to user added trackevents in ref table
if ( track._id ) {
Popcorn.addTrackEvent.ref( obj, track );
2011-02-16 00:55:52 +03:00
}
};
2011-02-16 00:55:52 +03:00
// Internal Only - Adds track event references to the instance object's trackRefs hash table
Popcorn.addTrackEvent.ref = function( obj, track ) {
obj.data.trackRefs[ track._id ] = track;
return obj;
2011-02-16 00:55:52 +03:00
};
Popcorn.removeTrackEvent = function( obj, removeId ) {
2011-02-14 21:38:50 +03:00
var start, end, animate,
historyLen = obj.data.history.length,
length = obj.data.trackEvents.byStart.length,
index = 0,
2011-02-14 21:38:50 +03:00
indexWasAt = 0,
byStart = [],
byEnd = [],
animating = [],
2011-02-14 21:38:50 +03:00
history = [];
while ( --length > -1 ) {
start = obj.data.trackEvents.byStart[ index ];
end = obj.data.trackEvents.byEnd[ index ];
// Padding events will not have _id properties.
// These should be safely pushed onto the front and back of the
// track event array
if ( !start._id ) {
byStart.push( start );
byEnd.push( end );
2011-02-14 21:38:50 +03:00
}
// Filter for user track events (vs system track events)
if ( start._id ) {
2011-02-14 21:38:50 +03:00
// If not a matching start event for removal
if ( start._id !== removeId ) {
byStart.push( start );
2011-02-14 21:38:50 +03:00
}
// If not a matching end event for removal
if ( end._id !== removeId ) {
byEnd.push( end );
2011-02-14 21:38:50 +03:00
}
2011-05-17 04:57:04 +04:00
// If the _id is matched, capture the current index
if ( start._id === removeId ) {
indexWasAt = index;
2011-02-14 21:38:50 +03:00
// If a _teardown function was defined,
// enforce for track event removals
if ( start._natives._teardown ) {
start._natives._teardown.call( obj, start );
}
}
2010-12-16 21:44:19 +03:00
}
// Increment the track index
index++;
}
// Reset length to be used by the condition below to determine
// if animating track events should also be filtered for removal.
// Reset index below to be used by the reverse while as an
// incrementing counter
length = obj.data.trackEvents.animating.length;
index = 0;
if ( length ) {
while ( --length > -1 ) {
animate = obj.data.trackEvents.animating[ index ];
// Padding events will not have _id properties.
// These should be safely pushed onto the front and back of the
// track event array
if ( !animate._id ) {
animating.push( animate );
}
// If not a matching animate event for removal
if ( animate._id && animate._id !== removeId ) {
animating.push( animate );
}
// Increment the track index
index++;
}
}
2011-02-14 21:38:50 +03:00
// Update
if ( indexWasAt <= obj.data.trackEvents.startIndex ) {
obj.data.trackEvents.startIndex--;
}
if ( indexWasAt <= obj.data.trackEvents.endIndex ) {
obj.data.trackEvents.endIndex--;
}
2011-02-14 21:38:50 +03:00
2010-12-16 21:44:19 +03:00
obj.data.trackEvents.byStart = byStart;
obj.data.trackEvents.byEnd = byEnd;
obj.data.trackEvents.animating = animating;
2010-12-16 21:44:19 +03:00
for ( var i = 0; i < historyLen; i++ ) {
if ( obj.data.history[ i ] !== removeId ) {
2011-05-17 04:57:04 +04:00
history.push( obj.data.history[ i ] );
2010-12-16 21:44:19 +03:00
}
2011-02-14 21:38:50 +03:00
}
// Update ordered history array
2010-12-16 21:44:19 +03:00
obj.data.history = history;
// Update track event references
Popcorn.removeTrackEvent.ref( obj, removeId );
2010-12-16 21:44:19 +03:00
};
2011-02-14 21:38:50 +03:00
// Internal Only - Removes track event references from instance object's trackRefs hash table
Popcorn.removeTrackEvent.ref = function( obj, removeId ) {
delete obj.data.trackRefs[ removeId ];
2011-02-14 21:38:50 +03:00
return obj;
};
2011-02-14 21:38:50 +03:00
// Return an array of track events bound to this instance object
Popcorn.getTrackEvents = function( obj ) {
var trackevents = [],
refs = obj.data.trackEvents.byStart,
length = refs.length,
idx = 0,
ref;
for ( ; idx < length; idx++ ) {
ref = refs[ idx ];
// Return only user attributed track event references
if ( ref._id ) {
trackevents.push( ref );
2011-02-14 21:38:50 +03:00
}
}
2011-02-14 21:38:50 +03:00
2010-12-16 21:44:19 +03:00
return trackevents;
};
2011-02-14 21:38:50 +03:00
// Internal Only - Returns an instance object's trackRefs hash table
Popcorn.getTrackEvents.ref = function( obj ) {
return obj.data.trackRefs;
};
// Return a single track event bound to this instance object
Popcorn.getTrackEvent = function( obj, trackId ) {
2011-06-02 19:30:25 +04:00
return obj.data.trackRefs[ trackId ];
};
// Internal Only - Returns an instance object's track reference by track id
Popcorn.getTrackEvent.ref = function( obj, trackId ) {
return obj.data.trackRefs[ trackId ];
};
2011-02-14 21:38:50 +03:00
2010-12-16 21:44:19 +03:00
Popcorn.getLastTrackEventId = function( obj ) {
return obj.data.history[ obj.data.history.length - 1 ];
};
2011-02-14 21:38:50 +03:00
2011-08-24 22:52:39 +04:00
Popcorn.timeUpdate = function( obj, event ) {
2011-09-06 19:35:47 +04:00
var currentTime = obj.media.currentTime,
previousTime = obj.data.trackEvents.previousUpdateTime,
tracks = obj.data.trackEvents,
end = tracks.endIndex,
2011-09-07 21:59:41 +04:00
start = tracks.startIndex,
byStartLen = tracks.byStart.length,
byEndLen = tracks.byEnd.length,
2011-09-06 22:27:59 +04:00
registryByName = Popcorn.registryByName,
trackstart = "trackstart",
trackend = "trackend",
2012-03-18 05:33:13 +04:00
byEnd, byStart, byAnimate, natives, type, runningPlugins;
2011-08-24 22:52:39 +04:00
// Playbar advancing
if ( previousTime <= currentTime ) {
2011-08-24 22:52:39 +04:00
2011-09-06 22:33:42 +04:00
while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end <= currentTime ) {
2011-09-06 19:35:47 +04:00
2011-09-06 22:33:42 +04:00
byEnd = tracks.byEnd[ end ];
natives = byEnd._natives;
2011-09-06 22:27:59 +04:00
type = natives && natives.type;
2011-09-06 19:35:47 +04:00
2011-08-24 22:52:39 +04:00
// If plugin does not exist on this instance, remove it
2011-09-06 19:35:47 +04:00
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
2011-08-25 23:23:27 +04:00
2011-09-06 19:35:47 +04:00
if ( byEnd._running === true ) {
2012-03-18 05:33:13 +04:00
2011-09-06 19:35:47 +04:00
byEnd._running = false;
2012-03-18 05:33:13 +04:00
runningPlugins = obj.data.running[ type ];
runningPlugins.splice( runningPlugins.indexOf( byEnd ), 1 );
if ( !obj.data.disabled[ type ] ) {
natives.end.call( obj, event, byEnd );
obj.emit( trackend,
Popcorn.extend({}, byEnd, {
plugin: type,
type: trackend
})
);
}
2011-08-24 22:52:39 +04:00
}
2011-09-06 19:35:47 +04:00
end++;
2011-08-24 22:52:39 +04:00
} else {
// remove track event
2011-09-06 19:35:47 +04:00
Popcorn.removeTrackEvent( obj, byEnd._id );
2011-08-24 22:52:39 +04:00
return;
}
}
2011-09-06 22:33:42 +04:00
while ( tracks.byStart[ start ] && tracks.byStart[ start ].start <= currentTime ) {
2011-09-06 19:35:47 +04:00
2011-09-06 22:33:42 +04:00
byStart = tracks.byStart[ start ];
2011-09-06 22:27:59 +04:00
natives = byStart._natives;
type = natives && natives.type;
2011-09-06 19:35:47 +04:00
2011-08-24 22:52:39 +04:00
// If plugin does not exist on this instance, remove it
2011-09-06 19:35:47 +04:00
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
2011-08-25 23:23:27 +04:00
2011-09-06 19:35:47 +04:00
if ( byStart.end > currentTime &&
2012-03-18 05:33:13 +04:00
byStart._running === false ) {
2011-08-24 22:52:39 +04:00
2011-09-06 19:35:47 +04:00
byStart._running = true;
2012-03-18 05:33:13 +04:00
obj.data.running[ type ].push( byStart );
2012-03-18 05:33:13 +04:00
if ( !obj.data.disabled[ type ] ) {
2012-03-18 05:33:13 +04:00
natives.start.call( obj, event, byStart );
2012-03-18 05:33:13 +04:00
obj.emit( trackstart,
Popcorn.extend({}, byStart, {
plugin: type,
type: trackstart
})
);
}
2011-08-24 22:52:39 +04:00
}
2011-09-06 19:35:47 +04:00
start++;
2011-08-24 22:52:39 +04:00
} else {
// remove track event
2011-09-06 19:35:47 +04:00
Popcorn.removeTrackEvent( obj, byStart._id );
2011-08-24 22:52:39 +04:00
return;
}
2011-08-25 23:23:27 +04:00
}
2011-08-24 22:52:39 +04:00
// Playbar receding
} else if ( previousTime > currentTime ) {
2011-09-06 22:33:42 +04:00
while ( tracks.byStart[ start ] && tracks.byStart[ start ].start > currentTime ) {
2011-09-06 19:35:47 +04:00
2011-09-06 22:33:42 +04:00
byStart = tracks.byStart[ start ];
2011-09-06 22:27:59 +04:00
natives = byStart._natives;
type = natives && natives.type;
2011-09-06 19:35:47 +04:00
2011-08-24 22:52:39 +04:00
// if plugin does not exist on this instance, remove it
2011-09-06 19:35:47 +04:00
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
2011-08-25 23:23:27 +04:00
2011-09-06 19:35:47 +04:00
if ( byStart._running === true ) {
2012-03-18 05:33:13 +04:00
2011-09-06 19:35:47 +04:00
byStart._running = false;
2012-03-18 05:33:13 +04:00
runningPlugins = obj.data.running[ type ];
runningPlugins.splice( runningPlugins.indexOf( byStart ), 1 );
if ( !obj.data.disabled[ type ] ) {
natives.end.call( obj, event, byStart );
obj.emit( trackend,
Popcorn.extend({}, byStart, {
2012-03-18 05:33:13 +04:00
plugin: type,
type: trackend
})
);
}
2011-08-24 22:52:39 +04:00
}
2011-09-06 19:35:47 +04:00
start--;
2011-08-24 22:52:39 +04:00
} else {
// remove track event
2011-09-06 19:35:47 +04:00
Popcorn.removeTrackEvent( obj, byStart._id );
2011-08-24 22:52:39 +04:00
return;
}
}
2011-09-06 22:33:42 +04:00
while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end > currentTime ) {
2011-09-06 19:35:47 +04:00
2011-09-06 22:33:42 +04:00
byEnd = tracks.byEnd[ end ];
2011-09-06 22:27:59 +04:00
natives = byEnd._natives;
type = natives && natives.type;
2011-09-06 19:35:47 +04:00
2011-08-24 22:52:39 +04:00
// if plugin does not exist on this instance, remove it
2011-09-06 19:35:47 +04:00
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
2011-08-25 23:23:27 +04:00
2011-09-06 19:35:47 +04:00
if ( byEnd.start <= currentTime &&
2012-03-18 05:33:13 +04:00
byEnd._running === false ) {
2011-08-24 22:52:39 +04:00
2011-09-06 19:35:47 +04:00
byEnd._running = true;
2012-03-18 05:33:13 +04:00
obj.data.running[ type ].push( byEnd );
if ( !obj.data.disabled[ type ] ) {
natives.start.call( obj, event, byEnd );
obj.emit( trackstart,
Popcorn.extend({}, byEnd, {
2012-03-18 05:33:13 +04:00
plugin: type,
type: trackstart
})
);
}
2011-08-24 22:52:39 +04:00
}
2011-09-06 19:35:47 +04:00
end--;
2011-08-24 22:52:39 +04:00
} else {
// remove track event
2011-09-06 19:35:47 +04:00
Popcorn.removeTrackEvent( obj, byEnd._id );
2011-08-24 22:52:39 +04:00
return;
2011-08-25 23:23:27 +04:00
}
2011-08-24 22:52:39 +04:00
}
}
2011-09-06 19:35:47 +04:00
tracks.endIndex = end;
tracks.startIndex = start;
2011-08-24 22:52:39 +04:00
tracks.previousUpdateTime = currentTime;
//enforce index integrity if trackRemoved
tracks.byStart.length < byStartLen && tracks.startIndex--;
tracks.byEnd.length < byEndLen && tracks.endIndex--;
2011-08-24 22:52:39 +04:00
};
2011-03-18 18:33:05 +03:00
// Map and Extend TrackEvent functions to all Popcorn instances
2010-12-16 21:44:19 +03:00
Popcorn.extend( Popcorn.p, {
2011-02-14 21:38:50 +03:00
2010-12-16 21:44:19 +03:00
getTrackEvents: function() {
return Popcorn.getTrackEvents.call( null, this );
},
2011-02-14 21:38:50 +03:00
getTrackEvent: function( id ) {
return Popcorn.getTrackEvent.call( null, this, id );
},
2011-02-14 21:38:50 +03:00
2010-12-16 21:44:19 +03:00
getLastTrackEventId: function() {
return Popcorn.getLastTrackEventId.call( null, this );
2011-02-14 21:38:50 +03:00
},
2010-12-16 21:44:19 +03:00
removeTrackEvent: function( id ) {
2010-12-16 21:44:19 +03:00
Popcorn.removeTrackEvent.call( null, this, id );
return this;
},
2011-02-16 00:55:52 +03:00
removePlugin: function( name ) {
Popcorn.removePlugin.call( null, this, name );
return this;
2011-08-24 22:52:39 +04:00
},
timeUpdate: function( event ) {
Popcorn.timeUpdate.call( null, this, event );
2011-09-06 19:35:47 +04:00
return this;
},
destroy: function() {
Popcorn.destroy.call( null, this );
return this;
2010-12-16 21:44:19 +03:00
}
});
2011-02-14 21:38:50 +03:00
// Plugin manifests
Popcorn.manifest = {};
2011-02-14 21:38:50 +03:00
// Plugins are registered
2010-12-04 23:54:38 +03:00
Popcorn.registry = [];
Popcorn.registryByName = {};
2011-02-14 21:38:50 +03:00
// An interface for extending Popcorn
2010-12-04 23:54:38 +03:00
// with plugin functionality
2011-02-14 21:38:50 +03:00
Popcorn.plugin = function( name, definition, manifest ) {
2010-12-04 23:54:38 +03:00
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
2010-12-04 23:54:38 +03:00
// Provides some sugar, but ultimately extends
2011-02-14 21:38:50 +03:00
// the definition into Popcorn.p
2011-02-23 07:30:20 +03:00
var reserved = [ "start", "end" ],
2011-01-19 22:10:06 +03:00
plugin = {},
2011-02-24 00:19:09 +03:00
setup,
2011-06-22 17:31:20 +04:00
isfn = typeof definition === "function",
methods = [ "_setup", "_teardown", "start", "end", "frame" ];
2011-02-14 21:38:50 +03:00
// combines calls of two function calls into one
var combineFn = function( first, second ) {
first = first || Popcorn.nop;
second = second || Popcorn.nop;
2011-06-18 00:12:40 +04:00
return function() {
first.apply( this, arguments );
second.apply( this, arguments );
};
};
2011-02-14 21:38:50 +03:00
2011-02-24 20:46:19 +03:00
// If `manifest` arg is undefined, check for manifest within the `definition` object
// If no `definition.manifest`, an empty object is a sufficient fallback
2011-07-22 19:34:14 +04:00
Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {};
// apply safe, and empty default functions
2011-06-22 17:31:20 +04:00
methods.forEach(function( method ) {
definition[ method ] = safeTry( definition[ method ] || Popcorn.nop, name );
2011-06-22 17:31:20 +04:00
});
2011-02-24 20:46:19 +03:00
var pluginFn = function( setup, options ) {
2011-02-14 21:38:50 +03:00
if ( !options ) {
return this;
2011-02-14 21:38:50 +03:00
}
// When the "ranges" property is set and its value is an array, short-circuit
// the pluginFn definition to recall itself with an options object generated from
// each range object in the ranges array. (eg. { start: 15, end: 16 } )
if ( options.ranges && Popcorn.isArray(options.ranges) ) {
Popcorn.forEach( options.ranges, function( range ) {
// Create a fresh object, extend with current options
// and start/end range object's properties
// Works with in/out as well.
var opts = Popcorn.extend( {}, options, range );
// Remove the ranges property to prevent infinitely
// entering this condition
delete opts.ranges;
// Call the plugin with the newly created opts object
this[ name ]( opts );
}, this);
// Return the Popcorn instance to avoid creating an empty track event
return this;
}
2011-02-23 07:30:20 +03:00
// Storing the plugin natives
var natives = options._natives = {},
compose = "",
originalOpts, manifestOpts;
Popcorn.extend( natives, setup );
2011-06-18 00:12:40 +04:00
options._natives.type = name;
options._running = false;
natives.start = natives.start || natives[ "in" ];
natives.end = natives.end || natives[ "out" ];
2012-05-04 19:21:33 +04:00
if ( options.once ) {
natives.end = combineFn( natives.end, function() {
this.removeTrackEvent( options._id );
});
}
// extend teardown to always call end if running
natives._teardown = combineFn(function() {
2012-03-18 05:33:13 +04:00
var args = slice.call( arguments ),
runningPlugins = this.data.running[ natives.type ];
// end function signature is not the same as teardown,
// put null on the front of arguments for the event parameter
args.unshift( null );
// only call end if event is running
2012-03-18 05:33:13 +04:00
args[ 1 ]._running &&
runningPlugins.splice( runningPlugins.indexOf( options ), 1 ) &&
natives.end.apply( this, args );
}, natives._teardown );
2011-06-18 00:12:40 +04:00
// default to an empty string if no effect exists
// split string into an array of effects
options.compose = options.compose && options.compose.split( " " ) || [];
2011-06-18 00:12:40 +04:00
options.effect = options.effect && options.effect.split( " " ) || [];
// join the two arrays together
options.compose = options.compose.concat( options.effect );
2011-06-23 22:47:05 +04:00
options.compose.forEach(function( composeOption ) {
2011-06-18 00:12:40 +04:00
// if the requested compose is garbage, throw it away
2011-06-23 22:47:05 +04:00
compose = Popcorn.compositions[ composeOption ] || {};
// extends previous functions with compose function
2011-06-22 17:31:20 +04:00
methods.forEach(function( method ) {
natives[ method ] = combineFn( natives[ method ], compose[ method ] );
});
2011-06-23 22:47:05 +04:00
});
2011-06-18 00:12:40 +04:00
2011-02-23 07:30:20 +03:00
// Ensure a manifest object, an empty object is a sufficient fallback
options._natives.manifest = manifest;
// Checks for expected properties
if ( !( "start" in options ) ) {
options.start = options[ "in" ] || 0;
}
if ( !options.end && options.end !== 0 ) {
options.end = options[ "out" ] || Number.MAX_VALUE;
}
// Use hasOwn to detect non-inherited toString, since all
// objects will receive a toString - its otherwise undetectable
if ( !hasOwn.call( options, "toString" ) ) {
options.toString = function() {
var props = [
"start: " + options.start,
"end: " + options.end,
"id: " + (options.id || options._id)
];
// Matches null and undefined, allows: false, 0, "" and truthy
if ( options.target != null ) {
props.push( "target: " + options.target );
}
return name + " ( " + props.join(", ") + " )";
};
}
2011-06-18 00:12:40 +04:00
// Resolves 239, 241, 242
if ( !options.target ) {
2011-02-14 21:38:50 +03:00
2011-06-18 00:12:40 +04:00
// Sometimes the manifest may be missing entirely
// or it has an options object that doesn't have a `target` property
manifestOpts = "options" in manifest && manifest.options;
2011-02-24 20:46:19 +03:00
options.target = manifestOpts && "target" in manifestOpts && manifestOpts.target;
}
2010-12-10 19:53:47 +03:00
// Trigger _setup method if exists
options._natives._setup && options._natives._setup.call( this, options );
2011-06-18 00:12:40 +04:00
// Create new track event for this instance
Popcorn.addTrackEvent( this, Popcorn.extend( options, options ) );
2010-12-10 19:53:47 +03:00
2011-02-14 21:38:50 +03:00
// Future support for plugin event definitions
// for all of the native events
2011-05-17 06:56:43 +04:00
Popcorn.forEach( setup, function( callback, type ) {
2011-02-14 21:38:50 +03:00
if ( type !== "type" ) {
2011-02-14 21:38:50 +03:00
2011-03-18 18:33:05 +03:00
if ( reserved.indexOf( type ) === -1 ) {
this.on( type, callback );
}
}
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
}, this );
2011-02-14 21:38:50 +03:00
return this;
};
// Extend Popcorn.p with new named definition
2011-02-14 21:38:50 +03:00
// Assign new named definition
Popcorn.p[ name ] = plugin[ name ] = function( options ) {
2012-03-18 05:33:13 +04:00
this.data.running[ name ] = this.data.running[ name ] || [];
// Merge with defaults if they exist, make sure per call is prioritized
var defaults = ( this.options.defaults && this.options.defaults[ name ] ) || {},
mergedSetupOpts = Popcorn.extend( {}, defaults, options );
return pluginFn.call( this, isfn ? definition.call( this, mergedSetupOpts ) : definition,
mergedSetupOpts );
2011-02-23 07:16:29 +03:00
};
2011-02-14 21:38:50 +03:00
// if the manifest parameter exists we should extend it onto the definition object
// so that it shows up when calling Popcorn.registry and Popcorn.registryByName
if ( manifest ) {
Popcorn.extend( definition, {
manifest: manifest
});
}
// Push into the registry
var entry = {
fn: plugin[ name ],
definition: definition,
base: definition,
parents: [],
name: name
};
2011-04-20 18:55:34 +04:00
Popcorn.registry.push(
Popcorn.extend( plugin, entry, {
type: name
})
);
Popcorn.registryByName[ name ] = entry;
2011-02-14 21:38:50 +03:00
return plugin;
2010-12-04 23:54:38 +03:00
};
2011-02-14 21:38:50 +03:00
// Storage for plugin function errors
Popcorn.plugin.errors = [];
// Returns wrapped plugin function
function safeTry( fn, pluginName ) {
return function() {
// When Popcorn.plugin.debug is true, do not suppress errors
if ( Popcorn.plugin.debug ) {
return fn.apply( this, arguments );
}
try {
return fn.apply( this, arguments );
} catch ( ex ) {
// Push plugin function errors into logging queue
Popcorn.plugin.errors.push({
plugin: pluginName,
thrown: ex,
source: fn.toString()
});
// Trigger an error that the instance can listen for
// and react to
this.emit( "pluginerror", Popcorn.plugin.errors );
}
};
}
// Debug-mode flag for plugin development
// True for Popcorn development versions, false for stable/tagged versions
Popcorn.plugin.debug = ( Popcorn.version === "@" + "VERSION" );
2011-07-20 00:19:13 +04:00
// removePlugin( type ) removes all tracks of that from all instances of popcorn
// removePlugin( obj, type ) removes all tracks of type from obj, where obj is a single instance of popcorn
Popcorn.removePlugin = function( obj, name ) {
// Check if we are removing plugin from an instance or from all of Popcorn
if ( !name ) {
// Fix the order
name = obj;
obj = Popcorn.p;
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
var registryLen = Popcorn.registry.length,
registryIdx;
// remove plugin reference from registry
for ( registryIdx = 0; registryIdx < registryLen; registryIdx++ ) {
if ( Popcorn.registry[ registryIdx ].name === name ) {
Popcorn.registry.splice( registryIdx, 1 );
delete Popcorn.registryByName[ name ];
delete Popcorn.manifest[ name ];
// delete the plugin
delete obj[ name ];
// plugin found and removed, stop checking, we are done
return;
}
}
}
var byStart = obj.data.trackEvents.byStart,
byEnd = obj.data.trackEvents.byEnd,
animating = obj.data.trackEvents.animating,
idx, sl;
// remove all trackEvents
for ( idx = 0, sl = byStart.length; idx < sl; idx++ ) {
if ( byStart[ idx ] && byStart[ idx ]._natives && byStart[ idx ]._natives.type === name ) {
byStart[ idx ]._natives._teardown && byStart[ idx ]._natives._teardown.call( obj, byStart[ idx ] );
byStart.splice( idx, 1 );
// update for loop if something removed, but keep checking
idx--; sl--;
if ( obj.data.trackEvents.startIndex <= idx ) {
obj.data.trackEvents.startIndex--;
obj.data.trackEvents.endIndex--;
}
}
2012-02-04 23:02:10 +04:00
// clean any remaining references in the end index
// we do this seperate from the above check because they might not be in the same order
if ( byEnd[ idx ] && byEnd[ idx ]._natives && byEnd[ idx ]._natives.type === name ) {
byEnd.splice( idx, 1 );
2012-02-04 23:02:10 +04:00
}
}
//remove all animating events
for ( idx = 0, sl = animating.length; idx < sl; idx++ ) {
if ( animating[ idx ] && animating[ idx ]._natives && animating[ idx ]._natives.type === name ) {
animating.splice( idx, 1 );
// update for loop if something removed, but keep checking
idx--; sl--;
}
}
};
Popcorn.compositions = {};
2011-04-22 01:37:04 +04:00
// Plugin inheritance
Popcorn.compose = function( name, definition, manifest ) {
2011-06-18 00:12:40 +04:00
// If `manifest` arg is undefined, check for manifest within the `definition` object
// If no `definition.manifest`, an empty object is a sufficient fallback
Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {};
2011-06-18 00:12:40 +04:00
// register the effect by name
Popcorn.compositions[ name ] = definition;
};
Popcorn.plugin.effect = Popcorn.effect = Popcorn.compose;
var rnaiveExpr = /^(?:\.|#|\[)/;
// Basic DOM utilities and helpers API. See #1037
Popcorn.dom = {
debug: false,
// Popcorn.dom.find( selector, context )
//
// Returns the first element that matches the specified selector
// Optionally provide a context element, defaults to `document`
//
// eg.
// Popcorn.dom.find("video") returns the first video element
// Popcorn.dom.find("#foo") returns the first element with `id="foo"`
// Popcorn.dom.find("foo") returns the first element with `id="foo"`
// Note: Popcorn.dom.find("foo") is the only allowed deviation
// from valid querySelector selector syntax
//
// Popcorn.dom.find(".baz") returns the first element with `class="baz"`
// Popcorn.dom.find("[preload]") returns the first element with `preload="..."`
// ...
// See https://developer.mozilla.org/En/DOM/Document.querySelector
//
//
find: function( selector, context ) {
var node = null;
// Trim leading/trailing whitespace to avoid false negatives
selector = selector.trim();
// Default context is the `document`
context = context || document;
if ( selector ) {
// If the selector does not begin with "#", "." or "[",
// it could be either a nodeName or ID w/o "#"
if ( !rnaiveExpr.test( selector ) ) {
// Try finding an element that matches by ID first
node = document.getElementById( selector );
// If a match was found by ID, return the element
if ( node !== null ) {
return node;
}
}
// Assume no elements have been found yet
// Catch any invalid selector syntax errors and bury them.
try {
node = context.querySelector( selector );
} catch ( e ) {
if ( Popcorn.dom.debug ) {
throw new Error(e);
}
}
}
return node;
}
};
// Cache references to reused RegExps
var rparams = /\?/,
// XHR Setup object
setup = {
2011-05-17 04:57:04 +04:00
url: "",
data: "",
dataType: "",
2010-12-15 22:32:48 +03:00
success: Popcorn.nop,
2011-05-17 04:57:04 +04:00
type: "GET",
2011-02-14 21:38:50 +03:00
async: true,
2011-05-17 04:57:04 +04:00
xhr: function() {
2010-12-20 18:59:32 +03:00
return new global.XMLHttpRequest();
2010-12-15 22:32:48 +03:00
}
2011-02-14 21:38:50 +03:00
};
2011-05-17 04:57:04 +04:00
Popcorn.xhr = function( options ) {
options.dataType = options.dataType && options.dataType.toLowerCase() || null;
2011-05-17 04:57:04 +04:00
if ( options.dataType &&
2011-05-17 04:57:04 +04:00
( options.dataType === "jsonp" || options.dataType === "script" ) ) {
2011-01-20 20:20:06 +03:00
2011-02-14 21:38:50 +03:00
Popcorn.xhr.getJSONP(
options.url,
options.success,
options.dataType === "script"
);
return;
}
2011-02-14 21:38:50 +03:00
2010-12-15 22:32:48 +03:00
var settings = Popcorn.extend( {}, setup, options );
2011-02-14 21:38:50 +03:00
// Create new XMLHttpRequest object
2010-12-15 22:32:48 +03:00
settings.ajax = settings.xhr();
2011-02-14 21:38:50 +03:00
2010-12-15 22:32:48 +03:00
if ( settings.ajax ) {
2011-02-14 21:38:50 +03:00
if ( settings.type === "GET" && settings.data ) {
2011-02-14 21:38:50 +03:00
// append query string
2011-03-18 18:33:05 +03:00
settings.url += ( rparams.test( settings.url ) ? "&" : "?" ) + settings.data;
2011-02-14 21:38:50 +03:00
// Garbage collect and reset settings.data
settings.data = null;
2011-02-14 21:38:50 +03:00
}
2010-12-15 22:32:48 +03:00
2011-02-14 21:38:50 +03:00
settings.ajax.open( settings.type, settings.url, settings.async );
2011-03-01 23:33:12 +03:00
settings.ajax.send( settings.data || null );
2010-12-15 22:32:48 +03:00
return Popcorn.xhr.httpData( settings );
2011-02-14 21:38:50 +03:00
}
2010-12-15 22:32:48 +03:00
};
2011-02-14 21:38:50 +03:00
2011-05-17 04:57:04 +04:00
Popcorn.xhr.httpData = function( settings ) {
2011-02-14 21:38:50 +03:00
2011-10-27 07:00:00 +04:00
var data, json = null,
parser, xml = null;
2011-02-14 21:38:50 +03:00
2010-12-20 18:59:32 +03:00
settings.ajax.onreadystatechange = function() {
2010-12-15 22:32:48 +03:00
2011-02-14 21:38:50 +03:00
if ( settings.ajax.readyState === 4 ) {
2010-12-15 22:32:48 +03:00
try {
2011-05-17 04:57:04 +04:00
json = JSON.parse( settings.ajax.responseText );
} catch( e ) {
2010-12-15 22:32:48 +03:00
//suppress
}
2010-12-15 22:32:48 +03:00
data = {
2011-02-14 21:38:50 +03:00
xml: settings.ajax.responseXML,
text: settings.ajax.responseText,
2010-12-15 22:32:48 +03:00
json: json
};
2011-02-14 21:38:50 +03:00
2011-10-29 20:00:27 +04:00
// Normalize: data.xml is non-null in IE9 regardless of if response is valid xml
if ( !data.xml || !data.xml.documentElement ) {
2011-10-29 08:43:23 +04:00
data.xml = null;
2011-10-29 20:00:27 +04:00
2011-10-27 07:00:00 +04:00
try {
parser = new DOMParser();
xml = parser.parseFromString( settings.ajax.responseText, "text/xml" );
if ( !xml.getElementsByTagName( "parsererror" ).length ) {
data.xml = xml;
}
} catch ( e ) {
2011-10-29 08:43:23 +04:00
// data.xml remains null
2011-10-27 07:00:00 +04:00
}
}
// If a dataType was specified, return that type of data
if ( settings.dataType ) {
data = data[ settings.dataType ];
}
2011-02-14 21:38:50 +03:00
2010-12-15 22:32:48 +03:00
settings.success.call( settings.ajax, data );
2011-02-14 21:38:50 +03:00
}
};
return data;
2010-12-15 22:32:48 +03:00
};
2011-05-17 04:57:04 +04:00
Popcorn.xhr.getJSONP = function( url, success, isScript ) {
2011-05-17 04:57:04 +04:00
var head = document.head || document.getElementsByTagName( "head" )[ 0 ] || document.documentElement,
script = document.createElement( "script" ),
paramStr = url.split( "?" )[ 1 ],
isFired = false,
params = [],
2011-02-17 00:47:47 +03:00
callback, parts, callparam;
2011-02-16 01:54:51 +03:00
if ( paramStr && !isScript ) {
2011-05-17 04:57:04 +04:00
params = paramStr.split( "&" );
}
2011-02-14 21:38:50 +03:00
2011-02-17 00:47:47 +03:00
if ( params.length ) {
2011-05-17 04:57:04 +04:00
parts = params[ params.length - 1 ].split( "=" );
2011-02-17 00:47:47 +03:00
}
2011-05-17 04:57:04 +04:00
callback = params.length ? ( parts[ 1 ] ? parts[ 1 ] : parts[ 0 ] ) : "jsonp";
2011-02-16 01:54:51 +03:00
if ( !paramStr && !isScript ) {
url += "?callback=" + callback;
}
2011-02-14 21:38:50 +03:00
2011-02-16 01:54:51 +03:00
if ( callback && !isScript ) {
2011-03-18 18:33:05 +03:00
// If a callback name already exists
2011-02-17 00:47:47 +03:00
if ( !!window[ callback ] ) {
// Create a new unique callback name
2011-02-17 00:47:47 +03:00
callback = Popcorn.guid( callback );
}
2011-03-18 18:33:05 +03:00
// Define the JSONP success callback globally
2011-05-17 04:57:04 +04:00
window[ callback ] = function( data ) {
// Fire success callbacks
2011-02-16 01:54:51 +03:00
success && success( data );
isFired = true;
};
2011-03-18 18:33:05 +03:00
2011-02-17 00:47:47 +03:00
// Replace callback param and callback name
2011-05-17 04:57:04 +04:00
url = url.replace( parts.join( "=" ), parts[ 0 ] + "=" + callback );
}
2011-03-18 18:33:05 +03:00
2012-02-26 11:20:41 +04:00
script.addEventListener( "load", function() {
// Handling remote script loading callbacks
if ( isScript ) {
// getScript
success && success();
}
2011-03-18 18:33:05 +03:00
// Executing for JSONP requests
if ( isFired ) {
// Garbage collect the callback
delete window[ callback ];
}
// Garbage collect the script resource
head.removeChild( script );
2012-02-26 11:20:41 +04:00
}, false );
script.src = url;
head.insertBefore( script, head.firstChild );
2011-03-18 18:33:05 +03:00
2011-02-16 01:54:51 +03:00
return;
};
2011-03-18 18:33:05 +03:00
2011-02-16 01:54:51 +03:00
Popcorn.getJSONP = Popcorn.xhr.getJSONP;
2011-03-18 18:33:05 +03:00
2011-02-16 01:54:51 +03:00
Popcorn.getScript = Popcorn.xhr.getScript = function( url, success ) {
return Popcorn.xhr.getJSONP( url, success, true );
};
2011-01-20 20:20:06 +03:00
Popcorn.util = {
// Simple function to parse a timestamp into seconds
// Acceptable formats are:
// HH:MM:SS.MMM
// HH:MM:SS;FF
// Hours and minutes are optional. They default to 0
toSeconds: function( timeStr, framerate ) {
// Hours and minutes are optional
// Seconds must be specified
// Seconds can be followed by milliseconds OR by the frame information
var validTimeFormat = /^([0-9]+:){0,2}[0-9]+([.;][0-9]+)?$/,
errorMessage = "Invalid time format",
digitPairs, lastIndex, lastPair, firstPair,
frameInfo, frameTime;
if ( typeof timeStr === "number" ) {
return timeStr;
}
if ( typeof timeStr === "string" &&
!validTimeFormat.test( timeStr ) ) {
Popcorn.error( errorMessage );
}
digitPairs = timeStr.split( ":" );
lastIndex = digitPairs.length - 1;
lastPair = digitPairs[ lastIndex ];
// Fix last element:
if ( lastPair.indexOf( ";" ) > -1 ) {
frameInfo = lastPair.split( ";" );
frameTime = 0;
if ( framerate && ( typeof framerate === "number" ) ) {
frameTime = parseFloat( frameInfo[ 1 ], 10 ) / framerate;
}
digitPairs[ lastIndex ] = parseInt( frameInfo[ 0 ], 10 ) + frameTime;
}
firstPair = digitPairs[ 0 ];
return {
1: parseFloat( firstPair, 10 ),
2: ( parseInt( firstPair, 10 ) * 60 ) +
parseFloat( digitPairs[ 1 ], 10 ),
3: ( parseInt( firstPair, 10 ) * 3600 ) +
( parseInt( digitPairs[ 1 ], 10 ) * 60 ) +
parseFloat( digitPairs[ 2 ], 10 )
}[ digitPairs.length || 1 ];
}
};
// alias for exec function
Popcorn.p.cue = Popcorn.p.exec;
// Protected API methods
Popcorn.protect = {
natives: getKeys( Popcorn.p ).map(function( val ) {
return val.toLowerCase();
})
};
// Setup logging for deprecated methods
Popcorn.forEach({
// Deprecated: Recommended
"listen": "on",
"unlisten": "off",
"trigger": "emit",
"exec": "cue"
}, function( recommend, api ) {
var original = Popcorn.p[ api ];
// Override the deprecated api method with a method of the same name
// that logs a warning and defers to the new recommended method
Popcorn.p[ api ] = function() {
if ( typeof console !== "undefined" && console.warn ) {
console.warn(
"Deprecated method '" + api + "', " +
(recommend == null ? "do not use." : "use '" + recommend + "' instead." )
);
// Restore api after first warning
Popcorn.p[ api ] = original;
}
return Popcorn.p[ recommend ].apply( this, [].slice.call( arguments ) );
};
});
2010-12-20 18:59:32 +03:00
// Exposes Popcorn to global context
2010-12-04 23:54:38 +03:00
global.Popcorn = Popcorn;
2011-02-08 23:58:30 +03:00
2011-02-16 00:55:52 +03:00
})(window, window.document);