* some upload from remote api improvements
[lhc/web/wiklou.git] / js2 / mwEmbed / mv_embed.js
1 /*
2 * ~mv_embed ~
3 * For details see: http://metavid.org/wiki/index.php/Mv_embed
4 *
5 * All Metavid Wiki code is released under the GPL2.
6 * For more information visit http://metavid.org/wiki/Code
7 *
8 * @url http://metavid.org
9 *
10 * parseUri:
11 * http://stevenlevithan.com/demo/parseuri/js/
12 *
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)
15 *
16 */
17 // Fix multiple instances of mv_embed (i.e. include twice from two different servers)
18 var MV_DO_INIT=true;
19 if( MV_EMBED_VERSION ){
20 MV_DO_INIT=false;
21 }
22 // Used to grab fresh copies of scripts.
23 var MV_EMBED_VERSION = '1.0r20';
24
25 /*
26 * Configuration variables should be set by extending mwConfigOptions
27 * here is the default config:
28 */
29 var mwDefaultConfig = {
30 'skin_name': 'mvpcf',
31 'jui_skin': 'redmond',
32 'video_size':'400x300'
33 }
34
35 // (We install the default config values for anything not set in mwConfig once we know we have jquery)
36 if( !mwConfig )
37 var mwConfig = {};
38
39 // parseUri 1.2.2
40 // (c) Steven Levithan <stevenlevithan.com>
41 // MIT License
42 function parseUri (str) {
43 var o = parseUri.options,
44 m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
45 uri = {},
46 i = 14;
47
48 while (i--) uri[o.key[i]] = m[i] || "";
49
50 uri[o.q.name] = {};
51 uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
52 if ($1) uri[o.q.name][$1] = $2;
53 });
54
55 return uri;
56 };
57 parseUri.options = {
58 strictMode: false,
59 key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
60 q: {
61 name: "queryKey",
62 parser: /(?:^|&)([^&=]*)=?([^&]*)/g
63 },
64 parser: {
65 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
66 loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
67 }
68 };
69
70 // For use when mv_embed with script-loader is in the root MediaWiki path
71 var mediaWiki_mvEmbed_path = 'js2/mwEmbed/';
72
73 var _global = this; // Global obj (depreciate use window)
74
75 /*
76 * setup the empty global $mw object
77 * will ensure all our functions are properly namespaced
78 */
79 if(!window['$mw']){
80 window['$mw'] = {}
81 }
82
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
88
89 // Get the mv_embed location if it has not been set
90 if( !mv_embed_path ) {
91 var mv_embed_path = getMvEmbedPath();
92 }
93 /**
94 * wrap the global $mw object here:
95 *
96 * Any global functions/classes that are not jQuery plugins should make
97 * there way into the $mw namespace
98 */
99 (function( $ ) {
100 /*
101 * Language classes $mw.lang
102 *
103 * Localized Language support attempts to mirror the functionality of Language.php in MediaWiki
104 * It contains methods for loading and transforming msg text
105 *
106 */
107 $.lang = {};
108 /**
109 * Setup the lang object
110 */
111 var gMsg = {};
112 var gRuleSet = {};
113
114 /**
115 * loadGM function
116 * Loads a set of json messages into the lng object.
117 *
118 * @param json msgSet The set of msgs to be loaded
119 */
120 $.lang.loadGM = function( msgSet ){
121 for( var i in msgSet ) {
122 gMsg[ i ] = msgSet[i];
123 }
124 },
125
126 /**
127 * loadRS function
128 * Loads a ruleset by given template key ie PLURAL : { //ruleSetObj }
129 *
130 * @param json ruleSet The ruleset object ( extends gRuleSet )
131 */
132 $.lang.loadRS = function( ruleSet ){
133 for( var i in ruleSet){
134 gRuleSet[ i ] = ruleSet[ i ];
135 }
136 }
137
138 /**
139 * Returns a transformed msg string
140 *
141 * it take a msg key and array of replacement values of form
142 * $1, $2 and does relevant msgkey transformation returning
143 * the user msg.
144 *
145 * @param string key The msg key as set by loadGm
146 * @param [mixed] args An array of replacement strings
147 * @return string
148 */
149 $.lang.gM = function( key , args ) {
150 if(! gMsg[ key ])
151 return '&lt;' + key + '&gt;';// Missing key placeholder
152
153 //swap in the arg values
154 var ms = $.lang.gMsgSwap( key, args) ;
155
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){
159 return ms;
160 //return ms;
161 }
162
163 //make sure we have the lagMagic setup:
164 $.lang.magicSetup();
165 //send the msg key through the parser
166 pObj = $.parser.pNew( ms );
167 //return the transformed msg
168 return pObj.getHTML();
169 }
170 /**
171 * gMsgSwap
172 *
173 * @param string key The msg key as set by loadGm
174 * @param [mixed] args An array or string to be replaced
175 * @return string
176 */
177 $.lang.gMsgSwap = function( key , args ){
178 if(! gMsg[ key ])
179 return '&lt;' + key + '&gt;';// Missing key placeholder
180 //get the messege string:
181 var ms = gMsg[ key ];
182
183 //replace values
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] );
189 }
190 } else if( typeof args =='string' || typeof args =='number' ) {
191 ms = ms.replace(/\$1/g, args);
192 }
193 return ms;
194 }
195
196 /**
197 * gMsgNoTrans
198 *
199 * @returns string The msg key without transforming it
200 */
201 $.lang.gMsgNoTrans = function( key ){
202 if( gMsg[ key ] )
203 return gMsg[ key ]
204
205 // Missing key placeholder
206 return '&lt;' + key + '&gt;';
207 }
208 /**
209 * Add Supported Magic Words to parser
210 */
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
217 })
218
219 $.lang.doneSetup = true;
220 }
221
222 }
223 /**
224 * Process the PLURAL special language template key:
225 */
226 $.lang.procPLURAL = function( tObj ){
227 //setup shortcuts
228 // (gRuleSet is loaded from script-loader to contains local ruleset)
229 var rs = gRuleSet['PLURAL'];
230
231 /*
232 * Plural matchRuleTest
233 */
234 function matchRuleTest(cRule, val){
235 js_log("matchRuleTest:: " + typeof cRule + ' ' + cRule + ' == ' + val );
236
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] )
242 return true;
243 }
244 }
245 //else do a direct compare
246 if(compare == val){
247 return true;
248 }
249 return false;
250 }
251 //check for simple cRule type:
252 if( typeof cRule == 'number'){
253 return ( parseInt( val ) == parseInt( cRule) );
254 }else if( typeof cRule == 'object' ){
255 var cmatch = {};
256 //if a list we need to match all for rule match
257 for(var i in cRule){
258 var cr = cRule[i];
259 //set cr type
260 var crType = '';
261 for( var j in cr ){
262 if(j == 'mod')
263 crType = 'mod'
264 }
265 switch(crType){
266 case 'mod':
267 if( cr ['is'] ){
268 if( checkValue( val % cr['mod'], cr ['is'] ) )
269 cmatch[i] = true;
270 }else if( cr['not']){
271 if( ! checkValue( val % cr['mod'], cr ['not'] ) )
272 cmatch[i] = true;
273 }
274 break;
275 }
276 }
277 //check all the matches (taking into consideration "or" order)
278 for(var i in cRule){
279 if( ! cmatch[i] )
280 return false;
281 }
282 return true;
283
284 }
285 }
286 /**
287 * Maps a given rule Index to template params:
288 *
289 * if index is out of range return last param
290 * @param
291 */
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 ];
298 }
299 var rCount=0
300 //run the actual rule lookup:
301 for(var ruleInx in rs){
302 cRule = rs[ruleInx];
303 if( matchRuleTest( cRule, tObj.arg ) ){
304 js_log("matched rule: " + ruleInx );
305 return getTempParamFromRuleInx(tObj, rCount );
306 }
307 rCount ++;
308 }
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 ];
312 }
313
314 /**
315 * gMsgLoadRemote loads remote msg strings
316 *
317 * @param mixed msgSet the set of msg to load remotely
318 * @param function callback the callback to issue once string is ready
319 */
320 $.lang.gMsgLoadRemote = function( msgSet, callback ) {
321 var ammessages = '';
322 if( typeof msgSet == 'object' ) {
323 for( var i in msgSet ) {
324 ammessages += msgSet[i] + '|';
325 }
326 } else if( typeof msgSet == 'string' ) {
327 ammessages += msgSet;
328 }
329 if( ammessages == '' ) {
330 js_log( 'gMsgLoadRemote: no message set requested' );
331 return false;
332 }
333 do_api_req({
334 'data': {
335 'meta': 'allmessages',
336 'ammessages': ammessages
337 }
338 }, function( data ) {
339 if( data.query.allmessages ) {
340 var msgs = data.query.allmessages;
341 for( var i in msgs ) {
342 var ld = {};
343 ld[ msgs[i]['name'] ] = msgs[i]['*'];
344 loadGM( ld );
345 }
346 }
347 callback();
348 });
349 }
350 /**
351 * Format a size in bytes for output, using an appropriate
352 * unit (B, KB, MB or GB) according to the magnitude in question
353 *
354 * @param size Size to format
355 * @return string Plain text (not HTML)
356 */
357 $.lang.formatSize = function ( size ) {
358 // For small sizes no decimal places are necessary
359 var round = 0;
360 var msg = '';
361 if( size > 1024 ) {
362 size = size / 1024;
363 if( size > 1024 ) {
364 size = size / 1024;
365 // For MB and bigger two decimal places are smarter
366 round = 2;
367 if( size > 1024 ) {
368 size = size / 1024;
369 msg = 'mwe-size-gigabytes';
370 } else {
371 msg = 'mwe-size-megabytes';
372 }
373 } else {
374 msg = 'mwe-size-kilobytes';
375 }
376 } else {
377 msg = 'mwe-size-bytes';
378 }
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 );
384 };
385
386
387 /**
388 * MediaWiki wikitext "Parser"
389 *
390 * This is not feature complete but we need a way to get at template properties
391 *
392 *
393 * @param wikiText the wikitext to be parsed
394 * @return parserObj returns a parser object that has methods for getting at
395 * things you would want
396 */
397 $.parser = {};
398 var pMagicSet = {};
399 /**
400 * parser addMagic
401 *
402 * lets you add a set of magic keys and associated callback funcions
403 * callback: @param ( Object Template )
404 * callback: @return the transformed template output
405 *
406 * @param object magicSet key:callback
407 */
408 $.parser.addMagic = function( magicSet ){
409 for(var i in magicSet)
410 pMagicSet[ i ] = magicSet[i];
411 }
412
413 //actual parse call (returns parser object)
414 $.parser.pNew = function( wikiText, opt ){
415 var parseObj = function( wikiText, opt){
416 return this.init( wikiText, opt )
417 }
418 parseObj.prototype = {
419 //the wikiText "DOM"... stores the parsed wikiText structure
420 //wtDOM : {}, (not yet supported )
421
422 pOut : '', //the parser output string container
423 init :function( wikiText ){
424 this.wikiText = wikiText;
425 },
426 updateText : function( wikiText ){
427 this.wikiText = wikiText;
428 //invalidate the output (will force a reparse)
429 this.pOut = '';
430 },
431 parse : function(){
432 this.pObj = {};
433 this.pObj.tmpl = new Array();
434
435 //refrences for swap key
436 this.pObj.tmpl_text = new Array();
437 this.pObj.tmpl_key = new Array();
438 this.pObj.tmpl_ns = '' ; // wikiText with place-holder
439
440 //get templates losly based on Magnus_Manske/tmpl.js code:
441 var tcnt = 0 ;
442 var ts = '' ;
443 var curt = 0 ;
444 var schar = 0;
445
446
447 //build out nested template holders:
448 var depth = 0;
449 var tKey = 0;
450 var ns = '';
451
452 /*
453 * quickly recursive / parse out templates with top down recurse decent
454 */
455
456 // ~ probably a better algorithm out there / should mirror php parser flow ~
457 // ... but I am having fun with recursion so here it is...
458 function rdpp ( txt ){
459 var node = {};
460 //if we should output node text
461 var ont = true;
462 //inspect each char
463 for(var a=0; a < txt.length; a++){
464 if( txt[a] == '{' && txt[a+1] == '{' ){
465 a=a+2;
466 node['p'] = node;
467 if(!node['c'])
468 node['c'] = new Array();
469
470 node['c'].push( rdpp( txt.substr( a ) ) );
471 ont=true;
472 }else if( txt[a] == '}' && txt[a+1] == '}'){
473 if( !node['p'] ){
474 return node;
475 }
476 node = node['p'];
477 ont=false;
478 a=a+2;
479 }
480 if(!node['t'])
481 node['t']='';
482
483 if( txt[a] )
484 node['t']+=txt[a];
485 }
486 return node;
487 }
488 /**
489 * parse template text as template name and named params
490 */
491 function parseTmplTxt( ts ){
492 var tObj = {};
493 //Get template name:
494 tname = ts.split('\|').shift() ;
495 tname = tname.split('\{').shift() ;
496 tname = tname.replace( /^\s+|\s+$/g, "" ); //trim
497
498 //check for arguments:
499 if( tname.split(':').length == 1 ){
500 tObj["name"] = tname;
501 }else{
502 tObj["name"] = tname.split(':').shift();
503 tObj["arg"] = tname.split(':').pop();
504 }
505
506 js_log("TNAME::" + tObj["arg"] + ' from:: ' + ts);
507
508 var pSet = ts.split('\|');
509 pSet.splice(0,1);
510 if( pSet.length ){
511 tObj.param = new Array();
512 for(var pInx in pSet){
513 var tStr = pSet[ pInx ];
514 for(var b=0 ; b < tStr.length ; b++){
515 if(tStr[b] == '=' && b>0 && b<tStr.length && tStr[b-1]!='\\'){
516 //named param
517 tObj.param[ tStr.split('=').shift() ] = tStr.split('=').pop();
518 }else{
519 //indexed param
520 tObj.param[ pInx ] = tStr;
521 }
522 }
523 }
524 }
525 return tObj;
526 }
527 function getMagicTxtFromTempNode( node ){
528 node.tObj = parseTmplTxt ( node.t );
529 //do magic swap if templet key found in pMagicSet
530 if( node.tObj.name in pMagicSet){
531 var nt = pMagicSet[ node.tObj.name ]( node.tObj );
532 return nt;
533 }else{
534 //don't swap just return text
535 return node.t;
536 }
537 }
538 /**
539 * recurse_magic_swap
540 *
541 * go last child first swap upward: (could probably be integrated above somehow)
542 */
543 var pNode = null;
544 function recurse_magic_swap( node ){
545 if( !pNode )
546 pNode = node;
547
548 if( node['c'] ){
549 //swap all the kids:
550 for(var i in node['c']){
551 var nt = recurse_magic_swap( node['c'][i] );
552 //swap it into current
553 if( node.t ){
554 node.t = node.t.replace( node['c'][i].t, nt);
555 }
556 //swap into parent
557 pNode.t = pNode.t.replace( node['c'][i].t, nt);
558 }
559 //do the current node:
560 var nt = getMagicTxtFromTempNode( node );
561 pNode.t = pNode.t.replace(node.t , nt);
562 //run the swap for the outer most node
563 return node.t;
564 }else{
565 //node.t = getMagicFromTempObj( node.t )
566 return getMagicTxtFromTempNode( node );
567 }
568 }
569 //get text node system:
570 var node = rdpp ( this.wikiText );
571 //debugger;
572 //parse out stuff:
573
574 this.pOut = recurse_magic_swap( node);
575
576 },
577 /**
578 * Returns the transformed wikitext
579 *
580 * Build output from swapable index
581 * (all transforms must be expanded in parse stage and linerarly rebuilt)
582 * Alternativly we could build output using a placeholder & replace system
583 * (this lets us be slightly more slopty with ordering and indexes, but probably slower)
584 *
585 * Ideal: we build a 'wiki DOM'
586 * When editing you update the data structure directly
587 * Then in output time you just go DOM->html-ish output without re-parsing anything
588 */
589 getHTML : function(){
590 //wikiText updates should invalidate pOut
591 if( this.pOut == ''){
592 this.parse();
593 }
594 return this.pOut;
595 }
596 };
597 //return the parserObj
598 return new parseObj( wikiText, opt) ;
599 }
600
601 })(window.$mw);
602 //setup legacy global shortcuts:
603 var loadGM = $mw.lang.loadGM;
604 var loadRS = $mw.lang.loadRS;
605 var gM = $mw.lang.gM;
606
607 //if some no-js2 script defined and loaded gMsg in global space:
608 if( _global['gMsg'] ){
609 loadGM( _global['gMsg'] );
610 }
611
612 // All default messages in [English] should be overwritten by the CMS language message system.
613 $mw.lang.loadGM({
614 "mwe-loading_txt" : "loading <blink>...<\/blink>",
615 "mwe-loading_title" : "Loading...",
616 "mwe-size-gigabytes" : "$1 GB",
617 "mwe-size-megabytes" : "$1 MB",
618 "mwe-size-kilobytes" : "$1 K",
619 "mwe-size-bytes" : "$1 B",
620 "mwe-error_load_lib" : "Error: JavaScript $1 was not retrievable or does not define $2"
621 });
622
623
624
625 /**
626 * AutoLoader paths (this should mirror the file: jsAutoloadLocalClasses.php )
627 * Any file _not_ listed here won't be auto-loadable
628 * @path The path to the file (or set of files) with ending slash
629 * @gClasses The set of classes
630 * if it's an array, $j.className becomes jquery.className.js
631 * if it's an associative object then key => value pairs are used
632 */
633 if( typeof mvAutoLoadClasses == 'undefined' )
634 mvAutoLoadClasses = {};
635
636 // The script that loads the class set
637 function lcPaths( classSet ){
638 for( var i in classSet ) {
639 mvAutoLoadClasses[i] = classSet[i];
640 }
641 }
642
643 function mvGetClassPath(k){
644 if( mvAutoLoadClasses[k] ) {
645 //js_log('got class path:' + k + ' : '+ mvClassPaths[k]);
646 return mvAutoLoadClasses[k];
647 } else {
648 js_log('Error:: Could not find path for requested class ' + k );
649 return false;
650 }
651 }
652 if( typeof mvCssPaths == 'undefined' )
653 mvCssPaths = {};
654
655 function lcCssPath( cssSet ) {
656 for( var i in cssSet ) {
657 mvCssPaths[i] = mv_embed_path + cssSet[i];
658 }
659 }
660
661 /*
662 * -- Load Class Paths --
663 *
664 * MUST BE VALID JSON (NOT JS)
665 * This is used by the script loader to auto-load classes (so we only define
666 * this once for PHP & JavaScript)
667 *
668 * This is more verbose than the earlier version that compressed paths
669 * but it's all good, gzipping helps compress path strings
670 * grouped by directory.
671 *
672 * Right now the PHP AutoLoader only reads this mv_embed.js file.
673 * In the future we could have multiple lcPath calls that PHP reads
674 * (if our autoloading class list becomes too long) just have to add those
675 * files to the jsAutoLoader file list.
676 */
677 lcPaths({
678 "mv_embed" : "mv_embed.js",
679 "window.jQuery" : "jquery/jquery-1.3.2.js",
680 "$j.fn.pngFix" : "jquery/plugins/jquery.pngFix.js",
681 "$j.fn.autocomplete": "jquery/plugins/jquery.autocomplete.js",
682 "$j.fn.hoverIntent" : "jquery/plugins/jquery.hoverIntent.js",
683 "$j.fn.datePicker" : "jquery/plugins/jquery.datePicker.js",
684 "$j.ui" : "jquery/jquery.ui/ui/ui.core.js",
685 "$j.fn.ColorPicker" : "libClipEdit/colorpicker/js/colorpicker.js",
686 "$j.Jcrop" : "libClipEdit/Jcrop/js/jquery.Jcrop.js",
687 "$j.fn.simpleUploadForm": "libAddMedia/simpleUploadForm.js",
688
689 "ctrlBuilder" : "skins/ctrlBuilder.js",
690 "kskinConfig" : "skins/kskin/kskin.js",
691 "mvpcfConfig" : "skins/mvpcf/mvpcf.js",
692
693 "$j.secureEvalJSON" : "jquery/plugins/jquery.secureEvalJSON.js",
694 "$j.cookie" : "jquery/plugins/jquery.cookie.js",
695 "$j.contextMenu" : "jquery/plugins/jquery.contextMenu.js",
696 "$j.fn.suggestions" : "jquery/plugins/jquery.suggestions.js",
697
698 "$j.effects.blind" : "jquery/jquery.ui/ui/effects.blind.js",
699 "$j.effects.drop" : "jquery/jquery.ui/ui/effects.drop.js",
700 "$j.effects.pulsate" : "jquery/jquery.ui/ui/effects.pulsate.js",
701 "$j.effects.transfer" : "jquery/jquery.ui/ui/effects.transfer.js",
702 "$j.ui.droppable" : "jquery/jquery.ui/ui/ui.droppable.js",
703 "$j.ui.slider" : "jquery/jquery.ui/ui/ui.slider.js",
704 "$j.effects.bounce" : "jquery/jquery.ui/ui/effects.bounce.js",
705 "$j.effects.explode" : "jquery/jquery.ui/ui/effects.explode.js",
706 "$j.effects.scale" : "jquery/jquery.ui/ui/effects.scale.js",
707 "$j.ui.datepicker" : "jquery/jquery.ui/ui/ui.datepicker.js",
708 "$j.ui.progressbar" : "jquery/jquery.ui/ui/ui.progressbar.js",
709 "$j.ui.sortable" : "jquery/jquery.ui/ui/ui.sortable.js",
710 "$j.effects.clip" : "jquery/jquery.ui/ui/effects.clip.js",
711 "$j.effects.fold" : "jquery/jquery.ui/ui/effects.fold.js",
712 "$j.effects.shake" : "jquery/jquery.ui/ui/effects.shake.js",
713 "$j.ui.dialog" : "jquery/jquery.ui/ui/ui.dialog.js",
714 "$j.ui.resizable" : "jquery/jquery.ui/ui/ui.resizable.js",
715 "$j.ui.tabs" : "jquery/jquery.ui/ui/ui.tabs.js",
716 "$j.effects.core" : "jquery/jquery.ui/ui/effects.core.js",
717 "$j.effects.highlight" : "jquery/jquery.ui/ui/effects.highlight.js",
718 "$j.effects.slide" : "jquery/jquery.ui/ui/effects.slide.js",
719 "$j.ui.accordion" : "jquery/jquery.ui/ui/ui.accordion.js",
720 "$j.ui.draggable" : "jquery/jquery.ui/ui/ui.draggable.js",
721 "$j.ui.selectable" : "jquery/jquery.ui/ui/ui.selectable.js",
722
723 "mvFirefogg" : "libAddMedia/mvFirefogg.js",
724 "mvAdvFirefogg" : "libAddMedia/mvAdvFirefogg.js",
725 "mvBaseUploadInterface" : "libAddMedia/mvBaseUploadInterface.js",
726 "remoteSearchDriver" : "libAddMedia/remoteSearchDriver.js",
727 "seqRemoteSearchDriver" : "libAddMedia/seqRemoteSearchDriver.js",
728
729 "baseRemoteSearch" : "libAddMedia/searchLibs/baseRemoteSearch.js",
730 "mediaWikiSearch" : "libAddMedia/searchLibs/mediaWikiSearch.js",
731 "metavidSearch" : "libAddMedia/searchLibs/metavidSearch.js",
732 "archiveOrgSearch" : "libAddMedia/searchLibs/archiveOrgSearch.js",
733 "baseRemoteSearch" : "libAddMedia/searchLibs/baseRemoteSearch.js",
734
735 "mvClipEdit" : "libClipEdit/mvClipEdit.js",
736
737 "embedVideo" : "libEmbedVideo/embedVideo.js",
738 "flashEmbed" : "libEmbedVideo/flashEmbed.js",
739 "genericEmbed" : "libEmbedVideo/genericEmbed.js",
740 "htmlEmbed" : "libEmbedVideo/htmlEmbed.js",
741 "javaEmbed" : "libEmbedVideo/javaEmbed.js",
742 "nativeEmbed" : "libEmbedVideo/nativeEmbed.js",
743 "quicktimeEmbed" : "libEmbedVideo/quicktimeEmbed.js",
744 "vlcEmbed" : "libEmbedVideo/vlcEmbed.js",
745
746 "mvPlayList" : "libSequencer/mvPlayList.js",
747 "mvSequencer" : "libSequencer/mvSequencer.js",
748 "mvFirefoggRender" : "libSequencer/mvFirefoggRender.js",
749 "mvTimedEffectsEdit": "libSequencer/mvTimedEffectsEdit.js",
750
751 "mvTextInterface" : "libTimedText/mvTextInterface.js"
752 });
753
754 // Dependency mapping for CSS files for self-contained included plugins:
755 lcCssPath({
756 '$j.Jcrop' : 'libClipEdit/Jcrop/css/jquery.Jcrop.css',
757 '$j.fn.ColorPicker' : 'libClipEdit/colorpicker/css/colorpicker.css'
758 })
759
760
761 // Get the loading image
762 function mv_get_loading_img( style, class_attr ){
763 var style_txt = (style)?style:'';
764 var class_attr = (class_attr)?'class="'+class_attr+'"':'class="mv_loading_img"';
765 return '<div '+class_attr+' style="' + style +'"></div>';
766 }
767
768 function mv_set_loading(target, load_id){
769 var id_attr = ( load_id )?' id="' + load_id + '" ':'';
770 $j(target).append('<div '+id_attr+' style="position:absolute;top:0px;left:0px;height:100%;width:100%;'+
771 'background-color:#FFF;">' +
772 mv_get_loading_img('top:30px;left:30px') +
773 '</div>');
774 }
775
776 /**
777 * mvJsLoader class handles initialization and js file loads
778 */
779
780 // Shortcut
781 function mwLoad( loadSet, callback ) {
782 mvJsLoader.doLoad( loadSet, callback );
783 }
784 var mvJsLoader = {
785 libreq : {},
786 libs : {},
787
788 // Base lib flags
789 onReadyEvents: new Array(),
790 doneReadyEvents: false,
791 jQuerySetupFlag: false,
792
793 // To keep consistency across threads
794 ptime: 0,
795 ctime: 0,
796
797 load_error: false, // Load error flag (false by default)
798 load_time: 0,
799 callbacks: new Array(),
800 cur_path: null,
801 missing_path : null,
802 doLoad: function( loadLibs, callback ) {
803 this.ctime++;
804
805 if( loadLibs && loadLibs.length != 0 ) {
806 // Set up this.libs
807 // First check if we already have this library loaded
808 var all_libs_loaded = true;
809 for( var i = 0; i< loadLibs.length; i++ ) {
810 // Check if the library is already loaded
811 if( ! this.checkObjPath( loadLibs[i] ) ) {
812 all_libs_loaded = false;
813 }
814 }
815 if( all_libs_loaded ) {
816 //js_log( 'Libraries ( ' + loadLibs + ') already loaded... skipping load request' );
817 callback();
818 return;
819 }
820 // Do a check for any CSS we may need and get it
821 for( var i = 0; i < loadLibs.length; i++ ) {
822 if( typeof mvCssPaths[ loadLibs[i] ] != 'undefined' ) {
823 loadExternalCss( mvCssPaths[ loadLibs[i] ] );
824 }
825 }
826
827 // Check if we should use the script loader to combine all the requests into one
828 if( typeof mwSlScript != 'undefined' ) {
829 var class_set = '';
830 var last_class = '';
831 var coma = '';
832 for( var i = 0; i < loadLibs.length; i++ ) {
833 var curLib = loadLibs[i];
834 // Only add if not included yet:
835 if( ! this.checkObjPath( curLib ) ) {
836 class_set += coma + curLib;
837 last_class = curLib;
838 coma = ',';
839 }
840 }
841 //Build the url to the scriptServer striping its request paramaters:
842 var puri = parseUri( getMvEmbedURL() );
843 if( ( getMvEmbedURL().indexOf('://') != -1 )
844 && puri.host != parseUri( document.URL ).host )
845 {
846 var scriptPath = puri.protocol + '://' + puri.authority + puri.path;
847 }else{
848 var scriptPath = puri.path;
849 }
850 //js_log('scriptServer Path is: ' + scriptPath + "\n host script path:" + getMvEmbedURL() );
851 var dbug_attr = ( puri.queryKey['debug'] ) ? '&debug=true' : '';
852 this.libs[ last_class ] = scriptPath + '?class=' + class_set +
853 '&urid=' + getMvUniqueReqId() + dbug_attr;
854
855 } else {
856 // Do many requests
857 for( var i = 0; i < loadLibs.length; i++ ) {
858 var curLib = loadLibs[i];
859 if( curLib ) {
860 var libLoc = mvGetClassPath( curLib );
861 // Do a direct load of the file (pass along unique request id from
862 // request or mv_embed Version )
863 var qmark = (libLoc.indexOf( '?' ) !== true) ? '?' : '&';
864 this.libs[curLib] = mv_embed_path + libLoc + qmark + 'urid=' + getMvUniqueReqId();
865 }
866 }
867 }
868 }
869 if( callback ) {
870 this.callbacks.push( callback );
871 }
872 if( this.checkLoading() ) {
873 //@@todo we should check the <script> Element .onLoad property to
874 //make sure its just not a very slow connection or we can run the callback
875 //(even though the class is not loaded)
876
877 if( this.load_time++ > 4000 ){ // Time out after ~80 seconds
878 js_log( gM('mwe-error_load_lib', [mvGetClassPath(this.missing_path), this.missing_path]) );
879 this.load_error = true;
880 } else {
881 setTimeout( 'mvJsLoader.doLoad()', 20 );
882 }
883 } else {
884 //js_log('checkLoading passed. Running callbacks...');
885 // Only do callbacks if we are in the same instance (weird concurrency issue)
886 var cb_count=0;
887 for( var i = 0; i < this.callbacks.length; i++ )
888 cb_count++;
889 //js_log('RESET LIBS: loading is: '+ loading + ' callback count: '+cb_count +
890 // ' p:'+ this.ptime +' c:'+ this.ctime);
891
892 // Reset the libs
893 this.libs = {};
894 //js_log('done loading, do call: ' + this.callbacks[0] );
895 while( this.callbacks.length != 0 ) {
896 if( this.ptime == this.ctime - 1 ) { // Enforce thread consistency
897 this.callbacks.pop()();
898 //func = this.callbacks.pop();
899 //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func);
900 //func();
901 } else {
902 // Re-issue doLoad ( ptime will be set to ctime so we should catch up)
903 setTimeout( 'mvJsLoader.doLoad()', 25 );
904 break;
905 }
906 }
907 }
908 this.ptime = this.ctime;
909 },
910 doLoadDepMode: function( loadChain, callback ) {
911 // Firefox executes JS in the order in which it is included, so just directly issue the request
912 if( $j.browser.firefox ) {
913 var loadSet = [];
914 for( var i = 0; i < loadChain.length; i++ ) {
915 for( var j = 0; j < loadChain[i].length; j++ ) {
916 loadSet.push( loadChain[i][j] );
917 }
918 }
919 mvJsLoader.doLoad( loadSet, callback );
920 } else {
921 // Safari and IE tend to execute out of order so load with dependency checks
922 mvJsLoader.doLoad( loadChain.shift(), function() {
923 if( loadChain.length != 0 ) {
924 mvJsLoader.doLoadDepMode( loadChain, callback );
925 } else {
926 callback();
927 }
928 });
929 }
930 },
931 checkLoading: function() {
932 var loading = 0;
933 var i = null;
934 for( var i in this.libs ) { // for/in loop is OK on an object
935 if( !this.checkObjPath( i ) ) {
936 if( !this.libreq[i] ) {
937 loadExternalJs( this.libs[i] );
938 }
939 this.libreq[i] = 1;
940 //js_log("has not yet loaded: " + i);
941 loading = 1;
942 }
943 }
944 return loading;
945 },
946 checkObjPath: function( libVar ) {
947 if( !libVar )
948 return false;
949 var objPath = libVar.split( '.' )
950 var cur_path = '';
951 for( var p = 0; p < objPath.length; p++ ) {
952 cur_path = (cur_path == '') ? cur_path + objPath[p] : cur_path + '.' + objPath[p];
953 eval( 'var ptest = typeof ( '+ cur_path + ' ); ');
954 if( ptest == 'undefined' ) {
955 this.missing_path = cur_path;
956 return false;
957 }
958 }
959 this.cur_path = cur_path;
960 return true;
961 },
962 /**
963 * checks for jQuery and adds the $j noConflict var
964 */
965 jQueryCheck: function( callback ) {
966 //js_log( 'jQueryCheck::' );
967 // Skip stuff if $j is already loaded:
968 if( _global['$j'] && callback )
969 callback();
970 var _this = this;
971 // Load jQuery
972 _this.doLoad([
973 'window.jQuery'
974 ], function() {
975 //only do the $j setup once:
976 if(!_global['$j']){
977 _global['$j'] = jQuery.noConflict();
978 }
979 if( _this.jQuerySetupFlag == false){
980 js_log('setup mv_embed jQuery bindings');
981 //setup our global settings using the (jQuery helper)
982 mwConfig = $j.extend( mwDefaultConfig, mwConfig);
983
984 // Set up the skin path
985 _global['mv_jquery_skin_path'] = mv_embed_path + 'jquery/jquery.ui/themes/' +mwConfig['jui_skin'] + '/';
986 _global['mv_skin_img_path'] = mv_embed_path + 'skins/' + mwConfig['skin_name'] + '/images/';
987 _global['mv_default_thumb_url'] = mv_skin_img_path + 'vid_default_thumb.jpg';
988
989 //setup skin dependent dependencies
990 lcCssPath({'embedVideo' : 'skins/' + mwConfig['skin_name'] + '/playerSkin.css'});
991
992 // Make sure the skin/style sheets are always available:
993 loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
994 loadExternalCss( mv_embed_path + 'skins/' + mwConfig['skin_name'] + '/styles.css' );
995
996 // Set up AJAX to not send dynamic URLs for loading scripts (we control that with
997 // the scriptLoader)
998 $j.ajaxSetup({
999 cache: true
1000 });
1001
1002 js_log( 'jQuery loaded into $j' );
1003 // Set up mvEmbed jQuery bindings and config based dependencies
1004 mv_jqueryBindings();
1005 _this.jQuerySetupFlag = true;
1006 }
1007 // Run the callback
1008 if( callback ) {
1009 callback();
1010 }
1011 });
1012 },
1013 embedVideoCheck:function( callback ) {
1014 var _this = this;
1015 js_log( 'embedVideoCheck:' );
1016 // Make sure we have jQuery
1017 _this.jQueryCheck( function() {
1018 //set class videonojs to hidden
1019 $j('.videonojs').html( gM('mwe-loading_txt') );
1020 //Set up the embed video player class request: (include the skin js as well)
1021 var depReq = [
1022 [
1023 '$j.ui',
1024 'embedVideo',
1025 'ctrlBuilder',
1026 '$j.cookie'
1027 ],
1028 [
1029 '$j.ui.slider'
1030 ]
1031 ];
1032 //add skin if set:
1033 if( mwConfig['skin_name'] )
1034 depReq[0].push( mwConfig['skin_name'] + 'Config' );
1035
1036 // Add PNG fix if needed:
1037 if( $j.browser.msie || $j.browser.version < 7 )
1038 depReq[0].push( '$j.fn.pngFix' );
1039
1040 //load the video libs:
1041 _this.doLoadDepMode( depReq, function() {
1042 embedTypes.init();
1043 callback();
1044 $j('.videonojs').remove();
1045 });
1046 });
1047 },
1048 addLoadEvent: function( fn ) {
1049 this.onReadyEvents.push( fn );
1050 },
1051 // Check the jQuery flag. This way, when remote embedding, we don't load jQuery
1052 // unless js2AddOnloadHook was used or there is video on the page.
1053 runQueuedFunctions: function() {
1054 var _this = this;
1055 this.doneReadyEvents = true;
1056 this.jQueryCheck( function() {
1057 _this.runReadyEvents();
1058 });
1059 },
1060 runReadyEvents: function() {
1061 js_log( "runReadyEvents" );
1062 while( this.onReadyEvents.length ) {
1063 this.onReadyEvents.shift()();
1064 }
1065 }
1066 }
1067
1068 // Load an external JS file. Similar to jquery .require plugin,
1069 // but checks for object availability rather than load state.
1070
1071 /*********** INITIALIZATION CODE *************
1072 * This will get called when the DOM is ready
1073 *********************************************/
1074 /* jQuery .ready does not work when jQuery is loaded dynamically.
1075 * For an example of the problem see: 1.1.3 working: http://pastie.caboo.se/92588
1076 * and >= 1.1.4 not working: http://pastie.caboo.se/92595
1077 * $j(document).ready( function(){ */
1078 function mwdomReady( force ) {
1079 js_log( 'f:mwdomReady:' );
1080 if( !force && mv_init_done ) {
1081 js_log( "mv_init_done already done, do nothing..." );
1082 return false;
1083 }
1084 mv_init_done = true;
1085 // Handle the execution of queued functions with jQuery "ready"
1086
1087 // Check if this page has a video or playlist
1088 var e = [
1089 document.getElementsByTagName( "video" ),
1090 document.getElementsByTagName( "audio" ),
1091 document.getElementsByTagName( "playlist" )
1092 ];
1093 if( e[0].length != 0 || e[1].length != 0 || e[2].length != 0 ) {
1094 js_log( 'we have items to rewrite' );
1095 setSwappableToLoading( e );
1096 // Load libs and process them
1097 mvJsLoader.embedVideoCheck( function() {
1098 // Run any queued global events:
1099 mv_video_embed( function() {
1100 mvJsLoader.runQueuedFunctions();
1101 });
1102 });
1103 } else {
1104 // If we already have jQuery, make sure it's loaded into its proper context $j
1105 // Run any queued global events
1106 mvJsLoader.runQueuedFunctions();
1107 }
1108 }
1109 // A quick function that sets the initial text of swappable elements to "loading".
1110 // jQuery might not be ready. Does not destroy inner elements.
1111 function setSwappableToLoading( e ) {
1112 //for(var i =0)
1113 //for(var j = 0; i < j.length; j++){
1114 //}
1115 }
1116 //js2AddOnloadHook: ensure jQuery and the DOM are ready
1117 function js2AddOnloadHook( func ) {
1118 // If we have already run the DOM-ready function, just run the function directly:
1119 if( mvJsLoader.doneReadyEvents ) {
1120 // Make sure jQuery is there:
1121 mvJsLoader.jQueryCheck( function() {
1122 func();
1123 });
1124 } else {
1125 mvJsLoader.addLoadEvent( func );
1126 }
1127 }
1128 // Deprecated mwAddOnloadHook in favor of js2 naming (for clear separation of js2 code from old MW code
1129 var mwAddOnloadHook = js2AddOnloadHook;
1130 /*
1131 * This function allows for targeted rewriting
1132 */
1133 function rewrite_by_id( vid_id, ready_callback ) {
1134 js_log( 'f:rewrite_by_id: ' + vid_id );
1135 // Force a re-check of the DOM for playlist or video elements:
1136 mvJsLoader.embedVideoCheck( function() {
1137 mv_video_embed( ready_callback, vid_id );
1138 });
1139 }
1140
1141
1142 /*********** INITIALIZATION CODE *************
1143 * set DOM-ready callback to init_mv_embed
1144 *********************************************/
1145 // for Mozilla browsers
1146 if ( document.addEventListener ) {
1147 document.addEventListener( "DOMContentLoaded", function(){ mwdomReady() }, false );
1148 } else {
1149 // Use the onload method instead when DOMContentLoaded does not exist
1150 window.onload = function() { mwdomReady() };
1151 }
1152 /*
1153 * Should deprecate and use jquery.ui.dialog instead
1154 */
1155 function mv_write_modal( content, speed ) {
1156 $j( '#modalbox,#mv_overlay' ).remove();
1157 $j( 'body' ).append(
1158 '<div id="modalbox" style="background:#DDD;border:3px solid #666666;font-size:115%;' +
1159 'top:30px;left:20px;right:20px;bottom:30px;position:fixed;z-index:100;">' +
1160 content +
1161 '</div>' +
1162 '<div id="mv_overlay" style="background:#000;cursor:wait;height:100%;left:0;position:fixed;' +
1163 'top:0;width:100%;z-index:5;filter:alpha(opacity=60);-moz-opacity: 0.6;' +
1164 'opacity: 0.6;"/>');
1165 $j( '#modalbox,#mv_overlay' ).show( speed );
1166 }
1167 function mv_remove_modal( speed ) {
1168 $j( '#modalbox,#mv_overlay' ).remove( speed );
1169 }
1170
1171 /*
1172 * Store all the mwEmbed jQuery-specific bindings
1173 * (set up after jQuery is available).
1174 * This lets you call rewrites in a jQuery way
1175 *
1176 * @@ eventually we should refactor mwCode over to jQuery style plugins
1177 * and mv_embed.js will just handle dependency mapping and loading.
1178 *
1179 */
1180 function mv_jqueryBindings() {
1181 js_log( 'mv_jqueryBindings' );
1182 (function( $ ) {
1183 $.fn.addMediaWiz = function( iObj, callback ) {
1184 // First set the cursor for the button to "loading"
1185 $j( this.selector ).css( 'cursor', 'wait' ).attr( 'title', gM( 'mwe-loading_title' ) );
1186
1187 iObj['target_invocation'] = this.selector;
1188
1189 // Load the mv_embed_base skin:
1190 loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
1191 loadExternalCss( mv_embed_path + 'skins/' + mwConfig['skin_name']+'/styles.css' );
1192 // Load all the required libs:
1193 mvJsLoader.jQueryCheck( function() {
1194 // Load with staged dependencies (for IE and Safari that don't execute in order)
1195 mvJsLoader.doLoadDepMode([
1196 [ 'remoteSearchDriver',
1197 '$j.cookie',
1198 '$j.ui'
1199 ],[
1200 '$j.ui.resizable',
1201 '$j.ui.draggable',
1202 '$j.ui.dialog',
1203 '$j.ui.tabs',
1204 '$j.ui.sortable'
1205 ]
1206 ], function() {
1207 iObj['instance_name'] = 'rsdMVRS';
1208 _global['rsdMVRS'] = new remoteSearchDriver( iObj );
1209 if( callback ) {
1210 callback( _global['rsdMVRS'] );
1211 }
1212 });
1213 });
1214 }
1215 $.fn.sequencer = function( iObj, callback ) {
1216 // Debugger
1217 iObj['target_sequence_container'] = this.selector;
1218 // Issue a request to get the CSS file (if not already included):
1219 loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
1220 loadExternalCss( mv_embed_path + 'skins/' + mwConfig['skin_name'] + '/mv_sequence.css' );
1221 // Make sure we have the required mv_embed libs (they are not loaded when no video
1222 // element is on the page)
1223 mvJsLoader.embedVideoCheck( function() {
1224 // Load the playlist object and then the jQuery UI stuff:
1225 mvJsLoader.doLoadDepMode([
1226 [
1227 'mvPlayList',
1228 '$j.ui',
1229 '$j.contextMenu',
1230 '$j.secureEvalJSON',
1231 'mvSequencer'
1232 ],
1233 [
1234 '$j.ui.accordion',
1235 '$j.ui.dialog',
1236 '$j.ui.droppable',
1237 '$j.ui.draggable',
1238 '$j.ui.progressbar',
1239 '$j.ui.sortable',
1240 '$j.ui.resizable',
1241 '$j.ui.slider',
1242 '$j.ui.tabs'
1243 ]
1244 ], function() {
1245 js_log( 'calling new mvSequencer' );
1246 // Initialise the sequence object (it will take over from there)
1247 // No more than one mvSeq obj for now:
1248 if( !_global['mvSeq'] ) {
1249 _global['mvSeq'] = new mvSequencer( iObj );
1250 } else {
1251 js_log( 'mvSeq already init' );
1252 }
1253 });
1254 });
1255 }
1256 /*
1257 * The Firefogg jQuery function:
1258 * @@note This Firefogg invocation could be made to work more like real jQuery plugins
1259 */
1260 $.fn.firefogg = function( iObj, callback ) {
1261 if( !iObj )
1262 iObj = {};
1263 // Add the base theme CSS:
1264 loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
1265 loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name'] + '/styles.css' );
1266
1267 // Check if we already have Firefogg loaded (the call just updates the element's
1268 // properties)
1269 var sElm = $j( this.selector ).get( 0 );
1270 if( sElm['firefogg'] ) {
1271 if( sElm['firefogg'] == 'loading' ) {
1272 js_log( "Error: called firefogg operations on Firefogg selector that is " +
1273 "not done loading" );
1274 return false;
1275 }
1276 // Update properties
1277 for( var i in iObj ) {
1278 js_log( "firefogg::updated: " + i + ' to '+ iObj[i] );
1279 sElm['firefogg'][i] = iObj[i];
1280 }
1281 return sElm['firefogg'];
1282 } else {
1283 // Avoid concurency
1284 sElm['firefogg'] = 'loading';
1285 }
1286 // Add the selector
1287 iObj['selector'] = this.selector;
1288
1289 var loadSet = [
1290 [
1291 'mvBaseUploadInterface',
1292 'mvFirefogg',
1293 '$j.ui'
1294 ],
1295 [
1296 '$j.ui.progressbar',
1297 '$j.ui.dialog',
1298 '$j.ui.draggable'
1299 ]
1300 ];
1301 if( iObj.encoder_interface ) {
1302 loadSet.push([
1303 'mvAdvFirefogg',
1304 '$j.cookie',
1305 '$j.ui.accordion',
1306 '$j.ui.slider',
1307 '$j.ui.datepicker'
1308 ]);
1309 }
1310 // Make sure we have everything loaded that we need:
1311 mvJsLoader.doLoadDepMode( loadSet, function() {
1312 js_log( 'firefogg libs loaded. target select:' + iObj.selector );
1313 // Select interface provider based on whether we want to include the
1314 // encoder interface or not
1315 if( iObj.encoder_interface ) {
1316 var myFogg = new mvAdvFirefogg( iObj );
1317 } else {
1318 var myFogg = new mvFirefogg( iObj );
1319 }
1320 if( myFogg ) {
1321 myFogg.doRewrite( callback );
1322 var selectorElement = $j( iObj.selector ).get( 0 );
1323 selectorElement['firefogg'] = myFogg;
1324 }
1325 });
1326 }
1327 // Take an input player as the selector and expose basic rendering controls
1328 $.fn.firefoggRender = function( iObj, callback ) {
1329 // Check if we already have render loaded then just pass on updates/actions
1330 var sElm = $j( this.selector ).get( 0 );
1331 if( sElm['fogg_render'] ) {
1332 if( sElm['fogg_render'] == 'loading' ) {
1333 js_log( "Error: called firefoggRender while loading" );
1334 return false;
1335 }
1336 // Call or update the property:
1337 }
1338 sElm['fogg_render'] = 'loading';
1339 // Add the selector
1340 iObj['player_target'] = this.selector;
1341 mvJsLoader.doLoad([
1342 'mvFirefogg',
1343 'mvFirefoggRender'
1344 ], function() {
1345 sElm['fogg_render'] = new mvFirefoggRender( iObj );
1346 if( callback && typeof callback == 'function' )
1347 callback( sElm['fogg_render'] );
1348 });
1349 }
1350
1351 $.fn.baseUploadInterface = function(iObj) {
1352 mvJsLoader.doLoadDepMode([
1353 [
1354 'mvBaseUploadInterface',
1355 '$j.ui',
1356 ],
1357 [
1358 '$j.ui.progressbar',
1359 '$j.ui.dialog'
1360 ]
1361 ], function() {
1362 myUp = new mvBaseUploadInterface( iObj );
1363 myUp.setupForm();
1364 });
1365 }
1366
1367 // Shortcut to a themed button
1368 $.btnHtml = function( msg, className, iconId, opt ) {
1369 if( !opt )
1370 opt = {};
1371 var href = (opt.href) ? opt.href : '#';
1372 var target_attr = (opt.target) ? ' target="' + opt.target + '" ' : '';
1373 var style_attr = (opt.style) ? ' style="' + opt.style + '" ' : '';
1374 return '<a href="' + href + '" ' + target_attr + style_attr +
1375 ' class="ui-state-default ui-corner-all ui-icon_link ' +
1376 className + '"><span class="ui-icon ui-icon-' + iconId + '" />' +
1377 '<span class="btnText">'+ msg +'<span></a>';
1378 }
1379 // Shortcut to bind hover state
1380 $.fn.btnBind = function() {
1381 $j( this ).hover(
1382 function() {
1383 $j( this ).addClass( 'ui-state-hover' );
1384 },
1385 function() {
1386 $j( this ).removeClass( 'ui-state-hover' );
1387 }
1388 )
1389 return this;
1390 }
1391 /**
1392 * addLoaderDialog
1393 * small helper for putting a loading dialog box on top of everything
1394 * (helps block for request that
1395 *
1396 * @param msg text text of the loader msg
1397 */
1398 $.addLoaderDialog = function( msg_txt ){
1399 if( $('#mwe_tmp_loader').length != 0 )
1400 $('#mwe_tmp_loader').remove();
1401
1402 $('body').append('<div id="mwe_tmp_loader" title="' + msg_txt + '" >' +
1403 gM('mwe-checking-resource') + '<br>' +
1404 mv_get_loading_img() +
1405 '</div>');
1406
1407 mvJsLoader.doLoadDepMode([
1408 [
1409 '$j.ui'
1410 ],
1411 [
1412 '$j.ui.dialog'
1413 ]
1414 ], function() {
1415 $('#mwe_tmp_loader').dialog({
1416 bgiframe: true,
1417 height: 140,
1418 modal: true
1419 });
1420 });
1421 }
1422 $.closeLoaderDialog = function(){
1423 $('#mwe_tmp_loader').dialog('close');
1424 }
1425
1426 })(jQuery);
1427 }
1428 /*
1429 * Utility functions:
1430 */
1431 // Simple URL rewriter (could probably be refactored into an inline regular exp)
1432 function getURLParamReplace( url, opt ) {
1433 var pSrc = parseUri( url );
1434 if( pSrc.protocol != '' ) {
1435 var new_url = pSrc.protocol + '://' + pSrc.authority + pSrc.path + '?';
1436 } else {
1437 var new_url = pSrc.path + '?';
1438 }
1439 var amp = '';
1440 for( var key in pSrc.queryKey ) {
1441 var val = pSrc.queryKey[ key ];
1442 // Do override if requested
1443 if( opt[ key ] )
1444 val = opt[ key ];
1445 new_url += amp + key + '=' + val;
1446 amp = '&';
1447 };
1448 // Add any vars that were not already there:
1449 for( var i in opt ) {
1450 if( !pSrc.queryKey[i] ) {
1451 new_url += amp + i + '=' + opt[i];
1452 amp = '&';
1453 }
1454 }
1455 return new_url;
1456 }
1457 /**
1458 * Given a float number of seconds, returns npt format response.
1459 *
1460 * @param float Seconds
1461 * @param boolean If we should show milliseconds or not.
1462 */
1463 function seconds2npt( sec, show_ms ) {
1464 if( isNaN( sec ) ) {
1465 // js_log("warning: trying to get npt time on NaN:" + sec);
1466 return '0:0:0';
1467 }
1468 var hours = Math.floor( sec / 3600 );
1469 var minutes = Math.floor( (sec / 60) % 60 );
1470 var seconds = sec % 60;
1471 // Round the number of seconds to the required number of significant digits
1472 if( show_ms ) {
1473 seconds = Math.round( seconds * 1000 ) / 1000;
1474 } else {
1475 seconds = Math.round( seconds );
1476 }
1477 if( seconds < 10 )
1478 seconds = '0' + seconds;
1479 if( minutes < 10 )
1480 minutes = '0' + minutes;
1481
1482 return hours + ":" + minutes + ":" + seconds;
1483 }
1484 /*
1485 * Take hh:mm:ss,ms or hh:mm:ss.ms input, return the number of seconds
1486 */
1487 function npt2seconds( npt_str ) {
1488 if( !npt_str ) {
1489 //js_log('npt2seconds:not valid ntp:'+ntp);
1490 return false;
1491 }
1492 // Strip "npt:" time definition if present
1493 npt_str = npt_str.replace( 'npt:', '' );
1494
1495 times = npt_str.split( ':' );
1496 if( times.length != 3 ){
1497 js_log( 'error: npt2seconds on ' + npt_str );
1498 return false;
1499 }
1500 // Sometimes a comma is used instead of period for ms
1501 times[2] = times[2].replace( /,\s?/, '.' );
1502 // Return seconds float
1503 return parseInt( times[0] * 3600) + parseInt( times[1] * 60 ) + parseFloat( times[2] );
1504 }
1505 /*
1506 * Simple helper to grab an edit token
1507 *
1508 * @param title The wiki page title you want to edit
1509 * @param api_url 'optional' The target API URL
1510 * @param callback The callback function to pass the token to
1511 */
1512 function get_mw_token( title, api_url, callback ) {
1513 js_log( ':get_mw_token:' );
1514 if( !title && wgUserName ) {
1515 title = 'User:' + wgUserName;
1516 }
1517 var reqObj = {
1518 'action': 'query',
1519 'prop': 'info',
1520 'intoken': 'edit',
1521 'titles': title
1522 };
1523 do_api_req( {
1524 'data': reqObj,
1525 'url' : api_url
1526 }, function(data) {
1527 for( var i in data.query.pages ) {
1528 if( data.query.pages[i]['edittoken'] ) {
1529 if( typeof callback == 'function' )
1530 callback ( data.query.pages[i]['edittoken'] );
1531 }
1532 }
1533 // No token found:
1534 return false;
1535 }
1536 );
1537 }
1538 // Do a remote or local API request based on request URL
1539 //@param options: url, data, cbParam, callback
1540 function do_api_req( options, callback ) {
1541 if( typeof options.data != 'object' ) {
1542 return js_error( 'Error: request paramaters must be an object' );
1543 }
1544 // Generate the URL if it's missing
1545 if( typeof options.url == 'undefined' || options.url === false ) {
1546 if( !wgServer || ! wgScriptPath ) {
1547 return js_error('Error: no api url for api request');
1548 }
1549 options.url = mwGetLocalApiUrl();
1550 }
1551 if( typeof options.data == 'undefined' )
1552 options.data = {};
1553
1554 // Force format to JSON
1555 options.data['format'] = 'json';
1556
1557 // If action is not set, assume query
1558 if( !options.data['action'] )
1559 options.data['action'] = 'query';
1560
1561 // js_log('do api req: ' + options.url +'?' + jQuery.param(options.data) );
1562 // Build request string
1563 if( parseUri( document.URL ).host == parseUri( options.url ).host ) {
1564 // Local request: do API request directly
1565 $j.ajax({
1566 type: "POST",
1567 url: options.url,
1568 data: options.data,
1569 dataType: 'json', // API requests _should_ always return JSON data:
1570 async: false,
1571 success: function( data ) {
1572 callback( data );
1573 },
1574 error: function( e ) {
1575 js_error( ' error' + e + ' in getting: ' + options.url );
1576 }
1577 });
1578 } else {
1579 // Remote request
1580 // Set the callback param if it's not already set
1581 if( typeof options.jsonCB == 'undefined' )
1582 options.jsonCB = 'callback';
1583
1584 var req_url = options.url;
1585 var paramAnd = ( req_url.indexOf( '?' ) == -1 ) ? '?' : '&';
1586 // Put all the parameters into the URL
1587 for( var i in options.data ) {
1588 req_url += paramAnd + encodeURIComponent( i ) + '=' + encodeURIComponent( options.data[i] );
1589 paramAnd = '&';
1590 }
1591 var fname = 'mycpfn_' + ( global_cb_count++ );
1592 _global[ fname ] = callback;
1593 req_url += '&' + options.jsonCB + '=' + fname;
1594 loadExternalJs( req_url );
1595 }
1596 }
1597 function mwGetLocalApiUrl( url ) {
1598 if ( wgServer && wgScriptPath ) {
1599 return wgServer + wgScriptPath + '/api.php';
1600 }
1601 return false;
1602 }
1603 // Grab wiki form error for wiki html page processing (should be deprecated because we use api now)
1604 function grabWikiFormError( result_page ) {
1605 var res = {};
1606 sp = result_page.indexOf( '<span class="error">' );
1607 if( sp != -1 ) {
1608 se = result_page.indexOf( '</span>', sp );
1609 res.error_txt = result_page.substr( sp, sp - se ) + '</span>';
1610 } else {
1611 // Look for warning
1612 sp = result_page.indexOf( '<ul class="warning">' )
1613 if( sp != -1 ) {
1614 se = result_page.indexOf( '</ul>', sp );
1615 res.error_txt = result_page.substr( sp, se - sp ) + '</ul>';
1616 // Try to add the ignore form item
1617 sfp = result_page.indexOf( '<form method="post"' );
1618 if( sfp != -1 ) {
1619 sfe = result_page.indexOf( '</form>', sfp );
1620 res.form_txt = result_page.substr( sfp, sfe - sfp ) + '</form>';
1621 }
1622 } else {
1623 // One more error type check
1624 sp = result_page.indexOf( 'class="mw-warning-with-logexcerpt">' )
1625 if( sp != -1 ) {
1626 se = result_page.indexOf( '</div>', sp );
1627 res.error_txt = result_page.substr( sp, se - sp ) + '</div>';
1628 }
1629 }
1630 }
1631 return res;
1632 }
1633 // Do a "normal" request
1634 function do_request( req_url, callback ) {
1635 js_log( 'do_request::req_url:' + req_url + ' != ' + parseUri( req_url ).host );
1636 // If we are doing a request to the same domain or relative link, do a normal GET
1637 if( parseUri( document.URL ).host == parseUri( req_url ).host ||
1638 req_url.indexOf('://') == -1 ) // Relative url
1639 {
1640 // Do a direct request
1641 $j.ajax({
1642 type: "GET",
1643 url: req_url,
1644 async: false,
1645 success: function( data ) {
1646 callback( data );
1647 }
1648 });
1649 } else {
1650 // Get data via DOM injection with callback
1651 global_req_cb.push( callback );
1652 // Prepend json_ to feed_format if not already requesting json format (metavid specific)
1653 if( req_url.indexOf( "feed_format=" ) != -1 && req_url.indexOf( "feed_format=json" ) == -1 )
1654 req_url = req_url.replace( /feed_format=/, 'feed_format=json_' );
1655 loadExternalJs( req_url + '&cb=mv_jsdata_cb&cb_inx=' + (global_req_cb.length - 1) );
1656 }
1657 }
1658
1659 function mv_jsdata_cb( response ) {
1660 js_log( 'f:mv_jsdata_cb:'+ response['cb_inx'] );
1661 // Run the callback from the global request callback object
1662 if( !global_req_cb[response['cb_inx']] ) {
1663 js_log( 'missing req cb index' );
1664 return false;
1665 }
1666 if( !response['pay_load'] ) {
1667 js_log( "missing pay load" );
1668 return false;
1669 }
1670 switch( response['content-type'] ) {
1671 case 'text/plain':
1672 break;
1673 case 'text/xml':
1674 if( typeof response['pay_load'] == 'string' ) {
1675 //js_log('load string:'+"\n"+ response['pay_load']);
1676 // Debugger;
1677 if( $j.browser.msie ) {
1678 // Attempt to parse as XML for IE
1679 var xmldata = new ActiveXObject("Microsoft.XMLDOM");
1680 xmldata.async = "false";
1681 xmldata.loadXML( response['pay_load'] );
1682 } else {
1683 // For others (Firefox, Safari etc.)
1684 try {
1685 var xmldata = (new DOMParser()).parseFromString( response['pay_load'], "text/xml" );
1686 } catch( e ) {
1687 js_log( 'XML parse ERROR: ' + e.message );
1688 }
1689 }
1690 //@@todo handle XML parser errors
1691 if( xmldata )response['pay_load'] = xmldata;
1692 }
1693 break
1694 default:
1695 js_log( 'bad response type' + response['content-type'] );
1696 return false;
1697 break;
1698 }
1699 global_req_cb[response['cb_inx']]( response['pay_load'] );
1700 }
1701 // Load external JS via DOM injection
1702 function loadExternalJs( url, callback ) {
1703 js_log( 'load js: '+ url );
1704 //if(window['$j']) // use jquery call:
1705 /*$j.ajax({
1706 type: "GET",
1707 url: url,
1708 dataType: 'script',
1709 cache: true
1710 });*/
1711 //else{
1712 var e = document.createElement( "script" );
1713 e.setAttribute( 'src', url );
1714 e.setAttribute( 'type', "text/javascript" );
1715 /*if(callback)
1716 e.onload = callback;
1717 */
1718 //e.setAttribute('defer', true);
1719 document.getElementsByTagName( "head" )[0].appendChild( e );
1720 // }
1721 }
1722 function styleSheetPresent( url ) {
1723 style_elements = document.getElementsByTagName( 'link' );
1724 if( style_elements.length > 0 ) {
1725 for( i = 0; i < style_elements.length; i++ ) {
1726 if( style_elements[i].href == url )
1727 return true;
1728 }
1729 }
1730 return false;
1731 }
1732 function loadExternalCss( url ) {
1733 // We could have the script loader group these CSS requests.
1734 // But it's debatable: it may hurt more than it helps with caching and all
1735 if( typeof url =='object' ) {
1736 for( var i in url ) {
1737 loadExternalCss( url[i] );
1738 }
1739 return ;
1740 }
1741
1742 if( url.indexOf('?') == -1 ) {
1743 url += '?' + getMvUniqueReqId();
1744 }
1745 if( !styleSheetPresent( url ) ) {
1746 js_log( 'load css: ' + url );
1747 var e = document.createElement( "link" );
1748 e.href = url;
1749 e.type = "text/css";
1750 e.rel = 'stylesheet';
1751 document.getElementsByTagName( "head" )[0].appendChild( e );
1752 }
1753 }
1754 function getMvEmbedURL() {
1755 if( _global['mv_embed_url'] )
1756 return _global['mv_embed_url'];
1757 var js_elements = document.getElementsByTagName( "script" );
1758 for( var i = 0; i < js_elements.length; i++ ) {
1759 // Check for mv_embed.js and/or script loader
1760 var src = js_elements[i].getAttribute( "src" );
1761 if( src ) {
1762 if( src.indexOf( 'mv_embed.js' ) != -1 || (
1763 ( src.indexOf( 'mwScriptLoader.php' ) != -1 || src.indexOf('jsScriptLoader.php') != -1 )
1764 && src.indexOf('mv_embed') != -1) ) //(check for class=mv_embed script_loader call)
1765 {
1766 _global['mv_embed_url'] = src;
1767 return src;
1768 }
1769 }
1770 }
1771 js_error( 'Error: getMvEmbedURL failed to get Embed Path' );
1772 return false;
1773 }
1774 // Get a unique request ID to ensure fresh JavaScript
1775 function getMvUniqueReqId() {
1776 if( _global['urid'] )
1777 return _global['urid'];
1778 var mv_embed_url = getMvEmbedURL();
1779 // If we have a URI, return it
1780 var urid = parseUri( mv_embed_url ).queryKey['urid']
1781 if( urid ) {
1782 _global['urid'] = urid;
1783 return urid;
1784 }
1785 // If we're in debug mode, get a fresh unique request key
1786 if( parseUri( mv_embed_url ).queryKey['debug'] == 'true' ) {
1787 var d = new Date();
1788 var urid = d.getTime();
1789 _global['urid'] = urid;
1790 return urid;
1791 }
1792 // Otherwise, just return the mv_embed version
1793 return MV_EMBED_VERSION;
1794 }
1795 /*
1796 * Set the global mv_embed path based on the script's location
1797 */
1798 function getMvEmbedPath() {
1799 if( _global['mv_embed_path'] )
1800 return _global['mv_embed_path'];
1801 var mv_embed_url = getMvEmbedURL();
1802 if( mv_embed_url.indexOf( 'mv_embed.js' ) !== -1 ) {
1803 mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'mv_embed.js' ) );
1804 } else if( mv_embed_url.indexOf( 'mwScriptLoader.php' ) !== -1 ) {
1805 // Script loader is in the root of MediaWiki, so include the default mv_embed extension path
1806 mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'mwScriptLoader.php' ) )
1807 + mediaWiki_mvEmbed_path;
1808 } else {
1809 mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'jsScriptLoader.php' ) );
1810 }
1811 // Make an absolute URL (if it's relative and we don't have an mv_embed path)
1812 if( mv_embed_path.indexOf( '://' ) == -1 ) {
1813 var pURL = parseUri( document.URL );
1814 if( mv_embed_path.charAt( 0 ) == '/' ) {
1815 mv_embed_path = pURL.protocol + '://' + pURL.authority + mv_embed_path;
1816 } else {
1817 // Relative
1818 if( mv_embed_path == '' ) {
1819 mv_embed_path = pURL.protocol + '://' + pURL.authority + pURL.directory + mv_embed_path;
1820 }
1821 }
1822 }
1823 _global['mv_embed_path'] = mv_embed_path;
1824 return mv_embed_path;
1825 }
1826
1827 if ( typeof DOMParser == "undefined" ) {
1828 DOMParser = function () {}
1829 DOMParser.prototype.parseFromString = function ( str, contentType ) {
1830 if ( typeof ActiveXObject != "undefined" ) {
1831 var d = new ActiveXObject( "MSXML.DomDocument" );
1832 d.loadXML( str );
1833 return d;
1834 } else if ( typeof XMLHttpRequest != "undefined" ) {
1835 var req = new XMLHttpRequest;
1836 req.open( "GET", "data:" + (contentType || "application/xml") +
1837 ";charset=utf-8," + encodeURIComponent(str), false );
1838 if ( req.overrideMimeType ) {
1839 req.overrideMimeType(contentType);
1840 }
1841 req.send( null );
1842 return req.responseXML;
1843 }
1844 }
1845 }
1846 /*
1847 * Utility functions
1848 */
1849 function js_log( string ) {
1850 if( window.console ) {
1851 window.console.log( string );
1852 } else {
1853 /*
1854 * IE and non-Firebug debug:
1855 */
1856 /*var log_elm = document.getElementById('mv_js_log');
1857 if(!log_elm){
1858 document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML +
1859 '<div style="position:absolute;z-index:500;top:0px;left:0px;right:0px;height:10px;">'+
1860 '<textarea id="mv_js_log" cols="120" rows="5"></textarea>'+
1861 '</div>';
1862
1863 var log_elm = document.getElementById('mv_js_log');
1864 }
1865 if(log_elm){
1866 log_elm.value+=string+"\n";
1867 }*/
1868 }
1869 return false;
1870 }
1871
1872 function js_error( string ) {
1873 alert( string );
1874 return false;
1875 }