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 information 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 (i.e. include twice from two different servers)
19 if( MV_EMBED_VERSION
){
22 // Used to grab fresh copies of scripts.
23 var MV_EMBED_VERSION
= '1.0r20';
26 * Configuration variables should be set by extending mwConfigOptions
27 * here is the default config:
29 var mwDefaultConfig
= {
31 'jui_skin': 'redmond',
32 'video_size':'400x300'
35 // (We install the default config values for anything not set in mwConfig once we know we have jquery)
40 // (c) Steven Levithan <stevenlevithan.com>
42 function parseUri (str
) {
43 var o
= parseUri
.options
,
44 m
= o
.parser
[o
.strictMode
? "strict" : "loose"].exec(str
),
48 while (i
--) uri
[o
.key
[i
]] = m
[i
] || "";
51 uri
[o
.key
[12]].replace(o
.q
.parser
, function ($0, $1, $2) {
52 if ($1) uri
[o
.q
.name
][$1] = $2;
59 key
: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
62 parser
: /(?:^|&)([^&=]*)=?([^&]*)/g
65 strict
: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
66 loose
: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
70 // For use when mv_embed with script-loader is in the root MediaWiki path
71 var mediaWiki_mvEmbed_path
= 'js2/mwEmbed/';
73 var _global
= this; // Global obj (depreciate use window)
76 * setup the empty global $mw object
77 * will ensure all our functions are properly namespaced
83 //@@todo move these into $mw
84 var mv_init_done
= false;
85 var global_cb_count
= 0;
86 var global_player_list
= new Array(); // The global player list per page
87 var global_req_cb
= new Array(); // The global request callback array
89 // Get the mv_embed location if it has not been set
90 if( !mv_embed_path
) {
91 var mv_embed_path
= getMvEmbedPath();
94 * The global $mw object:
96 * Any global functions/classes that are not jQuery plugins should make
97 * there way into the $mw namespace
101 * Language classes $mw.lang
103 * Localized Language support attempts to mirror the functionality of Language.php in MediaWiki
104 * It contains methods for loading and transforming msg text
109 * Setup the lang object
116 * Loads a set of json messages into the lng object.
118 * @param json msgSet The set of msgs to be loaded
120 $.lang
.loadGM = function( msgSet
){
121 for( var i
in msgSet
) {
122 gMsg
[ i
] = msgSet
[i
];
128 * Loads a ruleset by given template key ie PLURAL : { //ruleSetObj }
130 * @param json ruleSet The ruleset object ( extends gRuleSet )
132 $.lang
.loadRS = function( ruleSet
){
133 for( var i
in ruleSet
){
134 gRuleSet
[ i
] = ruleSet
[ i
];
139 * Returns a transformed msg string
141 * it take a msg key and array of replacement values of form
142 * $1, $2 and does relevant msgkey transformation returning
145 * @param string key The msg key as set by loadGm
146 * @param [mixed] args An array of replacement strings
149 $.lang
.gM = function( key
, args
) {
151 return '<' + key
+ '>';// Missing key placeholder
153 //swap in the arg values
154 var ms
= $.lang
.gMsgSwap( key
, args
) ;
156 //a quick check to see if we need to send the msg via the 'parser'
157 //(we can add more detailed check once we support more wiki syntax)
158 if(ms
.indexOf('{{')==-1){
163 //make sure we have the lagMagic setup:
165 //send the msg key through the parser
166 pObj
= $.parser
.pNew( ms
);
167 //return the transformed msg
168 return pObj
.getHTML();
173 * @param string key The msg key as set by loadGm
174 * @param [mixed] args An array or string to be replaced
177 $.lang
.gMsgSwap = function( key
, args
){
179 return '<' + key
+ '>';// Missing key placeholder
180 //get the messege string:
181 var ms
= gMsg
[ key
];
184 if( typeof args
== 'object' || typeof args
== 'array' ) {
185 for( var v
in args
) {
186 // Message test replace arguments start at 1 instead of zero:
187 var rep
= new RegExp('\\$'+ ( parseInt(v
) + 1 ), 'g');
188 ms
= ms
.replace( rep
, args
[v
] );
190 } else if( typeof args
=='string' || typeof args
=='number' ) {
191 ms
= ms
.replace(/\$1/g, args
);
199 * @returns string The msg key without transforming it
201 $.lang
.gMsgNoTrans = function( key
){
205 // Missing key placeholder
206 return '<' + key
+ '>';
209 * Add Supported Magic Words to parser
211 //set the setupflag to false:
212 $.lang
.doneSetup
=false;
213 $.lang
.magicSetup = function(){
214 if(!$.lang
.doneSetup
){
215 $.parser
.addMagic ( {
216 'PLURAL' : $.lang
.procPLURAL
219 $.lang
.doneSetup
= true;
224 * Process the PLURAL special language template key:
226 $.lang
.procPLURAL = function( tObj
){
228 // (gRuleSet is loaded from script-loader to contains local ruleset)
229 var rs
= gRuleSet
['PLURAL'];
232 * Plural matchRuleTest
234 function matchRuleTest(cRule
, val
){
235 js_log("matchRuleTest:: " + typeof cRule
+ ' ' + cRule
+ ' == ' + val
);
237 function checkValue(compare
, val
){
238 if(typeof compare
== 'string'){
239 range
= compare
.split('-');
240 if( range
.length
>= 1 ){
241 if( val
>= range
[0] && val
<= range
[1] )
245 //else do a direct compare
251 //check for simple cRule type:
252 if( typeof cRule
== 'number'){
253 return ( parseInt( val
) == parseInt( cRule
) );
254 }else if( typeof cRule
== 'object' ){
256 //if a list we need to match all for rule match
268 if( checkValue( val
% cr
['mod'], cr
['is'] ) )
270 }else if( cr
['not']){
271 if( ! checkValue( val
% cr
['mod'], cr
['not'] ) )
277 //check all the matches (taking into consideration "or" order)
287 * Maps a given rule Index to template params:
289 * if index is out of range return last param
292 function getTempParamFromRuleInx(tObj
, ruleInx
){
293 //js_log('getTempParamFromRuleInx: ruleInx: ' + ruleInx + ' tempParamLength ' + tObj.param.length );
294 if( ruleInx
>= tObj
.param
.length
)
295 return tObj
.param
[ tObj
.param
.length
-1 ];
296 //else return the requested index:
297 return tObj
.param
[ ruleInx
];
300 //run the actual rule lookup:
301 for(var ruleInx
in rs
){
303 if( matchRuleTest( cRule
, tObj
.arg
) ){
304 js_log("matched rule: " + ruleInx
);
305 return getTempParamFromRuleInx(tObj
, rCount
);
309 js_log('no match found for: ' + tObj
.arg
+ ' using last/other : ' + tObj
.param
[ tObj
.param
.length
-1 ] );
310 //return the last /"other" template param
311 return tObj
.param
[ tObj
.param
.length
-1 ];
315 * gMsgLoadRemote loads remote msg strings
317 * @param mixed msgSet the set of msg to load remotely
318 * @param function callback the callback to issue once string is ready
320 $.lang
.gMsgLoadRemote = function( msgSet
, callback
) {
322 if( typeof msgSet
== 'object' ) {
323 for( var i
in msgSet
) {
324 ammessages
+= msgSet
[i
] + '|';
326 } else if( typeof msgSet
== 'string' ) {
327 ammessages
+= msgSet
;
329 if( ammessages
== '' ) {
330 js_log( 'gMsgLoadRemote: no message set requested' );
335 'meta': 'allmessages',
336 'ammessages': ammessages
338 }, function( data
) {
339 if( data
.query
.allmessages
) {
340 var msgs
= data
.query
.allmessages
;
341 for( var i
in msgs
) {
343 ld
[ msgs
[i
]['name'] ] = msgs
[i
]['*'];
351 * Format a size in bytes for output, using an appropriate
352 * unit (B, KB, MB or GB) according to the magnitude in question
354 * @param size Size to format
355 * @return string Plain text (not HTML)
357 $.lang
.formatSize = function ( size
) {
358 // For small sizes no decimal places are necessary
365 // For MB and bigger two decimal places are smarter
369 msg
= 'mwe-size-gigabytes';
371 msg
= 'mwe-size-megabytes';
374 msg
= 'mwe-size-kilobytes';
377 msg
= 'mwe-size-bytes';
379 // JavaScript does not let you choose the precision when rounding
380 var p
= Math
.pow(10,round
);
381 var size
= Math
.round( size
* p
) / p
;
382 //@@todo we need a formatNum and we need to request some special packaged info to deal with that case.
383 return gM( msg
, size
);
386 $.lang
.formatNumber = function( num
){
389 Str: The number to be formatted, as a string or number.
390 outD: The decimal character for the output, such as ',' for the number 100,2
391 sep: The separator character for the output, such as ',' for the number 1,000.2
393 function addSeparatorsNF(nStr
, outD
, sep
){
395 var dpos
= nStr
.indexOf( '.' );
398 nStrEnd
= outD
+ nStr
.substring(dpos
+ 1, nStr
.length
);
399 nStr
= nStr
.substring(0, dpos
);
401 var rgx
= /(\d+)(\d{3})/;
402 while (rgx
.test(nStr
)) {
403 nStr
= nStr
.replace(rgx
, '$1' + sep
+ '$2');
405 return nStr
+ nStrEnd
;
407 //@@todo read language code and give periods or comas:
408 return addSeparatorsNF( num
, '.', ',');
414 * MediaWiki wikitext "Parser"
416 * This is not feature complete but we need a way to get at template properties
419 * @param wikiText the wikitext to be parsed
420 * @return parserObj returns a parser object that has methods for getting at
421 * things you would want
428 * lets you add a set of magic keys and associated callback funcions
429 * callback: @param ( Object Template )
430 * callback: @return the transformed template output
432 * @param object magicSet key:callback
434 $.parser
.addMagic = function( magicSet
){
435 for(var i
in magicSet
)
436 pMagicSet
[ i
] = magicSet
[i
];
439 //actual parse call (returns parser object)
440 $.parser
.pNew = function( wikiText
, opt
){
441 var parseObj = function( wikiText
, opt
){
442 return this.init( wikiText
, opt
)
444 parseObj
.prototype = {
445 //the wikiText "DOM"... stores the parsed wikiText structure
446 //wtDOM : {}, (not yet supported )
448 pOut
: '', //the parser output string container
449 init :function( wikiText
){
450 this.wikiText
= wikiText
;
452 updateText : function( wikiText
){
453 this.wikiText
= wikiText
;
454 //invalidate the output (will force a re-parse )
459 * quickly recursive / parse out templates:
462 // ~ probably a better algorithm out there / should mirror php parser flow ~
463 // ... but I am having fun with recursion so here it is...
464 // or at least mirror: http://www.mediawiki.org/wiki/Extension:Page_Object_Model
465 function rdpp ( txt
, cn
){
468 for(var a
=0; a
< txt
.length
; a
++){
469 if( txt
[a
] == '{' && txt
[a
+1] == '{' ){
473 node
['c'] = new Array();
475 node
['c'].push( rdpp( txt
.substr( a
), true ) );
476 }else if( txt
[a
] == '}' && txt
[a
+1] == '}'){
493 * parse template text as template name and named params
495 function parseTmplTxt( ts
){
498 tname
= ts
.split('\|').shift() ;
499 tname
= tname
.split('\{').shift() ;
500 tname
= tname
.replace( /^\s+|\s+$/g, "" ); //trim
502 //check for arguments:
503 if( tname
.split(':').length
== 1 ){
504 tObj
["name"] = tname
;
506 tObj
["name"] = tname
.split(':').shift();
507 tObj
["arg"] = tname
.split(':').pop();
510 js_log("TNAME::" + tObj
["name"] + ' from:: ' + ts
);
512 var pSet
= ts
.split('\|');
515 tObj
.param
= new Array();
516 for(var pInx
in pSet
){
517 var tStr
= pSet
[ pInx
];
518 for(var b
=0 ; b
< tStr
.length
; b
++){
519 if(tStr
[b
] == '=' && b
>0 && b
<tStr
.length
&& tStr
[b
-1]!='\\'){
521 tObj
.param
[ tStr
.split('=').shift() ] = tStr
.split('=').pop();
524 tObj
.param
[ pInx
] = tStr
;
531 function getMagicTxtFromTempNode( node
){
532 node
.tObj
= parseTmplTxt ( node
.t
);
533 //do magic swap if template key found in pMagicSet
534 if( node
.tObj
.name
in pMagicSet
){
535 var nt
= pMagicSet
[ node
.tObj
.name
]( node
.tObj
);
538 //don't swap just return text
545 * go last child first swap upward: (could probably be integrated above somehow)
548 function recurse_magic_swap( node
){
554 for(var i
in node
['c']){
555 var nt
= recurse_magic_swap( node
['c'][i
] );
556 //swap it into current
558 node
.t
= node
.t
.replace( node
['c'][i
].t
, nt
);
561 pNode
.t
= pNode
.t
.replace( node
['c'][i
].t
, nt
);
563 //do the current node:
564 var nt
= getMagicTxtFromTempNode( node
);
565 pNode
.t
= pNode
.t
.replace(node
.t
, nt
);
566 //run the swap for the outer most node
569 //node.t = getMagicFromTempObj( node.t )
570 return getMagicTxtFromTempNode( node
);
573 //parse out the template node structure:
574 this.pNode
= rdpp ( this.wikiText
);
575 //strip out the parent from the root
576 this.pNode
['p'] = null;
578 //do the recursive magic swap text:
579 this.pOut
= recurse_magic_swap( this.pNode
);
584 * parsed template api ~losely based off of ~POM~
585 * http://www.mediawiki.org/wiki/Extension:Page_Object_Model
591 * gets a requested template from the wikitext (if available)
594 templates: function( tname
){
596 var tmplSet
= new Array();
597 function getMatchingTmpl( node
){
599 for(var i
in node
['c']){
600 getMatchingTmpl( node
['c'] );
603 if( tname
&& node
.tObj
){
604 if( node
.tObj
['name'] == tname
)
605 tmplSet
.push( node
.tObj
);
606 }else if( node
.tObj
){
607 tmplSet
.push( node
.tObj
);
610 getMatchingTmpl( this.pNode
);
614 * Returns the transformed wikitext
616 * Build output from swappable index
617 * (all transforms must be expanded in parse stage and linearly rebuilt)
618 * Alternatively we could build output using a place-holder & replace system
619 * (this lets us be slightly more slopy with ordering and indexes, but probably slower)
621 * Ideal: we build a 'wiki DOM'
622 * When editing you update the data structure directly
623 * Then in output time you just go DOM->html-ish output without re-parsing anything
625 getHTML : function(){
626 //wikiText updates should invalidate pOut
627 if( this.pOut
== ''){
633 //return the parserObj
634 return new parseObj( wikiText
, opt
) ;
639 //setup legacy global shortcuts:
640 var loadGM
= $mw
.lang
.loadGM
;
641 var loadRS
= $mw
.lang
.loadRS
;
642 var gM
= $mw
.lang
.gM
;
644 // All default messages in [English] should be overwritten by the CMS language message system.
646 "mwe-loading_txt" : "loading ...",
647 "mwe-loading_title" : "Loading...",
648 "mwe-size-gigabytes" : "$1 GB",
649 "mwe-size-megabytes" : "$1 MB",
650 "mwe-size-kilobytes" : "$1 K",
651 "mwe-size-bytes" : "$1 B",
652 "mwe-error_load_lib" : "Error: JavaScript $1 was not retrievable or does not define $2",
653 "mwe-loading-add-media-wiz": "Loading add media wizard",
654 "mwe-apiproxy-setup" : "Setting up API proxy",
655 "mwe-load-drag-item" : "Loading draged item",
660 * AutoLoader paths (this should mirror the file: jsAutoloadLocalClasses.php )
661 * Any file _not_ listed here won't be auto-loadable
662 * @path The path to the file (or set of files) with ending slash
663 * @gClasses The set of classes
664 * if it's an array, $j.className becomes jquery.className.js
665 * if it's an associative object then key => value pairs are used
667 if( typeof mvAutoLoadClasses
== 'undefined' )
668 mvAutoLoadClasses
= {};
670 // The script that loads the class set
671 function lcPaths( classSet
){
672 for( var i
in classSet
) {
673 mvAutoLoadClasses
[i
] = classSet
[i
];
677 function mvGetClassPath(k
){
678 if( mvAutoLoadClasses
[k
] ) {
679 //js_log('got class path:' + k + ' : '+ mvClassPaths[k]);
680 return mvAutoLoadClasses
[k
];
682 js_log('Error:: Could not find path for requested class ' + k
);
686 if( typeof mvCssPaths
== 'undefined' )
689 function lcCssPath( cssSet
) {
690 for( var i
in cssSet
) {
691 mvCssPaths
[i
] = mv_embed_path
+ cssSet
[i
];
696 * -- Load Class Paths --
698 * MUST BE VALID JSON (NOT JS)
699 * This is used by the script loader to auto-load classes (so we only define
700 * this once for PHP & JavaScript)
702 * Right now the PHP AutoLoader only reads this mv_embed.js file.
703 * In the future we could have multiple lcPath calls that PHP reads
704 * (if our autoloading class list becomes too long) just have to add those
705 * files to the jsAutoLoader file list.
708 "mv_embed" : "mv_embed.js",
709 "window.jQuery" : "jquery/jquery-1.3.2.js",
710 "$j.fn.pngFix" : "jquery/plugins/jquery.pngFix.js",
711 "$j.fn.autocomplete": "jquery/plugins/jquery.autocomplete.js",
712 "$j.fn.hoverIntent" : "jquery/plugins/jquery.hoverIntent.js",
713 "$j.fn.datePicker" : "jquery/plugins/jquery.datePicker.js",
714 "$j.ui" : "jquery/jquery.ui/ui/ui.core.js",
715 "$j.fn.ColorPicker" : "libClipEdit/colorpicker/js/colorpicker.js",
716 "$j.Jcrop" : "libClipEdit/Jcrop/js/jquery.Jcrop.js",
717 "$j.fn.simpleUploadForm" : "libAddMedia/simpleUploadForm.js",
719 "$mw.proxy" : "libMwApi/mw.proxy.js",
721 "ctrlBuilder" : "skins/ctrlBuilder.js",
722 "kskinConfig" : "skins/kskin/kskin.js",
723 "mvpcfConfig" : "skins/mvpcf/mvpcf.js",
725 "JSON" : "libMwApi/json2.js",
726 "$j.cookie" : "jquery/plugins/jquery.cookie.js",
727 "$j.contextMenu" : "jquery/plugins/jquery.contextMenu.js",
728 "$j.fn.suggestions" : "jquery/plugins/jquery.suggestions.js",
730 "$j.effects.blind" : "jquery/jquery.ui/ui/effects.blind.js",
731 "$j.effects.drop" : "jquery/jquery.ui/ui/effects.drop.js",
732 "$j.effects.pulsate" : "jquery/jquery.ui/ui/effects.pulsate.js",
733 "$j.effects.transfer" : "jquery/jquery.ui/ui/effects.transfer.js",
734 "$j.ui.droppable" : "jquery/jquery.ui/ui/ui.droppable.js",
735 "$j.ui.slider" : "jquery/jquery.ui/ui/ui.slider.js",
736 "$j.effects.bounce" : "jquery/jquery.ui/ui/effects.bounce.js",
737 "$j.effects.explode" : "jquery/jquery.ui/ui/effects.explode.js",
738 "$j.effects.scale" : "jquery/jquery.ui/ui/effects.scale.js",
739 "$j.ui.datepicker" : "jquery/jquery.ui/ui/ui.datepicker.js",
740 "$j.ui.progressbar" : "jquery/jquery.ui/ui/ui.progressbar.js",
741 "$j.ui.sortable" : "jquery/jquery.ui/ui/ui.sortable.js",
742 "$j.effects.clip" : "jquery/jquery.ui/ui/effects.clip.js",
743 "$j.effects.fold" : "jquery/jquery.ui/ui/effects.fold.js",
744 "$j.effects.shake" : "jquery/jquery.ui/ui/effects.shake.js",
745 "$j.ui.dialog" : "jquery/jquery.ui/ui/ui.dialog.js",
746 "$j.ui.resizable" : "jquery/jquery.ui/ui/ui.resizable.js",
747 "$j.ui.tabs" : "jquery/jquery.ui/ui/ui.tabs.js",
748 "$j.effects.core" : "jquery/jquery.ui/ui/effects.core.js",
749 "$j.effects.highlight" : "jquery/jquery.ui/ui/effects.highlight.js",
750 "$j.effects.slide" : "jquery/jquery.ui/ui/effects.slide.js",
751 "$j.ui.accordion" : "jquery/jquery.ui/ui/ui.accordion.js",
752 "$j.ui.draggable" : "jquery/jquery.ui/ui/ui.draggable.js",
753 "$j.ui.selectable" : "jquery/jquery.ui/ui/ui.selectable.js",
755 "$mw.dragDropFile" : "libAddMedia/dragDropFile.js",
756 "mvFirefogg" : "libAddMedia/mvFirefogg.js",
757 "mvAdvFirefogg" : "libAddMedia/mvAdvFirefogg.js",
758 "mvBaseUploadInterface" : "libAddMedia/mvBaseUploadInterface.js",
759 "remoteSearchDriver" : "libAddMedia/remoteSearchDriver.js",
760 "seqRemoteSearchDriver" : "libSequencer/seqRemoteSearchDriver.js",
762 "baseRemoteSearch" : "libAddMedia/searchLibs/baseRemoteSearch.js",
763 "mediaWikiSearch" : "libAddMedia/searchLibs/mediaWikiSearch.js",
764 "metavidSearch" : "libAddMedia/searchLibs/metavidSearch.js",
765 "archiveOrgSearch" : "libAddMedia/searchLibs/archiveOrgSearch.js",
766 "flickrSearch" : "libAddMedia/searchLibs/flickrSearch.js",
767 "baseRemoteSearch" : "libAddMedia/searchLibs/baseRemoteSearch.js",
769 "mvClipEdit" : "libClipEdit/mvClipEdit.js",
771 "embedVideo" : "libEmbedVideo/embedVideo.js",
772 "flashEmbed" : "libEmbedVideo/flashEmbed.js",
773 "genericEmbed" : "libEmbedVideo/genericEmbed.js",
774 "htmlEmbed" : "libEmbedVideo/htmlEmbed.js",
775 "javaEmbed" : "libEmbedVideo/javaEmbed.js",
776 "nativeEmbed" : "libEmbedVideo/nativeEmbed.js",
777 "quicktimeEmbed" : "libEmbedVideo/quicktimeEmbed.js",
778 "vlcEmbed" : "libEmbedVideo/vlcEmbed.js",
780 "mvPlayList" : "libSequencer/mvPlayList.js",
781 "mvSequencer" : "libSequencer/mvSequencer.js",
782 "mvFirefoggRender" : "libSequencer/mvFirefoggRender.js",
783 "mvTimedEffectsEdit": "libSequencer/mvTimedEffectsEdit.js",
785 "mvTextInterface" : "libTimedText/mvTextInterface.js"
788 // Dependency mapping for CSS files for self-contained included plugins:
790 '$j.Jcrop' : 'libClipEdit/Jcrop/css/jquery.Jcrop.css',
791 '$j.fn.ColorPicker' : 'libClipEdit/colorpicker/css/colorpicker.css'
795 // Get the loading image
796 function mv_get_loading_img( style
, class_attr
){
797 var style_txt
= (style
)?style
:'';
798 var class_attr
= (class_attr
)?'class="'+class_attr
+'"':'class="mv_loading_img"';
799 return '<div '+class_attr
+' style="' + style
+'"></div>';
802 function mv_set_loading(target
, load_id
){
803 var id_attr
= ( load_id
)?' id="' + load_id
+ '" ':'';
804 $j(target
).append('<div '+id_attr
+' style="position:absolute;top:0px;left:0px;height:100%;width:100%;'+
805 'background-color:#FFF;">' +
806 mv_get_loading_img('top:30px;left:30px') +
811 * mvJsLoader class handles initialization and js file loads
819 onReadyEvents
: new Array(),
820 doneReadyEvents
: false,
821 jQuerySetupFlag
: false,
823 // To keep consistency across threads
827 load_error
: false, // Load error flag (false by default)
829 callbacks
: new Array(),
832 doLoad: function( loadLibs
, callback
) {
835 if( loadLibs
&& loadLibs
.length
!= 0 ) {
837 // First check if we already have this library loaded
838 var all_libs_loaded
= true;
839 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
840 // Check if the library is already loaded
841 if( ! this.checkObjPath( loadLibs
[i
] ) ) {
842 all_libs_loaded
= false;
845 if( all_libs_loaded
) {
846 //js_log( 'Libraries ( ' + loadLibs + ') already loaded... skipping load request' );
850 // Do a check for any CSS we may need and get it
851 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
852 if( typeof mvCssPaths
[ loadLibs
[i
] ] != 'undefined' ) {
853 loadExternalCss( mvCssPaths
[ loadLibs
[i
] ] );
857 // Check if we should use the script loader to combine all the requests into one
858 if( typeof mwSlScript
!= 'undefined' ) {
862 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
863 var curLib
= loadLibs
[i
];
864 // Only add if not included yet:
865 if( ! this.checkObjPath( curLib
) ) {
866 class_set
+= coma
+ curLib
;
871 //Build the url to the scriptServer striping its request paramaters:
872 var puri
= parseUri( getMvEmbedURL() );
873 if( ( getMvEmbedURL().indexOf('://') != -1 )
874 && puri
.host
!= parseUri( document
.URL
).host
)
876 var scriptPath
= puri
.protocol
+ '://' + puri
.authority
+ puri
.path
;
878 var scriptPath
= puri
.path
;
880 //js_log('scriptServer Path is: ' + scriptPath + "\n host script path:" + getMvEmbedURL() );
881 var dbug_attr
= ( puri
.queryKey
['debug'] ) ? '&debug=true' : '';
882 this.libs
[ last_class
] = scriptPath
+ '?class=' + class_set
+
883 '&urid=' + getMvUniqueReqId() + dbug_attr
;
887 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
888 var curLib
= loadLibs
[i
];
890 var libLoc
= mvGetClassPath( curLib
);
891 // Do a direct load of the file (pass along unique request id from
892 // request or mv_embed Version )
893 var qmark
= (libLoc
.indexOf( '?' ) !== true) ? '?' : '&';
894 this.libs
[curLib
] = mv_embed_path
+ libLoc
+ qmark
+ 'urid=' + getMvUniqueReqId();
900 this.callbacks
.push( callback
);
902 if( this.checkLoading() ) {
903 //@@todo we should check the <script> Element .onLoad property to
904 //make sure its just not a very slow connection or we can run the callback
905 //(even though the class is not loaded)
907 if( this.load_time
++ > 4000 ){ // Time out after ~80 seconds
908 js_log( gM('mwe-error_load_lib', [mvGetClassPath(this.missing_path
), this.missing_path
]) );
909 this.load_error
= true;
911 setTimeout( 'mvJsLoader.doLoad()', 20 );
914 //js_log('checkLoading passed. Running callbacks...');
915 // Only do callbacks if we are in the same instance (weird concurrency issue)
917 for( var i
= 0; i
< this.callbacks
.length
; i
++ )
919 //js_log('RESET LIBS: loading is: '+ loading + ' callback count: '+cb_count +
920 // ' p:'+ this.ptime +' c:'+ this.ctime);
924 //js_log('done loading, do call: ' + this.callbacks[0] );
925 while( this.callbacks
.length
!= 0 ) {
926 if( this.ptime
== this.ctime
- 1 ) { // Enforce thread consistency
927 this.callbacks
.pop()();
928 //func = this.callbacks.pop();
929 //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func);
932 // Re-issue doLoad ( ptime will be set to ctime so we should catch up)
933 setTimeout( 'mvJsLoader.doLoad()', 25 );
938 this.ptime
= this.ctime
;
940 doLoadDepMode: function( loadChain
, callback
) {
941 // Firefox executes JS in the order in which it is included, so just directly issue the request
942 if( $j
.browser
.firefox
) {
944 for( var i
= 0; i
< loadChain
.length
; i
++ ) {
945 for( var j
= 0; j
< loadChain
[i
].length
; j
++ ) {
946 loadSet
.push( loadChain
[i
][j
] );
949 mvJsLoader
.doLoad( loadSet
, callback
);
951 // Safari and IE tend to execute out of order so load with dependency checks
952 mvJsLoader
.doLoad( loadChain
.shift(), function() {
953 if( loadChain
.length
!= 0 ) {
954 mvJsLoader
.doLoadDepMode( loadChain
, callback
);
961 checkLoading: function() {
964 for( var i
in this.libs
) { // for/in loop is OK on an object
965 if( !this.checkObjPath( i
) ) {
966 if( !this.libreq
[i
] ) {
967 loadExternalJs( this.libs
[i
] );
970 //js_log("has not yet loaded: " + i);
976 checkObjPath: function( libVar
) {
979 var objPath
= libVar
.split( '.' )
981 for( var p
= 0; p
< objPath
.length
; p
++ ) {
982 cur_path
= (cur_path
== '') ? cur_path
+ objPath
[p
] : cur_path
+ '.' + objPath
[p
];
983 eval( 'var ptest = typeof ( '+ cur_path
+ ' ); ');
984 if( ptest
== 'undefined' ) {
985 this.missing_path
= cur_path
;
989 this.cur_path
= cur_path
;
993 * checks for jQuery and adds the $j noConflict var
995 jQueryCheck: function( callback
) {
996 js_log( 'jQueryCheck::' );
997 // Skip stuff if $j is already loaded:
998 if( _global
['$j'] && callback
)
1005 //only do the $j setup once:
1007 _global
['$j'] = jQuery
.noConflict();
1009 if( _this
.jQuerySetupFlag
== false){
1010 js_log('setup mv_embed jQuery bindings');
1011 //setup our global settings using the (jQuery helper)
1012 mwConfig
= $j
.extend( mwDefaultConfig
, mwConfig
);
1014 // Set up the skin path
1015 _global
['mv_jquery_skin_path'] = mv_embed_path
+ 'jquery/jquery.ui/themes/' +mwConfig
['jui_skin'] + '/';
1016 _global
['mv_skin_img_path'] = mv_embed_path
+ 'skins/' + mwConfig
['skin_name'] + '/images/';
1017 _global
['mv_default_thumb_url'] = mv_skin_img_path
+ 'vid_default_thumb.jpg';
1019 //setup skin dependent dependencies
1020 lcCssPath({'embedVideo' : 'skins/' + mwConfig
['skin_name'] + '/playerSkin.css'});
1022 // Make sure the skin/style sheets are always available:
1023 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1024 loadExternalCss( mv_embed_path
+ 'skins/' + mwConfig
['skin_name'] + '/styles.css' );
1026 // Set up AJAX to not send dynamic URLs for loading scripts (we control that with
1027 // the scriptLoader)
1032 js_log( 'jQuery loaded into $j' );
1033 // Set up mvEmbed jQuery bindings and config based dependencies
1034 mv_jqueryBindings();
1035 _this
.jQuerySetupFlag
= true;
1043 embedVideoCheck:function( callback
) {
1045 js_log( 'embedVideoCheck:' );
1046 // Make sure we have jQuery
1047 _this
.jQueryCheck( function() {
1048 //set class videonojs to loading
1049 $j('.videonojs').html( gM('mwe-loading_txt') );
1050 //Set up the embed video player class request: (include the skin js as well)
1063 if( mwConfig
['skin_name'] )
1064 depReq
[0].push( mwConfig
['skin_name'] + 'Config' );
1066 // Add PNG fix if needed:
1067 if( $j
.browser
.msie
|| $j
.browser
.version
< 7 )
1068 depReq
[0].push( '$j.fn.pngFix' );
1070 //load the video libs:
1071 _this
.doLoadDepMode( depReq
, function() {
1074 $j('.videonojs').remove();
1078 addLoadEvent: function( fn
) {
1079 this.onReadyEvents
.push( fn
);
1081 // Check the jQuery flag. This way, when remote embedding, we don't load jQuery
1082 // unless js2AddOnloadHook was used or there is video on the page.
1083 runQueuedFunctions: function() {
1084 js_log("runQueuedFunctions");
1086 this.jQueryCheck( function() {
1087 this.doneReadyEvents
= true;
1088 _this
.runReadyEvents();
1091 runReadyEvents: function() {
1092 js_log( "runReadyEvents" );
1093 while( this.onReadyEvents
.length
) {
1094 this.onReadyEvents
.shift()();
1099 // Shortcut ( @@todo consolidate shortcuts & re-factor mvJsLoader )
1100 function mwLoad( loadSet
, callback
) {
1101 mvJsLoader
.doLoad( loadSet
, callback
);
1106 // Load an external JS file. Similar to jquery .require plugin,
1107 // but checks for object availability rather than load state.
1109 /*********** INITIALIZATION CODE *************
1110 * This will get called when the DOM is ready
1111 *********************************************/
1112 /* jQuery .ready does not work when jQuery is loaded dynamically.
1113 * For an example of the problem see: 1.1.3 working: http://pastie.caboo.se/92588
1114 * and >= 1.1.4 not working: http://pastie.caboo.se/92595
1115 * $j(document).ready( function(){ */
1116 function mwdomReady( force
) {
1117 js_log( 'f:mwdomReady:' );
1118 if( !force
&& mv_init_done
) {
1119 js_log( "mv_init_done already done, do nothing..." );
1122 mv_init_done
= true;
1123 // Handle the execution of queued functions with jQuery "ready"
1125 // Check if this page has a video or playlist
1127 document
.getElementsByTagName( "video" ),
1128 document
.getElementsByTagName( "audio" ),
1129 document
.getElementsByTagName( "playlist" )
1131 if( e
[0].length
!= 0 || e
[1].length
!= 0 || e
[2].length
!= 0 ) {
1132 // Load libs and process them
1133 mvJsLoader
.embedVideoCheck( function() {
1134 // Run any queued global events:
1135 mv_video_embed( function() {
1136 mvJsLoader
.runQueuedFunctions();
1140 // If we already have jQuery, make sure it's loaded into its proper context $j
1141 // Run any queued global events
1142 mvJsLoader
.runQueuedFunctions();
1146 //js2AddOnloadHook: ensure jQuery and the DOM are ready
1147 function js2AddOnloadHook( func
) {
1148 // If we have already run the DOM-ready function, just run the function directly:
1149 if( mvJsLoader
.doneReadyEvents
) {
1150 // Make sure jQuery is there:
1151 mvJsLoader
.jQueryCheck( function() {
1155 mvJsLoader
.addLoadEvent( func
);
1158 // Deprecated mwAddOnloadHook in favor of js2 naming (for clear separation of js2 code from old MW code
1159 var mwAddOnloadHook
= js2AddOnloadHook
;
1161 * This function allows for targeted rewriting
1163 function rewrite_by_id( vid_id
, ready_callback
) {
1164 js_log( 'f:rewrite_by_id: ' + vid_id
);
1165 // Force a re-check of the DOM for playlist or video elements:
1166 mvJsLoader
.embedVideoCheck( function() {
1167 mv_video_embed( ready_callback
, vid_id
);
1172 /*********** INITIALIZATION CODE *************
1173 * set DOM-ready callback to init_mv_embed
1174 *********************************************/
1175 // for Mozilla / modern browsers
1176 if ( document
.addEventListener
) {
1177 document
.addEventListener( "DOMContentLoaded", mwdomReady
, false );
1180 if( window
.onload
) {
1181 temp_f
= window
.onload
;
1183 // Use the onload method as a backup (mwdomReady hanndles dobule init calls)
1184 window
.onload = function () {
1191 * Store all the mwEmbed jQuery-specific bindings
1192 * (set up after jQuery is available).
1194 * These functions are generaly are loaders that do the dynamic mapping of
1195 * dependencies for a given componet
1199 function mv_jqueryBindings() {
1200 js_log( 'mv_jqueryBindings' );
1203 * dragDrop file loader
1205 $.fn
.dragFileUpload = function ( conf
){
1206 if( this.selector
){
1208 //load the dragger and "setup"
1209 $mw
.load( ['$mw.dragDropFile'], function(){
1210 $mw
.dragDropFile( _this
.selector
);
1215 * apiProxy Loader loader:
1217 * @param mode is either 'server' or 'client'
1219 $.apiProxy = function( mode
, pConf
, callback
){
1220 js_log('do apiProxy setup');
1221 mvJsLoader
.doLoad( [
1225 //do the proxy setup or
1226 if( mode
== 'client'){
1227 //just do the setup (no callbcak for client setup)
1228 $mw
.proxy
.client( pConf
);
1231 }else if( mode
=='server' ){
1232 //do the request with the callback
1233 $mw
.proxy
.server( pConf
, callback
);
1237 //non selector based add-media-wizard direct invocation with loader
1238 $.addMediaWiz = function( iObj
, callback
){
1239 js_log(".addMediaWiz call");
1240 //check if already loaded:
1241 if( _global
['rsdMVRS'] ){
1242 _global
['rsdMVRS'].doReDisplay();
1244 callback( _global
['rsdMVRS'] );
1248 $.addLoaderDialog( gM('mwe-loading-add-media-wiz') );
1249 //load the addMedia wizard without a target:
1250 $.fn
.addMediaWiz ( iObj
, function( amwObj
){
1252 $.closeLoaderDialog();
1253 //do the add-media-wizard display
1254 amwObj
.doInitDisplay();
1255 //call the parent callback:
1257 callback( _global
['rsdMVRS'] );
1260 $.fn
.addMediaWiz = function( iObj
, callback
) {
1261 if( this.selector
){
1262 // First set the cursor for the button to "loading"
1263 $j( this.selector
).css( 'cursor', 'wait' ).attr( 'title', gM( 'mwe-loading_title' ) );
1265 iObj
['target_invocation'] = this.selector
;
1268 // Load the mv_embed_base skin:
1269 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1270 loadExternalCss( mv_embed_path
+ 'skins/' + mwConfig
['skin_name']+'/styles.css' );
1271 // Load all the required libs:
1272 mvJsLoader
.jQueryCheck( function() {
1273 // Load with staged dependencies (for IE that does not execute in order)
1274 mvJsLoader
.doLoadDepMode([
1275 [ 'remoteSearchDriver',
1286 iObj
['instance_name'] = 'rsdMVRS';
1287 _global
['rsdMVRS'] = new remoteSearchDriver( iObj
);
1289 callback( _global
['rsdMVRS'] );
1294 $.fn
.sequencer = function( iObj
, callback
) {
1296 iObj
['target_sequence_container'] = this.selector
;
1297 // Issue a request to get the CSS file (if not already included):
1298 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1299 loadExternalCss( mv_embed_path
+ 'skins/' + mwConfig
['skin_name'] + '/mv_sequence.css' );
1300 // Make sure we have the required mv_embed libs (they are not loaded when no video
1301 // element is on the page)
1302 mvJsLoader
.embedVideoCheck( function() {
1303 // Load the playlist object and then the jQuery UI stuff:
1304 mvJsLoader
.doLoadDepMode([
1317 '$j.ui.progressbar',
1324 js_log( 'calling new mvSequencer' );
1325 // Initialise the sequence object (it will take over from there)
1326 // No more than one mvSeq obj for now:
1327 if( !_global
['mvSeq'] ) {
1328 _global
['mvSeq'] = new mvSequencer( iObj
);
1330 js_log( 'mvSeq already init' );
1336 * The Firefogg jQuery function:
1337 * @@note This Firefogg invocation could be made to work more like real jQuery plugins
1339 var queuedFirefoggConf
= {};
1340 $.fn
.firefogg = function( iObj
, callback
) {
1343 // Add the base theme CSS:
1344 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1345 loadExternalCss( mv_embed_path
+ 'skins/'+mwConfig
['skin_name'] + '/styles.css' );
1347 // Check if we already have Firefogg loaded (the call just updates the element's
1349 var sElm
= $j( this.selector
).get( 0 );
1350 if( sElm
['firefogg'] ) {
1351 if( sElm
['firefogg'] == 'loading' ) {
1352 js_log( "Queued firefogg operations ( firefogg " +
1353 "not done loading ) " );
1354 $j
.extend( queuedFirefoggConf
, iObj
);
1357 // Update properties
1358 for( var i
in iObj
) {
1359 js_log( "firefogg::updated: " + i
+ ' to '+ iObj
[i
] );
1360 sElm
['firefogg'][i
] = iObj
[i
];
1362 return sElm
['firefogg'];
1365 sElm
['firefogg'] = 'loading';
1368 iObj
['selector'] = this.selector
;
1372 'mvBaseUploadInterface',
1377 '$j.ui.progressbar',
1382 if( iObj
.encoder_interface
) {
1391 // Make sure we have everything loaded that we need:
1392 mvJsLoader
.doLoadDepMode( loadSet
, function() {
1393 js_log( 'firefogg libs loaded. target select:' + iObj
.selector
);
1394 // Select interface provider based on whether we want to include the
1395 // encoder interface or not
1396 if( iObj
.encoder_interface
) {
1397 var myFogg
= new mvAdvFirefogg( iObj
);
1399 var myFogg
= new mvFirefogg( iObj
);
1402 myFogg
.doRewrite( callback
);
1403 var selectorElement
= $j( iObj
.selector
).get( 0 );
1404 selectorElement
['firefogg'] = myFogg
;
1406 js_log('pre:'+ selectorElement
['firefogg']['firefogg_form_action'])
1407 if(queuedFirefoggConf
)
1408 $j
.extend(selectorElement
['firefogg'], queuedFirefoggConf
);
1409 js_log('post:'+ selectorElement
['firefogg']['firefogg_form_action'])
1413 // Take an input player as the selector and expose basic rendering controls
1414 $.fn
.firefoggRender = function( iObj
, callback
) {
1415 // Check if we already have render loaded then just pass on updates/actions
1416 var sElm
= $j( this.selector
).get( 0 );
1417 if( sElm
['fogg_render'] ) {
1418 if( sElm
['fogg_render'] == 'loading' ) {
1419 js_log( "Error: called firefoggRender while loading" );
1422 // Call or update the property:
1424 sElm
['fogg_render'] = 'loading';
1426 iObj
['player_target'] = this.selector
;
1431 sElm
['fogg_render'] = new mvFirefoggRender( iObj
);
1432 if( callback
&& typeof callback
== 'function' )
1433 callback( sElm
['fogg_render'] );
1437 $.fn
.baseUploadInterface = function(iObj
) {
1438 mvJsLoader
.doLoadDepMode([
1440 'mvBaseUploadInterface',
1444 '$j.ui.progressbar',
1448 myUp
= new mvBaseUploadInterface( iObj
);
1453 // Shortcut to a themed button
1454 $.btnHtml = function( msg
, className
, iconId
, opt
) {
1457 var href
= (opt
.href
) ? opt
.href
: '#';
1458 var target_attr
= (opt
.target
) ? ' target="' + opt
.target
+ '" ' : '';
1459 var style_attr
= (opt
.style
) ? ' style="' + opt
.style
+ '" ' : '';
1460 return '<a href="' + href
+ '" ' + target_attr
+ style_attr
+
1461 ' class="ui-state-default ui-corner-all ui-icon_link ' +
1462 className
+ '"><span class="ui-icon ui-icon-' + iconId
+ '" />' +
1463 '<span class="btnText">'+ msg
+'<span></a>';
1465 // Shortcut to bind hover state
1466 $.fn
.btnBind = function() {
1469 $j( this ).addClass( 'ui-state-hover' );
1472 $j( this ).removeClass( 'ui-state-hover' );
1479 * small helper for putting a loading dialog box on top of everything
1480 * (helps block for request that
1482 * @param msg text text of the loader msg
1484 $.addLoaderDialog = function( msg_txt
){
1485 $.addDialog( msg_txt
, msg_txt
+ '<br>' + mv_get_loading_img() );
1488 $.addDialog = function ( title
, msg_txt
, btn
){
1489 $('#mwe_tmp_loader').remove();
1490 //append the style free loader ontop:
1491 $('body').append('<div id="mwe_tmp_loader" style="display:none" title="' + title
+ '" >' +
1494 //special btn == ok gives empty give a single "oky" -> "close"
1496 btn
[ gM('mwe-ok') ] = function(){
1497 $j('#mwe_tmp_loader').close();
1500 //turn the loader into a real dialog loader:
1501 mvJsLoader
.doLoadDepMode([
1509 $('#mwe_tmp_loader').dialog({
1519 $.closeLoaderDialog = function(){
1520 mvJsLoader
.doLoadDepMode([
1528 $j('#mwe_tmp_loader').dialog('close');
1532 $.mwProxy = function( apiConf
){
1533 mvJsLoader
.doLoad( ['$mw.apiProxy'],
1535 $mw
.apiProxy( apiConf
);
1541 * Utility functions:
1543 // Simple URL rewriter (could probably be refactored into an inline regular exp)
1544 function getURLParamReplace( url
, opt
) {
1545 var pSrc
= parseUri( url
);
1546 if( pSrc
.protocol
!= '' ) {
1547 var new_url
= pSrc
.protocol
+ '://' + pSrc
.authority
+ pSrc
.path
+ '?';
1549 var new_url
= pSrc
.path
+ '?';
1552 for( var key
in pSrc
.queryKey
) {
1553 var val
= pSrc
.queryKey
[ key
];
1554 // Do override if requested
1557 new_url
+= amp
+ key
+ '=' + val
;
1560 // Add any vars that were not already there:
1561 for( var i
in opt
) {
1562 if( !pSrc
.queryKey
[i
] ) {
1563 new_url
+= amp
+ i
+ '=' + opt
[i
];
1570 * Given a float number of seconds, returns npt format response.
1572 * @param float Seconds
1573 * @param boolean If we should show milliseconds or not.
1575 function seconds2npt( sec
, show_ms
) {
1576 if( isNaN( sec
) ) {
1577 // js_log("warning: trying to get npt time on NaN:" + sec);
1580 var hours
= Math
.floor( sec
/ 3600 );
1581 var minutes
= Math
.floor( (sec
/ 60) % 60 );
1582 var seconds
= sec
% 60;
1583 // Round the number of seconds to the required number of significant digits
1585 seconds
= Math
.round( seconds
* 1000 ) / 1000;
1587 seconds
= Math
.round( seconds
);
1590 seconds
= '0' + seconds
;
1592 minutes
= '0' + minutes
;
1594 return hours
+ ":" + minutes
+ ":" + seconds
;
1597 * Take hh:mm:ss,ms or hh:mm:ss.ms input, return the number of seconds
1599 function npt2seconds( npt_str
) {
1601 //js_log('npt2seconds:not valid ntp:'+ntp);
1604 // Strip "npt:" time definition if present
1605 npt_str
= npt_str
.replace( 'npt:', '' );
1607 times
= npt_str
.split( ':' );
1608 if( times
.length
!= 3 ){
1609 js_log( 'error: npt2seconds on ' + npt_str
);
1612 // Sometimes a comma is used instead of period for ms
1613 times
[2] = times
[2].replace( /,\s?/, '.' );
1614 // Return seconds float
1615 return parseInt( times
[0] * 3600) + parseInt( times
[1] * 60 ) + parseFloat( times
[2] );
1618 * Simple helper to grab an edit token
1620 * @param title The wiki page title you want to edit
1621 * @param api_url 'optional' The target API URL
1622 * @param callback The callback function to pass the token to
1624 function get_mw_token( title
, api_url
, callback
) {
1625 js_log( ':get_mw_token:' );
1626 if( !title
&& wgUserName
) {
1627 title
= 'User:' + wgUserName
;
1639 for( var i
in data
.query
.pages
) {
1640 if( data
.query
.pages
[i
]['edittoken'] ) {
1641 if( typeof callback
== 'function' )
1642 callback ( data
.query
.pages
[i
]['edittoken'] );
1650 // Do a remote or local API request based on request URL
1651 //@param options: url, data, cbParam, callback
1652 function do_api_req( options
, callback
) {
1653 if( typeof options
.data
!= 'object' ) {
1654 return js_error( 'Error: request paramaters must be an object' );
1656 // Generate the URL if it's missing
1657 if( typeof options
.url
== 'undefined' || options
.url
=== false ) {
1658 if( !wgServer
|| ! wgScriptPath
) {
1659 return js_error('Error: no api url for api request');
1661 options
.url
= mwGetLocalApiUrl();
1663 if( typeof options
.data
== 'undefined' )
1666 // Force format to JSON
1667 options
.data
['format'] = 'json';
1669 // If action is not set, assume query
1670 if( !options
.data
['action'] )
1671 options
.data
['action'] = 'query';
1673 // js_log('do api req: ' + options.url +'?' + jQuery.param(options.data) );
1674 if( options
.url
== 'proxy' && $mw
.proxy
){
1675 //assume the proxy is already "setup" since $mw.proxy is defined.
1676 // @@todo we probably integrate that setup into the api call
1677 $mw
.proxy
.doRequest( options
.data
, callback
);
1678 }else if( parseUri( document
.URL
).host
== parseUri( options
.url
).host
) {
1679 // Local request: do API request directly
1684 dataType
: 'json', // API requests _should_ always return JSON data:
1686 success: function( data
) {
1689 error: function( e
) {
1690 js_error( ' error' + e
+ ' in getting: ' + options
.url
);
1695 // Set the callback param if it's not already set
1696 if( typeof options
.jsonCB
== 'undefined' )
1697 options
.jsonCB
= 'callback';
1699 var req_url
= options
.url
;
1700 var paramAnd
= ( req_url
.indexOf( '?' ) == -1 ) ? '?' : '&';
1701 // Put all the parameters into the URL
1702 for( var i
in options
.data
) {
1703 req_url
+= paramAnd
+ encodeURIComponent( i
) + '=' + encodeURIComponent( options
.data
[i
] );
1706 var fname
= 'mycpfn_' + ( global_cb_count
++ );
1707 _global
[ fname
] = callback
;
1708 req_url
+= '&' + options
.jsonCB
+ '=' + fname
;
1709 loadExternalJs( req_url
);
1712 function mwGetLocalApiUrl( url
) {
1713 if ( wgServer
&& wgScriptPath
) {
1714 return wgServer
+ wgScriptPath
+ '/api.php';
1718 // Grab wiki form error for wiki html page processing (should be deprecated because we use api now)
1719 function grabWikiFormError( result_page
) {
1721 sp
= result_page
.indexOf( '<span class="error">' );
1723 se
= result_page
.indexOf( '</span>', sp
);
1724 res
.error_txt
= result_page
.substr( sp
, sp
- se
) + '</span>';
1727 sp
= result_page
.indexOf( '<ul class="warning">' )
1729 se
= result_page
.indexOf( '</ul>', sp
);
1730 res
.error_txt
= result_page
.substr( sp
, se
- sp
) + '</ul>';
1731 // Try to add the ignore form item
1732 sfp
= result_page
.indexOf( '<form method="post"' );
1734 sfe
= result_page
.indexOf( '</form>', sfp
);
1735 res
.form_txt
= result_page
.substr( sfp
, sfe
- sfp
) + '</form>';
1738 // One more error type check
1739 sp
= result_page
.indexOf( 'class="mw-warning-with-logexcerpt">' )
1741 se
= result_page
.indexOf( '</div>', sp
);
1742 res
.error_txt
= result_page
.substr( sp
, se
- sp
) + '</div>';
1748 // Do a "normal" request
1749 function do_request( req_url
, callback
) {
1750 js_log( 'do_request::req_url:' + req_url
+ ' != ' + parseUri( req_url
).host
);
1751 // If we are doing a request to the same domain or relative link, do a normal GET
1752 if( parseUri( document
.URL
).host
== parseUri( req_url
).host
||
1753 req_url
.indexOf('://') == -1 ) // Relative url
1755 // Do a direct request
1760 success: function( data
) {
1765 // Get data via DOM injection with callback
1766 global_req_cb
.push( callback
);
1767 // Prepend json_ to feed_format if not already requesting json format (metavid specific)
1768 if( req_url
.indexOf( "feed_format=" ) != -1 && req_url
.indexOf( "feed_format=json" ) == -1 )
1769 req_url
= req_url
.replace( /feed_format=/, 'feed_format=json_' );
1770 loadExternalJs( req_url
+ '&cb=mv_jsdata_cb&cb_inx=' + (global_req_cb
.length
- 1) );
1774 function mv_jsdata_cb( response
) {
1775 js_log( 'f:mv_jsdata_cb:'+ response
['cb_inx'] );
1776 // Run the callback from the global request callback object
1777 if( !global_req_cb
[response
['cb_inx']] ) {
1778 js_log( 'missing req cb index' );
1781 if( !response
['pay_load'] ) {
1782 js_log( "missing pay load" );
1785 switch( response
['content-type'] ) {
1789 if( typeof response
['pay_load'] == 'string' ) {
1790 //js_log('load string:'+"\n"+ response['pay_load']);
1792 if( $j
.browser
.msie
) {
1793 // Attempt to parse as XML for IE
1794 var xmldata
= new ActiveXObject("Microsoft.XMLDOM");
1795 xmldata
.async
= "false";
1796 xmldata
.loadXML( response
['pay_load'] );
1798 // For others (Firefox, Safari etc.)
1800 var xmldata
= (new DOMParser()).parseFromString( response
['pay_load'], "text/xml" );
1802 js_log( 'XML parse ERROR: ' + e
.message
);
1805 //@@todo handle XML parser errors
1806 if( xmldata
)response
['pay_load'] = xmldata
;
1810 js_log( 'bad response type' + response
['content-type'] );
1814 global_req_cb
[response
['cb_inx']]( response
['pay_load'] );
1816 // Load external JS via DOM injection
1817 function loadExternalJs( url
, callback
) {
1818 js_log( 'load js: '+ url
);
1819 //if(window['$j']) // use jquery call:
1827 var e
= document
.createElement( "script" );
1828 e
.setAttribute( 'src', url
);
1829 e
.setAttribute( 'type', "text/javascript" );
1831 e.onload = callback;
1833 //e.setAttribute('defer', true);
1834 document
.getElementsByTagName( "head" )[0].appendChild( e
);
1837 function styleSheetPresent( url
) {
1838 style_elements
= document
.getElementsByTagName( 'link' );
1839 if( style_elements
.length
> 0 ) {
1840 for( i
= 0; i
< style_elements
.length
; i
++ ) {
1841 if( style_elements
[i
].href
== url
)
1847 function loadExternalCss( url
) {
1848 // We could have the script loader group these CSS requests.
1849 // But it's debatable: it may hurt more than it helps with caching and all
1850 if( typeof url
=='object' ) {
1851 for( var i
in url
) {
1852 loadExternalCss( url
[i
] );
1857 if( url
.indexOf('?') == -1 ) {
1858 url
+= '?' + getMvUniqueReqId();
1860 if( !styleSheetPresent( url
) ) {
1861 js_log( 'load css: ' + url
);
1862 var e
= document
.createElement( "link" );
1864 e
.type
= "text/css";
1865 e
.rel
= 'stylesheet';
1866 document
.getElementsByTagName( "head" )[0].appendChild( e
);
1869 function getMvEmbedURL() {
1870 if( _global
['mv_embed_url'] )
1871 return _global
['mv_embed_url'];
1872 var js_elements
= document
.getElementsByTagName( "script" );
1873 for( var i
= 0; i
< js_elements
.length
; i
++ ) {
1874 // Check for mv_embed.js and/or script loader
1875 var src
= js_elements
[i
].getAttribute( "src" );
1877 if( src
.indexOf( 'mv_embed.js' ) != -1 || (
1878 ( src
.indexOf( 'mwScriptLoader.php' ) != -1 || src
.indexOf('jsScriptLoader.php') != -1 )
1879 && src
.indexOf('mv_embed') != -1) ) //(check for class=mv_embed script_loader call)
1881 _global
['mv_embed_url'] = src
;
1886 js_error( 'Error: getMvEmbedURL failed to get Embed Path' );
1889 // Get a unique request ID to ensure fresh JavaScript
1890 function getMvUniqueReqId() {
1891 if( _global
['urid'] )
1892 return _global
['urid'];
1893 var mv_embed_url
= getMvEmbedURL();
1894 // If we have a URI, return it
1895 var urid
= parseUri( mv_embed_url
).queryKey
['urid']
1897 _global
['urid'] = urid
;
1900 // If we're in debug mode, get a fresh unique request key
1901 if( parseUri( mv_embed_url
).queryKey
['debug'] == 'true' ) {
1903 var urid
= d
.getTime();
1904 _global
['urid'] = urid
;
1907 // Otherwise, just return the mv_embed version
1908 return MV_EMBED_VERSION
;
1911 * Set the global mv_embed path based on the script's location
1913 function getMvEmbedPath() {
1914 if( _global
['mv_embed_path'] )
1915 return _global
['mv_embed_path'];
1916 var mv_embed_url
= getMvEmbedURL();
1917 if( mv_embed_url
.indexOf( 'mv_embed.js' ) !== -1 ) {
1918 mv_embed_path
= mv_embed_url
.substr( 0, mv_embed_url
.indexOf( 'mv_embed.js' ) );
1919 } else if( mv_embed_url
.indexOf( 'mwScriptLoader.php' ) !== -1 ) {
1920 // Script loader is in the root of MediaWiki, so include the default mv_embed extension path
1921 mv_embed_path
= mv_embed_url
.substr( 0, mv_embed_url
.indexOf( 'mwScriptLoader.php' ) )
1922 + mediaWiki_mvEmbed_path
;
1924 mv_embed_path
= mv_embed_url
.substr( 0, mv_embed_url
.indexOf( 'jsScriptLoader.php' ) );
1926 // Make an absolute URL (if it's relative and we don't have an mv_embed path)
1927 if( mv_embed_path
.indexOf( '://' ) == -1 ) {
1928 var pURL
= parseUri( document
.URL
);
1929 if( mv_embed_path
.charAt( 0 ) == '/' ) {
1930 mv_embed_path
= pURL
.protocol
+ '://' + pURL
.authority
+ mv_embed_path
;
1933 if( mv_embed_path
== '' ) {
1934 mv_embed_path
= pURL
.protocol
+ '://' + pURL
.authority
+ pURL
.directory
+ mv_embed_path
;
1938 _global
['mv_embed_path'] = mv_embed_path
;
1939 return mv_embed_path
;
1942 if ( typeof DOMParser
== "undefined" ) {
1943 DOMParser = function () {}
1944 DOMParser
.prototype.parseFromString = function ( str
, contentType
) {
1945 if ( typeof ActiveXObject
!= "undefined" ) {
1946 var d
= new ActiveXObject( "MSXML.DomDocument" );
1949 } else if ( typeof XMLHttpRequest
!= "undefined" ) {
1950 var req
= new XMLHttpRequest
;
1951 req
.open( "GET", "data:" + (contentType
|| "application/xml") +
1952 ";charset=utf-8," + encodeURIComponent(str
), false );
1953 if ( req
.overrideMimeType
) {
1954 req
.overrideMimeType(contentType
);
1957 return req
.responseXML
;
1964 function js_log( string
) {
1965 ///add any prepend debug strings if nessesary
1966 if( mwConfig
['debug_pre'] )
1967 string
= mwConfig
['debug_pre']+ string
;
1969 if( window
.console
) {
1970 window
.console
.log( string
);
1973 * IE and non-Firebug debug:
1975 /*var log_elm = document.getElementById('mv_js_log');
1977 document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML +
1978 '<div style="position:absolute;z-index:500;top:0px;left:0px;right:0px;height:10px;">'+
1979 '<textarea id="mv_js_log" cols="120" rows="5"></textarea>'+
1982 var log_elm = document.getElementById('mv_js_log');
1985 log_elm.value+=string+"\n";
1991 function js_error( string
) {