2 * ~mv_embed version 1.0~
3 * for details see: http://metavid.org/wiki/index.php/Mv_embed
5 * All Metavid Wiki code is Released under the GPL2
6 * for more info visit http://metavid.org/wiki/Code
8 * @url http://metavid.org
11 * http://stevenlevithan.com/demo/parseuri/js/
13 * config values you can manually set the location of the mv_embed folder here
14 * (in cases where media will be hosted in a different place than the embedding page)
17 //fix multiple instances of mv_embed (ie include twice from two different servers)
19 if( MV_EMBED_VERSION
){
22 //used to grab fresh copies of scripts. (should be changed on commit)
23 var MV_EMBED_VERSION
= '1.0r18';
26 * Configuration variables (can be set from some precceding script)
28 //the name of the player skin (default is mvpcf)
30 var mv_skin_name
= 'mvpcf';
33 var mwjQueryUiSkin
= 'redmond';
35 //whether or not to load java from an iframe.
36 //note: this is necessary for remote embedding because of java security model)
38 var mv_java_iframe
= true;
40 //the default height/width of the video (if no style or width attribute provided)
41 if(!mv_default_video_size
)
42 var mv_default_video_size
= '400x300';
44 //for when useing mv_embed with script-loader in root mediawiki path
45 var mediaWiki_mvEmbed_path
= 'js2/mwEmbed/';
47 var global_player_list
= new Array(); //the global player list per page
48 var global_req_cb
= new Array(); //the global request callback array
49 var _global
= this; //global obj
50 var mv_init_done
=false;
51 var global_cb_count
=0;
53 /*parseUri class parses URIs:*/
54 var parseUri=function(d
){var o
=parseUri
.options
,value
=o
.parser
[o
.strictMode
?"strict":"loose"].exec(d
);for(var i
=0,uri
={};i
<14;i
++){uri
[o
.key
[i
]]=value
[i
]||""}uri
[o
.q
.name
]={};uri
[o
.key
[12]].replace(o
.q
.parser
,function(a
,b
,c
){if(b
)uri
[o
.q
.name
][b
]=c
});return uri
};parseUri
.options
={strictMode
:false,key
:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q
:{name
:"queryKey",parser
:/(?:^|&)([^&=]*)=?([^&]*)/g},parser
:{strict
:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose
:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};
57 //get mv_embed location if it has not been set
59 var mv_embed_path
= getMvEmbedPath();
61 var jQueryUiVN
= 'jquery.ui-1.7.1';
64 //setup the skin path:
65 var mv_jquery_skin_path
= mv_embed_path
+ 'jquery/' + jQueryUiVN
+ '/themes/' + mwjQueryUiSkin
+ '/';
66 var mv_skin_img_path
= mv_embed_path
+ 'skins/' + mv_skin_name
+ '/images/';
67 var mv_default_thumb_url
= mv_skin_img_path
+ 'vid_default_thumb.jpg';
70 //init the global Msg if not already
71 if(!gMsg
){var gMsg
={};}
74 function loadGM( msgSet
){
76 gMsg
[ i
] = msgSet
[i
];
80 //all default msg in [English] should be overwritten by the CMS language msg system.
82 "loading_txt":"loading <blink>...</blink>",
83 "loading_title" : "Loading...",
85 "size-gigabytes" : "$1 GB",
86 "size-megabytes" : "$1 MB",
87 "size-kilobytes" : "$1 K",
93 * AutoLoader paths (this should mirror the file: jsAutoloadLocalClasses.php )
94 * any file _not_ listed here won't be auto-loadable
95 * @path the path to the file (or set of files) with ending slash
96 * @gClasses the set of classes
97 * if an array $j.className become jquery.className.js
98 * if an asssociative object then key => value paris are used
100 if(typeof mvClassPaths
== 'undefined')
103 function lcPaths( path
, gClasses
, opt
){
106 if(typeof opt
['j_replace'] == 'undefined')
107 opt
['j_replace'] = 'jquery.';
112 for(var i
=0; i
< gClasses
.length
; i
++){
113 if(typeof gClasses
[i
] != 'undefined'){
114 //setup normal replacement of j with jquery
115 var jsName
= ( gClasses
[i
].substr(0,3) == '$j.' ) ? opt
['j_replace'] + gClasses
[i
].substr(3) : gClasses
[i
];
116 mvClassPaths
[ gClasses
[i
] ] = path
+ jsName
+ '.js';
121 for(var i
in gClasses
){
122 //assume object with key:path:
123 mvClassPaths
[i
] = path
+ gClasses
[ i
];
127 function mvGetClassPath(k
){
128 if( mvClassPaths
[k
] ){
129 //js_log('got classpath:' + k + ' : '+ mvClassPaths[k]);
130 return mvClassPaths
[k
];
132 return js_error('could not find path for requested class ' + k
);
135 if(typeof mvCssPaths
== 'undefined')
138 function lcCssPath(cssSet
){
139 for(var i
in cssSet
){
140 mvCssPaths
[i
]= mv_embed_path
+ cssSet
[i
];
143 //core and (non-standard named files relative to class the init):
145 'mv_embed' : 'mv_embed.js',
146 'window.jQuery' : 'jquery/jquery-1.3.2.js',
147 '$j.fn.pngFix' : 'jquery/plugins/jquery.pngFix.js',
148 '$j.fn.autocomplete': 'jquery/plugins/jquery.autocomplete.js',
149 '$j.fn.hoverIntent' : 'jquery/plugins/jquery.hoverIntent.js',
150 '$j.fn.datePicker' : 'jquery/plugins/jquery.datePicker.js',
151 '$j.ui' : 'jquery/jquery.ui-1.7.1/ui/ui.core.js',
152 '$j.fn.ColorPicker' : 'libClipEdit/colorpicker/js/colorpicker.js',
153 '$j.Jcrop' : 'libClipEdit/Jcrop/js/jquery.Jcrop.js',
154 '$j.fn.simpleUploadForm': 'libAddMedia/simpleUploadForm.js'
157 lcPaths( 'jquery/plugins/', [
163 lcPaths('jquery/jquery.ui-1.7.1/ui/', [
166 '$j.effects.pulsate',
167 '$j.effects.transfer',
171 '$j.effects.explode',
183 '$j.effects.highlight',
191 lcPaths('libAddMedia/', [
194 'mvBaseUploadInterface',
195 'remoteSearchDriver',
196 'seqRemoteSearchDriver'
199 lcPaths('libAddMedia/searchLibs/', [
207 lcPaths( 'libClipEdit/', [
210 //libEmbedObj (we could load all these clasess in embedVideo):
211 lcPaths( 'libEmbedVideo/', [
222 lcPaths( 'libSequencer/', [
229 lcPaths( 'libTimedText/', [
233 //depencency mapping for css files for self contained included plugins:
235 '$j.Jcrop' : 'libClipEdit/Jcrop/css/jquery.Jcrop.css',
236 '$j.fn.ColorPicker': 'libClipEdit/colorpicker/css/colorpicker.css'
240 * Language Functions:
242 * These functions try to losely mirro the functionality of Language.php in mediaWiki
244 function gM( key
, args
) {
248 if(typeof args
== 'object' || typeof args
== 'array'){
250 //msg test replace arguments start at 1 insted of zero:
251 var rep
= '\$'+ ( parseInt(v
) + 1 );
252 ms
= ms
.replace( rep
, args
[v
]);
254 }else if(typeof args
=='string' || typeof args
=='number'){
255 ms
= ms
.replace(/\$1/, args
);
259 //key is missing return indication:
260 return '<' + key
+ '>';
264 * msgSet is either a string corresponding to a single msg to load
265 * or msgSet is an array with set of msg to load
267 function gMsgLoadRemote(msgSet
, callback
){
269 if(typeof msgSet
== 'object' ){
270 for(var i
in msgSet
){
271 ammessages
+= msgSet
[i
] + '|';
273 }else if(typeof msgSet
== 'string'){
274 ammessages
+= msgSet
;
276 if(ammessages
== ''){
277 js_log('gMsgLoadRemote::no msg set requested');
282 'meta':'allmessages',
283 'ammessages':ammessages
286 if(data
.query
.allmessages
){
287 var msgs
= data
.query
.allmessages
;
290 ld
[ msgs
[i
]['name'] ] = msgs
[i
]['*'];
294 //load the result into local msg var
300 * Format a size in bytes for output, using an appropriate
301 * unit (B, KB, MB or GB) according to the magnitude in question
303 * @param size Size to format
304 * @return string Plain text (not HTML)
306 function formatSize( size
) {
307 // For small sizes no decimal places necessary
314 // For MB and bigger two decimal places are smarter
318 msg
= 'size-gigabytes';
320 msg
= 'size-megabytes';
323 msg
= 'size-kilobytes';
328 //javascript does not let you do precession points in rounding
329 var p
= Math
.pow(10,round
);
330 var size
= Math
.round( size
* p
) / p
;
331 //@@todo we need a formatNum and we need to request some special packaged info to deal with that case.
332 return gM( msg
, size
);
335 //gets the loading image:
336 function mv_get_loading_img( style
, class_attr
){
337 var style_txt
= (style
)?style
:'';
338 var class_attr
= (class_attr
)?'class="'+class_attr
+'"':'class="mv_loading_img"';
339 return '<div '+class_attr
+' style="' + style
+'"></div>';
342 function mv_set_loading(target
, load_id
){
343 var id_attr
= ( load_id
)?' id="' + load_id
+ '" ':'';
344 $j(target
).append('<div '+id_attr
+' style="position:absolute;top:0px;left:0px;height:100%;width:100%;'+
345 'background-color:#FFF;">' +
346 mv_get_loading_img('top:30px;left:30px') +
351 * mvJsLoader class handles initialization and js file loads
357 onReadyEvents
:new Array(),
358 doneReadyEvents
:false,
359 jQueryCheckFlag
:false,
360 //to keep consistency across threads:
363 load_error
:false, //load error flag (false by default)
365 callbacks
:new Array(),
368 doLoad:function(loadLibs
, callback
){
370 if( loadLibs
&& loadLibs
.length
!=0 ){ //setup this.libs:
372 //first check if we already have this lib loaded
373 var all_libs_loaded
=true;
374 for(var i
=0; i
< loadLibs
.length
; i
++){
375 //check if the lib is already loaded:
376 if( ! this.checkObjPath( loadLibs
[i
] ) ){
377 all_libs_loaded
=false;
380 if( all_libs_loaded
){
381 js_log('all libs already loaded skipping... load req');
385 //do a check for any css we may need and get it:
386 for(var i
=0; i
< loadLibs
.length
; i
++){
387 if( typeof mvCssPaths
[ loadLibs
[i
] ] != 'undefined' ){
388 loadExternalCss( mvCssPaths
[ loadLibs
[i
] ]);
392 //check if we should use the script loader to combine all the requests into one:
393 if( typeof mwSlScript
!= 'undefined' ){
397 for(var i
=0; i
< loadLibs
.length
; i
++){
398 var curLib
= loadLibs
[i
];
399 //only add if not included yet:
400 if( ! this.checkObjPath( curLib
) ){
401 class_set
+=coma
+ curLib
;
406 var puri
= parseUri( getMvEmbedURL() );
407 if( (getMvEmbedURL().indexOf('://')!=-1) && puri
.host
!= parseUri( document
.URL
).host
){
408 mwSlScript
= puri
.protocol
+ '://' + puri
.authority
+ mwSlScript
;
411 var dbug_attr
= (puri
.queryKey
['debug'])?'&debug=true':'';
412 this.libs
[ last_class
] = mwSlScript
+ '?class=' + class_set
+
413 '&urid=' + getMvUniqueReqId() + dbug_attr
;
417 for(var i
=0; i
< loadLibs
.length
; i
++){
418 var curLib
= loadLibs
[i
];
420 var libLoc
= mvGetClassPath(curLib
);
421 // do a direct load of the file (pass along unique request id from request or mv_embed Version )
422 var qmark
= (libLoc
.indexOf('?')!==true)?'?':'&';
423 this.libs
[curLib
] = mv_embed_path
+ libLoc
+ qmark
+ 'urid='+ getMvUniqueReqId();
429 this.callbacks
.push(callback
);
431 if( this.checkLoading() ){
432 if( this.load_time
++ > 1000){ //time out after ~80seconds
433 js_error( gM('error_load_lib') + this.missing_path
);
434 this.load_error
=true;
436 setTimeout( 'mvJsLoader.doLoad()', 20 );
439 //js_log('checkLoading passed run callbacks');
440 //only do callback if we are in the same instance (weird concurency issue)
442 for(var i
=0; i
< this.callbacks
.length
; i
++)
444 //js_log('REST LIBS: loading is: '+ loading + ' run callbacks: '+cb_count +' p:'+ this.ptime +' c:'+ this.ctime);
447 //js_log('done loading do call: ' + this.callbacks[0] );
448 while( this.callbacks
.length
!=0 ){
449 if( this.ptime
== ( this.ctime
-1) ){ //enforce thread consistency
450 this.callbacks
.pop()();
451 //func = this.callbacks.pop();
452 //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func);
455 //re-issue doLoad ( ptime will be set to ctime so we should catch up)
456 setTimeout( 'mvJsLoader.doLoad()', 25 );
461 this.ptime
=this.ctime
;
463 doLoadFullPaths:function(loadObj
, callback
){
466 doLoadDepMode:function(loadChain
, callback
){
467 //firefox executes js ~in-order of it being included~ so just directly issue request:
468 if( $j
.browser
.firefox
){
470 for(var i
=0; i
< loadChain
.length
;i
++){
471 for(var j
=0;j
<loadChain
[i
].length
;j
++){
472 loadSet
.push(loadChain
[i
][j
]);
475 mvJsLoader
.doLoad(loadSet
, callback
);
477 //safari and IE tend to execute out of order so load with dependenciy checks
478 mvJsLoader
.doLoad(loadChain
.shift(),function(){
479 if(loadChain
.length
!=0){
480 mvJsLoader
.doLoadDepMode(loadChain
, callback
);
486 checkLoading:function(){
489 for(var i
in this.libs
){ //for in loop oky on object
490 if( !this.checkObjPath( i
) ){
492 loadExternalJs( this.libs
[i
] );
496 //js_log("has not yet loaded: " + i);
502 checkObjPath:function( libVar
){
505 var objPath
= libVar
.split('.')
507 for(var p
=0; p
< objPath
.length
; p
++){
508 cur_path
= (cur_path
=='')?cur_path
+objPath
[p
]:cur_path
+'.'+objPath
[p
];
509 eval( 'var ptest = typeof ( '+ cur_path
+ ' ); ');
510 if( ptest
== 'undefined'){
511 this.missing_path
= cur_path
;
515 this.cur_path
= cur_path
;
519 * checks for jQuery and adds the $j noConflict var
521 jQueryCheck:function(callback
){
522 //skip stuff if $j is already loaded:
523 if(_global
['$j'] && callback
)
530 _global
['$j'] = jQuery
.noConflict();
531 //set up ajax to not send dynamic urls for loading scripts (we control that with the scriptLoader)
535 js_log('jquery loaded');
536 //setup mvEmbed jquery bindigns:
544 embedVideoCheck:function( callback
){
546 js_log('embedVideoCheck:');
547 //issue a style sheet request get both mv_embed and jquery styles:
548 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
549 loadExternalCss( mv_embed_path
+ 'skins/'+mv_skin_name
+'/styles.css');
551 //make sure we have jQuery
552 _this
.jQueryCheck(function(){
563 //add png fix if needed:
564 if($j
.browser
.msie
|| $j
.browser
.version
< 7)
565 depReq
[0].push( '$j.fn.pngFix' );
567 _this
.doLoadDepMode(depReq
,function(){
573 addLoadEvent:function(fn
){
574 this.onReadyEvents
.push(fn
);
576 //checks the jQuery flag (this way when remote embeding we don't load jQuery
577 // unless js2AddOnloadHook was used or there is video on the page
578 runQuededFunctions:function(){
580 this.doneReadyEvents
=true;
581 if(this.jQueryCheckFlag
){
582 this.jQueryCheck(function(){
583 _this
.runReadyEvents();
586 this.runReadyEvents();
589 runReadyEvents:function(){
590 js_log("runReadyEvents");
591 while( this.onReadyEvents
.length
){
592 this.onReadyEvents
.shift()();
597 //load an external JS (similar to jquery .require plugin)
598 //but checks for object availability rather than load state
600 /*********** INITIALIZATION CODE *************
601 * this will get called when DOM is ready
602 *********************************************/
603 /* jQuery .ready does not work when jQuery is loaded dynamically
604 * for an example of the problem see:1.1.3 working:http://pastie.caboo.se/92588
605 * and >= 1.1.4 not working: http://pastie.caboo.se/92595
606 * $j(document).ready( function(){ */
607 function mwdomReady(force
){
608 js_log('f:mwdomReady:');
609 if( !force
&& mv_init_done
){
610 js_log("mv_init_done already done do nothing...");
614 //handle the execution of Queded function with jQuery "ready"
616 //check if this page does have video or playlist
617 if(document
.getElementsByTagName("video").length
!=0 ||
618 document
.getElementsByTagName("audio").length
!=0 ||
619 document
.getElementsByTagName("playlist").length
!=0){
620 js_log('we have things to rewrite');
621 //load libs and proccess:
622 mvJsLoader
.embedVideoCheck(function(){
623 //run any queded global events:
624 mv_video_embed( function(){
625 mvJsLoader
.runQuededFunctions();
629 //if we already have jQuery make sure its loaded into its proper context $j
630 //run any queded global events:
631 mvJsLoader
.runQuededFunctions();
634 //js2AddOnloadHook: ensure jQuery and the DOM are ready:
635 function js2AddOnloadHook( func
) {
636 //make sure the skin/style sheets are avaliable always:
637 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
638 loadExternalCss( mv_embed_path
+ 'skins/'+mv_skin_name
+'/styles.css');
640 //if we have already run the dom ready just run the function directly:
641 if( mvJsLoader
.doneReadyEvents
){
642 //make sure jQuery is there:
643 mvJsLoader
.jQueryCheck(function(){
647 //if using js2AddOnloadHook we need to get jQuery into place (if its not already included)
648 mvJsLoader
.jQueryCheckFlag
= true;
649 mvJsLoader
.addLoadEvent( func
);
652 //depreciated mwAddOnloadHook in favor of js2 naming (for clear seperation of js2 code from old mw code
653 var mwAddOnloadHook
= js2AddOnloadHook
;
655 * this function allows for targeted rewriting
657 function rewrite_by_id( vid_id
, ready_callback
){
658 js_log('f:rewrite_by_id: ' + vid_id
);
659 //force a recheck of the dom for playlist or video element:
660 mvJsLoader
.embedVideoCheck(function(){
661 mv_video_embed(ready_callback
, vid_id
);
664 //depricated in favor of updates to oggHanlder
665 function rewrite_for_oggHanlder( vidIdList
){
666 for(var i
= 0; i
< vidIdList
.length
; i
++){
667 var vidId
= vidIdList
[i
];
668 js_log('looking at vid: ' + i
+' ' + vidId
);
669 //grab the thumbnail and src video
670 var pimg
= $j('#'+vidId
+ ' img');
671 var poster_attr
= 'poster = "' + pimg
.attr('src') + '" ';
672 var pwidth
= pimg
.attr('width');
673 var pheight
= pimg
.attr('height');
677 if( pwidth
=='22' && pheight
=='22'){
680 type_attr
= 'type="audio/ogg"';
688 var re
= new RegExp( /videoUrl(":?\s*)*([^&]*)/ );
689 src
= re
.exec( $j('#'+vidId
).html() )[2];
691 var re
= new RegExp( /length(":?\s*)*([^&]*)/ );
692 duration
= re
.exec( $j('#'+vidId
).html() )[2];
694 var re
= new RegExp( /offset(":?\s*)*([^&]*)/ );
695 offset
= re
.exec( $j('#'+vidId
).html() )[2];
696 var offset_attr
= (offset
)? 'startOffset="'+ offset
+ '"': '';
699 //replace the top div with mv_embed based player:
700 var vid_html
= '<video id="vid_' + i
+'" '+
701 'src="' + src
+ '" ' +
705 'duration="' + duration
+ '" ' +
706 'style="width:' + pwidth
+ 'px;height:' +
707 pheight
+ 'px;"></video>';
708 //js_log("video html: " + vid_html);
709 $j('#'+vidId
).html( vid_html
);
712 //rewrite that video id:
713 rewrite_by_id('vid_' + i
);
718 /*********** INITIALIZATION CODE *************
719 * set DOM ready callback to init_mv_embed
720 *********************************************/
721 // for Mozilla browsers
722 if (document
.addEventListener
) {
723 document
.addEventListener("DOMContentLoaded", function(){mwdomReady()}, false);
725 //backup "onload" method in case on DOMContentLoaded does not exist
726 window
.onload = function(){ mwdomReady() };
729 * should depreciate and use jquery.ui.dialog instead
731 function mv_write_modal(content
, speed
){
732 $j('#modalbox,#mv_overlay').remove();
733 $j('body').append('<div id="modalbox" style="background:#DDD;border:3px solid #666666;font-size:115%;'+
734 'top:30px;left:20px;right:20px;bottom:30px;position:fixed;z-index:100;">'+
737 '<div id="mv_overlay" style="background:#000;cursor:wait;height:100%;left:0;position:fixed;'+
738 'top:0;width:100%;z-index:5;filter:alpha(opacity=60);-moz-opacity: 0.6;'+
740 $j('#modalbox,#mv_overlay').show( speed
);
742 function mv_remove_modal(speed
){
743 $j('#modalbox,#mv_overlay').remove( speed
);
747 * stores all the mwEmbed jQuery specific bindings
748 * (setup after jQuery is avaliable)
749 * lets you call rewrites in a jquery "way"
751 * @@ eventually we should refactor mwCode over to jQuery style plugins
752 * and mv_embed.js will just hanndle dependency mapping and loading.
755 function mv_jqueryBindings(){
756 js_log('mv_jqueryBindings');
758 $.fn
.addMediaWiz = function( iObj
, callback
){
759 //first set the cursor for the button to "loading"
760 $j(this.selector
).css('cursor','wait').attr('title', gM('loading_title'));
762 iObj
['target_invocation'] = this.selector
;
764 //load the mv_embed_base skin:
765 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
766 loadExternalCss( mv_embed_path
+ 'skins/'+mv_skin_name
+'/styles.css' );
767 //load all the req libs:
768 mvJsLoader
.jQueryCheck(function(){
769 //load with staged dependeinces (for ie and safari that don't execute in order)
770 mvJsLoader
.doLoadDepMode([
771 [ 'remoteSearchDriver',
782 iObj
['instance_name']= 'rsdMVRS';
783 _global
['rsdMVRS'] = new remoteSearchDriver( iObj
);
785 callback( _global
['rsdMVRS'] );
790 $.fn
.sequencer = function( iObj
, callback
){
792 iObj
['target_sequence_container'] = this.selector
;
793 //issue a request to get the css file (if not already included):
794 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css');
795 loadExternalCss( mv_embed_path
+'skins/'+mv_skin_name
+'/mv_sequence.css');
796 //make sure we have the required mv_embed libs (they are not loaded when no video element is on the page)
797 mvJsLoader
.embedVideoCheck(function(){
798 //load playlist object and then jquery ui stuff:
799 mvJsLoader
.doLoadDepMode([
819 js_log('calling new mvSequencer');
820 //init the sequence object (it will take over from there) no more than one mvSeq obj for now:
821 if(!_global
['mvSeq']){
822 _global
['mvSeq'] = new mvSequencer(iObj
);
824 js_log('mvSeq already init');
830 * the firefogg jquery function:
831 * @@note this firefogg envocation could be made to work more like real jquery plugins
833 $.fn
.firefogg = function( iObj
, callback
) {
836 //add base theme css:
837 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css');
838 loadExternalCss( mv_embed_path
+ 'skins/'+mv_skin_name
+'/styles.css' );
840 //check if we already have firefogg loaded (the call just updates properties for that element)
841 var sElm
= $j(this.selector
).get(0);
842 if(sElm
['firefogg']){
843 if(sElm
['firefogg']=='loading'){
844 js_log("Error: called firefogg operations on Firefogg selector that is not done loading");
849 js_log("firefogg::updated: "+ i
+ ' to '+ iObj
[i
]);
850 sElm
['firefogg'][i
] = iObj
[i
];
852 return sElm
['firefogg'];
855 sElm
['firefogg'] = 'loading';
858 iObj
['selector'] = this.selector
;
862 'mvBaseUploadInterface',
871 if( iObj
.encoder_interface
){
880 //make sure we have everything loaded that we need:
881 mvJsLoader
.doLoadDepMode( loadSet
, function(){
882 js_log('firefogg libs loaded. target select:' + iObj
.selector
);
883 //select interface provicer based on if we want to include the encoder interface or not:
884 if(iObj
.encoder_interface
){
885 var myFogg
= new mvAdvFirefogg( iObj
);
887 var myFogg
= new mvFirefogg( iObj
);
890 myFogg
.doRewrite( callback
);
891 var selectorElement
= $j( iObj
.selector
).get(0);
892 selectorElement
['firefogg']=myFogg
;
896 //takes a input player as the selector and exposes basic rendering controls
897 $.fn
.firefoggRender = function( iObj
, callback
){
898 //check if we already have render loaded then just pass on updates/actions
899 var sElm
= $j(this.selector
).get(0);
900 if(sElm
['fogg_render']){
901 if(sElm
['fogg_render']=='loading'){
902 js_log("Error: called firefoggRender while loading");
905 //call or update the property:
907 sElm
['fogg_render']='loading';
909 iObj
['player_target'] = this.selector
;
914 sElm
['fogg_render']= new mvFirefoggRender( iObj
);
915 if( callback
&& typeof callback
== 'function' )
916 callback( sElm
['fogg_render'] );
920 $.fn
.baseUploadInterface = function(iObj
){
921 mvJsLoader
.doLoadDepMode([
923 'mvBaseUploadInterface',
931 myUp
= new mvBaseUploadInterface( iObj
);
936 //shortcut to a themed button:
937 $.btnHtml = function(msg
, className
, iconId
, opt
){
940 var href
= (opt
.href
)?opt
.href
:'#';
941 var target_attr
= (opt
.target
)?' target="' + opt
.target
+ '" ':'';
942 var style_attr
= (opt
.style
)?' style="'+opt
.style
+'" ':'';
943 return '<a href="' + href
+ '" ' + target_attr
+ style_attr
+' class="ui-state-default ui-corner-all ui-icon_link ' +
944 className
+ '"><span class="ui-icon ui-icon-' + iconId
+ '" />' +
947 //shortcut to bind hover state:
948 $.fn
.btnBind = function(){
951 $j(this).addClass('ui-state-hover');
954 $j(this).removeClass('ui-state-hover');
965 //simple url re-writer for rewriting urls (could probably be refactored into an inline regular expresion)
966 function getURLParamReplace( url
, opt
){
967 var pSrc
= parseUri( url
);
968 if(pSrc
.protocol
!= '' ){
969 var new_url
= pSrc
.protocol
+'://'+ pSrc
.authority
+ pSrc
.path
+'?';
971 var new_url
= pSrc
.path
+'?';
974 for(var key
in pSrc
.queryKey
){
975 var val
= pSrc
.queryKey
[ key
];
976 //do override if requested
979 new_url
+= amp
+ key
+ '=' + val
;
982 //add any vars that did were not originally there:
984 if(!pSrc
.queryKey
[i
]){
985 new_url
+=amp
+ i
+ '=' + opt
[i
];
992 * seconds2npt given a float seconds returns npt format response:
993 * @param float seconds
994 * @param boolean if we should show ms or not.
996 function seconds2npt(sec
, show_ms
){
998 //js_log("warning: trying to get npt time on NaN:" + sec);
1001 var hours
= Math
.floor(sec
/ 3600);
1002 var minutes
= Math
.floor((sec
/60) % 60);
1003 var seconds
= sec
% 60;
1004 //round the second amount requested significant digits
1006 seconds
= Math
.round( seconds
* 1000 ) / 1000;
1008 seconds
= Math
.round( seconds
);
1011 seconds
= '0'+ seconds
;
1013 minutes
= '0' + minutes
;
1015 return hours
+":"+minutes
+":"+seconds
;
1018 * takes hh:mm:ss,ms or hh:mm:ss.ms input returns number of seconds
1020 function npt2seconds( npt_str
){
1022 //js_log('npt2seconds:not valid ntp:'+ntp);
1025 //strip npt: time definition if present
1026 npt_str
= npt_str
.replace('npt:', '');
1028 times
= npt_str
.split(':');
1029 if(times
.length
!=3){
1030 js_log('error: npt2seconds on ' + npt_str
);
1033 //sometimes the comma is used inplace of pereid for ms
1034 times
[2] = times
[2].replace(/,\s?/,'.');
1035 //return seconds float (ie take seconds float value if present):
1036 return parseInt(times
[0]*3600)+parseInt(times
[1]*60)+parseFloat(times
[2]);
1039 * simple helper to grab a edit token
1041 * @param title the wiki page title you want to edit )
1042 * @param api_url 'optional' the target api url
1043 * @param callback the callback function to pass the token or "false" to
1045 function get_mw_token( title
, api_url
, callback
){
1046 js_log(':get_mw_token:');
1047 if(!title
&& wgUserName
){
1048 title
= 'User:' + wgUserName
;
1060 for(var i
in data
.query
.pages
){
1061 if(data
.query
.pages
[i
]['edittoken']){
1062 if(typeof callback
== 'function')
1063 callback ( data
.query
.pages
[i
]['edittoken'] );
1071 //does a remote or local api request based on request url
1072 //@param options: url, data, cbParam, callback
1073 function do_api_req( options
, callback
){
1074 if(typeof options
.data
!= 'object'){
1075 return js_error('Error: request paramaters must be an object');;
1077 //gennerate the url if its missing:
1078 if( typeof options
.url
== 'undefined' || options
.url
=== false){
1079 if(!wgServer
|| ! wgScriptPath
){
1080 return js_error('Error: no api url for api request');;
1082 //update to api.php (if index.php was in the wgScript path):
1083 options
.url
= mwGetLocalApiUrl();
1085 if( typeof options
.data
== 'undefined' )
1088 //force format to json (if not already set)
1089 options
.data
['format'] = 'json';
1091 //if action not set assume query
1092 if(!options
.data
['action'])
1093 options
.data
['action']='query';
1095 js_log('do api req: ' + options
.url
+'?' + jQuery
.param(options
.data
) );
1096 //build request string:
1097 if( parseUri( document
.URL
).host
== parseUri( options
.url
).host
){
1098 //local request do api request directly
1103 dataType
:'json', //api requests _should_ always return JSON data:
1105 success:function(data
){
1109 js_error( ' error' + e
+' in getting: ' + options
.url
);
1113 //set the callback param if not already set:
1114 if( typeof options
.jsonCB
== 'undefined')
1115 options
.jsonCB
= 'callback';
1117 var req_url
= options
.url
;
1118 var paramAnd
= (req_url
.indexOf('?')==-1)?'?':'&';
1119 //put all the values into the GET req:
1120 for(var i
in options
.data
){
1121 req_url
+= paramAnd
+ encodeURIComponent( i
) + '=' + encodeURIComponent( options
.data
[i
] );
1124 var fname
= 'mycpfn_' + ( global_cb_count
++ );
1125 _global
[ fname
] = callback
;
1126 req_url
+= '&' + options
.jsonCB
+ '=' + fname
;
1127 loadExternalJs( req_url
);
1130 function mwGetLocalApiUrl(url
){
1131 if (wgServer
&& wgScriptPath
){
1132 return wgServer
+ wgScriptPath
+ '/api.php';
1136 //grab wiki form error for wiki html page proccessing (should be depricated)
1137 function grabWikiFormError ( result_page
){
1139 sp
= result_page
.indexOf('<span class="error">');
1141 se
= result_page
.indexOf('</span>', sp
);
1142 res
.error_txt
= result_page
.substr(sp
, (sp
-se
)) + '</span>';
1145 sp
= result_page
.indexOf('<ul class="warning">')
1147 se
= result_page
.indexOf('</ul>', sp
);
1148 res
.error_txt
= result_page
.substr(sp
, (se
-sp
)) + '</ul>';
1149 //try and add the ignore form item:
1150 sfp
= result_page
.indexOf('<form method="post"');
1152 sfe
= result_page
.indexOf('</form>', sfp
);
1153 res
.form_txt
= result_page
.substr(sfp
, ( sfe
- sfp
)) + '</form>';
1156 //one more error type check:
1157 sp
= result_page
.indexOf('class="mw-warning-with-logexcerpt">')
1159 se
= result_page
.indexOf('</div>', sp
);
1160 res
.error_txt
= result_page
.substr(sp
, ( se
- sp
)) + '</div>';
1166 //do a "normal" request
1167 function do_request(req_url
, callback
){
1168 js_log('do_request::req_url:' + req_url
+ ' != ' + parseUri( req_url
).host
);
1169 //if we are doing a request to the same domain or relative link do a normal GET:
1170 if( parseUri(document
.URL
).host
== parseUri(req_url
).host
||
1171 req_url
.indexOf('://') == -1 ){ //relative url
1172 //do a direct request:
1177 success:function(data
){
1182 //get data via DOM injection with callback
1183 global_req_cb
.push(callback
);
1184 //prepend json_ to feed_format if not already requesting json format
1185 if( req_url
.indexOf("feed_format=")!=-1 && req_url
.indexOf("feed_format=json")==-1)
1186 req_url
= req_url
.replace(/feed_format=/, 'feed_format=json_');
1187 loadExternalJs(req_url
+'&cb=mv_jsdata_cb&cb_inx='+(global_req_cb
.length
-1));
1191 function mv_jsdata_cb(response
){
1192 js_log('f:mv_jsdata_cb:'+ response
['cb_inx']);
1193 //run the callback from the global req cb object:
1194 if( !global_req_cb
[response
['cb_inx']] ){
1195 js_log('missing req cb index');
1198 if( !response
['pay_load'] ){
1199 js_log("missing pay load");
1202 //switch on content type:
1203 switch(response
['content-type']){
1207 if(typeof response
['pay_load'] == 'string'){
1208 //js_log('load string:'+"\n"+ response['pay_load']);
1210 //attempt to parse as xml for IE
1211 if( $j
.browser
.msie
){
1212 var xmldata
=new ActiveXObject("Microsoft.XMLDOM");
1213 xmldata
.async
="false";
1214 xmldata
.loadXML(response
['pay_load']);
1215 }else{ //for others (firefox, safari etc)
1217 var xmldata
= (new DOMParser()).parseFromString(response
['pay_load'], "text/xml");
1219 js_log('XML parse ERROR: ' + e
.message
);
1222 //@@todo hanndle xml parser errors
1223 if(xmldata
)response
['pay_load']=xmldata
;
1227 js_log('bad response type' + response
['content-type']);
1231 global_req_cb
[response
['cb_inx']]( response
['pay_load'] );
1233 //load external js via dom injection
1234 function loadExternalJs( url
){
1235 js_log('load js: '+ url
);
1236 //if(window['$j']) //use jquery call:
1244 var e
= document
.createElement("script");
1245 e
.setAttribute('src', url
);
1246 e
.setAttribute('type',"text/javascript");
1247 //e.setAttribute('defer', true);
1248 document
.getElementsByTagName("head")[0].appendChild(e
);
1252 function styleSheetPresent(url
){
1253 style_elements
= document
.getElementsByTagName('link');
1254 if( style_elements
.length
> 0) {
1255 for(i
= 0; i
< style_elements
.length
; i
++) {
1256 if(style_elements
[i
].href
== url
)
1262 function loadExternalCss(url
){
1263 //if could have script loader group thes css request
1264 //but debatable it may hurt more than it helps with caching and all
1265 if(typeof url
=='object'){
1267 loadExternalCss ( url
[i
] );
1272 if( url
.indexOf('?') == -1 ){
1273 url
+='?'+getMvUniqueReqId();
1275 if(!styleSheetPresent(url
) ){
1276 js_log('load css: ' + url
);
1277 var e
= document
.createElement("link");
1279 e
.type
= "text/css";
1280 e
.rel
= 'stylesheet';
1281 document
.getElementsByTagName("head")[0].appendChild(e
);
1284 function getMvEmbedURL(){
1285 if( _global
['mv_embed_url'] )
1286 return _global
['mv_embed_url'];
1287 var js_elements
= document
.getElementsByTagName("script");
1288 for(var i
=0; i
< js_elements
.length
; i
++){
1289 //check for normal mv_embed.js and or script loader
1290 var src
= js_elements
[i
].getAttribute("src");
1292 if( src
.indexOf('mv_embed.js') !=-1 || (
1293 ( src
.indexOf('mwScriptLoader.php') != -1 || src
.indexOf('jsScriptLoader.php') != -1 )
1294 && src
.indexOf('mv_embed') != -1) ){ //(check for class=mv_embed script_loader call)
1295 _global
['mv_embed_url'] = src
;
1300 js_error('Error: getMvEmbedURL failed to get Embed Path');
1303 //gets a unique request id to ensure fresh javascript
1304 function getMvUniqueReqId(){
1305 if( _global
['urid'] )
1306 return _global
['urid'];
1307 var mv_embed_url
= getMvEmbedURL();
1308 //if we have a uri retun that:
1309 var urid
= parseUri( mv_embed_url
).queryKey
['urid']
1311 _global
['urid'] = urid
;
1314 //if in debug mode get a fresh unique request key:
1315 if( parseUri( mv_embed_url
).queryKey
['debug'] == 'true'){
1317 var urid
= d
.getTime();
1318 _global
['urid'] = urid
;
1321 //else just return the mv_embed version;
1322 return MV_EMBED_VERSION
;
1325 * sets the global mv_embed path based on the scripts location
1327 function getMvEmbedPath(){
1328 if( _global
['mv_embed_path'])
1329 return _global
['mv_embed_path'];
1330 var mv_embed_url
= getMvEmbedURL();
1331 if( mv_embed_url
.indexOf('mv_embed.js') !== -1 ){
1332 mv_embed_path
= mv_embed_url
.substr(0, mv_embed_url
.indexOf('mv_embed.js'));
1333 }else if(mv_embed_url
.indexOf('mwScriptLoader.php')!==-1){
1334 //script load is in the root of mediaWiki so include the default mv_embed extention path (if using the script loader)
1335 mv_embed_path
= mv_embed_url
.substr(0, mv_embed_url
.indexOf('mwScriptLoader.php')) + mediaWiki_mvEmbed_path
;
1337 mv_embed_path
= mv_embed_url
.substr(0, mv_embed_url
.indexOf('jsScriptLoader.php'));
1339 //absolute the url (if relative) (if we don't have mv_embed path)
1340 if( mv_embed_path
.indexOf('://') == -1){
1341 var pURL
= parseUri( document
.URL
);
1342 if(mv_embed_path
.charAt(0)=='/'){
1343 mv_embed_path
= pURL
.protocol
+ '://' + pURL
.authority
+ mv_embed_path
;
1346 if(mv_embed_path
==''){
1347 mv_embed_path
= pURL
.protocol
+ '://' + pURL
.authority
+ pURL
.directory
+ mv_embed_path
;
1351 _global
['mv_embed_path'] = mv_embed_path
;
1352 return mv_embed_path
;
1355 if (typeof DOMParser
== "undefined") {
1356 DOMParser = function () {}
1357 DOMParser
.prototype.parseFromString = function (str
, contentType
) {
1358 if (typeof ActiveXObject
!= "undefined") {
1359 var d
= new ActiveXObject("MSXML.DomDocument");
1362 } else if (typeof XMLHttpRequest
!= "undefined") {
1363 var req
= new XMLHttpRequest
;
1364 req
.open("GET", "data:" + (contentType
|| "application/xml") +
1365 ";charset=utf-8," + encodeURIComponent(str
), false);
1366 if (req
.overrideMimeType
) {
1367 req
.overrideMimeType(contentType
);
1370 return req
.responseXML
;
1375 * utility functions:
1377 function js_log(string
){
1378 if( window
.console
){
1379 window
.console
.log(string
);
1382 * IE and non-firebug debug:
1384 /*var log_elm = document.getElementById('mv_js_log');
1386 document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML +
1387 '<div style="position:absolute;z-index:500;top:0px;left:0px;right:0px;height:10px;">'+
1388 '<textarea id="mv_js_log" cols="120" rows="5"></textarea>'+
1391 var log_elm = document.getElementById('mv_js_log');
1394 log_elm.value+=string+"\n";
1400 function js_error(string
){