7cffc260dc9bb3161cdf07a5d877e8a1e2cd1a0a
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)
20 * @path The path to the file (or set of files) with ending slash
21 * @gClasses The set of classes
22 * if it's an array, $j.className becomes jquery.className.js
23 * if it's an associative object then key => value pairs are used
25 if( typeof mvAutoLoadClasses
== 'undefined' )
26 mvAutoLoadClasses
= {};
28 // The script that loads the class set
29 function lcPaths( classSet
){
30 for( var i
in classSet
) {
31 mvAutoLoadClasses
[i
] = classSet
[i
];
35 function mvGetClassPath(k
){
36 if( mvAutoLoadClasses
[k
] ) {
37 //js_log('got class path:' + k + ' : '+ mvClassPaths[k]);
38 return mvAutoLoadClasses
[k
];
40 js_log('Error:: Could not find path for requested class ' + k
);
44 if( typeof mvCssPaths
== 'undefined' )
47 function lcCssPath( cssSet
) {
48 for( var i
in cssSet
) {
49 mvCssPaths
[i
] = mv_embed_path
+ cssSet
[i
];
54 * -- Load Class Paths --
56 * MUST BE VALID JSON (NOT JS)
57 * This is used by the script loader to auto-load classes (so we only define
58 * this once for PHP & JavaScript)
60 * Right now the PHP AutoLoader only reads this mv_embed.js file.
61 * In the future we could have multiple lcPath calls that PHP reads
62 * (if our autoloading class list becomes too long)
64 * we could support direct file requests to the script loader instead
65 * of shared class names read from a central location.
68 "mv_embed" : "mv_embed.js",
69 "window.jQuery" : "jquery/jquery-1.3.2.js",
70 "$j.fn.pngFix" : "jquery/plugins/jquery.pngFix.js",
71 "$j.fn.autocomplete": "jquery/plugins/jquery.autocomplete.js",
72 "$j.fn.hoverIntent" : "jquery/plugins/jquery.hoverIntent.js",
73 "$j.fn.datePicker" : "jquery/plugins/jquery.datePicker.js",
74 "$j.ui" : "jquery/jquery.ui/ui/ui.core.js",
75 "$j.fn.ColorPicker" : "libClipEdit/colorpicker/js/colorpicker.js",
76 "$j.Jcrop" : "libClipEdit/Jcrop/js/jquery.Jcrop.js",
77 "$j.fn.simpleUploadForm" : "libAddMedia/simpleUploadForm.js",
79 "$mw.proxy" : "libMwApi/mw.proxy.js",
81 "$mw.testLang" : "tests/testLang.js",
83 "ctrlBuilder" : "skins/ctrlBuilder.js",
84 "kskinConfig" : "skins/kskin/kskin.js",
85 "mvpcfConfig" : "skins/mvpcf/mvpcf.js",
87 "JSON" : "libMwApi/json2.js",
88 "$j.cookie" : "jquery/plugins/jquery.cookie.js",
89 "$j.contextMenu" : "jquery/plugins/jquery.contextMenu.js",
90 "$j.fn.suggestions" : "jquery/plugins/jquery.suggestions.js",
92 "$j.effects.blind" : "jquery/jquery.ui/ui/effects.blind.js",
93 "$j.effects.drop" : "jquery/jquery.ui/ui/effects.drop.js",
94 "$j.effects.pulsate" : "jquery/jquery.ui/ui/effects.pulsate.js",
95 "$j.effects.transfer" : "jquery/jquery.ui/ui/effects.transfer.js",
96 "$j.ui.droppable" : "jquery/jquery.ui/ui/ui.droppable.js",
97 "$j.ui.slider" : "jquery/jquery.ui/ui/ui.slider.js",
98 "$j.effects.bounce" : "jquery/jquery.ui/ui/effects.bounce.js",
99 "$j.effects.explode" : "jquery/jquery.ui/ui/effects.explode.js",
100 "$j.effects.scale" : "jquery/jquery.ui/ui/effects.scale.js",
101 "$j.ui.datepicker" : "jquery/jquery.ui/ui/ui.datepicker.js",
102 "$j.ui.progressbar" : "jquery/jquery.ui/ui/ui.progressbar.js",
103 "$j.ui.sortable" : "jquery/jquery.ui/ui/ui.sortable.js",
104 "$j.effects.clip" : "jquery/jquery.ui/ui/effects.clip.js",
105 "$j.effects.fold" : "jquery/jquery.ui/ui/effects.fold.js",
106 "$j.effects.shake" : "jquery/jquery.ui/ui/effects.shake.js",
107 "$j.ui.dialog" : "jquery/jquery.ui/ui/ui.dialog.js",
108 "$j.ui.resizable" : "jquery/jquery.ui/ui/ui.resizable.js",
109 "$j.ui.tabs" : "jquery/jquery.ui/ui/ui.tabs.js",
110 "$j.effects.core" : "jquery/jquery.ui/ui/effects.core.js",
111 "$j.effects.highlight" : "jquery/jquery.ui/ui/effects.highlight.js",
112 "$j.effects.slide" : "jquery/jquery.ui/ui/effects.slide.js",
113 "$j.ui.accordion" : "jquery/jquery.ui/ui/ui.accordion.js",
114 "$j.ui.draggable" : "jquery/jquery.ui/ui/ui.draggable.js",
115 "$j.ui.selectable" : "jquery/jquery.ui/ui/ui.selectable.js",
117 "$j.fn.dragDropFile" : "libAddMedia/dragDropFile.js",
118 "mvFirefogg" : "libAddMedia/mvFirefogg.js",
119 "mvAdvFirefogg" : "libAddMedia/mvAdvFirefogg.js",
120 "mvBaseUploadInterface" : "libAddMedia/mvBaseUploadInterface.js",
121 "remoteSearchDriver" : "libAddMedia/remoteSearchDriver.js",
122 "seqRemoteSearchDriver" : "libSequencer/seqRemoteSearchDriver.js",
124 "baseRemoteSearch" : "libAddMedia/searchLibs/baseRemoteSearch.js",
125 "mediaWikiSearch" : "libAddMedia/searchLibs/mediaWikiSearch.js",
126 "metavidSearch" : "libAddMedia/searchLibs/metavidSearch.js",
127 "archiveOrgSearch" : "libAddMedia/searchLibs/archiveOrgSearch.js",
128 "flickrSearch" : "libAddMedia/searchLibs/flickrSearch.js",
129 "baseRemoteSearch" : "libAddMedia/searchLibs/baseRemoteSearch.js",
131 "mvClipEdit" : "libClipEdit/mvClipEdit.js",
133 "embedVideo" : "libEmbedVideo/embedVideo.js",
134 "flashEmbed" : "libEmbedVideo/flashEmbed.js",
135 "genericEmbed" : "libEmbedVideo/genericEmbed.js",
136 "htmlEmbed" : "libEmbedVideo/htmlEmbed.js",
137 "javaEmbed" : "libEmbedVideo/javaEmbed.js",
138 "nativeEmbed" : "libEmbedVideo/nativeEmbed.js",
139 "quicktimeEmbed" : "libEmbedVideo/quicktimeEmbed.js",
140 "vlcEmbed" : "libEmbedVideo/vlcEmbed.js",
142 "mvPlayList" : "libSequencer/mvPlayList.js",
143 "mvSequencer" : "libSequencer/mvSequencer.js",
144 "mvFirefoggRender" : "libSequencer/mvFirefoggRender.js",
145 "mvTimedEffectsEdit": "libSequencer/mvTimedEffectsEdit.js",
147 "mvTextInterface" : "libTimedText/mvTextInterface.js",
148 "mvTimedTextEdit" : "libTimedText/mvTimedTextEdit.js"
151 // Dependency mapping for CSS files for self-contained included plugins:
153 '$j.Jcrop' : 'libClipEdit/Jcrop/css/jquery.Jcrop.css',
154 '$j.fn.ColorPicker' : 'libClipEdit/colorpicker/css/colorpicker.css'
159 // (c) Steven Levithan <stevenlevithan.com>
161 function parseUri (str
) {
162 var o
= parseUri
.options
,
163 m
= o
.parser
[o
.strictMode
? "strict" : "loose"].exec(str
),
167 while (i
--) uri
[o
.key
[i
]] = m
[i
] || "";
170 uri
[o
.key
[12]].replace(o
.q
.parser
, function ($0, $1, $2) {
171 if ($1) uri
[o
.q
.name
][$1] = $2;
178 key
: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
181 parser
: /(?:^|&)([^&=]*)=?([^&]*)/g
184 strict
: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
185 loose
: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
189 // For use when mv_embed with script-loader is in the root MediaWiki path
190 var mediaWiki_mvEmbed_path
= 'js2/mwEmbed/';
192 //The global scope: will be depreciated once we get everything into $mw
196 * setup the empty global $mw object
197 * will ensure all our functions and variables are properly namespaced
198 * reducing chance of conflicts
204 //@@todo move these into $mw
205 var global_req_cb
= new Array(); // The global request callback array
207 // Get the mv_embed location if it has not been set
208 if( !mv_embed_path
) {
209 var mv_embed_path
= getMvEmbedPath();
212 * The global $mw object:
214 * Any global functions/classes that are not jQuery plugins should make
215 * there way into the $mw namespace
222 'skin_name' : 'mvpcf',
223 'jui_skin' : 'redmond',
224 'video_size' : '400x300'
226 //list valid skins here:
227 $.valid_skins
= ['mvpcf', 'kskin'];
228 // the version of mwEmbed
229 $.version
= '1.0r21';
232 * some global containers flags
234 $.skin_list
= new Array();
237 $.player_list
= new Array(), // The global player list per page
238 $.req_cb
= new Array() // The global request callback array
241 * Language classes $mw.lang
243 * Localized Language support attempts to mirror the functionality of Language.php in MediaWiki
244 * It contains methods for loading and transforming msg text
249 * Setup the lang object
256 * Loads a set of json messages into the lng object.
258 * @param json msgSet The set of msgs to be loaded
260 $.lang
.loadGM = function( msgSet
){
261 for( var i
in msgSet
) {
262 gMsg
[ i
] = msgSet
[i
];
268 * Loads a ruleset by given template key ie PLURAL : { //ruleSetObj }
270 * @param json ruleSet The ruleset object ( extends gRuleSet )
272 $.lang
.loadRS = function( ruleSet
){
273 for( var i
in ruleSet
){
274 gRuleSet
[ i
] = ruleSet
[ i
];
279 * Returns a transformed msg string
281 * it take a msg key and array of replacement values of form
282 * $1, $2 and does relevant msgkey transformation returning
285 * @param string key The msg key as set by loadGm
286 * @param [mixed] args An array of replacement strings
289 $.lang
.gM = function( key
, args
) {
291 return '<' + key
+ '>';// Missing key placeholder
293 //swap in the arg values
294 var ms
= $.lang
.gMsgSwap( key
, args
) ;
298 //a quick check to see if we need to send the msg via the 'parser'
299 //(we can add more detailed check once we support more wiki syntax)
300 if( ms
.indexOf('{{') === -1 && ms
.indexOf('[') === -1){
304 //make sure we have the lagMagic setup:
305 //@@todo move to init
307 //send the msg key through the parser
308 var pObj
= $.parser
.pNew( ms
);
309 //return the transformed msg
310 return pObj
.getHTML();
315 * @param string key The msg key as set by loadGm
316 * @param [mixed] args An array or string to be replaced
319 $.lang
.gMsgSwap = function( key
, args
){
321 return '<' + key
+ '>';// Missing key placeholder
322 //get the messege string:
323 var ms
= gMsg
[ key
];
326 if( typeof args
== 'object' || typeof args
== 'array' ) {
327 for( var v
in args
) {
328 // Message test replace arguments start at 1 instead of zero:
329 var rep
= new RegExp('\\$'+ ( parseInt(v
) + 1 ), 'g');
330 ms
= ms
.replace( rep
, args
[v
] );
332 } else if( typeof args
=='string' || typeof args
=='number' ) {
333 ms
= ms
.replace(/\$1/g, args
);
341 * @returns string The msg key without transforming it
343 $.lang
.gMsgNoTrans = function( key
){
347 // Missing key placeholder
348 return '<' + key
+ '>';
351 * Add Supported Magic Words to parser
353 //set the setupflag to false:
354 $.lang
.doneSetup
=false;
355 $.lang
.magicSetup = function(){
356 if(!$.lang
.doneSetup
){
357 $.parser
.addMagic ( {
358 'PLURAL' : $.lang
.procPLURAL
361 $.lang
.doneSetup
= true;
366 * Process the PLURAL special language template key:
368 $.lang
.procPLURAL = function( tObj
){
370 // (gRuleSet is loaded from script-loader to contains local ruleset)
371 var rs
= gRuleSet
['PLURAL'];
374 * Plural matchRuleTest
376 function matchRuleTest(cRule
, val
){
377 //js_log("matchRuleTest:: " + typeof cRule + ' ' + cRule + ' == ' + val );
379 function checkValue(compare
, val
){
380 if(typeof compare
== 'string'){
381 range
= compare
.split('-');
382 if( range
.length
>= 1 ){
383 if( val
>= range
[0] && val
<= range
[1] )
387 //else do a direct compare
393 //check for simple cRule type:
394 if( typeof cRule
== 'number'){
395 return ( parseInt( val
) == parseInt( cRule
) );
396 }else if( typeof cRule
== 'object' ){
398 //if a list we need to match all for rule match
410 if( checkValue( val
% cr
['mod'], cr
['is'] ) )
412 }else if( cr
['not']){
413 if( ! checkValue( val
% cr
['mod'], cr
['not'] ) )
419 //check all the matches (taking into consideration "or" order)
429 * Maps a given rule Index to template params:
431 * if index is out of range return last param
434 function getTempParamFromRuleInx(tObj
, ruleInx
){
435 //js_log('getTempParamFromRuleInx: ruleInx: ' + ruleInx + ' tempParamLength ' + tObj.param.length );
436 if( ruleInx
>= tObj
.param
.length
)
437 return tObj
.param
[ tObj
.param
.length
-1 ];
438 //else return the requested index:
439 return tObj
.param
[ ruleInx
];
442 //run the actual rule lookup:
443 for(var ruleInx
in rs
){
445 if( matchRuleTest( cRule
, tObj
.arg
) ){
446 //js_log("matched rule: " + ruleInx );
447 return getTempParamFromRuleInx(tObj
, rCount
);
451 //js_log('no match found for: ' + tObj.arg + ' using last/other : ' + tObj.param [ tObj.param.length -1 ] );
452 //return the last /"other" template param
453 return tObj
.param
[ tObj
.param
.length
-1 ];
457 * gMsgLoadRemote loads remote msg strings
459 * @param mixed msgSet the set of msg to load remotely
460 * @param function callback the callback to issue once string is ready
462 $.lang
.gMsgLoadRemote = function( msgSet
, callback
) {
464 if( typeof msgSet
== 'object' ) {
465 for( var i
in msgSet
) {
466 ammessages
+= msgSet
[i
] + '|';
468 } else if( typeof msgSet
== 'string' ) {
469 ammessages
+= msgSet
;
471 if( ammessages
== '' ) {
472 js_log( 'gMsgLoadRemote: no message set requested' );
477 'meta': 'allmessages',
478 'ammessages': ammessages
480 }, function( data
) {
481 if( data
.query
.allmessages
) {
482 var msgs
= data
.query
.allmessages
;
483 for( var i
in msgs
) {
485 ld
[ msgs
[i
]['name'] ] = msgs
[i
]['*'];
493 * Format a size in bytes for output, using an appropriate
494 * unit (B, KB, MB or GB) according to the magnitude in question
496 * @param size Size to format
497 * @return string Plain text (not HTML)
499 $.lang
.formatSize = function ( size
) {
500 // For small sizes no decimal places are necessary
507 // For MB and bigger two decimal places are smarter
511 msg
= 'mwe-size-gigabytes';
513 msg
= 'mwe-size-megabytes';
516 msg
= 'mwe-size-kilobytes';
519 msg
= 'mwe-size-bytes';
521 // JavaScript does not let you choose the precision when rounding
522 var p
= Math
.pow(10,round
);
523 var size
= Math
.round( size
* p
) / p
;
524 //@@todo we need a formatNum and we need to request some special packaged info to deal with that case.
525 return gM( msg
, size
);
528 $.lang
.formatNumber = function( num
){
531 Str: The number to be formatted, as a string or number.
532 outD: The decimal character for the output, such as ',' for the number 100,2
533 sep: The separator character for the output, such as ',' for the number 1,000.2
535 function addSeparatorsNF(nStr
, outD
, sep
){
537 var dpos
= nStr
.indexOf( '.' );
540 nStrEnd
= outD
+ nStr
.substring(dpos
+ 1, nStr
.length
);
541 nStr
= nStr
.substring(0, dpos
);
543 var rgx
= /(\d+)(\d{3})/;
544 while (rgx
.test(nStr
)) {
545 nStr
= nStr
.replace(rgx
, '$1' + sep
+ '$2');
547 return nStr
+ nStrEnd
;
549 //@@todo read language code and give periods or comas:
550 return addSeparatorsNF( num
, '.', ',');
556 * MediaWiki wikitext "Parser"
558 * This is not feature complete but we need a way to get at template properties
561 * @param wikiText the wikitext to be parsed
562 * @return parserObj returns a parser object that has methods for getting at
563 * things you would want
570 * lets you add a set of magic keys and associated callback functions
571 * callback: @param ( Object Template )
572 * callback: @return the transformed template output
574 * @param object magicSet key:callback
576 $.parser
.addMagic = function( magicSet
){
577 for(var i
in magicSet
)
578 pMagicSet
[ i
] = magicSet
[i
];
581 //actual parse call (returns parser object)
582 $.parser
.pNew = function( wikiText
, opt
){
583 var parseObj = function( wikiText
, opt
){
584 return this.init( wikiText
, opt
)
586 parseObj
.prototype = {
587 //the wikiText "DOM"... stores the parsed wikiText structure
588 //wtDOM : {}, (not yet supported )
590 pOut
: '', //the parser output string container
591 init :function( wikiText
){
592 this.wikiText
= wikiText
;
594 updateText : function( wikiText
){
595 this.wikiText
= wikiText
;
596 //invalidate the output (will force a re-parse )
601 * quickly recursive / parse out templates:
604 // ~ probably a better algorithm out there / should mirror php parser flow ~
605 // (we are already running white-space issues ie php parse strips whitespace diffrently)
607 // ... but I am having fun with recursion so here it is...
608 // or at least mirror: http://www.mediawiki.org/wiki/Extension:Page_Object_Model
609 function rdpp ( txt
, cn
){
612 for(var a
=0; a
< txt
.length
; a
++){
613 if( txt
[a
] == '{' && txt
[a
+1] == '{' ){
617 node
['c'] = new Array();
619 node
['c'].push( rdpp( txt
.substr( a
), true ) );
620 }else if( txt
[a
] == '}' && txt
[a
+1] == '}'){
629 //dont put closures into output:
630 if( txt
[a
] && txt
[a
]!='}' )
637 * parse template text as template name and named params
639 function parseTmplTxt( ts
){
642 tname
= ts
.split('\|').shift() ;
643 tname
= tname
.split('\{').shift() ;
644 tname
= tname
.replace( /^\s+|\s+$/g, "" ); //trim
646 //check for arguments:
647 if( tname
.split(':').length
== 1 ){
648 tObj
["name"] = tname
;
650 tObj
["name"] = tname
.split(':').shift();
651 tObj
["arg"] = tname
.split(':').pop();
654 //js_log("TNAME::" + tObj["name"] + ' from:: ' + ts);
655 var pSet
= ts
.split('\|');
658 tObj
.param
= new Array();
659 for(var pInx
in pSet
){
660 var tStr
= pSet
[ pInx
];
661 //check for empty param
663 tObj
.param
[ pInx
] = '';
666 for(var b
=0 ; b
< tStr
.length
; b
++){
667 if(tStr
[b
] == '=' && b
>0 && b
<tStr
.length
&& tStr
[b
-1]!='\\'){
669 tObj
.param
[ tStr
.split('=').shift() ] = tStr
.split('=').pop();
672 tObj
.param
[ pInx
] = tStr
;
679 function getMagicTxtFromTempNode( node
){
680 node
.tObj
= parseTmplTxt ( node
.t
);
681 //do magic swap if template key found in pMagicSet
682 if( node
.tObj
.name
in pMagicSet
){
683 var nt
= pMagicSet
[ node
.tObj
.name
]( node
.tObj
);
686 //don't swap just return text
693 * go last child first swap upward: (could probably be integrated above somehow)
696 function recurse_magic_swap( node
){
702 for(var i
in node
['c']){
703 var nt
= recurse_magic_swap( node
['c'][i
] );
704 //swap it into current
706 node
.t
= node
.t
.replace( node
['c'][i
].t
, nt
);
709 pNode
.t
= pNode
.t
.replace( node
['c'][i
].t
, nt
);
711 //do the current node:
712 var nt
= getMagicTxtFromTempNode( node
);
713 pNode
.t
= pNode
.t
.replace(node
.t
, nt
);
714 //run the swap for the outer most node
717 //node.t = getMagicFromTempObj( node.t )
718 return getMagicTxtFromTempNode( node
);
721 //parse out the template node structure:
722 this.pNode
= rdpp ( this.wikiText
);
723 //strip out the parent from the root
724 this.pNode
['p'] = null;
726 //do the recursive magic swap text:
727 this.pOut
= recurse_magic_swap( this.pNode
);
732 * parsed template api ~losely based off of ~POM~
733 * http://www.mediawiki.org/wiki/Extension:Page_Object_Model
739 * gets a requested template from the wikitext (if available)
742 templates: function( tname
){
744 var tmplSet
= new Array();
745 function getMatchingTmpl( node
){
747 for(var i
in node
['c']){
748 getMatchingTmpl( node
['c'] );
751 if( tname
&& node
.tObj
){
752 if( node
.tObj
['name'] == tname
)
753 tmplSet
.push( node
.tObj
);
754 }else if( node
.tObj
){
755 tmplSet
.push( node
.tObj
);
758 getMatchingTmpl( this.pNode
);
762 * Returns the transformed wikitext
764 * Build output from swappable index
765 * (all transforms must be expanded in parse stage and linearly rebuilt)
766 * Alternatively we could build output using a place-holder & replace system
767 * (this lets us be slightly more slopy with ordering and indexes, but probably slower)
769 * Ideal: we build a 'wiki DOM'
770 * When editing you update the data structure directly
771 * Then in output time you just go DOM->html-ish output without re-parsing anything
773 getHTML : function(){
774 //wikiText updates should invalidate pOut
775 if( this.pOut
== ''){
781 //return the parserObj
782 return new parseObj( wikiText
, opt
) ;
787 //setup legacy global shortcuts:
788 var loadGM
= $mw
.lang
.loadGM
;
789 var loadRS
= $mw
.lang
.loadRS
;
790 var gM
= $mw
.lang
.gM
;
792 // All default messages in [English] should be overwritten by the CMS language message system.
794 "mwe-loading_txt" : "Loading ...",
795 "mwe-size-gigabytes" : "$1 GB",
796 "mwe-size-megabytes" : "$1 MB",
797 "mwe-size-kilobytes" : "$1 K",
798 "mwe-size-bytes" : "$1 B",
799 "mwe-error_load_lib" : "Error: JavaScript $1 was not retrievable or does not define $2",
800 "mwe-loading-add-media-wiz" : "Loading add media wizard",
801 "mwe-apiproxy-setup" : "Setting up API proxy",
802 "mwe-load-drag-item" : "Loading dragged item",
804 "mwe-cancel" : "Cancel"
808 // Get the loading image
809 function mv_get_loading_img( style
, class_attr
){
810 var style_txt
= (style
)?style
:'';
811 var class_attr
= (class_attr
) ? 'class="' + class_attr
+ '"' : 'class="mv_loading_img"';
812 return '<div '+class_attr
+' style="' + style
+'"></div>';
815 function mv_set_loading(target
, load_id
){
816 var id_attr
= ( load_id
)?' id="' + load_id
+ '" ':'';
817 $j(target
).append('<div '+id_attr
+' style="position:absolute;top:0px;left:0px;height:100%;width:100%;'+
818 'background-color:#FFF;">' +
819 mv_get_loading_img('top:30px;left:30px') +
824 * mvJsLoader class handles initialization and js file loads
831 onReadyEvents
: new Array(),
832 doneReadyEvents
: false,
833 jQuerySetupFlag
: false,
835 // To keep consistency across threads
839 load_error
: false, // Load error flag (false by default)
841 callbacks
: new Array(),
844 doLoad: function( loadLibs
, callback
) {
846 if( loadLibs
&& loadLibs
.length
!= 0 ) {
847 //js_log("doLoad setup::" + JSON.stringify( loadLibs ) );
849 // First check if we already have this library loaded
850 var all_libs_loaded
= true;
851 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
852 // Check if the library is already loaded
853 if( ! this.checkObjPath( loadLibs
[i
] ) ) {
854 all_libs_loaded
= false;
857 if( all_libs_loaded
) {
858 js_log( 'Libraries ( ' + loadLibs
+ ') already loaded... skipping load request' );
862 // Do a check for any CSS we may need and get it
863 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
864 if( typeof mvCssPaths
[ loadLibs
[i
] ] != 'undefined' ) {
865 loadExternalCss( mvCssPaths
[ loadLibs
[i
] ] );
869 // Check if we should use the script loader to combine all the requests into one
870 if( typeof mwSlScript
!= 'undefined' ) {
874 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
875 var curLib
= loadLibs
[i
];
876 // Only add if not included yet:
877 if( ! this.checkObjPath( curLib
) ) {
878 class_set
+= coma
+ curLib
;
883 //Build the url to the scriptServer striping its request parameters:
884 var puri
= parseUri( getMvEmbedURL() );
885 if( ( getMvEmbedURL().indexOf('://') != -1 )
886 && puri
.host
!= parseUri( document
.URL
).host
)
888 var scriptPath
= puri
.protocol
+ '://' + puri
.authority
+ puri
.path
;
890 var scriptPath
= puri
.path
;
892 //js_log('scriptServer Path is: ' + scriptPath + "\n host script path:" + getMvEmbedURL() );
893 this.libs
[ last_class
] = scriptPath
+ '?class=' + class_set
+
894 '&' + getMwReqParam();
898 for( var i
= 0; i
< loadLibs
.length
; i
++ ) {
899 var curLib
= loadLibs
[i
];
901 var libLoc
= mvGetClassPath( curLib
);
902 // Do a direct load of the file (pass along unique request id from
903 // request or mv_embed Version )
904 var qmark
= (libLoc
.indexOf( '?' ) !== true) ? '?' : '&';
905 this.libs
[curLib
] = mv_embed_path
+ libLoc
+ qmark
+ getMwReqParam();
912 this.callbacks
.push( callback
);
914 if( this.checkLoading() ) {
915 //@@todo we should check the <script> Element .onLoad property to
916 //make sure its just not a very slow connection
917 //(even though the class is not loaded)
918 if( this.load_time
++ > 4000 ){ // Time out after ~80 seconds
919 js_log( gM('mwe-error_load_lib', [mvGetClassPath(this.missing_path
), this.missing_path
]) );
920 this.load_error
= true;
922 setTimeout( 'mvJsLoader.doLoad()', 20 );
925 //js_log('checkLoading passed. Running callbacks...');
926 // Only do callbacks if we are in the same instance (weird concurrency issue)
928 for( var i
= 0; i
< this.callbacks
.length
; i
++ )
930 //js_log('RESET LIBS: loading is: '+ loading + ' callback count: '+cb_count +
931 // ' p:'+ this.ptime +' c:'+ this.ctime);
935 //js_log('done loading, do call: ' + this.callbacks[0] );
936 while( this.callbacks
.length
!= 0 ) {
937 if( this.ptime
== this.ctime
- 1 ) { // Enforce thread consistency
938 this.callbacks
.pop()();
939 //func = this.callbacks.pop();
940 //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func);
943 // Re-issue doLoad ( ptime will be set to ctime so we should catch up)
944 setTimeout( 'mvJsLoader.doLoad()', 25 );
949 this.ptime
= this.ctime
;
951 doLoadDepMode: function( loadChain
, callback
) {
952 // Firefox executes JS in the order in which it is included, so just directly issue the request
953 if( $j
.browser
.firefox
) {
955 for( var i
= 0; i
< loadChain
.length
; i
++ ) {
956 for( var j
= 0; j
< loadChain
[i
].length
; j
++ ) {
957 loadSet
.push( loadChain
[i
][j
] );
960 mvJsLoader
.doLoad( loadSet
, callback
);
962 // Safari and IE tend to execute out of order so load with dependency checks
963 mvJsLoader
.doLoad( loadChain
.shift(), function() {
964 if( loadChain
.length
!= 0 ) {
965 mvJsLoader
.doLoadDepMode( loadChain
, callback
);
972 checkLoading: function() {
975 for( var i
in this.libs
) { // for/in loop is OK on an object
976 if( !this.checkObjPath( i
) ) {
977 if( !this.libreq
[i
] ) {
978 loadExternalJs( this.libs
[i
] );
981 //js_log("has not yet loaded: " + i);
987 checkObjPath: function( libVar
) {
990 var objPath
= libVar
.split( '.' )
992 for( var p
= 0; p
< objPath
.length
; p
++ ) {
993 cur_path
= (cur_path
== '') ? cur_path
+ objPath
[p
] : cur_path
+ '.' + objPath
[p
];
994 eval( 'var ptest = typeof ( '+ cur_path
+ ' ); ');
995 if( ptest
== 'undefined' ) {
996 this.missing_path
= cur_path
;
1000 this.cur_path
= cur_path
;
1004 * checks for jQuery and adds the $j noConflict var
1006 jQueryCheck: function( callback
) {
1007 js_log( 'jQueryCheck::' );
1008 // Skip stuff if $j is already loaded:
1009 if( _global
['$j'] && callback
){
1018 //only do the $j setup once:
1020 _global
['$j'] = jQuery
.noConflict();
1022 if( _this
.jQuerySetupFlag
== false){
1023 js_log('setup mv_embed jQuery bindings');
1024 //setup our global settings using the (jQuery helper)
1026 // Set up the skin path
1027 _global
['mv_jquery_skin_path'] = mv_embed_path
+ 'jquery/jquery.ui/themes/' + $mw
.conf
['jui_skin'] + '/';
1028 _global
['mv_skin_img_path'] = mv_embed_path
+ 'skins/' + $mw
.conf
['skin_name'] + '/images/';
1029 _global
['mv_default_thumb_url'] = mv_skin_img_path
+ 'vid_default_thumb.jpg';
1031 // Make sure the skin/style sheets are always available:
1032 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1033 loadExternalCss( mv_embed_path
+ 'skins/' + $mw
.conf
['skin_name'] + '/styles.css' );
1035 // Set up AJAX to not send dynamic URLs for loading scripts (we control that with
1036 // the scriptLoader)
1041 js_log( 'jQuery loaded into $j' );
1042 // Set up mvEmbed jQuery bindings and config based dependencies
1043 mv_jqueryBindings();
1044 _this
.jQuerySetupFlag
= true;
1052 embedVideoCheck:function( callback
) {
1054 js_log( 'embedVideoCheck:' );
1055 // Make sure we have jQuery
1056 _this
.jQueryCheck( function() {
1057 //set class videonojs to loading
1058 $j('.videonojs').html( gM('mwe-loading_txt') );
1059 //Set up the embed video player class request: (include the skin js as well)
1072 //add any requested skins (suports multiple skins per single page)
1073 if( $mw
.skin_list
){
1074 for(var i
in $mw
.skin_list
){
1075 depReq
[0].push( $mw
.skin_list
[i
] + 'Config' );
1080 // Add PNG fix if needed:
1081 if( $j
.browser
.msie
|| $j
.browser
.version
< 7 )
1082 depReq
[0].push( '$j.fn.pngFix' );
1084 //load the video libs:
1085 _this
.doLoadDepMode( depReq
, function() {
1088 $j('.videonojs').remove();
1092 addLoadEvent: function( fn
) {
1093 this.onReadyEvents
.push( fn
);
1095 // Check the jQuery flag. This way, when remote embedding, we don't load jQuery
1096 // unless js2AddOnloadHook was used or there is video on the page.
1097 runQueuedFunctions: function() {
1098 js_log("runQueuedFunctions");
1100 this.jQueryCheck( function() {
1101 _this
.runReadyEvents();
1102 _this
.doneReadyEvents
= true;
1105 runReadyEvents: function() {
1106 js_log( "runReadyEvents" );
1107 while( this.onReadyEvents
.length
) {
1108 this.onReadyEvents
.shift()();
1113 // Shortcut ( @@todo consolidate shortcuts & re-factor mvJsLoader )
1114 function mwLoad( loadSet
, callback
) {
1115 mvJsLoader
.doLoad( loadSet
, callback
);
1120 // Load an external JS file. Similar to jquery .require plugin,
1121 // but checks for object availability rather than load state.
1123 /*********** INITIALIZATION CODE *************
1124 * This will get called when the DOM is ready
1125 *********************************************/
1126 /* jQuery .ready does not work when jQuery is loaded dynamically.
1127 * For an example of the problem see: 1.1.3 working: http://pastie.caboo.se/92588
1128 * and >= 1.1.4 not working: http://pastie.caboo.se/92595
1129 * $j(document).ready( function(){ */
1130 function mwdomReady( force
) {
1131 js_log( 'f:mwdomReady:' );
1132 if( !force
&& $mw
.init_done
) {
1133 js_log( "mw done, do nothing..." );
1136 $mw
.init_done
= true;
1137 // Handle the execution of queued functions with jQuery "ready"
1139 // Check if this page has a video, audio or playlist tag
1141 document
.getElementsByTagName( "video" ),
1142 document
.getElementsByTagName( "audio" ),
1143 document
.getElementsByTagName( "playlist" )
1145 if( e
[0].length
!= 0 || e
[1].length
!= 0 || e
[2].length
!= 0 ) {
1146 //look for any skin classes we have to load:
1149 if(e
[j
][k
] && typeof( e
[j
][k
]) == 'object'){
1150 var sn
= e
[j
][k
].getAttribute('class');
1151 if( sn
&& sn
!= ''){
1152 for(var n
=0;n
< $mw
.valid_skins
.length
;n
++){
1153 if( sn
.indexOf($mw
.valid_skins
[n
]) !== -1){
1154 $mw
.skin_list
.push( $mw
.valid_skins
[n
] );
1161 // Load libs and process videos
1162 mvJsLoader
.embedVideoCheck( function() {
1163 // Run any queued global events:
1164 mv_video_embed( function() {
1165 mvJsLoader
.runQueuedFunctions();
1169 mvJsLoader
.runQueuedFunctions();
1173 //js2AddOnloadHook: ensure jQuery and the DOM are ready
1174 function js2AddOnloadHook( func
) {
1175 //js_log('js2AddOnloadHook::' );
1176 // If we have already run the DOM-ready function, just run the function directly:
1177 if( mvJsLoader
.doneReadyEvents
) {
1180 mvJsLoader
.jQueryCheck( function() {
1181 mvJsLoader
.addLoadEvent( func
);
1185 // Deprecated mwAddOnloadHook in favor of js2 naming (for clear separation of js2 code from old MW code
1186 var mwAddOnloadHook
= js2AddOnloadHook
;
1188 * This function allows for targeted rewriting
1190 function rewrite_by_id( vid_id
, ready_callback
) {
1191 js_log( 'f:rewrite_by_id: ' + vid_id
);
1192 // Force a re-check of the DOM for playlist or video elements:
1193 mvJsLoader
.embedVideoCheck( function() {
1194 mv_video_embed( ready_callback
, vid_id
);
1199 /*********** INITIALIZATION CODE *************
1200 * set DOM-ready callback to init_mv_embed
1201 *********************************************/
1202 // for Mozilla / modern browsers
1203 if ( document
.addEventListener
) {
1204 document
.addEventListener( "DOMContentLoaded", mwdomReady
, false );
1207 if( window
.onload
) {
1208 temp_f
= window
.onload
;
1210 // Use the onload method as a backup
1211 window
.onload = function () {
1218 * Store all the mwEmbed jQuery-specific bindings
1219 * (set up after jQuery is available).
1221 * These functions are genneraly are loaders that do the dynamic mapping of
1222 * dependencies for a given commponet
1226 function mv_jqueryBindings() {
1227 js_log( 'mv_jqueryBindings' );
1230 * dragDrop file loader
1232 $.fn
.dragFileUpload = function ( conf
){
1233 if( this.selector
){
1235 //load the dragger and "setup"
1236 $mw
.load( ['$j.fn.dragDropFile'], function(){
1237 $j(_this
.selector
).dragDropFile();
1242 * apiProxy Loader loader:
1244 * @param mode is either 'server' or 'client'
1246 $.apiProxy = function( mode
, pConf
, callback
){
1247 js_log('do apiProxy setup');
1248 mvJsLoader
.doLoad( [
1252 //do the proxy setup or
1253 if( mode
== 'client'){
1254 //just do the setup (no callbcak for client setup)
1255 $mw
.proxy
.client( pConf
);
1258 }else if( mode
=='server' ){
1259 //do the request with the callback
1260 $mw
.proxy
.server( pConf
, callback
);
1265 //non selector based add-media-wizard direct invocation with loader
1266 $.addMediaWiz = function( iObj
, callback
){
1267 js_log(".addMediaWiz call");
1268 //check if already loaded:
1269 if( _global
['rsdMVRS'] ){
1270 _global
['rsdMVRS'].doReDisplay();
1272 callback( _global
['rsdMVRS'] );
1276 $.addLoaderDialog( gM('mwe-loading-add-media-wiz') );
1277 //load the addMedia wizard without a target:
1278 $.fn
.addMediaWiz ( iObj
, function( amwObj
){
1280 $.closeLoaderDialog();
1281 //do the add-media-wizard display
1282 amwObj
.doInitDisplay();
1283 //call the parent callback:
1285 callback( _global
['rsdMVRS'] );
1288 $.fn
.addMediaWiz = function( iObj
, callback
) {
1289 if( this.selector
){
1290 // First set the cursor for the button to "loading"
1291 $j( this.selector
).css( 'cursor', 'wait' ).attr( 'title', gM( 'mwe-loading_txt' ) );
1293 iObj
['target_invocation'] = this.selector
;
1296 // Load the mv_embed_base skin:
1297 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1298 loadExternalCss( mv_embed_path
+ 'skins/' + $mw
.conf
['skin_name'] + '/styles.css' );
1299 // Load all the required libs:
1300 mvJsLoader
.jQueryCheck( function() {
1301 // Load with staged dependencies (for IE that does not execute in order)
1302 mvJsLoader
.doLoadDepMode([
1303 [ 'remoteSearchDriver',
1314 iObj
['instance_name'] = 'rsdMVRS';
1315 if( ! _global
['rsdMVRS'] )
1316 _global
['rsdMVRS'] = new remoteSearchDriver( iObj
);
1318 callback( _global
['rsdMVRS'] );
1326 $.fn
.sequencer = function( iObj
, callback
) {
1328 iObj
['target_sequence_container'] = this.selector
;
1329 // Issue a request to get the CSS file (if not already included):
1330 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1331 loadExternalCss( mv_embed_path
+ 'skins/' + $mw
.conf
['skin_name'] + '/mv_sequence.css' );
1332 // Make sure we have the required mv_embed libs (they are not loaded when no video
1333 // element is on the page)
1334 mvJsLoader
.embedVideoCheck( function() {
1335 // Load the playlist object and then the jQuery UI stuff:
1336 mvJsLoader
.doLoadDepMode([
1349 '$j.ui.progressbar',
1356 js_log( 'calling new mvSequencer' );
1357 // Initialise the sequence object (it will take over from there)
1358 // No more than one mvSeq obj for now:
1359 if( !_global
['mvSeq'] ) {
1360 _global
['mvSeq'] = new mvSequencer( iObj
);
1362 js_log( 'mvSeq already init' );
1368 * The Firefogg jQuery function:
1369 * @@note This Firefogg invocation could be made to work more like real jQuery plugins
1371 var queuedFirefoggConf
= {};
1372 $.fn
.firefogg = function( iObj
, callback
) {
1375 // Add the base theme CSS:
1376 loadExternalCss( mv_jquery_skin_path
+ 'jquery-ui-1.7.1.custom.css' );
1377 loadExternalCss( mv_embed_path
+ 'skins/' + $mw
.conf
['skin_name'] + '/styles.css' );
1379 // Check if we already have Firefogg loaded (the call just updates the element's
1381 var sElm
= $j( this.selector
).get( 0 );
1382 if( sElm
['firefogg'] ) {
1383 if( sElm
['firefogg'] == 'loading' ) {
1384 js_log( "Queued firefogg operations ( firefogg " +
1385 "not done loading ) " );
1386 $j
.extend( queuedFirefoggConf
, iObj
);
1389 // Update properties
1390 for( var i
in iObj
) {
1391 js_log( "firefogg::updated: " + i
+ ' to '+ iObj
[i
] );
1392 sElm
['firefogg'][i
] = iObj
[i
];
1394 return sElm
['firefogg'];
1397 sElm
['firefogg'] = 'loading';
1400 iObj
['selector'] = this.selector
;
1404 'mvBaseUploadInterface',
1409 '$j.ui.progressbar',
1414 if( iObj
.encoder_interface
) {
1423 // Make sure we have everything loaded that we need:
1424 mvJsLoader
.doLoadDepMode( loadSet
, function() {
1425 js_log( 'firefogg libs loaded. target select:' + iObj
.selector
);
1426 // Select interface provider based on whether we want to include the
1427 // encoder interface or not
1428 if( iObj
.encoder_interface
) {
1429 var myFogg
= new mvAdvFirefogg( iObj
);
1431 var myFogg
= new mvFirefogg( iObj
);
1434 myFogg
.doRewrite( callback
);
1435 var selectorElement
= $j( iObj
.selector
).get( 0 );
1436 selectorElement
['firefogg'] = myFogg
;
1438 js_log('pre:'+ selectorElement
['firefogg']['firefogg_form_action'])
1439 if(queuedFirefoggConf
)
1440 $j
.extend(selectorElement
['firefogg'], queuedFirefoggConf
);
1441 js_log('post:'+ selectorElement
['firefogg']['firefogg_form_action'])
1445 // Take an input player as the selector and expose basic rendering controls
1446 $.fn
.firefoggRender = function( iObj
, callback
) {
1447 // Check if we already have render loaded then just pass on updates/actions
1448 var sElm
= $j( this.selector
).get( 0 );
1449 if( sElm
['fogg_render'] ) {
1450 if( sElm
['fogg_render'] == 'loading' ) {
1451 js_log( "Error: called firefoggRender while loading" );
1454 // Call or update the property:
1456 sElm
['fogg_render'] = 'loading';
1458 iObj
['player_target'] = this.selector
;
1463 sElm
['fogg_render'] = new mvFirefoggRender( iObj
);
1464 if( callback
&& typeof callback
== 'function' )
1465 callback( sElm
['fogg_render'] );
1469 $.fn
.baseUploadInterface = function(iObj
) {
1470 mvJsLoader
.doLoadDepMode([
1472 'mvBaseUploadInterface',
1476 '$j.ui.progressbar',
1480 myUp
= new mvBaseUploadInterface( iObj
);
1485 // Shortcut to a themed button
1486 $.btnHtml = function( msg
, className
, iconId
, opt
) {
1489 var href
= (opt
.href
) ? opt
.href
: '#';
1490 var target_attr
= (opt
.target
) ? ' target="' + opt
.target
+ '" ' : '';
1491 var style_attr
= (opt
.style
) ? ' style="' + opt
.style
+ '" ' : '';
1492 return '<a href="' + href
+ '" ' + target_attr
+ style_attr
+
1493 ' class="ui-state-default ui-corner-all ui-icon_link ' +
1494 className
+ '"><span class="ui-icon ui-icon-' + iconId
+ '" />' +
1495 '<span class="btnText">'+ msg
+'<span></a>';
1497 // Shortcut to bind hover state
1498 $.fn
.btnBind = function() {
1501 $j( this ).addClass( 'ui-state-hover' );
1504 $j( this ).removeClass( 'ui-state-hover' );
1510 * resize the dialog to fit the window
1512 $.fn
.dialogFitWindow = function(opt
){
1513 var opt_default
= {'hspace':50,'vspace':50};
1516 $j
.extend(opt
, opt_default
);
1517 $j( this.selector
).dialog('option', 'width', $j(window
).width() - opt
.hspace
);
1518 $j( this.selector
).dialog('option', 'height', $j(window
).height() - opt
.vspace
);
1519 $j( this.selector
).dialog('option', 'position','center');
1520 //update the child position: (some of this should be pushed up-stream via dialog config options
1521 $j( this.selector
+'~ .ui-dialog-buttonpane').css({
1522 'position':'absolute',
1531 * small helper for putting a loading dialog box on top of everything
1532 * (helps block for request that
1534 * @param msg text text of the loader msg
1536 $.addLoaderDialog = function( msg_txt
){
1537 $.addDialog( msg_txt
, msg_txt
+ '<br>' + mv_get_loading_img() );
1540 $.addDialog = function ( title
, msg_txt
, btn
){
1541 $('#mwe_tmp_loader').remove();
1542 //append the style free loader ontop:
1543 $('body').append('<div id="mwe_tmp_loader" style="display:none" title="' + title
+ '" >' +
1546 //special btn == ok gives empty give a single "oky" -> "close"
1548 btn
[ gM('mwe-ok') ] = function(){
1549 $j('#mwe_tmp_loader').close();
1552 //turn the loader into a real dialog loader:
1553 mvJsLoader
.doLoadDepMode([
1561 $('#mwe_tmp_loader').dialog({
1571 $.closeLoaderDialog = function(){
1572 mvJsLoader
.doLoadDepMode([
1580 $j('#mwe_tmp_loader').dialog('close');
1584 $.mwProxy = function( apiConf
){
1585 mvJsLoader
.doLoad( ['$mw.apiProxy'],
1587 $mw
.apiProxy( apiConf
);
1593 * Utility functions:
1595 // Simple URL rewriter (could probably be refactored into an inline regular exp)
1596 function getURLParamReplace( url
, opt
) {
1597 var pSrc
= parseUri( url
);
1598 if( pSrc
.protocol
!= '' ) {
1599 var new_url
= pSrc
.protocol
+ '://' + pSrc
.authority
+ pSrc
.path
+ '?';
1601 var new_url
= pSrc
.path
+ '?';
1604 for( var key
in pSrc
.queryKey
) {
1605 var val
= pSrc
.queryKey
[ key
];
1606 // Do override if requested
1609 new_url
+= amp
+ key
+ '=' + val
;
1612 // Add any vars that were not already there:
1613 for( var i
in opt
) {
1614 if( !pSrc
.queryKey
[i
] ) {
1615 new_url
+= amp
+ i
+ '=' + opt
[i
];
1622 * Given a float number of seconds, returns npt format response.
1624 * @param float Seconds
1625 * @param boolean If we should show milliseconds or not.
1627 function seconds2npt( sec
, show_ms
) {
1628 if( isNaN( sec
) ) {
1629 // js_log("warning: trying to get npt time on NaN:" + sec);
1632 var hours
= Math
.floor( sec
/ 3600 );
1633 var minutes
= Math
.floor( (sec
/ 60) % 60 );
1634 var seconds
= sec
% 60;
1635 // Round the number of seconds to the required number of significant digits
1637 seconds
= Math
.round( seconds
* 1000 ) / 1000;
1639 seconds
= Math
.round( seconds
);
1642 seconds
= '0' + seconds
;
1644 minutes
= '0' + minutes
;
1646 return hours
+ ":" + minutes
+ ":" + seconds
;
1649 * Take hh:mm:ss,ms or hh:mm:ss.ms input, return the number of seconds
1651 function npt2seconds( npt_str
) {
1653 //js_log('npt2seconds:not valid ntp:'+ntp);
1656 // Strip "npt:" time definition if present
1657 npt_str
= npt_str
.replace( 'npt:', '' );
1659 times
= npt_str
.split( ':' );
1660 if( times
.length
!= 3 ){
1661 js_log( 'error: npt2seconds on ' + npt_str
);
1664 // Sometimes a comma is used instead of period for ms
1665 times
[2] = times
[2].replace( /,\s?/, '.' );
1666 // Return seconds float
1667 return parseInt( times
[0] * 3600) + parseInt( times
[1] * 60 ) + parseFloat( times
[2] );
1670 * Simple helper to grab an edit token
1672 * @param title The wiki page title you want to edit
1673 * @param api_url 'optional' The target API URL
1674 * @param callback The callback function to pass the token to
1676 function get_mw_token( title
, api_url
, callback
) {
1677 js_log( ':get_mw_token:' );
1678 if( !title
&& wgUserName
) {
1679 title
= 'User:' + wgUserName
;
1691 for( var i
in data
.query
.pages
) {
1692 if( data
.query
.pages
[i
]['edittoken'] ) {
1693 if( typeof callback
== 'function' )
1694 callback ( data
.query
.pages
[i
]['edittoken'] );
1702 // Do a remote or local API request based on request URL
1703 //@param options: url, data, cbParam, callback
1704 function do_api_req( options
, callback
) {
1705 if( typeof options
.data
!= 'object' ) {
1706 return js_error( 'Error: request paramaters must be an object' );
1708 // Generate the URL if it's missing
1709 if( typeof options
.url
== 'undefined' || !options
.url
) {
1710 if( !wgServer
|| ! wgScriptPath
) {
1711 return js_error('Error: no api url for api request');
1713 options
.url
= mwGetLocalApiUrl();
1715 if( typeof options
.data
== 'undefined' )
1718 // Force format to JSON
1719 options
.data
['format'] = 'json';
1721 // If action is not set, assume query
1722 if( ! options
.data
['action'] )
1723 options
.data
['action'] = 'query';
1725 // js_log('do api req: ' + options.url +'?' + jQuery.param(options.data) );
1726 if( options
.url
== 'proxy' && $mw
.proxy
){
1727 //assume the proxy is already "setup" since $mw.proxy is defined.
1728 // @@todo we probably integrate that setup into the api call
1729 $mw
.proxy
.doRequest( options
.data
, callback
);
1730 }else if( parseUri( document
.URL
).host
== parseUri( options
.url
).host
) {
1731 // Local request: do API request directly
1736 dataType
: 'json', // API requests _should_ always return JSON data:
1738 success: function( data
) {
1741 error: function( e
) {
1742 js_error( ' error' + e
+ ' in getting: ' + options
.url
);
1747 // Set the callback param if it's not already set
1748 if( typeof options
.jsonCB
== 'undefined' )
1749 options
.jsonCB
= 'callback';
1751 var req_url
= options
.url
;
1752 var paramAnd
= ( req_url
.indexOf( '?' ) == -1 ) ? '?' : '&';
1753 // Put all the parameters into the URL
1754 for( var i
in options
.data
) {
1755 req_url
+= paramAnd
+ encodeURIComponent( i
) + '=' + encodeURIComponent( options
.data
[i
] );
1758 var fname
= 'mycpfn_' + ( $mw
.cb_count
++ );
1759 _global
[ fname
] = callback
;
1760 req_url
+= '&' + options
.jsonCB
+ '=' + fname
;
1761 loadExternalJs( req_url
);
1764 function mwGetLocalApiUrl( url
) {
1765 if ( wgServer
&& wgScriptPath
) {
1766 return wgServer
+ wgScriptPath
+ '/api.php';
1770 // Do a "normal" request
1771 function do_request( req_url
, callback
) {
1772 js_log( 'do_request::req_url:' + req_url
+ ' != ' + parseUri( req_url
).host
);
1773 // If we are doing a request to the same domain or relative link, do a normal GET
1774 if( parseUri( document
.URL
).host
== parseUri( req_url
).host
||
1775 req_url
.indexOf('://') == -1 ) // Relative url
1777 // Do a direct request
1782 success: function( data
) {
1787 // Get data via DOM injection with callback
1788 global_req_cb
.push( callback
);
1789 // Prepend json_ to feed_format if not already requesting json format (metavid specific)
1790 if( req_url
.indexOf( "feed_format=" ) != -1 && req_url
.indexOf( "feed_format=json" ) == -1 )
1791 req_url
= req_url
.replace( /feed_format=/, 'feed_format=json_' );
1793 loadExternalJs( req_url
+ '&cb=mv_jsdata_cb&cb_inx=' + (global_req_cb
.length
- 1) );
1797 function mv_jsdata_cb( response
) {
1798 js_log( 'f:mv_jsdata_cb:'+ response
['cb_inx'] );
1799 // Run the callback from the global request callback object
1800 if( !global_req_cb
[response
['cb_inx']] ) {
1801 js_log( 'missing req cb index' );
1804 if( !response
['pay_load'] ) {
1805 js_log( "missing pay load" );
1808 switch( response
['content-type'] ) {
1812 if( typeof response
['pay_load'] == 'string' ) {
1813 //js_log('load string:'+"\n"+ response['pay_load']);
1815 if( $j
.browser
.msie
) {
1816 // Attempt to parse as XML for IE
1817 var xmldata
= new ActiveXObject("Microsoft.XMLDOM");
1818 xmldata
.async
= "false";
1819 xmldata
.loadXML( response
['pay_load'] );
1821 // For others (Firefox, Safari etc.)
1823 var xmldata
= (new DOMParser()).parseFromString( response
['pay_load'], "text/xml" );
1825 js_log( 'XML parse ERROR: ' + e
.message
);
1828 //@@todo handle XML parser errors
1829 if( xmldata
)response
['pay_load'] = xmldata
;
1833 js_log( 'bad response type' + response
['content-type'] );
1837 global_req_cb
[response
['cb_inx']]( response
['pay_load'] );
1839 // Load external JS via DOM injection
1840 function loadExternalJs( url
, callback
) {
1841 js_log( 'load js: '+ url
);
1842 //if(window['$j']) // use jquery call:
1850 var e
= document
.createElement( "script" );
1851 e
.setAttribute( 'src', url
);
1852 e
.setAttribute( 'type', "text/javascript" );
1854 e.onload = callback;
1856 //e.setAttribute('defer', true);
1857 document
.getElementsByTagName( "head" )[0].appendChild( e
);
1860 function styleSheetPresent( url
) {
1861 style_elements
= document
.getElementsByTagName( 'link' );
1862 if( style_elements
.length
> 0 ) {
1863 for( i
= 0; i
< style_elements
.length
; i
++ ) {
1864 if( style_elements
[i
].href
== url
)
1870 function loadExternalCss( url
) {
1871 // We could have the script loader group these CSS requests.
1872 // But it's debatable: it may hurt more than it helps with caching and all
1873 if( typeof url
=='object' ) {
1874 for( var i
in url
) {
1875 loadExternalCss( url
[i
] );
1880 if( url
.indexOf('?') == -1 ) {
1881 url
+= '?' + getMwReqParam();
1883 if( !styleSheetPresent( url
) ) {
1884 js_log( 'load css: ' + url
);
1885 var e
= document
.createElement( "link" );
1887 e
.type
= "text/css";
1888 e
.rel
= 'stylesheet';
1889 document
.getElementsByTagName( "head" )[0].appendChild( e
);
1892 function getMvEmbedURL() {
1893 if( _global
['mv_embed_url'] )
1894 return _global
['mv_embed_url'];
1895 var js_elements
= document
.getElementsByTagName( "script" );
1896 for( var i
= 0; i
< js_elements
.length
; i
++ ) {
1897 // Check for mv_embed.js and/or script loader
1898 var src
= js_elements
[i
].getAttribute( "src" );
1900 if( src
.indexOf( 'mv_embed.js' ) != -1 || (
1901 ( src
.indexOf( 'mwScriptLoader.php' ) != -1 || src
.indexOf('jsScriptLoader.php') != -1 )
1902 && src
.indexOf('mv_embed') != -1) ) //(check for class=mv_embed script_loader call)
1904 _global
['mv_embed_url'] = src
;
1909 js_error( 'Error: getMvEmbedURL failed to get Embed Path' );
1912 // Get a unique request ID to ensure fresh JavaScript
1913 function getMwReqParam() {
1914 if( _global
['req_param'] )
1915 return _global
['req_param'];
1916 var mv_embed_url
= getMvEmbedURL();
1920 // If we have a URI, add it to the req
1921 var urid
= parseUri( mv_embed_url
).queryKey
['urid']
1922 // If we're in debug mode, get a fresh unique request key and pass on "debug" param
1923 if( parseUri( mv_embed_url
).queryKey
['debug'] == 'true' ){
1925 req_param
+= 'urid=' + d
.getTime() + '&debug=true';
1927 // Set from request urid:
1928 req_param
+= 'urid=' + urid
;
1930 // Otherwise, just use the mv_embed version
1931 req_param
+= 'urid=' + $mw
.version
;
1933 //add the lang param:
1934 var langKey
= parseUri( mv_embed_url
).queryKey
['uselang'];
1936 req_param
+= '&uselang=' + langKey
;
1938 _global
['req_param'] = req_param
;
1940 return _global
['req_param'];
1943 * Set the global mv_embed path based on the script's location
1945 function getMvEmbedPath() {
1946 if( _global
['mv_embed_path'] )
1947 return _global
['mv_embed_path'];
1948 var mv_embed_url
= getMvEmbedURL();
1949 if( mv_embed_url
.indexOf( 'mv_embed.js' ) !== -1 ) {
1950 mv_embed_path
= mv_embed_url
.substr( 0, mv_embed_url
.indexOf( 'mv_embed.js' ) );
1951 } else if( mv_embed_url
.indexOf( 'mwScriptLoader.php' ) !== -1 ) {
1952 // Script loader is in the root of MediaWiki, so include the default mv_embed extension path
1953 mv_embed_path
= mv_embed_url
.substr( 0, mv_embed_url
.indexOf( 'mwScriptLoader.php' ) )
1954 + mediaWiki_mvEmbed_path
;
1956 mv_embed_path
= mv_embed_url
.substr( 0, mv_embed_url
.indexOf( 'jsScriptLoader.php' ) );
1958 // Make an absolute URL (if it's relative and we don't have an mv_embed path)
1959 if( mv_embed_path
.indexOf( '://' ) == -1 ) {
1960 var pURL
= parseUri( document
.URL
);
1961 if( mv_embed_path
.charAt( 0 ) == '/' ) {
1962 mv_embed_path
= pURL
.protocol
+ '://' + pURL
.authority
+ mv_embed_path
;
1965 if( mv_embed_path
== '' ) {
1966 mv_embed_path
= pURL
.protocol
+ '://' + pURL
.authority
+ pURL
.directory
+ mv_embed_path
;
1970 _global
['mv_embed_path'] = mv_embed_path
;
1971 return mv_embed_path
;
1974 if ( typeof DOMParser
== "undefined" ) {
1975 DOMParser = function () {}
1976 DOMParser
.prototype.parseFromString = function ( str
, contentType
) {
1977 if ( typeof ActiveXObject
!= "undefined" ) {
1978 var d
= new ActiveXObject( "MSXML.DomDocument" );
1981 } else if ( typeof XMLHttpRequest
!= "undefined" ) {
1982 var req
= new XMLHttpRequest
;
1983 req
.open( "GET", "data:" + (contentType
|| "application/xml") +
1984 ";charset=utf-8," + encodeURIComponent(str
), false );
1985 if ( req
.overrideMimeType
) {
1986 req
.overrideMimeType(contentType
);
1989 return req
.responseXML
;
1996 function js_log( string
) {
1997 ///add any prepend debug strings if nessesary (used for cross browser)
1998 if( $mw
.conf
['debug_pre'] )
1999 string
= $mw
.conf
['debug_pre']+ string
;
2001 if( window
.console
) {
2002 window
.console
.log( string
);
2005 * IE and non-Firebug debug:
2007 /*var log_elm = document.getElementById('mv_js_log');
2009 document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML +
2010 '<div style="position:absolute;z-index:500;top:0px;left:0px;right:0px;height:10px;">'+
2011 '<textarea id="mv_js_log" cols="120" rows="5"></textarea>'+
2014 var log_elm = document.getElementById('mv_js_log');
2017 log_elm.value+=string+"\n";
2023 function js_error( string
) {