r56009 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r56008‎ | r56009 | r56010 >
Date:02:04, 8 September 2009
Author:tstarling
Status:deferred
Tags:
Comment:
* Fixed whitespace, indenting, line length. Ran stylize.php on the PHP files, did the JS ones by hand.
* Fixed spelling, grammar, etc. in comments. Removed some unnecessary comments.
* Other code style tweaks, e.g. removed some redundant brackets.
* Renamed functions which were misspellings: runQuededFunctions -> runQueuedFunctions, setSwapableToLoading -> setSwappableToLoading, rewrite_for_oggHanlder -> rewrite_for_OggHandler, doProccessJsFile -> doProcessJsFile
Modified paths:
  • /trunk/phase3/js2/editPage.js (modified) (history)
  • /trunk/phase3/js2/mwEmbed/jsScriptLoader.php (modified) (history)
  • /trunk/phase3/js2/mwEmbed/mv_embed.js (modified) (history)
  • /trunk/phase3/js2/mwEmbed/php/jsAutoloadLocalClasses.php (modified) (history)
  • /trunk/phase3/js2/mwEmbed/php/maintenance/mergeJavascriptMsg.php (modified) (history)
  • /trunk/phase3/js2/mwEmbed/php/mv_embed_iframe.php (modified) (history)
  • /trunk/phase3/js2/mwEmbed/php/noMediaWikiConfig.php (modified) (history)
  • /trunk/phase3/js2/remoteMwEmbed.js (modified) (history)
  • /trunk/phase3/js2/uploadPage.js (modified) (history)

Diff [purge]

Index: trunk/phase3/js2/mwEmbed/php/maintenance/mergeJavascriptMsg.php
@@ -64,7 +64,7 @@
6565
6666 $objects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ), RecursiveIteratorIterator::SELF_FIRST );
6767 foreach ( $objects as $fname => $object ) {
68 - if ( substr( $fname, -3 ) == '.js' ) {
 68+ if ( substr( $fname, - 3 ) == '.js' ) {
6969 $jsFileText = file_get_contents( $fname );
7070 $mwPos = strpos( $fname, 'mwEmbed' ) + 7;
7171 $curFileName = substr( $fname, $mwPos );
@@ -171,9 +171,9 @@
172172 }
173173 break;
174174 case ':':
175 - if($inquote){
 175+ if ( $inquote ) {
176176 $result .= $char;
177 - }else{
 177+ } else {
178178 $result .= ' ' . $char . ' ';
179179 }
180180 break;
Index: trunk/phase3/js2/mwEmbed/php/jsAutoloadLocalClasses.php
@@ -3,27 +3,27 @@
44
55 global $wgJSAutoloadLocalClasses, $wgMwEmbedDirectory;
66
7 -//load classes from mv_embed.js::
 7+// Load classes from mv_embed.js
88
9 -//read the file:
10 -if( is_file( $wgMwEmbedDirectory . 'mv_embed.js' )){
 9+if ( is_file( $wgMwEmbedDirectory . 'mv_embed.js' ) ) {
 10+ // Read the file
 11+ $str = @file_get_contents( $wgMwEmbedDirectory . 'mv_embed.js' );
1112
12 - $str = @file_get_contents( $wgMwEmbedDirectory . 'mv_embed.js');
13 -
 13+ // Call jsClassPathLoader() for each lcPaths() call in the JS source
1414 $str = preg_replace_callback(
1515 '/lcPaths\s*\(\s*{(.*)}\s*\)\s*/siU',
1616 'jsClassPathLoader',
1717 $str
1818 );
1919 }
20 -function jsClassPathLoader($jvar){
21 - global $wgJSAutoloadLocalClasses,$wgMwEmbedDirectory;
22 - if( !isset( $jvar[1] ) )
 20+function jsClassPathLoader( $jvar ) {
 21+ global $wgJSAutoloadLocalClasses, $wgMwEmbedDirectory;
 22+ if ( !isset( $jvar[1] ) )
2323 return false;
2424 $jClassSet = json_decode( '{' . $jvar[1] . '}', true );
25 - foreach( $jClassSet as $jClass => $jPath ){
26 - //strip $ from jsclass (as they are striped on url request param input)
27 - $jClass = str_replace('$', '', $jClass);
 25+ foreach ( $jClassSet as $jClass => $jPath ) {
 26+ // Strip $ from jClass (as they are stripped on URL request parameter input)
 27+ $jClass = str_replace( '$', '', $jClass );
2828 $wgJSAutoloadLocalClasses[$jClass] = $wgMwEmbedDirectory . $jPath;
2929 }
3030 }
Index: trunk/phase3/js2/mwEmbed/php/mv_embed_iframe.php
@@ -1,31 +1,32 @@
22 <?php
33 /*
44 mv_embed_iframe.php
5 -this allows for remote embedding without exposing the hosting site to remote javascript.
 5+This allows for remote embedding, without exposing the hosting site to remote JavaScript.
66 */
77
88 mv_embed_iframe();
99
1010 function mv_embed_iframe() {
11 - if( !function_exists( 'filter_input' ) ){
 11+ if ( !function_exists( 'filter_input' ) ) {
1212 die( 'your version of PHP lacks <b>filter_input()</b> function<br />' );
1313 }
14 - // default to null media in not provided:
15 - $stream_name = ( isset( $_GET['sn'] ) )? $_GET['sn'] : die('no stream name provided');
16 - $time = ( isset( $_GET['t'] ) )? $_GET['t']: '';
17 - $width = ( isset( $_GET['width'] ) )? intval( $_GET['width'] ) : '400';
18 - $height = ( isset( $_GET['height'] ) )? intval( $_GET['height'] ) : '300'; //
 14+ // Default to null media if not provided
 15+ $stream_name = ( isset( $_GET['sn'] ) ) ? $_GET['sn'] : die( 'no stream name provided' );
 16+ $time = ( isset( $_GET['t'] ) ) ? $_GET['t']: '';
 17+ $width = ( isset( $_GET['width'] ) ) ? intval( $_GET['width'] ) : '400';
 18+ $height = ( isset( $_GET['height'] ) ) ? intval( $_GET['height'] ) : '300'; //
1919
20 - $roe_url = 'http://metavid.org/wiki/Special:MvExportStream?feed_format=roe&stream_name=' . htmlspecialchars( $stream_name ) .
21 - '&t=' . htmlspecialchars( $time );
22 - //everything good output page:
23 - output_page(array(
 20+ $roe_url = 'http://metavid.org/wiki/Special:MvExportStream?feed_format=roe' .
 21+ '&stream_name=' . htmlspecialchars( $stream_name ) .
 22+ '&t=' . htmlspecialchars( $time );
 23+ // Everything good, output page:
 24+ output_page( array(
2425 'roe_url' => $roe_url,
2526 'width' => $width,
2627 'height' => $height,
27 - ));
 28+ ) );
2829 }
29 -function output_page( $params ){
 30+function output_page( $params ) {
3031 extract( $params );
3132 ?>
3233 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
@@ -80,4 +81,4 @@
8182 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
8283 );
8384 return strtr( $string, $pairs );
84 -}
\ No newline at end of file
 85+}
Index: trunk/phase3/js2/mwEmbed/php/noMediaWikiConfig.php
@@ -1,25 +1,26 @@
22 <?php
3 -//give us true for mediaWiki
 3+
 4+// Give us true for MediaWiki
45 define( 'MEDIAWIKI', true );
56
6 -define('MWEMBED_STANDALONE', true);
 7+define( 'MWEMBED_STANDALONE', true );
78
8 -//setup the globals: (for documentation see: DefaultSettings.php )
 9+// Setup the globals: (for documentation see: DefaultSettings.php )
910
1011 $wgJSAutoloadLocalClasses = array();
1112
12 -$IP = realpath(dirname(__FILE__).'/../');
 13+$IP = realpath( dirname( __FILE__ ) . '/../' );
1314
14 -//$wgMwEmbedDirectory becomes the root $IP
 15+// $wgMwEmbedDirectory becomes the root $IP
1516 $wgMwEmbedDirectory = '';
1617
17 -$wgFileCacheDirectory = realpath(dirname(__FILE__)) . '/script-cache';
 18+$wgFileCacheDirectory = realpath( dirname( __FILE__ ) ) . '/script-cache';
1819
1920 $wgUseFileCache = true;
2021
2122 $wgEnableScriptLoaderJsFile = false;
2223
23 -//init our wg Globals
 24+// Init our wg Globals
2425 $wgJSAutoloadClasses = array();
2526 $wgJSAutoloadLocalClasses = array();
2627
@@ -27,7 +28,7 @@
2829 $wgEnableScriptLocalization = true;
2930 $mwLanguageCode = 'en';
3031
31 -$wgContLanguageCode ='';
 32+$wgContLanguageCode = '';
3233
3334 $wgStyleVersion = '218';
3435
@@ -43,30 +44,30 @@
4445
4546 $wgJsMimeType = 'text/javascript';
4647
47 -//get the autoLoadClasses
48 -require_once( realpath( dirname(__FILE__) ) . '/jsAutoloadLocalClasses.php' );
 48+// Get the autoload classes
 49+require_once( realpath( dirname( __FILE__ ) ) . '/jsAutoloadLocalClasses.php' );
4950
50 -//get the JSmin class:
51 -require_once( realpath( dirname(__FILE__) ) . '/minify/JSMin.php' );
 51+// Get the JSmin class:
 52+require_once( realpath( dirname( __FILE__ ) ) . '/minify/JSMin.php' );
5253
53 -//some static utility mediaWiki functions that we use:
 54+// Some static utility MediaWiki functions that we use:
5455 function wfClientAcceptsGzip() {
5556 global $wgUseGzip;
56 - if( $wgUseGzip ) {
 57+ if ( $wgUseGzip ) {
5758 # FIXME: we may want to blacklist some broken browsers
5859 $m = array();
59 - if( preg_match(
 60+ if ( preg_match(
6061 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
6162 $_SERVER['HTTP_ACCEPT_ENCODING'],
6263 $m ) ) {
63 - if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
 64+ if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
6465 wfDebug( " accepts gzip\n" );
6566 return true;
6667 }
6768 }
6869 return false;
6970 }
70 -function wfDebug(){
 71+function wfDebug() {
7172 return false;
7273 }
7374
@@ -85,7 +86,7 @@
8687 wfDebug( "$caller: called wfMkdirParents($dir)" );
8788 }
8889
89 - if( strval( $dir ) === '' || file_exists( $dir ) )
 90+ if ( strval( $dir ) === '' || file_exists( $dir ) )
9091 return true;
9192
9293 if ( is_null( $mode ) )
@@ -93,15 +94,15 @@
9495
9596 return @mkdir( $dir, $mode, true ); // PHP5 <3
9697 }
97 -function wfMsgNoTrans($msgKey){
 98+function wfMsgNoTrans( $msgKey ) {
9899 global $messages, $mwLanguageCode;
99 - //make sure we have the messages file:
100 - require_once( realpath( dirname(__FILE__) ) . '/languages/mwEmbed.i18n.php' );
 100+ // Make sure we have the messages file:
 101+ require_once( realpath( dirname( __FILE__ ) ) . '/languages/mwEmbed.i18n.php' );
101102
102 - if(isset($messages[$mwLanguageCode]) && isset($messages[$mwLanguageCode][$msgKey]) ){
 103+ if ( isset( $messages[$mwLanguageCode] ) && isset( $messages[$mwLanguageCode][$msgKey] ) ) {
103104 return $messages[$mwLanguageCode][$msgKey];
104 - }else{
 105+ } else {
105106 return '&lt;' . $msgKey . '&gt;';
106107 }
107108 }
108 -?>
\ No newline at end of file
 109+?>
Index: trunk/phase3/js2/mwEmbed/mv_embed.js
@@ -1,31 +1,31 @@
22 /*
33 * ~mv_embed ~
4 - * for details see: http://metavid.org/wiki/index.php/Mv_embed
 4+ * For details see: http://metavid.org/wiki/index.php/Mv_embed
55 *
6 - * All Metavid Wiki code is Released under the GPL2
7 - * for more info visit http://metavid.org/wiki/Code
 6+ * All Metavid Wiki code is released under the GPL2.
 7+ * For more information visit http://metavid.org/wiki/Code
88 *
99 * @url http://metavid.org
1010 *
1111 * parseUri:
1212 * http://stevenlevithan.com/demo/parseuri/js/
1313 *
14 - * config values you can manually set the location of the mv_embed folder here
 14+ * Config values: you can manually set the location of the mv_embed folder here
1515 * (in cases where media will be hosted in a different place than the embedding page)
1616 *
1717 */
18 -//fix multiple instances of mv_embed (ie include twice from two different servers)
 18+// Fix multiple instances of mv_embed (i.e. include twice from two different servers)
1919 var MV_DO_INIT=true;
2020 if( MV_EMBED_VERSION ){
2121 MV_DO_INIT=false;
2222 }
23 -//used to grab fresh copies of scripts. (should be changed on commit)
 23+// Used to grab fresh copies of scripts. (should be changed on commit)
2424 var MV_EMBED_VERSION = '1.0r19';
2525
2626 /*
27 - * Configuration variables (can be set from some precceding script)
28 - * set up mwConfig global overide any of the defaultMwConfig values:
29 - * @@ more config valuse on the way ;)
 27+ * Configuration variables (can be set from some preceding script).
 28+ * Set up mwConfig global, override any of the defaultMwConfig values:
 29+ * @@ more config values on the way ;)
3030 */
3131 var defaultMwConfig = {
3232 'skin_name': 'mvpcf',
@@ -33,52 +33,54 @@
3434 'video_size':'400x300'
3535 }
3636
37 -if(!mwConfig)
38 - var mwConfig = {};
 37+if( !mwConfig )
 38+ var mwConfig = {};
3939
40 -//install the default config values for anything not set in mwConfig
 40+// Install the default config values for anything not set in mwConfig
4141 checkDefaultMwConfig();
4242
43 -//whether or not to load java from an iframe.
44 -//note: this is necessary for remote embedding because of java security model)
45 -if(!mv_java_iframe)
 43+// Whether or not to load java from an iframe.
 44+// Note: this is necessary for remote embedding because of Java's security model)
 45+if( !mv_java_iframe )
4646 var mv_java_iframe = true;
4747
48 -//for when useing mv_embed with script-loader in root mediawiki path
 48+// For use when mv_embed with script-loader is in the root MediaWiki path
4949 var mediaWiki_mvEmbed_path = 'js2/mwEmbed/';
5050
51 -var global_player_list = new Array(); //the global player list per page
52 -var global_req_cb = new Array(); //the global request callback array
53 -var _global = this; //global obj
 51+var global_player_list = new Array(); // The global player list per page
 52+var global_req_cb = new Array(); // The global request callback array
 53+var _global = this; // Global obj
5454 var mv_init_done = false;
55 -var global_cb_count =0;
 55+var global_cb_count = 0;
5656
5757 /*parseUri class parses URIs:*/
5858 var parseUri=function(d){var o=parseUri.options,value=o.parser[o.strictMode?"strict":"loose"].exec(d);for(var i=0,uri={};i<14;i++){uri[o.key[i]]=value[i]||""}uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function(a,b,c){if(b)uri[o.q.name][b]=c});return uri};parseUri.options={strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};
5959
6060
61 -//get mv_embed location if it has not been set
62 -if( !mv_embed_path ){
 61+// Get the mv_embed location if it has not been set
 62+if( !mv_embed_path ) {
6363 var mv_embed_path = getMvEmbedPath();
6464 }
6565
66 -//setup the skin path:
 66+// Set up the skin path
6767 var mv_jquery_skin_path = mv_embed_path + 'jquery/jquery.ui/themes/' +mwConfig['jui_skin'] + '/';
6868 var mv_skin_img_path = mv_embed_path + 'skins/' + mwConfig['skin_name'] + '/images/';
6969 var mv_default_thumb_url = mv_skin_img_path + 'vid_default_thumb.jpg';
7070
7171
72 -//init the global Msg if not already
73 -if(!gMsg){var gMsg={};}
 72+// Init the global message table if it has not been initialised already
 73+if( !gMsg ) {
 74+ var gMsg = {};
 75+}
7476
75 -//laguage msg loader:
76 -function loadGM( msgSet ){
77 - for(var i in msgSet){
 77+// Language msg loader
 78+function loadGM( msgSet ) {
 79+ for( var i in msgSet ) {
7880 gMsg[ i ] = msgSet[i];
7981 }
8082 }
8183
82 -//all default msg in [English] should be overwritten by the CMS language msg system.
 84+// All default messages in [English] should be overwritten by the CMS language message system.
8385 loadGM({
8486 "mwe-loading_txt" : "loading <blink>...<\/blink>",
8587 "mwe-loading_title" : "Loading...",
@@ -90,36 +92,36 @@
9193
9294 /**
9395 * AutoLoader paths (this should mirror the file: jsAutoloadLocalClasses.php )
94 - * any file _not_ listed here won't be auto-loadable
95 - * @path the path to the file (or set of files) with ending slash
96 - * @gClasses the set of classes
97 - * if an array $j.className become jquery.className.js
98 - * if an asssociative object then key => value paris are used
 96+ * Any file _not_ listed here won't be auto-loadable
 97+ * @path The path to the file (or set of files) with ending slash
 98+ * @gClasses The set of classes
 99+ * if it's an array, $j.className becomes jquery.className.js
 100+ * if it's an associative object then key => value pairs are used
99101 */
100 -if(typeof mvAutoLoadClasses == 'undefined')
 102+if( typeof mvAutoLoadClasses == 'undefined' )
101103 mvAutoLoadClasses = {};
102104
103 -//the script that loads the classet
104 -function lcPaths( classSet){
105 - for(var i in classSet){
 105+// The script that loads the class set
 106+function lcPaths( classSet ){
 107+ for( var i in classSet ) {
106108 mvAutoLoadClasses[i] = classSet[i];
107109 }
108110 }
109111
110112 function mvGetClassPath(k){
111 - if( mvAutoLoadClasses[k] ){
112 - //js_log('got classpath:' + k + ' : '+ mvClassPaths[k]);
 113+ if( mvAutoLoadClasses[k] ) {
 114+ //js_log('got class path:' + k + ' : '+ mvClassPaths[k]);
113115 return mvAutoLoadClasses[k];
114 - }else{
 116+ } else {
115117 return js_error('could not find path for requested class ' + k );
116118 }
117119 }
118 -if(typeof mvCssPaths == 'undefined')
 120+if( typeof mvCssPaths == 'undefined' )
119121 mvCssPaths = {};
120122
121 -function lcCssPath(cssSet){
122 - for(var i in cssSet){
123 - mvCssPaths[i]= mv_embed_path + cssSet[i];
 123+function lcCssPath( cssSet ) {
 124+ for( var i in cssSet ) {
 125+ mvCssPaths[i] = mv_embed_path + cssSet[i];
124126 }
125127 }
126128
@@ -127,15 +129,16 @@
128130 * -- Load Class Paths --
129131 *
130132 * MUST BE VALID JSON (NOT JS)
131 - * is used by the scriptloader to autoLoad classes (so we only define this once for php & javascript)
 133+ * This is used by the script loader to auto-load classes (so we only define
 134+ * this once for PHP & JavaScript)
132135 *
133 - * this is more verbose than earlier version that compressed paths
134 - * but its all good gziping help compress repetative path strings
135 - * grouped by
 136+ * This is more verbose than the earlier version that compressed paths
 137+ * but it's all good, gzipping helps compress repetetive path strings
 138+ * grouped by directory.
136139 *
137 - * right now php AutoLoader only reads this mv_embed.js file
138 - * in the future we could have multiple lcPath calls that php reads
139 - * (if our autoloading class list becomes too long) just have to add thouse
 140+ * Right now the PHP AutoLoader only reads this mv_embed.js file.
 141+ * In the future we could have multiple lcPath calls that PHP reads
 142+ * (if our autoloading class list becomes too long) just have to add those
140143 * files to the jsAutoLoader file list.
141144 */
142145 lcPaths({
@@ -185,7 +188,7 @@
186189
187190 "mvFirefogg" : "libAddMedia/mvFirefogg.js",
188191 "mvAdvFirefogg" : "libAddMedia/mvAdvFirefogg.js",
189 - "mvBaseUploadInterface" : "libAddMedia/mvBaseUploadInterface.js",
 192+ "mvBaseUploadInterface" : "libAddMedia/mvBaseUploadInterface.js",
190193 "remoteSearchDriver" : "libAddMedia/remoteSearchDriver.js",
191194 "seqRemoteSearchDriver" : "libAddMedia/seqRemoteSearchDriver.js",
192195
@@ -215,7 +218,7 @@
216219
217220 });
218221
219 -//depencency mapping for css files for self contained included plugins:
 222+// Dependency mapping for CSS files for self-contained included plugins:
220223 lcCssPath({
221224 '$j.Jcrop' : 'libClipEdit/Jcrop/css/jquery.Jcrop.css',
222225 '$j.fn.ColorPicker' : 'libClipEdit/colorpicker/css/colorpicker.css'
@@ -224,59 +227,59 @@
225228 /**
226229 * Language Functions:
227230 *
228 - * These functions try to losely mirro the functionality of Language.php in mediaWiki
 231+ * These functions try to loosely mirror the functionality of Language.php in MediaWiki
229232 */
230233 function gM( key , args ) {
231 - var ms ='';
 234+ var ms = '';
232235 if ( key in gMsg ) {
233236 ms = gMsg[ key ];
234 - if(typeof args == 'object' || typeof args == 'array'){
235 - for(var v in args){
236 - //msg test replace arguments start at 1 insted of zero:
237 - var rep = '\$'+ ( parseInt(v) + 1 );
238 - ms = ms.replace( rep, args[v]);
239 - }
240 - }else if(typeof args =='string' || typeof args =='number'){
 237+ if( typeof args == 'object' || typeof args == 'array' ) {
 238+ for( var v in args ) {
 239+ // Message test replace arguments start at 1 instead of zero:
 240+ var rep = '\$'+ ( parseInt(v) + 1 );
 241+ ms = ms.replace( rep, args[v] );
 242+ }
 243+ } else if( typeof args =='string' || typeof args =='number' ) {
241244 ms = ms.replace(/\$1/, args);
242 - }
243 - return ms;
244 - } else{
245 - //key is missing return indication:
 245+ }
 246+ return ms;
 247+ } else {
 248+ // Missing key placeholder
246249 return '&lt;' + key + '&gt;';
247250 }
248251 }
249252 /*
250 - * msgSet is either a string corresponding to a single msg to load
251 - * or msgSet is an array with set of msg to load
 253+ * msgSet is either a string corresponding to a single message to load, or an
 254+ * array with a set of messages to load.
252255 */
253 -function gMsgLoadRemote(msgSet, callback){
 256+function gMsgLoadRemote( msgSet, callback ) {
254257 var ammessages = '';
255 - if(typeof msgSet == 'object' ){
256 - for(var i in msgSet){
257 - ammessages += msgSet[i] + '|';
 258+ if( typeof msgSet == 'object' ) {
 259+ for( var i in msgSet ) {
 260+ ammessages += msgSet[i] + '|';
258261 }
259 - }else if(typeof msgSet == 'string'){
 262+ } else if( typeof msgSet == 'string' ) {
260263 ammessages += msgSet;
261264 }
262 - if(ammessages == ''){
263 - js_log('gMsgLoadRemote::no msg set requested');
 265+ if( ammessages == '' ) {
 266+ js_log( 'gMsgLoadRemote: no message set requested' );
264267 return false;
265268 }
266269 do_api_req({
267 - 'data':{
268 - 'meta':'allmessages',
269 - 'ammessages':ammessages
 270+ 'data': {
 271+ 'meta': 'allmessages',
 272+ 'ammessages': ammessages
270273 }
271 - },function(data){
272 - if(data.query.allmessages){
 274+ }, function( data ) {
 275+ if( data.query.allmessages ) {
273276 var msgs = data.query.allmessages;
274 - for(var i in msgs){
 277+ for( var i in msgs ) {
275278 var ld = {};
276 - ld[ msgs[i]['name'] ] = msgs[i]['*'];
 279+ ld[ msgs[i]['name'] ] = msgs[i]['*'];
277280 loadGM( ld );
278281 }
279282 }
280 - //load the result into local msg var
 283+ // Load the result into local msg var
281284 callback();
282285 });
283286 }
@@ -289,7 +292,7 @@
290293 * @return string Plain text (not HTML)
291294 */
292295 function formatSize( size ) {
293 - // For small sizes no decimal places necessary
 296+ // For small sizes no decimal places are necessary
294297 var round = 0;
295298 var msg = '';
296299 if( size > 1024 ) {
@@ -310,15 +313,15 @@
311314 } else {
312315 msg = 'mwe-size-bytes';
313316 }
314 - //javascript does not let you do precession points in rounding
315 - var p = Math.pow(10,round);
316 - var size = Math.round( size * p ) / p;
 317+ // JavaScript does not let you choose the precision when rounding
 318+ var p = Math.pow(10,round);
 319+ var size = Math.round( size * p ) / p;
317320 //@@todo we need a formatNum and we need to request some special packaged info to deal with that case.
318 - return gM( msg , size );
 321+ return gM( msg , size );
319322 }
320323
321 -//gets the loading image:
322 -function mv_get_loading_img( style , class_attr ){
 324+// Get the loading image
 325+function mv_get_loading_img( style, class_attr ){
323326 var style_txt = (style)?style:'';
324327 var class_attr = (class_attr)?'class="'+class_attr+'"':'class="mv_loading_img"';
325328 return '<div '+class_attr+' style="' + style +'"></div>';
@@ -335,172 +338,182 @@
336339 /**
337340 * mvJsLoader class handles initialization and js file loads
338341 */
339 -
340 -//shortcut:
341 -function mwLoad(loadSet, callback){
342 - mvJsLoader.doLoad(loadSet, callback);
343 -}
 342+
 343+// Shortcut
 344+function mwLoad( loadSet, callback ) {
 345+ mvJsLoader.doLoad( loadSet, callback );
 346+}
344347 var mvJsLoader = {
345 - libreq : {},
346 - libs : {},
347 - //base lib flags:
348 - onReadyEvents:new Array(),
349 - doneReadyEvents:false,
350 - jQueryCheckFlag:false,
351 - //to keep consistency across threads:
352 - ptime:0,
353 - ctime:0,
354 - load_error:false, //load error flag (false by default)
355 - load_time:0,
356 - callbacks:new Array(),
357 - cur_path: null,
358 - missing_path : null,
359 - doLoad:function(loadLibs, callback){
360 - this.ctime++;
361 - if( loadLibs && loadLibs.length!=0 ){ //setup this.libs:
 348+ libreq : {},
 349+ libs : {},
362350
363 - //first check if we already have this lib loaded
364 - var all_libs_loaded=true;
365 - for(var i=0; i< loadLibs.length; i++){
366 - //check if the lib is already loaded:
367 - if( ! this.checkObjPath( loadLibs[i] ) ){
368 - all_libs_loaded=false;
 351+ // Base lib flags
 352+ onReadyEvents: new Array(),
 353+ doneReadyEvents: false,
 354+ jQueryCheckFlag: false,
 355+
 356+ // To keep consistency across threads
 357+ ptime: 0,
 358+ ctime: 0,
 359+
 360+ load_error: false, // Load error flag (false by default)
 361+ load_time: 0,
 362+ callbacks: new Array(),
 363+ cur_path: null,
 364+ missing_path : null,
 365+ doLoad: function( loadLibs, callback ) {
 366+ this.ctime++;
 367+
 368+ if( loadLibs && loadLibs.length != 0 ) {
 369+ // Set up this.libs
 370+ // First check if we already have this library loaded
 371+ var all_libs_loaded = true;
 372+ for( var i = 0; i< loadLibs.length; i++ ) {
 373+ // Check if the library is already loaded
 374+ if( ! this.checkObjPath( loadLibs[i] ) ) {
 375+ all_libs_loaded = false;
369376 }
370 - }
371 - if( all_libs_loaded ){
372 - js_log('all libs already loaded skipping... load req');
 377+ }
 378+ if( all_libs_loaded ) {
 379+ js_log( 'All libraries already loaded, skipping load request' );
373380 callback();
374 - return ;
 381+ return;
375382 }
376 - //do a check for any css we may need and get it:
377 - for(var i=0; i< loadLibs.length; i++){
378 - if( typeof mvCssPaths[ loadLibs[i] ] != 'undefined' ){
379 - loadExternalCss( mvCssPaths[ loadLibs[i] ]);
 383+ // Do a check for any CSS we may need and get it
 384+ for( var i = 0; i < loadLibs.length; i++ ) {
 385+ if( typeof mvCssPaths[ loadLibs[i] ] != 'undefined' ) {
 386+ loadExternalCss( mvCssPaths[ loadLibs[i] ] );
380387 }
381388 }
382389
383 - //check if we should use the script loader to combine all the requests into one:
384 - if( typeof mwSlScript != 'undefined' ){
 390+ // Check if we should use the script loader to combine all the requests into one
 391+ if( typeof mwSlScript != 'undefined' ) {
385392 var class_set = '';
386 - var last_class = '';
387 - var coma = '';
388 - for(var i=0; i< loadLibs.length; i++){
389 - var curLib = loadLibs[i];
390 - //only add if not included yet:
391 - if( ! this.checkObjPath( curLib ) ){
392 - class_set+=coma + curLib ;
393 - last_class=curLib;
394 - coma=',';
395 - }
396 - }
397 - var puri = parseUri( getMvEmbedURL() );
398 - if( (getMvEmbedURL().indexOf('://')!=-1) && puri.host != parseUri( document.URL).host){
399 - mwSlScript = puri.protocol + '://' + puri.authority + mwSlScript;
400 - }
 393+ var last_class = '';
 394+ var coma = '';
 395+ for( var i = 0; i < loadLibs.length; i++ ) {
 396+ var curLib = loadLibs[i];
 397+ // Only add if not included yet:
 398+ if( ! this.checkObjPath( curLib ) ) {
 399+ class_set += coma + curLib;
 400+ last_class = curLib;
 401+ coma = ',';
 402+ }
 403+ }
 404+ var puri = parseUri( getMvEmbedURL() );
 405+ if( ( getMvEmbedURL().indexOf('://') != -1 )
 406+ && puri.host != parseUri( document.URL ).host )
 407+ {
 408+ mwSlScript = puri.protocol + '://' + puri.authority + mwSlScript;
 409+ }
401410
402 - var dbug_attr = (puri.queryKey['debug'])?'&debug=true':'';
403 - this.libs[ last_class ] = mwSlScript + '?class=' + class_set +
404 - '&urid=' + getMvUniqueReqId() + dbug_attr;
 411+ var dbug_attr = ( puri.queryKey['debug'] ) ? '&debug=true' : '';
 412+ this.libs[ last_class ] = mwSlScript + '?class=' + class_set +
 413+ '&urid=' + getMvUniqueReqId() + dbug_attr;
405414
406 - }else{
407 - //do many requests:
408 - for(var i=0; i< loadLibs.length; i++){
409 - var curLib = loadLibs[i];
410 - if(curLib){
411 - var libLoc = mvGetClassPath(curLib);
412 - // do a direct load of the file (pass along unique request id from request or mv_embed Version )
413 - var qmark = (libLoc.indexOf('?')!==true)?'?':'&';
414 - this.libs[curLib] = mv_embed_path + libLoc + qmark + 'urid='+ getMvUniqueReqId();
415 - }
416 - }
 415+ } else {
 416+ // Do many requests
 417+ for( var i = 0; i < loadLibs.length; i++ ) {
 418+ var curLib = loadLibs[i];
 419+ if( curLib ) {
 420+ var libLoc = mvGetClassPath( curLib );
 421+ // Do a direct load of the file (pass along unique request id from
 422+ // request or mv_embed Version )
 423+ var qmark = (libLoc.indexOf( '?' ) !== true) ? '?' : '&';
 424+ this.libs[curLib] = mv_embed_path + libLoc + qmark + 'urid=' + getMvUniqueReqId();
 425+ }
 426+ }
417427 }
418428 }
419 - if( callback ){
420 - this.callbacks.push(callback);
 429+ if( callback ) {
 430+ this.callbacks.push( callback );
421431 }
422 - if( this.checkLoading() ){
423 - if( this.load_time++ > 2000){ //time out after ~80seconds
424 - js_error( gM('mwe-error_load_lib') + this.missing_path );
425 - this.load_error = true;
426 - }else{
 432+ if( this.checkLoading() ) {
 433+ if( this.load_time++ > 2000 ){ // Time out after ~80 seconds
 434+ js_error( gM('mwe-error_load_lib') + this.missing_path );
 435+ this.load_error = true;
 436+ } else {
427437 setTimeout( 'mvJsLoader.doLoad()', 20 );
428 - }
429 - }else{
430 - //js_log('checkLoading passed run callbacks');
431 - //only do callback if we are in the same instance (weird concurency issue)
432 - var cb_count=0;
433 - for(var i=0; i < this.callbacks.length; i++)
434 - cb_count++;
435 - //js_log('REST LIBS: loading is: '+ loading + ' run callbacks: '+cb_count +' p:'+ this.ptime +' c:'+ this.ctime);
436 - //reset the libs
437 - this.libs={};
438 - //js_log('done loading do call: ' + this.callbacks[0] );
439 - while( this.callbacks.length !=0 ){
440 - if( this.ptime== ( this.ctime-1) ){ //enforce thread consistency
441 - this.callbacks.pop()();
442 - //func = this.callbacks.pop();
443 - //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func);
 438+ }
 439+ } else {
 440+ //js_log('checkLoading passed. Running callbacks...');
 441+ // Only do callbacks if we are in the same instance (weird concurency issue)
 442+ var cb_count=0;
 443+ for( var i = 0; i < this.callbacks.length; i++ )
 444+ cb_count++;
 445+ //js_log('RESET LIBS: loading is: '+ loading + ' callback count: '+cb_count +
 446+ // ' p:'+ this.ptime +' c:'+ this.ctime);
 447+
 448+ // Reset the libs
 449+ this.libs = {};
 450+ //js_log('done loading, do call: ' + this.callbacks[0] );
 451+ while( this.callbacks.length != 0 ) {
 452+ if( this.ptime == this.ctime - 1 ) { // Enforce thread consistency
 453+ this.callbacks.pop()();
 454+ //func = this.callbacks.pop();
 455+ //js_log(' run: '+this.ctime+ ' p: ' + this.ptime + ' ' +loading+ ' :'+ func);
444456 //func();
445 - }else{
446 - //re-issue doLoad ( ptime will be set to ctime so we should catch up)
447 - setTimeout( 'mvJsLoader.doLoad()', 25 );
448 - break;
449 - }
450 - }
451 - }
452 - this.ptime=this.ctime;
453 - },
454 - doLoadFullPaths:function(loadObj, callback){
 457+ } else {
 458+ // Re-issue doLoad ( ptime will be set to ctime so we should catch up)
 459+ setTimeout( 'mvJsLoader.doLoad()', 25 );
 460+ break;
 461+ }
 462+ }
 463+ }
 464+ this.ptime = this.ctime;
 465+ },
 466+ doLoadFullPaths: function( loadObj, callback ) {
455467
456 - },
457 - doLoadDepMode:function(loadChain, callback){
458 - //firefox executes js ~in-order of it being included~ so just directly issue request:
459 - if( $j.browser.firefox ){
460 - var loadSet = [];
461 - for(var i=0; i< loadChain.length;i++){
462 - for(var j=0;j<loadChain[i].length;j++){
463 - loadSet.push(loadChain[i][j]);
464 - }
465 - }
466 - mvJsLoader.doLoad(loadSet, callback);
467 - }else{
468 - //safari and IE tend to execute out of order so load with dependenciy checks
469 - mvJsLoader.doLoad(loadChain.shift(),function(){
470 - if(loadChain.length!=0){
471 - mvJsLoader.doLoadDepMode(loadChain, callback);
472 - }else{
473 - callback();
474 - }
475 - });
476 - } },
477 - checkLoading:function(){
478 - var loading=0;
479 - var i=null;
480 - for(var i in this.libs){ //for in loop oky on object
481 - if( !this.checkObjPath( i ) ){
482 - if(!this.libreq[i]){
483 - loadExternalJs( this.libs[i] );
484 - }
 468+ },
 469+ doLoadDepMode: function( loadChain, callback ) {
 470+ // Firefox executes JS in the order in which it is included, so just directly issue the request
 471+ if( $j.browser.firefox ) {
 472+ var loadSet = [];
 473+ for( var i = 0; i < loadChain.length; i++ ) {
 474+ for( var j = 0; j < loadChain[i].length; j++ ) {
 475+ loadSet.push( loadChain[i][j] );
 476+ }
 477+ }
 478+ mvJsLoader.doLoad( loadSet, callback );
 479+ } else {
 480+ // Safari and IE tend to execute out of order so load with dependency checks
 481+ mvJsLoader.doLoad( loadChain.shift(), function() {
 482+ if( loadChain.length != 0 ) {
 483+ mvJsLoader.doLoadDepMode( loadChain, callback );
 484+ } else {
 485+ callback();
 486+ }
 487+ });
 488+ }
 489+ },
 490+ checkLoading: function() {
 491+ var loading = 0;
 492+ var i = null;
 493+ for( var i in this.libs ) { // for/in loop is OK on an object
 494+ if( !this.checkObjPath( i ) ) {
 495+ if( !this.libreq[i] ) {
 496+ loadExternalJs( this.libs[i] );
 497+ }
485498
486 - this.libreq[i]=1;
487 - //js_log("has not yet loaded: " + i);
488 - loading=1;
489 - }
490 - }
491 - return loading;
 499+ this.libreq[i] = 1;
 500+ //js_log("has not yet loaded: " + i);
 501+ loading = 1;
 502+ }
 503+ }
 504+ return loading;
492505 },
493 - checkObjPath:function( libVar ){
494 - if(!libVar)
 506+ checkObjPath: function( libVar ) {
 507+ if( !libVar )
495508 return false;
496 - var objPath = libVar.split('.')
497 - var cur_path ='';
498 - for(var p=0; p < objPath.length; p++){
499 - cur_path = (cur_path=='')?cur_path+objPath[p]:cur_path+'.'+objPath[p];
500 - eval( 'var ptest = typeof ( '+ cur_path + ' ); ');
501 - if( ptest == 'undefined'){
502 - this.missing_path = cur_path;
503 - return false;
504 - }
 509+ var objPath = libVar.split( '.' )
 510+ var cur_path = '';
 511+ for( var p = 0; p < objPath.length; p++ ) {
 512+ cur_path = (cur_path == '') ? cur_path + objPath[p] : cur_path + '.' + objPath[p];
 513+ eval( 'var ptest = typeof ( '+ cur_path + ' ); ');
 514+ if( ptest == 'undefined' ) {
 515+ this.missing_path = cur_path;
 516+ return false;
 517+ }
505518 }
506519 this.cur_path = cur_path;
507520 return true;
@@ -508,39 +521,40 @@
509522 /**
510523 * checks for jQuery and adds the $j noConflict var
511524 */
512 - jQueryCheck:function(callback){
513 - //skip stuff if $j is already loaded:
514 - if(_global['$j'] && callback)
 525+ jQueryCheck: function( callback ) {
 526+ // Skip stuff if $j is already loaded
 527+ if( _global['$j'] && callback )
515528 callback();
516529 var _this = this;
517 - //load jquery
 530+ // Load jQuery
518531 _this.doLoad([
519 - 'window.jQuery'
520 - ],function(){
 532+ 'window.jQuery'
 533+ ], function() {
521534 _global['$j'] = jQuery.noConflict();
522 - //set up ajax to not send dynamic urls for loading scripts (we control that with the scriptLoader)
 535+ // Set up AJAX to not send dynamic URLs for loading scripts (we control that with
 536+ // the scriptLoader)
523537 $j.ajaxSetup({
524 - cache: true
 538+ cache: true
525539 });
526 - js_log('jquery loaded');
527 - //setup mvEmbed jquery bindigns:
 540+ js_log( 'jquery loaded' );
 541+ // Set up mvEmbed jQuery bindings:
528542 mv_jqueryBindings();
529 - //run the callback
530 - if(callback){
 543+ // Run the callback
 544+ if( callback ) {
531545 callback();
532546 }
533547 });
534548 },
535 - embedVideoCheck:function( callback ){
 549+ embedVideoCheck:function( callback ) {
536550 var _this = this;
537 - js_log('embedVideoCheck:');
538 - //set videonojs to loading
539 - //issue a style sheet request get both mv_embed and jquery styles:
 551+ js_log( 'embedVideoCheck:' );
 552+ // Set videonojs to loading
 553+ // Issue a style sheet request to get both mv_embed and jQuery styles:
540554 loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
541 - loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name']+'/styles.css');
 555+ loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name'] + '/styles.css' );
542556
543 - //make sure we have jQuery
544 - _this.jQueryCheck(function(){
 557+ // Make sure we have jQuery
 558+ _this.jQueryCheck( function() {
545559 $j('.videonojs').html( gM('mwe-loading_txt') );
546560 var depReq = [
547561 [
@@ -553,226 +567,226 @@
554568 '$j.ui.slider'
555569 ]
556570 ];
557 - //add png fix if needed:
558 - if($j.browser.msie || $j.browser.version < 7)
 571+ // Add PNG fix if needed:
 572+ if( $j.browser.msie || $j.browser.version < 7 )
559573 depReq[0].push( '$j.fn.pngFix' );
560574
561 - _this.doLoadDepMode(depReq,function(){
 575+ _this.doLoadDepMode( depReq, function() {
562576 embedTypes.init();
563577 callback();
564578 $j('.videonojs').remove();
565579 });
566580 });
567581 },
568 - addLoadEvent:function(fn){
569 - this.onReadyEvents.push(fn);
 582+ addLoadEvent: function( fn ) {
 583+ this.onReadyEvents.push( fn );
570584 },
571 - //checks the jQuery flag (this way when remote embeding we don't load jQuery
572 - // unless js2AddOnloadHook was used or there is video on the page
573 - runQuededFunctions:function(){
 585+ // Check the jQuery flag. This way, when remote embedding, we don't load jQuery
 586+ // unless js2AddOnloadHook was used or there is video on the page.
 587+ runQueuedFunctions: function() {
574588 var _this = this;
575 - this.doneReadyEvents=true;
576 - if(this.jQueryCheckFlag){
577 - this.jQueryCheck(function(){
 589+ this.doneReadyEvents = true;
 590+ if( this.jQueryCheckFlag ) {
 591+ this.jQueryCheck( function() {
578592 _this.runReadyEvents();
579593 });
580 - }else{
 594+ } else {
581595 this.runReadyEvents();
582596 }
583597 },
584 - runReadyEvents:function(){
585 - js_log("runReadyEvents");
586 - while( this.onReadyEvents.length ){
 598+ runReadyEvents: function() {
 599+ js_log( "runReadyEvents" );
 600+ while( this.onReadyEvents.length ) {
587601 this.onReadyEvents.shift()();
588602 }
589603 }
590 -
591604 }
592 -//load an external JS (similar to jquery .require plugin)
593 -//but checks for object availability rather than load state
594605
 606+// Load an external JS file. Similar to jquery .require plugin,
 607+// but checks for object availability rather than load state.
 608+
595609 /*********** INITIALIZATION CODE *************
596 - * this will get called when DOM is ready
 610+ * This will get called when the DOM is ready
597611 *********************************************/
598 -/* jQuery .ready does not work when jQuery is loaded dynamically
599 - * for an example of the problem see:1.1.3 working:http://pastie.caboo.se/92588
 612+/* jQuery .ready does not work when jQuery is loaded dynamically.
 613+ * For an example of the problem see: 1.1.3 working: http://pastie.caboo.se/92588
600614 * and >= 1.1.4 not working: http://pastie.caboo.se/92595
601615 * $j(document).ready( function(){ */
602 -function mwdomReady(force){
603 - js_log('f:mwdomReady:');
604 - if( !force && mv_init_done ){
605 - js_log("mv_init_done already done do nothing...");
 616+function mwdomReady( force ) {
 617+ js_log( 'f:mwdomReady:' );
 618+ if( !force && mv_init_done ) {
 619+ js_log( "mv_init_done already done, do nothing..." );
606620 return false;
607621 }
608 - mv_init_done=true;
609 - //handle the execution of Queded function with jQuery "ready"
 622+ mv_init_done = true;
 623+ // Handle the execution of queued functions with jQuery "ready"
610624
611 - //check if this page does have video or playlist
 625+ // Check if this page has a video or playlist
612626 var e = [
613 - document.getElementsByTagName("video"),
614 - document.getElementsByTagName("audio"),
615 - document.getElementsByTagName("playlist")
 627+ document.getElementsByTagName( "video" ),
 628+ document.getElementsByTagName( "audio" ),
 629+ document.getElementsByTagName( "playlist" )
616630 ];
617 - if(e[0].length!=0 || e[1].length!=0 || e[2].length!=0){
618 - js_log('we have items to rewrite');
619 - setSwapableToLoading(e);
620 - //load libs and proccess:
621 - mvJsLoader.embedVideoCheck(function(){
622 - //run any queded global events:
623 - mv_video_embed( function(){
624 - mvJsLoader.runQuededFunctions();
 631+ if( e[0].length != 0 || e[1].length != 0 || e[2].length != 0 ) {
 632+ js_log( 'we have items to rewrite' );
 633+ setSwappableToLoading( e );
 634+ // Load libs and process them
 635+ mvJsLoader.embedVideoCheck( function() {
 636+ // Run any queued global events:
 637+ mv_video_embed( function() {
 638+ mvJsLoader.runQueuedFunctions();
625639 });
626640 });
627 - }else{
628 - //if we already have jQuery make sure its loaded into its proper context $j
629 - //run any queded global events:
630 - mvJsLoader.runQuededFunctions();
 641+ } else {
 642+ // If we already have jQuery, make sure it's loaded into its proper context $j
 643+ // Run any queued global events
 644+ mvJsLoader.runQueuedFunctions();
631645 }
632646 }
633 -//a quick function that sets the intial text of swapable elements to "loading"
634 -// (jquery might not be ready)
635 -//(does not destroy inner elements)
636 -function setSwapableToLoading(e){
 647+// A quick function that sets the initial text of swappable elements to "loading".
 648+// jQuery might not be ready. Does not destroy inner elements.
 649+function setSwappableToLoading( e ) {
637650 //for(var i =0)
638651 //for(var j = 0; i < j.length; j++){
639652 //}
640653 }
641 -//js2AddOnloadHook: ensure jQuery and the DOM are ready:
 654+//js2AddOnloadHook: ensure jQuery and the DOM are ready
642655 function js2AddOnloadHook( func ) {
643 - //make sure the skin/style sheets are avaliable always:
 656+ // Make sure the skin/style sheets are always available:
644657 loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
645 - loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name']+'/styles.css');
 658+ loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name'] + '/styles.css' );
646659
647 - //if we have already run the dom ready just run the function directly:
648 - if( mvJsLoader.doneReadyEvents ){
649 - //make sure jQuery is there:
650 - mvJsLoader.jQueryCheck(function(){
 660+ // If we have already run the DOM-ready function, just run the function directly:
 661+ if( mvJsLoader.doneReadyEvents ) {
 662+ // Make sure jQuery is there:
 663+ mvJsLoader.jQueryCheck( function() {
651664 func();
652665 });
653 - }else{
654 - //if using js2AddOnloadHook we need to get jQuery into place (if its not already included)
 666+ } else {
 667+ // If we are using js2AddOnloadHook we need to get jQuery into place (if it's not already included)
655668 mvJsLoader.jQueryCheckFlag = true;
656669 mvJsLoader.addLoadEvent( func );
657 - };
 670+ }
658671 }
659 -//depreciated mwAddOnloadHook in favor of js2 naming (for clear seperation of js2 code from old mw code
 672+// Deprecated mwAddOnloadHook in favor of js2 naming (for clear separation of js2 code from old MW code
660673 var mwAddOnloadHook = js2AddOnloadHook;
661674 /*
662 - * this function allows for targeted rewriting
 675+ * This function allows for targeted rewriting
663676 */
664 -function rewrite_by_id( vid_id, ready_callback ){
665 - js_log('f:rewrite_by_id: ' + vid_id);
666 - //force a recheck of the dom for playlist or video element:
667 - mvJsLoader.embedVideoCheck(function(){
668 - mv_video_embed(ready_callback, vid_id );
 677+function rewrite_by_id( vid_id, ready_callback ) {
 678+ js_log( 'f:rewrite_by_id: ' + vid_id );
 679+ // Force a recheck of the DOM for playlist or video elements:
 680+ mvJsLoader.embedVideoCheck( function() {
 681+ mv_video_embed( ready_callback, vid_id );
669682 });
670683 }
671 -//depricated in favor of updates to oggHanlder
672 -function rewrite_for_oggHanlder( vidIdList ){
673 - for(var i = 0; i < vidIdList.length ; i++){
 684+// Deprecated in favor of updates to OggHandler
 685+function rewrite_for_OggHandler( vidIdList ){
 686+ for( var i = 0; i < vidIdList.length; i++ ) {
674687 var vidId = vidIdList[i];
675 - js_log('looking at vid: ' + i +' ' + vidId);
676 - //grab the thumbnail and src video
677 - var pimg = $j('#'+vidId + ' img');
678 - var poster_attr = 'poster = "' + pimg.attr('src') + '" ';
679 - var pwidth = pimg.attr('width');
680 - var pheight = pimg.attr('height');
 688+ js_log( 'looking at vid: ' + i +' ' + vidId );
 689+ // Grab the thumbnail and src of the video
 690+ var pimg = $j( '#' + vidId + ' img' );
 691+ var poster_attr = 'poster = "' + pimg.attr( 'src' ) + '" ';
 692+ var pwidth = pimg.attr( 'width' );
 693+ var pheight = pimg.attr( 'height' );
681694
682695 var type_attr = '';
683 - //check for audio
684 - if( pwidth=='22' && pheight=='22'){
685 - pwidth='400';
686 - pheight='300';
 696+ // Check for audio
 697+ if( pwidth == '22' && pheight == '22' ) {
 698+ pwidth = '400';
 699+ pheight = '300';
687700 type_attr = 'type="audio/ogg"';
688701 poster_attr = '';
689702 }
690703
691 - //parsed values:
 704+ // Parsed values:
692705 var src = '';
693706 var duration = '';
694707
695708 var re = new RegExp( /videoUrl(&quot;:?\s*)*([^&]*)/ );
696 - src = re.exec( $j('#'+vidId).html() )[2];
 709+ src = re.exec( $j( '#'+vidId).html() )[2];
697710
698711 var re = new RegExp( /length(&quot;:?\s*)*([^&]*)/ );
699 - duration = re.exec( $j('#'+vidId).html() )[2];
 712+ duration = re.exec( $j( '#'+vidId).html() )[2];
700713
701714 var re = new RegExp( /offset(&quot;:?\s*)*([^&]*)/ );
702 - offset = re.exec( $j('#'+vidId).html() )[2];
703 - var offset_attr = (offset)? 'startOffset="'+ offset + '"': '';
 715+ offset = re.exec( $j( '#'+vidId).html() )[2];
 716+ var offset_attr = offset ? 'startOffset="' + offset + '"' : '';
704717
705 - if( src ){
706 - //replace the top div with mv_embed based player:
 718+ if( src ) {
 719+ // Replace the top div with the mv_embed based player:
707720 var vid_html = '<video id="vid_' + i +'" '+
708 - 'src="' + src + '" ' +
709 - poster_attr + ' ' +
710 - type_attr + ' ' +
711 - offset_attr + ' ' +
712 - 'duration="' + duration + '" ' +
713 - 'style="width:' + pwidth + 'px;height:' +
714 - pheight + 'px;"></video>';
715 - //js_log("video html: " + vid_html);
716 - $j('#'+vidId).html( vid_html );
 721+ 'src="' + src + '" ' +
 722+ poster_attr + ' ' +
 723+ type_attr + ' ' +
 724+ offset_attr + ' ' +
 725+ 'duration="' + duration + '" ' +
 726+ 'style="width:' + pwidth + 'px;height:' +
 727+ pheight + 'px;"></video>';
 728+ //js_log("Video HTML: " + vid_html);
 729+ $j( '#'+vidId ).html( vid_html );
717730 }
718731
719 - //rewrite that video id:
720 - rewrite_by_id('vid_' + i);
 732+ // Rewrite that video ID:
 733+ rewrite_by_id( 'vid_' + i );
721734 }
722735 }
723736
724737
725738 /*********** INITIALIZATION CODE *************
726 - * set DOM ready callback to init_mv_embed
 739+ * set DOM-ready callback to init_mv_embed
727740 *********************************************/
728741 // for Mozilla browsers
729 -if (document.addEventListener ) {
730 - document.addEventListener("DOMContentLoaded", function(){mwdomReady()}, false);
731 -}else{
732 - //backup "onload" method in case on DOMContentLoaded does not exist
733 - window.onload = function(){ mwdomReady() };
 742+if ( document.addEventListener ) {
 743+ document.addEventListener( "DOMContentLoaded", function(){ mwdomReady() }, false );
 744+} else {
 745+ // Use the onload method instead when DOMContentLoaded does not exist
 746+ window.onload = function() { mwdomReady() };
734747 }
735748 /*
736 - * should depreciate and use jquery.ui.dialog instead
 749+ * Should deprecate and use jquery.ui.dialog instead
737750 */
738 -function mv_write_modal(content, speed){
739 - $j('#modalbox,#mv_overlay').remove();
740 - $j('body').append('<div id="modalbox" style="background:#DDD;border:3px solid #666666;font-size:115%;'+
741 - 'top:30px;left:20px;right:20px;bottom:30px;position:fixed;z-index:100;">'+
742 - content +
743 - '</div>'+
744 - '<div id="mv_overlay" style="background:#000;cursor:wait;height:100%;left:0;position:fixed;'+
745 - 'top:0;width:100%;z-index:5;filter:alpha(opacity=60);-moz-opacity: 0.6;'+
746 - 'opacity: 0.6;"/>');
747 - $j('#modalbox,#mv_overlay').show( speed );
 751+function mv_write_modal( content, speed ) {
 752+ $j( '#modalbox,#mv_overlay' ).remove();
 753+ $j( 'body' ).append(
 754+ '<div id="modalbox" style="background:#DDD;border:3px solid #666666;font-size:115%;' +
 755+ 'top:30px;left:20px;right:20px;bottom:30px;position:fixed;z-index:100;">' +
 756+ content +
 757+ '</div>' +
 758+ '<div id="mv_overlay" style="background:#000;cursor:wait;height:100%;left:0;position:fixed;' +
 759+ 'top:0;width:100%;z-index:5;filter:alpha(opacity=60);-moz-opacity: 0.6;' +
 760+ 'opacity: 0.6;"/>');
 761+ $j( '#modalbox,#mv_overlay' ).show( speed );
748762 }
749 -function mv_remove_modal(speed){
750 - $j('#modalbox,#mv_overlay').remove( speed);
 763+function mv_remove_modal( speed ) {
 764+ $j( '#modalbox,#mv_overlay' ).remove( speed );
751765 }
752766
753767 /*
754 - * stores all the mwEmbed jQuery specific bindings
755 - * (setup after jQuery is avaliable)
756 - * lets you call rewrites in a jquery "way"
 768+ * Store all the mwEmbed jQuery-specific bindings
 769+ * (set up after jQuery is available).
 770+ * This lets you call rewrites in a jQuery way
757771 *
758772 * @@ eventually we should refactor mwCode over to jQuery style plugins
759 - * and mv_embed.js will just hanndle dependency mapping and loading.
 773+ * and mv_embed.js will just handle dependency mapping and loading.
760774 *
761775 */
762 -function mv_jqueryBindings(){
763 - js_log('mv_jqueryBindings');
764 - (function($) {
765 - $.fn.addMediaWiz = function( iObj, callback ){
766 - //first set the cursor for the button to "loading"
767 - $j(this.selector).css('cursor','wait').attr('title', gM('mwe-loading_title'));
 776+function mv_jqueryBindings() {
 777+ js_log( 'mv_jqueryBindings' );
 778+ (function( $ ) {
 779+ $.fn.addMediaWiz = function( iObj, callback ) {
 780+ // First set the cursor for the button to "loading"
 781+ $j( this.selector ).css( 'cursor', 'wait' ).attr( 'title', gM( 'mwe-loading_title' ) );
768782
769783 iObj['target_invocation'] = this.selector;
770784
771 - //load the mv_embed_base skin:
 785+ // Load the mv_embed_base skin:
772786 loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
773 - loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name']+'/styles.css' );
774 - //load all the req libs:
775 - mvJsLoader.jQueryCheck(function(){
776 - //load with staged dependeinces (for ie and safari that don't execute in order)
 787+ loadExternalCss( mv_embed_path + 'skins/' + mwConfig['skin_name']+'/styles.css' );
 788+ // Load all the required libs:
 789+ mvJsLoader.jQueryCheck( function() {
 790+ // Load with staged dependencies (for IE and Safari that don't execute in order)
777791 mvJsLoader.doLoadDepMode([
778792 [ 'remoteSearchDriver',
779793 '$j.cookie',
@@ -784,83 +798,87 @@
785799 '$j.ui.tabs',
786800 '$j.ui.sortable'
787801 ]
788 - ], function(){
789 - iObj['instance_name']= 'rsdMVRS';
 802+ ], function() {
 803+ iObj['instance_name'] = 'rsdMVRS';
790804 _global['rsdMVRS'] = new remoteSearchDriver( iObj );
791 - if( callback ){
792 - callback( _global['rsdMVRS'] );
 805+ if( callback ) {
 806+ callback( _global['rsdMVRS'] );
793807 }
794808 });
795809 });
796810 }
797 - $.fn.sequencer = function( iObj, callback){
798 - //debugger;
 811+ $.fn.sequencer = function( iObj, callback ) {
 812+ // Debugger
799813 iObj['target_sequence_container'] = this.selector;
800 - //issue a request to get the css file (if not already included):
801 - loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css');
802 - loadExternalCss( mv_embed_path+'skins/'+mwConfig['skin_name']+'/mv_sequence.css');
803 - //make sure we have the required mv_embed libs (they are not loaded when no video element is on the page)
804 - mvJsLoader.embedVideoCheck(function(){
805 - //load playlist object and then jquery ui stuff:
806 - mvJsLoader.doLoadDepMode([
807 - [
808 - 'mvPlayList',
809 - '$j.ui',
810 - '$j.contextMenu',
811 - '$j.secureEvalJSON',
812 - 'mvSequencer'
813 - ],
814 - [
815 - '$j.ui.accordion',
816 - '$j.ui.dialog',
817 - '$j.ui.droppable',
818 - '$j.ui.draggable',
819 - '$j.ui.progressbar',
820 - '$j.ui.sortable',
821 - '$j.ui.resizable',
822 - '$j.ui.slider',
823 - '$j.ui.tabs'
824 - ]
825 - ], function(){
826 - js_log('calling new mvSequencer');
827 - //init the sequence object (it will take over from there) no more than one mvSeq obj for now:
828 - if(!_global['mvSeq']){
829 - _global['mvSeq'] = new mvSequencer(iObj);
830 - }else{
831 - js_log('mvSeq already init');
832 - }
833 - });
834 - });
 814+ // Issue a request to get the CSS file (if not already included):
 815+ loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
 816+ loadExternalCss( mv_embed_path + 'skins/' + mwConfig['skin_name'] + '/mv_sequence.css' );
 817+ // Make sure we have the required mv_embed libs (they are not loaded when no video
 818+ // element is on the page)
 819+ mvJsLoader.embedVideoCheck( function() {
 820+ // Load the playlist object and then the jQuery UI stuff:
 821+ mvJsLoader.doLoadDepMode([
 822+ [
 823+ 'mvPlayList',
 824+ '$j.ui',
 825+ '$j.contextMenu',
 826+ '$j.secureEvalJSON',
 827+ 'mvSequencer'
 828+ ],
 829+ [
 830+ '$j.ui.accordion',
 831+ '$j.ui.dialog',
 832+ '$j.ui.droppable',
 833+ '$j.ui.draggable',
 834+ '$j.ui.progressbar',
 835+ '$j.ui.sortable',
 836+ '$j.ui.resizable',
 837+ '$j.ui.slider',
 838+ '$j.ui.tabs'
 839+ ]
 840+ ], function() {
 841+ js_log( 'calling new mvSequencer' );
 842+ // Initialise the sequence object (it will take over from there)
 843+ // No more than one mvSeq obj for now:
 844+ if( !_global['mvSeq'] ) {
 845+ _global['mvSeq'] = new mvSequencer( iObj );
 846+ } else {
 847+ js_log( 'mvSeq already init' );
 848+ }
 849+ });
 850+ });
835851 }
836852 /*
837 - * the firefogg jquery function:
838 - * @@note this firefogg envocation could be made to work more like real jquery plugins
 853+ * The Firefogg jQuery function:
 854+ * @@note This Firefogg invocation could be made to work more like real jQuery plugins
839855 */
840856 $.fn.firefogg = function( iObj, callback ) {
841 - if(!iObj)
842 - iObj={};
843 - //add base theme css:
844 - loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css');
845 - loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name']+'/styles.css' );
 857+ if( !iObj )
 858+ iObj = {};
 859+ // Add the base theme CSS:
 860+ loadExternalCss( mv_jquery_skin_path + 'jquery-ui-1.7.1.custom.css' );
 861+ loadExternalCss( mv_embed_path + 'skins/'+mwConfig['skin_name'] + '/styles.css' );
846862
847 - //check if we already have firefogg loaded (the call just updates properties for that element)
848 - var sElm = $j(this.selector).get(0);
849 - if(sElm['firefogg']){
850 - if(sElm['firefogg']=='loading'){
851 - js_log("Error: called firefogg operations on Firefogg selector that is not done loading");
 863+ // Check if we already have Firefogg loaded (the call just updates the element's
 864+ // properties)
 865+ var sElm = $j( this.selector ).get( 0 );
 866+ if( sElm['firefogg'] ) {
 867+ if( sElm['firefogg'] == 'loading' ) {
 868+ js_log( "Error: called firefogg operations on Firefogg selector that is " +
 869+ "not done loading" );
852870 return false;
853871 }
854 - //update properties:
855 - for(var i in iObj){
856 - js_log("firefogg::updated: "+ i + ' to '+ iObj[i]);
 872+ // Update properties
 873+ for( var i in iObj ) {
 874+ js_log( "firefogg::updated: " + i + ' to '+ iObj[i] );
857875 sElm['firefogg'][i] = iObj[i];
858876 }
859877 return sElm['firefogg'];
860 - }else{
861 - //avoid concurency
 878+ } else {
 879+ // Avoid concurency
862880 sElm['firefogg'] = 'loading';
863881 }
864 - //add the selector:
 882+ // Add the selector
865883 iObj['selector'] = this.selector;
866884
867885 var loadSet = [
@@ -874,7 +892,7 @@
875893 '$j.ui.dialog'
876894 ]
877895 ];
878 - if( iObj.encoder_interface ){
 896+ if( iObj.encoder_interface ) {
879897 loadSet.push([
880898 'mvAdvFirefogg',
881899 '$j.cookie',
@@ -883,81 +901,83 @@
884902 '$j.ui.datepicker'
885903 ]);
886904 }
887 - //make sure we have everything loaded that we need:
888 - mvJsLoader.doLoadDepMode( loadSet, function(){
889 - js_log('firefogg libs loaded. target select:' + iObj.selector);
890 - //select interface provicer based on if we want to include the encoder interface or not:
891 - if(iObj.encoder_interface){
 905+ // Make sure we have everything loaded that we need:
 906+ mvJsLoader.doLoadDepMode( loadSet, function() {
 907+ js_log( 'firefogg libs loaded. target select:' + iObj.selector );
 908+ // Select interface provider based on whether we want to include the
 909+ // encoder interface or not
 910+ if( iObj.encoder_interface ) {
892911 var myFogg = new mvAdvFirefogg( iObj );
893 - }else{
 912+ } else {
894913 var myFogg = new mvFirefogg( iObj );
895914 }
896 - if(myFogg){
 915+ if( myFogg ) {
897916 myFogg.doRewrite( callback );
898 - var selectorElement = $j( iObj.selector ).get(0);
899 - selectorElement['firefogg']=myFogg;
 917+ var selectorElement = $j( iObj.selector ).get( 0 );
 918+ selectorElement['firefogg'] = myFogg;
900919 }
901920 });
902921 }
903 - //takes a input player as the selector and exposes basic rendering controls
904 - $.fn.firefoggRender = function( iObj, callback ){
905 - //check if we already have render loaded then just pass on updates/actions
906 - var sElm = $j(this.selector).get(0);
907 - if(sElm['fogg_render']){
908 - if(sElm['fogg_render']=='loading'){
909 - js_log("Error: called firefoggRender while loading");
 922+ // Take an input player as the selector and expose basic rendering controls
 923+ $.fn.firefoggRender = function( iObj, callback ) {
 924+ // Check if we already have render loaded then just pass on updates/actions
 925+ var sElm = $j( this.selector ).get( 0 );
 926+ if( sElm['fogg_render'] ) {
 927+ if( sElm['fogg_render'] == 'loading' ) {
 928+ js_log( "Error: called firefoggRender while loading" );
910929 return false;
911930 }
912 - //call or update the property:
 931+ // Call or update the property:
913932 }
914 - sElm['fogg_render']='loading';
915 - //add the selector:
 933+ sElm['fogg_render'] = 'loading';
 934+ // Add the selector
916935 iObj['player_target'] = this.selector;
917936 mvJsLoader.doLoad([
918937 'mvFirefogg',
919938 'mvFirefoggRender'
920 - ],function(){
921 - sElm['fogg_render']= new mvFirefoggRender( iObj );
 939+ ], function() {
 940+ sElm['fogg_render'] = new mvFirefoggRender( iObj );
922941 if( callback && typeof callback == 'function' )
923942 callback( sElm['fogg_render'] );
924943 });
925944 }
926945
927 - $.fn.baseUploadInterface = function(iObj){
 946+ $.fn.baseUploadInterface = function(iObj) {
928947 mvJsLoader.doLoadDepMode([
929948 [
930949 'mvBaseUploadInterface',
931950 '$j.ui',
932951 ],
933952 [
934 - '$j.ui.progressbar',
935 - '$j.ui.dialog'
 953+ '$j.ui.progressbar',
 954+ '$j.ui.dialog'
936955 ]
937 - ],function(){
 956+ ], function() {
938957 myUp = new mvBaseUploadInterface( iObj );
939958 myUp.setupForm();
940959 });
941960 }
942961
943 - //shortcut to a themed button:
944 - $.btnHtml = function(msg, className, iconId, opt){
945 - if(!opt)
946 - opt = {};
947 - var href = (opt.href)?opt.href:'#';
948 - var target_attr = (opt.target)?' target="' + opt.target + '" ':'';
949 - var style_attr = (opt.style)?' style="'+opt.style +'" ':'';
950 - return '<a href="' + href + '" ' + target_attr + style_attr +' class="ui-state-default ui-corner-all ui-icon_link ' +
951 - className + '"><span class="ui-icon ui-icon-' + iconId + '" />' +
952 - msg + '</a>';
 962+ // Shortcut to a themed button
 963+ $.btnHtml = function( msg, className, iconId, opt ) {
 964+ if( !opt )
 965+ opt = {};
 966+ var href = (opt.href) ? opt.href : '#';
 967+ var target_attr = (opt.target) ? ' target="' + opt.target + '" ' : '';
 968+ var style_attr = (opt.style) ? ' style="' + opt.style + '" ' : '';
 969+ return '<a href="' + href + '" ' + target_attr + style_attr +
 970+ ' class="ui-state-default ui-corner-all ui-icon_link ' +
 971+ className + '"><span class="ui-icon ui-icon-' + iconId + '" />' +
 972+ msg + '</a>';
953973 }
954 - //shortcut to bind hover state:
955 - $.fn.btnBind = function(){
956 - $j(this).hover(
957 - function(){
958 - $j(this).addClass('ui-state-hover');
 974+ // Shortcut to bind hover state
 975+ $.fn.btnBind = function() {
 976+ $j( this ).hover(
 977+ function() {
 978+ $j( this ).addClass( 'ui-state-hover' );
959979 },
960 - function(){
961 - $j(this).removeClass('ui-state-hover');
 980+ function() {
 981+ $j( this ).removeClass( 'ui-state-hover' );
962982 }
963983 )
964984 return this;
@@ -966,392 +986,396 @@
967987 })(jQuery);
968988 }
969989 /*
970 -* utility functions:
 990+* Utility functions:
971991 */
972 -//simple url re-writer for rewriting urls (could probably be refactored into an inline regular expresion)
973 -function getURLParamReplace( url, opt ){
 992+// Simple URL rewriter (could probably be refactored into an inline regular expresion)
 993+function getURLParamReplace( url, opt ) {
974994 var pSrc = parseUri( url );
975 - if(pSrc.protocol != '' ){
976 - var new_url = pSrc.protocol +'://'+ pSrc.authority + pSrc.path +'?';
977 - }else{
978 - var new_url = pSrc.path +'?';
 995+ if( pSrc.protocol != '' ) {
 996+ var new_url = pSrc.protocol + '://' + pSrc.authority + pSrc.path + '?';
 997+ } else {
 998+ var new_url = pSrc.path + '?';
979999 }
9801000 var amp = '';
981 - for(var key in pSrc.queryKey){
 1001+ for( var key in pSrc.queryKey ) {
9821002 var val = pSrc.queryKey[ key ];
983 - //do override if requested
 1003+ // Do override if requested
9841004 if( opt[ key ] )
9851005 val = opt[ key ];
986 - new_url+= amp + key + '=' + val;
 1006+ new_url += amp + key + '=' + val;
9871007 amp = '&';
9881008 };
989 - //add any vars that did were not originally there:
990 - for(var i in opt){
991 - if(!pSrc.queryKey[i]){
992 - new_url+=amp + i + '=' + opt[i];
993 - amp = '&';
 1009+ // Add any vars that were not already there:
 1010+ for( var i in opt ) {
 1011+ if( !pSrc.queryKey[i] ) {
 1012+ new_url += amp + i + '=' + opt[i];
 1013+ amp = '&';
9941014 }
9951015 }
9961016 return new_url;
9971017 }
9981018 /**
999 - * seconds2npt given a float seconds returns npt format response:
1000 - * @param float seconds
1001 - * @param boolean if we should show ms or not.
 1019+ * Given a float number of seconds, returns npt format response.
 1020+ *
 1021+ * @param float Seconds
 1022+ * @param boolean If we should show milliseconds or not.
10021023 */
1003 -function seconds2npt(sec, show_ms){
1004 - if( isNaN( sec ) ){
1005 - //js_log("warning: trying to get npt time on NaN:" + sec);
 1024+function seconds2npt( sec, show_ms ) {
 1025+ if( isNaN( sec ) ) {
 1026+ // js_log("warning: trying to get npt time on NaN:" + sec);
10061027 return '0:0:0';
10071028 }
1008 - var hours = Math.floor(sec/ 3600);
1009 - var minutes = Math.floor((sec/60) % 60);
 1029+ var hours = Math.floor( sec / 3600 );
 1030+ var minutes = Math.floor( (sec / 60) % 60 );
10101031 var seconds = sec % 60;
1011 - //round the second amount requested significant digits
1012 - if(show_ms){
 1032+ // Round the number of seconds to the required number of significant digits
 1033+ if( show_ms ) {
10131034 seconds = Math.round( seconds * 1000 ) / 1000;
1014 - }else{
 1035+ } else {
10151036 seconds = Math.round( seconds );
10161037 }
1017 - if(seconds <10 )
1018 - seconds = '0'+ seconds;
1019 - if(minutes < 10 )
 1038+ if( seconds < 10 )
 1039+ seconds = '0' + seconds;
 1040+ if( minutes < 10 )
10201041 minutes = '0' + minutes;
10211042
1022 - return hours+":"+minutes+":"+seconds;
 1043+ return hours + ":" + minutes + ":" + seconds;
10231044 }
10241045 /*
1025 - * takes hh:mm:ss,ms or hh:mm:ss.ms input returns number of seconds
 1046+ * Take hh:mm:ss,ms or hh:mm:ss.ms input, return the number of seconds
10261047 */
1027 -function npt2seconds( npt_str ){
1028 - if(!npt_str){
 1048+function npt2seconds( npt_str ) {
 1049+ if( !npt_str ) {
10291050 //js_log('npt2seconds:not valid ntp:'+ntp);
10301051 return false;
10311052 }
1032 - //strip npt: time definition if present
1033 - npt_str = npt_str.replace('npt:', '');
 1053+ // Strip "npt:" time definition if present
 1054+ npt_str = npt_str.replace( 'npt:', '' );
10341055
1035 - times = npt_str.split(':');
1036 - if(times.length!=3){
1037 - js_log('error: npt2seconds on ' + npt_str);
 1056+ times = npt_str.split( ':' );
 1057+ if( times.length != 3 ){
 1058+ js_log( 'error: npt2seconds on ' + npt_str );
10381059 return false;
10391060 }
1040 - //sometimes the comma is used inplace of pereid for ms
1041 - times[2] = times[2].replace(/,\s?/,'.');
1042 - //return seconds float (ie take seconds float value if present):
1043 - return parseInt(times[0]*3600)+parseInt(times[1]*60)+parseFloat(times[2]);
 1061+ // Sometimes a comma is used instead of period for ms
 1062+ times[2] = times[2].replace( /,\s?/, '.' );
 1063+ // Return seconds float
 1064+ return parseInt( times[0] * 3600) + parseInt( times[1] * 60 ) + parseFloat( times[2] );
10441065 }
10451066 /*
1046 - * simple helper to grab a edit token
 1067+ * Simple helper to grab an edit token
10471068 *
1048 - * @param title the wiki page title you want to edit )
1049 - * @param api_url 'optional' the target api url
1050 - * @param callback the callback function to pass the token or "false" to
 1069+ * @param title The wiki page title you want to edit
 1070+ * @param api_url 'optional' The target API URL
 1071+ * @param callback The callback function to pass the token to
10511072 */
1052 -function get_mw_token( title, api_url, callback){
1053 - js_log(':get_mw_token:');
1054 - if(!title && wgUserName){
 1073+function get_mw_token( title, api_url, callback ) {
 1074+ js_log( ':get_mw_token:' );
 1075+ if( !title && wgUserName ) {
10551076 title = 'User:' + wgUserName;
10561077 }
10571078 var reqObj = {
1058 - 'action':'query',
1059 - 'prop':'info',
1060 - 'intoken':'edit',
1061 - 'titles':title
 1079+ 'action': 'query',
 1080+ 'prop': 'info',
 1081+ 'intoken': 'edit',
 1082+ 'titles': title
10621083 };
1063 - do_api_req( {
1064 - 'data': reqObj,
1065 - 'url' : api_url
1066 - },function(data){
1067 - for(var i in data.query.pages){
1068 - if(data.query.pages[i]['edittoken']){
1069 - if(typeof callback == 'function')
1070 - callback ( data.query.pages[i]['edittoken'] );
1071 - }
 1084+ do_api_req( {
 1085+ 'data': reqObj,
 1086+ 'url' : api_url
 1087+ }, function(data) {
 1088+ for( var i in data.query.pages ) {
 1089+ if( data.query.pages[i]['edittoken'] ) {
 1090+ if( typeof callback == 'function' )
 1091+ callback ( data.query.pages[i]['edittoken'] );
10721092 }
1073 - //no token found:
1074 - return false;
10751093 }
1076 - );
 1094+ // No token found:
 1095+ return false;
 1096+ }
 1097+ );
10771098 }
1078 -//does a remote or local api request based on request url
 1099+// Do a remote or local API request based on request URL
10791100 //@param options: url, data, cbParam, callback
1080 -function do_api_req( options, callback ){
1081 - if(typeof options.data != 'object'){
1082 - return js_error('Error: request paramaters must be an object');;
 1101+function do_api_req( options, callback ) {
 1102+ if( typeof options.data != 'object' ) {
 1103+ return js_error( 'Error: request paramaters must be an object' );
10831104 }
1084 - //gennerate the url if its missing:
1085 - if( typeof options.url == 'undefined' || options.url === false){
1086 - if(!wgServer || ! wgScriptPath){
1087 - return js_error('Error: no api url for api request');;
 1105+ // Generate the URL if it's missing
 1106+ if( typeof options.url == 'undefined' || options.url === false ) {
 1107+ if( !wgServer || ! wgScriptPath ) {
 1108+ return js_error('Error: no api url for api request');
10881109 }
1089 - //update to api.php (if index.php was in the wgScript path):
1090 - options.url = mwGetLocalApiUrl();
 1110+ options.url = mwGetLocalApiUrl();
10911111 }
10921112 if( typeof options.data == 'undefined' )
10931113 options.data = {};
10941114
1095 - //force format to json (if not already set)
 1115+ // Force format to JSON
10961116 options.data['format'] = 'json';
10971117
1098 - //if action not set assume query
1099 - if(!options.data['action'])
1100 - options.data['action']='query';
 1118+ // If action is not set, assume query
 1119+ if( !options.data['action'] )
 1120+ options.data['action'] = 'query';
11011121
1102 - //js_log('do api req: ' + options.url +'?' + jQuery.param(options.data) );
1103 - //build request string:
1104 - if( parseUri( document.URL ).host == parseUri( options.url ).host ){
1105 - //local request do api request directly
 1122+ // js_log('do api req: ' + options.url +'?' + jQuery.param(options.data) );
 1123+ // Build request string
 1124+ if( parseUri( document.URL ).host == parseUri( options.url ).host ) {
 1125+ // Local request: do API request directly
11061126 $j.ajax({
11071127 type: "POST",
11081128 url: options.url,
11091129 data: options.data,
1110 - dataType:'json', //api requests _should_ always return JSON data:
 1130+ dataType: 'json', // API requests _should_ always return JSON data:
11111131 async: false,
1112 - success:function(data){
1113 - callback( data );
 1132+ success: function( data ) {
 1133+ callback( data );
11141134 },
1115 - error:function(e){
1116 - js_error( ' error' + e +' in getting: ' + options.url);
 1135+ error: function( e ) {
 1136+ js_error( ' error' + e + ' in getting: ' + options.url );
11171137 }
11181138 });
1119 - }else{
1120 - //set the callback param if not already set:
1121 - if( typeof options.jsonCB == 'undefined')
 1139+ } else {
 1140+ // Remote request
 1141+ // Set the callback param if it's not already set
 1142+ if( typeof options.jsonCB == 'undefined' )
11221143 options.jsonCB = 'callback';
11231144
11241145 var req_url = options.url;
1125 - var paramAnd = (req_url.indexOf('?')==-1)?'?':'&';
1126 - //put all the values into the GET req:
1127 - for(var i in options.data){
 1146+ var paramAnd = ( req_url.indexOf( '?' ) == -1 ) ? '?' : '&';
 1147+ // Put all the parameters into the URL
 1148+ for( var i in options.data ) {
11281149 req_url += paramAnd + encodeURIComponent( i ) + '=' + encodeURIComponent( options.data[i] );
1129 - paramAnd ='&';
 1150+ paramAnd = '&';
11301151 }
11311152 var fname = 'mycpfn_' + ( global_cb_count++ );
1132 - _global[ fname ] = callback;
 1153+ _global[ fname ] = callback;
11331154 req_url += '&' + options.jsonCB + '=' + fname;
11341155 loadExternalJs( req_url );
11351156 }
11361157 }
1137 -function mwGetLocalApiUrl(url){
1138 - if (wgServer && wgScriptPath){
 1158+function mwGetLocalApiUrl( url ) {
 1159+ if ( wgServer && wgScriptPath ) {
11391160 return wgServer + wgScriptPath + '/api.php';
11401161 }
11411162 return false;
11421163 }
1143 -//grab wiki form error for wiki html page proccessing (should be depricated)
1144 -function grabWikiFormError ( result_page ){
 1164+// Grab wiki form error for wiki html page proccessing (should be deprecated)
 1165+function grabWikiFormError( result_page ) {
11451166 var res = {};
1146 - sp = result_page.indexOf('<span class="error">');
1147 - if(sp!=-1){
1148 - se = result_page.indexOf('</span>', sp);
1149 - res.error_txt = result_page.substr(sp, (sp-se)) + '</span>';
1150 - }else{
1151 - //look for warning:
1152 - sp = result_page.indexOf('<ul class="warning">')
1153 - if(sp != -1){
1154 - se = result_page.indexOf('</ul>', sp);
1155 - res.error_txt = result_page.substr(sp, (se-sp)) + '</ul>';
1156 - //try and add the ignore form item:
1157 - sfp = result_page.indexOf('<form method="post"');
1158 - if(sfp!=-1){
1159 - sfe = result_page.indexOf('</form>', sfp);
1160 - res.form_txt = result_page.substr(sfp, ( sfe - sfp )) + '</form>';
 1167+ sp = result_page.indexOf( '<span class="error">' );
 1168+ if( sp != -1 ) {
 1169+ se = result_page.indexOf( '</span>', sp );
 1170+ res.error_txt = result_page.substr( sp, sp - se ) + '</span>';
 1171+ } else {
 1172+ // Look for warning
 1173+ sp = result_page.indexOf( '<ul class="warning">' )
 1174+ if( sp != -1 ) {
 1175+ se = result_page.indexOf( '</ul>', sp );
 1176+ res.error_txt = result_page.substr( sp, se - sp ) + '</ul>';
 1177+ // Try to add the ignore form item
 1178+ sfp = result_page.indexOf( '<form method="post"' );
 1179+ if( sfp != -1 ) {
 1180+ sfe = result_page.indexOf( '</form>', sfp );
 1181+ res.form_txt = result_page.substr( sfp, sfe - sfp ) + '</form>';
11611182 }
1162 - }else{
1163 - //one more error type check:
1164 - sp = result_page.indexOf('class="mw-warning-with-logexcerpt">')
1165 - if(sp!=-1){
1166 - se = result_page.indexOf('</div>', sp);
1167 - res.error_txt = result_page.substr(sp, ( se - sp )) + '</div>';
 1183+ } else {
 1184+ // One more error type check
 1185+ sp = result_page.indexOf( 'class="mw-warning-with-logexcerpt">' )
 1186+ if( sp != -1 ) {
 1187+ se = result_page.indexOf( '</div>', sp );
 1188+ res.error_txt = result_page.substr( sp, se - sp ) + '</div>';
11681189 }
11691190 }
11701191 }
11711192 return res;
11721193 }
1173 -//do a "normal" request
1174 -function do_request(req_url, callback){
1175 - js_log('do_request::req_url:' + req_url + ' != ' + parseUri( req_url).host);
1176 - //if we are doing a request to the same domain or relative link do a normal GET:
1177 - if( parseUri(document.URL).host == parseUri(req_url).host ||
1178 - req_url.indexOf('://') == -1 ){ //relative url
1179 - //do a direct request:
 1194+// Do a "normal" request
 1195+function do_request( req_url, callback ) {
 1196+ js_log( 'do_request::req_url:' + req_url + ' != ' + parseUri( req_url ).host );
 1197+ // If we are doing a request to the same domain or relative link, do a normal GET
 1198+ if( parseUri( document.URL ).host == parseUri( req_url ).host ||
 1199+ req_url.indexOf('://') == -1 ) // Relative url
 1200+ {
 1201+ // Do a direct request
11801202 $j.ajax({
11811203 type: "GET",
1182 - url:req_url,
1183 - async: false,
1184 - success:function(data){
 1204+ url: req_url,
 1205+ async: false,
 1206+ success: function( data ) {
11851207 callback( data );
11861208 }
11871209 });
1188 - }else{
1189 - //get data via DOM injection with callback
1190 - global_req_cb.push(callback);
1191 - //prepend json_ to feed_format if not already requesting json format
1192 - if( req_url.indexOf("feed_format=")!=-1 && req_url.indexOf("feed_format=json")==-1)
1193 - req_url = req_url.replace(/feed_format=/, 'feed_format=json_');
1194 - loadExternalJs( req_url + '&cb=mv_jsdata_cb&cb_inx=' + (global_req_cb.length-1));
 1210+ } else {
 1211+ // Get data via DOM injection with callback
 1212+ global_req_cb.push( callback );
 1213+ // Prepend json_ to feed_format if not already requesting json format
 1214+ if( req_url.indexOf( "feed_format=" ) != -1 && req_url.indexOf( "feed_format=json" ) == -1 )
 1215+ req_url = req_url.replace( /feed_format=/, 'feed_format=json_' );
 1216+ loadExternalJs( req_url + '&cb=mv_jsdata_cb&cb_inx=' + (global_req_cb.length - 1) );
11951217 }
11961218 }
11971219
1198 -function mv_jsdata_cb(response){
1199 - js_log('f:mv_jsdata_cb:'+ response['cb_inx']);
1200 - //run the callback from the global req cb object:
1201 - if( !global_req_cb[response['cb_inx']] ){
1202 - js_log('missing req cb index');
 1220+function mv_jsdata_cb( response ) {
 1221+ js_log( 'f:mv_jsdata_cb:'+ response['cb_inx'] );
 1222+ // Run the callback from the global request callback object
 1223+ if( !global_req_cb[response['cb_inx']] ) {
 1224+ js_log( 'missing req cb index' );
12031225 return false;
12041226 }
1205 - if( !response['pay_load'] ){
1206 - js_log("missing pay load");
 1227+ if( !response['pay_load'] ) {
 1228+ js_log( "missing pay load" );
12071229 return false;
12081230 }
1209 - //switch on content type:
1210 - switch(response['content-type']){
 1231+ switch( response['content-type'] ) {
12111232 case 'text/plain':
12121233 break;
12131234 case 'text/xml':
1214 - if(typeof response['pay_load'] == 'string'){
 1235+ if( typeof response['pay_load'] == 'string' ) {
12151236 //js_log('load string:'+"\n"+ response['pay_load']);
1216 - //debugger;
1217 - //attempt to parse as xml for IE
1218 - if( $j.browser.msie ){
1219 - var xmldata=new ActiveXObject("Microsoft.XMLDOM");
1220 - xmldata.async="false";
1221 - xmldata.loadXML(response['pay_load']);
1222 - }else{ //for others (firefox, safari etc)
1223 - try{
1224 - var xmldata = (new DOMParser()).parseFromString(response['pay_load'], "text/xml");
1225 - }catch(e) {
1226 - js_log('XML parse ERROR: ' + e.message);
1227 - }
 1237+ // Debugger;
 1238+ if( $j.browser.msie ) {
 1239+ // Attempt to parse as XML for IE
 1240+ var xmldata = new ActiveXObject("Microsoft.XMLDOM");
 1241+ xmldata.async = "false";
 1242+ xmldata.loadXML( response['pay_load'] );
 1243+ } else {
 1244+ // For others (Firefox, Safari etc.)
 1245+ try {
 1246+ var xmldata = (new DOMParser()).parseFromString( response['pay_load'], "text/xml" );
 1247+ } catch( e ) {
 1248+ js_log( 'XML parse ERROR: ' + e.message );
 1249+ }
12281250 }
1229 - //@@todo hanndle xml parser errors
1230 - if(xmldata)response['pay_load']=xmldata;
 1251+ //@@todo handle XML parser errors
 1252+ if( xmldata )response['pay_load'] = xmldata;
12311253 }
12321254 break
12331255 default:
1234 - js_log('bad response type' + response['content-type']);
 1256+ js_log( 'bad response type' + response['content-type'] );
12351257 return false;
12361258 break;
12371259 }
12381260 global_req_cb[response['cb_inx']]( response['pay_load'] );
12391261 }
1240 -//load external js via dom injection
1241 -function loadExternalJs( url, callback ){
1242 - js_log('load js: '+ url);
1243 - //if(window['$j']) //use jquery call:
1244 - /*$j.ajax({
 1262+// Load external JS via DOM injection
 1263+function loadExternalJs( url, callback ) {
 1264+ js_log( 'load js: '+ url );
 1265+ //if(window['$j']) // use jquery call:
 1266+ /*$j.ajax({
12451267 type: "GET",
12461268 url: url,
12471269 dataType: 'script',
12481270 cache: true
12491271 });*/
1250 - // else{
1251 - var e = document.createElement("script");
1252 - e.setAttribute('src', url);
1253 - e.setAttribute('type', "text/javascript");
 1272+ //else{
 1273+ var e = document.createElement( "script" );
 1274+ e.setAttribute( 'src', url );
 1275+ e.setAttribute( 'type', "text/javascript" );
12541276 /*if(callback)
12551277 e.onload = callback;
12561278 */
12571279 //e.setAttribute('defer', true);
1258 - document.getElementsByTagName("head")[0].appendChild(e);
1259 - // }
 1280+ document.getElementsByTagName( "head" )[0].appendChild( e );
 1281+ // }
12601282 }
1261 -function styleSheetPresent(url){
1262 - style_elements = document.getElementsByTagName('link');
1263 - if( style_elements.length > 0) {
1264 - for(i = 0; i < style_elements.length; i++) {
1265 - if(style_elements[i].href == url)
 1283+function styleSheetPresent( url ) {
 1284+ style_elements = document.getElementsByTagName( 'link' );
 1285+ if( style_elements.length > 0 ) {
 1286+ for( i = 0; i < style_elements.length; i++ ) {
 1287+ if( style_elements[i].href == url )
12661288 return true;
12671289 }
12681290 }
12691291 return false;
12701292 }
1271 -function loadExternalCss(url){
1272 - //if could have script loader group thes css request
1273 - //but debatable it may hurt more than it helps with caching and all
1274 - if(typeof url =='object'){
1275 - for(var i in url){
1276 - loadExternalCss ( url[i] );
 1293+function loadExternalCss( url ) {
 1294+ // We could have the script loader group these CSS requests.
 1295+ // But it's debatable: it may hurt more than it helps with caching and all
 1296+ if( typeof url =='object' ) {
 1297+ for( var i in url ) {
 1298+ loadExternalCss( url[i] );
12771299 }
12781300 return ;
12791301 }
12801302
1281 - if( url.indexOf('?') == -1 ){
1282 - url+='?'+getMvUniqueReqId();
 1303+ if( url.indexOf('?') == -1 ) {
 1304+ url += '?' + getMvUniqueReqId();
12831305 }
1284 - if(!styleSheetPresent(url) ){
1285 - js_log('load css: ' + url);
1286 - var e = document.createElement("link");
1287 - e.href = url;
1288 - e.type = "text/css";
1289 - e.rel = 'stylesheet';
1290 - document.getElementsByTagName("head")[0].appendChild(e);
 1306+ if( !styleSheetPresent( url ) ) {
 1307+ js_log( 'load css: ' + url );
 1308+ var e = document.createElement( "link" );
 1309+ e.href = url;
 1310+ e.type = "text/css";
 1311+ e.rel = 'stylesheet';
 1312+ document.getElementsByTagName( "head" )[0].appendChild( e );
12911313 }
12921314 }
1293 -function getMvEmbedURL(){
 1315+function getMvEmbedURL() {
12941316 if( _global['mv_embed_url'] )
12951317 return _global['mv_embed_url'];
1296 - var js_elements = document.getElementsByTagName("script");
1297 - for(var i=0; i < js_elements.length; i++){
1298 - //check for normal mv_embed.js and or script loader
1299 - var src = js_elements[i].getAttribute("src");
1300 - if( src ){
1301 - if( src.indexOf('mv_embed.js') !=-1 || (
1302 - ( src.indexOf('mwScriptLoader.php') != -1 || src.indexOf('jsScriptLoader.php') != -1 )
1303 - && src.indexOf('mv_embed') != -1) ){ //(check for class=mv_embed script_loader call)
 1318+ var js_elements = document.getElementsByTagName( "script" );
 1319+ for( var i = 0; i < js_elements.length; i++ ) {
 1320+ // Check for mv_embed.js and/or script loader
 1321+ var src = js_elements[i].getAttribute( "src" );
 1322+ if( src ) {
 1323+ if( src.indexOf( 'mv_embed.js' ) != -1 || (
 1324+ ( src.indexOf( 'mwScriptLoader.php' ) != -1 || src.indexOf('jsScriptLoader.php') != -1 )
 1325+ && src.indexOf('mv_embed') != -1) ) //(check for class=mv_embed script_loader call)
 1326+ {
13041327 _global['mv_embed_url'] = src;
1305 - return src;
 1328+ return src;
13061329 }
13071330 }
13081331 }
1309 - js_error('Error: getMvEmbedURL failed to get Embed Path');
 1332+ js_error( 'Error: getMvEmbedURL failed to get Embed Path' );
13101333 return false;
13111334 }
1312 -//gets a unique request id to ensure fresh javascript
1313 -function getMvUniqueReqId(){
 1335+// Get a unique request ID to ensure fresh JavaScript
 1336+function getMvUniqueReqId() {
13141337 if( _global['urid'] )
13151338 return _global['urid'];
13161339 var mv_embed_url = getMvEmbedURL();
1317 - //if we have a uri retun that:
1318 - var urid = parseUri( mv_embed_url).queryKey['urid']
1319 - if( urid ){
 1340+ // If we have a URI, return it
 1341+ var urid = parseUri( mv_embed_url ).queryKey['urid']
 1342+ if( urid ) {
13201343 _global['urid'] = urid;
13211344 return urid;
13221345 }
1323 - //if in debug mode get a fresh unique request key:
1324 - if( parseUri( mv_embed_url ).queryKey['debug'] == 'true'){
 1346+ // If we're in debug mode, get a fresh unique request key
 1347+ if( parseUri( mv_embed_url ).queryKey['debug'] == 'true' ) {
13251348 var d = new Date();
13261349 var urid = d.getTime();
13271350 _global['urid'] = urid;
13281351 return urid;
13291352 }
1330 - //else just return the mv_embed version;
 1353+ // Otherwise, just return the mv_embed version
13311354 return MV_EMBED_VERSION;
13321355 }
13331356 /*
1334 - * sets the global mv_embed path based on the scripts location
 1357+ * Set the global mv_embed path based on the script's location
13351358 */
1336 -function getMvEmbedPath(){
1337 - if( _global['mv_embed_path'])
 1359+function getMvEmbedPath() {
 1360+ if( _global['mv_embed_path'] )
13381361 return _global['mv_embed_path'];
13391362 var mv_embed_url = getMvEmbedURL();
1340 - if( mv_embed_url.indexOf('mv_embed.js') !== -1 ){
1341 - mv_embed_path = mv_embed_url.substr(0, mv_embed_url.indexOf('mv_embed.js'));
1342 - }else if(mv_embed_url.indexOf('mwScriptLoader.php')!==-1){
1343 - //script load is in the root of mediaWiki so include the default mv_embed extention path (if using the script loader)
1344 - mv_embed_path = mv_embed_url.substr(0, mv_embed_url.indexOf('mwScriptLoader.php')) + mediaWiki_mvEmbed_path ;
1345 - }else{
1346 - mv_embed_path = mv_embed_url.substr(0, mv_embed_url.indexOf('jsScriptLoader.php'));
 1363+ if( mv_embed_url.indexOf( 'mv_embed.js' ) !== -1 ) {
 1364+ mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'mv_embed.js' ) );
 1365+ } else if( mv_embed_url.indexOf( 'mwScriptLoader.php' ) !== -1 ) {
 1366+ // Script loader is in the root of MediaWiki, so include the default mv_embed extension path
 1367+ mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'mwScriptLoader.php' ) )
 1368+ + mediaWiki_mvEmbed_path;
 1369+ } else {
 1370+ mv_embed_path = mv_embed_url.substr( 0, mv_embed_url.indexOf( 'jsScriptLoader.php' ) );
13471371 }
1348 - //absolute the url (if relative) (if we don't have mv_embed path)
1349 - if( mv_embed_path.indexOf('://') == -1){
 1372+ // Make an absolute URL (if it's relative and we don't have an mv_embed path)
 1373+ if( mv_embed_path.indexOf( '://' ) == -1 ) {
13501374 var pURL = parseUri( document.URL );
1351 - if(mv_embed_path.charAt(0)=='/'){
 1375+ if( mv_embed_path.charAt( 0 ) == '/' ) {
13521376 mv_embed_path = pURL.protocol + '://' + pURL.authority + mv_embed_path;
1353 - }else{
1354 - //relative:
1355 - if(mv_embed_path==''){
 1377+ } else {
 1378+ // Relative
 1379+ if( mv_embed_path == '' ) {
13561380 mv_embed_path = pURL.protocol + '://' + pURL.authority + pURL.directory + mv_embed_path;
13571381 }
13581382 }
@@ -1360,60 +1384,60 @@
13611385 return mv_embed_path;
13621386 }
13631387
1364 -if (typeof DOMParser == "undefined") {
1365 - DOMParser = function () {}
1366 - DOMParser.prototype.parseFromString = function (str, contentType) {
1367 - if (typeof ActiveXObject != "undefined") {
1368 - var d = new ActiveXObject("MSXML.DomDocument");
1369 - d.loadXML(str);
1370 - return d;
1371 - } else if (typeof XMLHttpRequest != "undefined") {
1372 - var req = new XMLHttpRequest;
1373 - req.open("GET", "data:" + (contentType || "application/xml") +
1374 - ";charset=utf-8," + encodeURIComponent(str), false);
1375 - if (req.overrideMimeType) {
1376 - req.overrideMimeType(contentType);
1377 - }
1378 - req.send(null);
1379 - return req.responseXML;
1380 - }
1381 - }
 1388+if ( typeof DOMParser == "undefined" ) {
 1389+ DOMParser = function () {}
 1390+ DOMParser.prototype.parseFromString = function ( str, contentType ) {
 1391+ if ( typeof ActiveXObject != "undefined" ) {
 1392+ var d = new ActiveXObject( "MSXML.DomDocument" );
 1393+ d.loadXML( str );
 1394+ return d;
 1395+ } else if ( typeof XMLHttpRequest != "undefined" ) {
 1396+ var req = new XMLHttpRequest;
 1397+ req.open( "GET", "data:" + (contentType || "application/xml") +
 1398+ ";charset=utf-8," + encodeURIComponent(str), false );
 1399+ if ( req.overrideMimeType ) {
 1400+ req.overrideMimeType(contentType);
 1401+ }
 1402+ req.send( null );
 1403+ return req.responseXML;
 1404+ }
 1405+ }
13821406 }
13831407 /*
1384 -* utility functions:
 1408+* Utility functions
13851409 */
1386 -function js_log(string){
1387 - if( window.console ){
1388 - window.console.log(string);
1389 - }else{
1390 - /*
1391 - * IE and non-firebug debug:
1392 - */
1393 - /*var log_elm = document.getElementById('mv_js_log');
1394 - if(!log_elm){
1395 - document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML +
1396 - '<div style="position:absolute;z-index:500;top:0px;left:0px;right:0px;height:10px;">'+
1397 - '<textarea id="mv_js_log" cols="120" rows="5"></textarea>'+
1398 - '</div>';
 1410+function js_log( string ) {
 1411+ if( window.console ) {
 1412+ window.console.log( string );
 1413+ } else {
 1414+ /*
 1415+ * IE and non-Firebug debug:
 1416+ */
 1417+ /*var log_elm = document.getElementById('mv_js_log');
 1418+ if(!log_elm){
 1419+ document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML +
 1420+ '<div style="position:absolute;z-index:500;top:0px;left:0px;right:0px;height:10px;">'+
 1421+ '<textarea id="mv_js_log" cols="120" rows="5"></textarea>'+
 1422+ '</div>';
13991423
1400 - var log_elm = document.getElementById('mv_js_log');
1401 - }
1402 - if(log_elm){
1403 - log_elm.value+=string+"\n";
1404 - }*/
1405 - }
1406 - return false;
 1424+ var log_elm = document.getElementById('mv_js_log');
 1425+ }
 1426+ if(log_elm){
 1427+ log_elm.value+=string+"\n";
 1428+ }*/
 1429+ }
 1430+ return false;
14071431 }
14081432
1409 -function checkDefaultMwConfig(){
1410 - for(var i in defaultMwConfig){
1411 - if(typeof(mwConfig[i])=='undefined'){
1412 - mwConfig[i] =defaultMwConfig[i];
1413 - }
1414 - }
 1433+function checkDefaultMwConfig() {
 1434+ for( var i in defaultMwConfig ) {
 1435+ if( typeof( mwConfig[i] ) == 'undefined' ) {
 1436+ mwConfig[i] = defaultMwConfig[i];
 1437+ }
14151438 }
 1439+}
14161440
1417 -function js_error(string){
1418 - alert(string);
 1441+function js_error( string ) {
 1442+ alert( string );
14191443 return false;
14201444 }
Index: trunk/phase3/js2/mwEmbed/jsScriptLoader.php
@@ -3,155 +3,153 @@
44 * This core jsScriptLoader class provides the script loader functionality
55 * @file
66 */
7 -// check if we are being invoked in MediaWiki context or stand alone usage:
8 -if ( !defined( 'MEDIAWIKI' ) ){
9 - // load noMediaWiki helper:
 7+// Check if we are being invoked in a MediaWiki context or stand alone usage:
 8+if ( !defined( 'MEDIAWIKI' ) ) {
 9+ // Load noMediaWiki helper
1010 require_once( realpath( dirname( __FILE__ ) ) . '/php/noMediaWikiConfig.php' );
11 -
12 - // run the main action:
1311 $myScriptLoader = new jsScriptLoader();
14 - // preset request values via normal $_GET operation:
1512 $myScriptLoader->doScriptLoader();
1613 } else {
1714 $wgExtensionMessagesFiles['mwEmbed'] = realpath( dirname( __FILE__ ) ) . '/php/mwEmbed.i18n.php';
1815 }
1916
20 -// setup page output hook
2117 class jsScriptLoader {
2218 var $jsFileList = array();
2319 var $jsout = '';
2420 var $rKey = ''; // the request key
2521 var $error_msg = '';
2622 var $debug = false;
27 - var $jsvarurl = false; // if we should include generated js (special class '-')
 23+ var $jsvarurl = false; // whether we should include generated JS (special class '-')
2824 var $doProcReqFlag = true;
2925
30 - function doScriptLoader(){
 26+ function doScriptLoader() {
3127 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoaderJsFile, $IP,
3228 $wgEnableScriptMinify, $wgUseFileCache;
3329
34 - // process the request
 30+ // Process the request
3531 $this->procRequestVars();
3632
37 - // if cache is on and file is present grab it from there:
38 - if( $wgUseFileCache && !$this->debug ) {
39 - // setup file cache obj:
 33+ // If the cache is on and the file is present, grab it from there
 34+ if ( $wgUseFileCache && !$this->debug ) {
 35+ // Setup file cache object
4036 $this->sFileCache = new simpleFileCache( $this->rKey );
41 - if( $this->sFileCache->isFileCached() ){
42 - // just output headers so we can use php "efficient" readfile
 37+ if ( $this->sFileCache->isFileCached() ) {
 38+ // Just output headers so we can use PHP's "efficient" readfile
4339 $this->outputJsHeaders();
4440 $this->sFileCache->outputFromFileCache();
4541 die();
4642 }
4743 }
4844
49 - // setup script loader header info
 45+ // Setup script loader header info
5046 $this->jsout .= 'var mwSlScript = "' . htmlspecialchars( $_SERVER['SCRIPT_NAME'] ) . '";' . "\n";
51 - $this->jsout .= 'var mwSlGenISODate = "' . date( 'c' ) . '";' ."\n";
52 - $this->jsout .= 'var mwSlURID = "' . htmlspecialchars( $this->urid ) . '";' ."\n";
53 - // Build the output:
54 - // swap in the appropriate language per js_file
55 - foreach( $this->jsFileList as $classKey => $file_name ){
 47+ $this->jsout .= 'var mwSlGenISODate = "' . date( 'c' ) . '";' . "\n";
 48+ $this->jsout .= 'var mwSlURID = "' . htmlspecialchars( $this->urid ) . '";' . "\n";
 49+ // Build the output
5650
57 - // special case: - title classes:
58 - if( substr( $classKey, 0, 3 ) == 'WT:' ){
 51+ // Swap in the appropriate language per js_file
 52+ foreach ( $this->jsFileList as $classKey => $file_name ) {
 53+ // Special case: title classes
 54+ if ( substr( $classKey, 0, 3 ) == 'WT:' ) {
5955 global $wgUser;
60 - // get just the tile part:
 56+ // Get just the title part
6157 $title_block = substr( $classKey, 3 );
62 - if( $title_block[0] == '-' && strpos( $title_block, '|' ) !== false ){
63 - // special case of "-" title with skin
 58+ if ( $title_block[0] == '-' && strpos( $title_block, '|' ) !== false ) {
 59+ // Special case of "-" title with skin
6460 $parts = explode( '|', $title_block );
6561 $title = array_shift( $parts );
66 - foreach( $parts as $tparam ){
 62+ foreach ( $parts as $tparam ) {
6763 list( $key, $val ) = explode( '=', $tparam );
68 - if( $key == 'useskin' ){
 64+ if ( $key == 'useskin' ) {
6965 $skin = $val;
7066 }
7167 }
7268 $sk = $wgUser->getSkin();
73 - // make sure the skin name is valid
 69+ // Make sure the skin name is valid
7470 $skinNames = Skin::getSkinNames();
75 - // get the lower case skin name (array keys)
7671 $skinNames = array_keys( $skinNames );
77 - if( in_array( strtolower( $skin ), $skinNames ) ){
 72+ if ( in_array( strtolower( $skin ), $skinNames ) ) {
7873 $this->jsout .= $sk->generateUserJs( $skin ) . "\n";
79 - // success continue:
 74+ // success
8075 continue;
8176 }
8277 } else {
83 - //make sure the wiki title ends with .js
84 - if( substr( $title_block, -3 ) != '.js'){
 78+ // Make sure the wiki title ends with .js
 79+ if ( substr( $title_block, - 3 ) != '.js' ) {
8580 $this->error_msg .= 'WikiTitle includes should end with .js';
8681 continue;
8782 }
88 - // it's a wikiTitle append the output of the wikitext:
 83+ // It's a wiki title, append the output of the wikitext:
8984 $t = Title::newFromText( $title_block );
9085 $a = new Article( $t );
91 - // only get content if the page is not empty:
92 - if( $a->getID() !== 0 ){
 86+ // Only get the content if the page is not empty:
 87+ if ( $a->getID() !== 0 ) {
9388 $this->jsout .= $a->getContent() . "\n";
9489 }
9590 continue;
9691 }
9792 }
98 - //dealing with files::
99 - //check that the filename ends with .js and does not include ../ traversing
100 - if( substr( $file_name, -3 ) != '.js'){
101 - $this->error_msg .= "\nError file name must end with .js: ". htmlspecialchars( $file_name ) . " \n ";
 93+
 94+ // Dealing with files
 95+
 96+ // Check that the filename ends with .js and does not include ../ traversing
 97+ if ( substr( $file_name, - 3 ) != '.js' ) {
 98+ $this->error_msg .= "\nError file name must end with .js: " . htmlspecialchars( $file_name ) . " \n ";
10299 continue;
103100 }
104 - if( strpos($file_name, '../') !== false ){
105 - $this->error_msg .= "\nError file name must not traverse paths: ". htmlspecialchars( $file_name ) . " \n ";
 101+ if ( strpos( $file_name, '../' ) !== false ) {
 102+ $this->error_msg .= "\nError file name must not traverse paths: " . htmlspecialchars( $file_name ) . " \n ";
106103 continue;
107104 }
108105
109 - if( trim( $file_name ) != '' ){
110 - // if in debug add a comment with the file name:
111 - if( $this->debug )
 106+ if ( trim( $file_name ) != '' ) {
 107+ // If in debug mode, add a comment with the file name
 108+ if ( $this->debug )
112109 $this->jsout .= "\n/**
113 -* File: ". htmlspecialchars( $file_name ) ."
 110+* File: " . htmlspecialchars( $file_name ) . "
114111 */\n";
115 - $this->jsout .= ( $this->doProccessJsFile( $file_name ) ) . "\n";
 112+ $this->jsout .= ( $this->doProcessJsFile( $file_name ) ) . "\n";
116113 }
117114 }
118115
119 - // check if we should minify :
120 - if( $wgEnableScriptMinify && !$this->debug ){
 116+ // Check if we should minify
 117+ if ( $wgEnableScriptMinify && !$this->debug ) {
121118 // do the minification and output
122 - $this->jsout = JSMin::minify( $this->jsout);
 119+ $this->jsout = JSMin::minify( $this->jsout );
123120 }
124 - // save to the file cache:
125 - if( $wgUseFileCache && !$this->debug ) {
 121+ // Save to the file cache
 122+ if ( $wgUseFileCache && !$this->debug ) {
126123 $status = $this->sFileCache->saveToFileCache( $this->jsout );
127 - if( $status !== true )
128 - $this->error_msg.= $status;
 124+ if ( $status !== true )
 125+ $this->error_msg .= $status;
129126 }
130 - // check for error msg:
131 - if( $this->error_msg != ''){
132 - echo 'alert(\'Error With ScriptLoader.php ::' . str_replace( "\n", '\'+"\n"+'."\n'", $this->error_msg ) . '\');';
 127+ // Check for an error msg
 128+ if ( $this->error_msg != '' ) {
 129+ echo 'alert(\'Error With ScriptLoader.php ::' . str_replace( "\n", '\'+"\n"+' . "\n'", $this->error_msg ) . '\');';
133130 echo trim( $this->jsout );
134131 } else {
135 - // all good lets output cache forever headers:
 132+ // All good, let's output "cache forever" headers
136133 $this->outputJsWithHeaders();
137134 }
138135 }
139136
140 - function outputJsHeaders(){
 137+ function outputJsHeaders() {
141138 global $wgJsMimeType;
142 - // output js mime type:
143 - header( 'Content-type: ' . $wgJsMimeType );
 139+ // Output JS MIME type:
 140+ header( 'Content-Type: ' . $wgJsMimeType );
144141 header( 'Pragma: public' );
145 - // cache forever:
146 - // (the point is we never have to revalidate since we should always change the request url based on the svn or article version)
147 - $one_year = 60*60*24*365;
 142+ // Cache forever
 143+ // The point is we never have to revalidate, since we should always change the request URL
 144+ // based on the SVN or article version.
 145+ $one_year = 60 * 60 * 24 * 365;
148146 header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $one_year ) . " GM" );
149147 }
150148
151 - function outputJsWithHeaders(){
 149+ function outputJsWithHeaders() {
152150 global $wgUseGzip;
153151 $this->outputJsHeaders();
154 - if( $wgUseGzip ) {
155 - if( wfClientAcceptsGzip() ) {
 152+ if ( $wgUseGzip ) {
 153+ if ( wfClientAcceptsGzip() ) {
156154 header( 'Content-Encoding: gzip' );
157155 echo gzencode( $this->jsout );
158156 } else {
@@ -163,115 +161,116 @@
164162 }
165163
166164 /**
167 - * updates the proc Request
 165+ * Process request variables and load them into $this
168166 */
169 - function procRequestVars(){
 167+ function procRequestVars() {
170168 global $wgContLanguageCode, $wgEnableScriptMinify, $wgJSAutoloadClasses,
171169 $wgJSAutoloadLocalClasses, $wgStyleVersion, $wgEnableScriptLoaderJsFile;
172170
173 - // set debug flag:
174 - if( ( isset( $_GET['debug'] ) && $_GET['debug'] == 'true' ) || ( isset( $wgEnableScriptDebug ) && $wgEnableScriptDebug == true ) ){
 171+ // Set debug flag
 172+ if ( ( isset( $_GET['debug'] ) && $_GET['debug'] == 'true' ) || ( isset( $wgEnableScriptDebug ) && $wgEnableScriptDebug == true ) ) {
175173 $this->debug = true;
176174 }
177175
178 - // set the urid: (be sure to escape it as it goes into our js output)
179 - if( isset( $_GET['urid'] ) && $_GET['urid'] !=''){
 176+ // Set the urid. Be sure to escape it as it goes into our JS output.
 177+ if ( isset( $_GET['urid'] ) && $_GET['urid'] != '' ) {
180178 $this->urid = htmlspecialchars( $_GET['urid'] );
181179 } else {
182 - // just give it the current style sheet id:
 180+ // Just give it the current style sheet ID:
183181 // @@todo read the svn version number
184182 $this->urid = $wgStyleVersion;
185183 }
186184
187185 $reqClassList = false;
188 - if( isset( $_GET['class'] ) && $_GET['class'] != '' ){
 186+ if ( isset( $_GET['class'] ) && $_GET['class'] != '' ) {
189187 $reqClassList = explode( ',', $_GET['class'] );
190188 }
191189
192 - // check for the requested classes
193 - if( $reqClassList ){
194 - // clean the class list and populate jsFileList
195 - foreach( $reqClassList as $reqClass ){
196 - if( trim( $reqClass ) != '' ){
197 - // check for special case '-' class for user generated js
198 - if( substr( $reqClass, 0, 3 ) == 'WT:' ){
 190+ // Check for the requested classes
 191+ if ( $reqClassList ) {
 192+ // Clean the class list and populate jsFileList
 193+ foreach ( $reqClassList as $reqClass ) {
 194+ if ( trim( $reqClass ) != '' ) {
 195+ // Check for special case '-' class for user-generated JS
 196+ if ( substr( $reqClass, 0, 3 ) == 'WT:' ) {
199197 $this->jsFileList[$reqClass] = true;
200198 $this->rKey .= $reqClass;
201199 $this->jsvarurl = true;
202200 continue;
203201 }
204202
205 - $reqClass = preg_replace("/[^A-Za-z0-9_\-\.]/", '', $reqClass );
 203+ $reqClass = preg_replace( "/[^A-Za-z0-9_\-\.]/", '', $reqClass );
206204
207 - if( isset( $wgJSAutoloadLocalClasses[$reqClass] ) ){
 205+ if ( isset( $wgJSAutoloadLocalClasses[$reqClass] ) ) {
208206 $this->jsFileList[$reqClass] = $wgJSAutoloadLocalClasses[$reqClass];
209 - $this->rKey.= $reqClass;
210 - } else if( isset( $wgJSAutoloadClasses[$reqClass] ) ) {
 207+ $this->rKey .= $reqClass;
 208+ } else if ( isset( $wgJSAutoloadClasses[$reqClass] ) ) {
211209 $this->jsFileList[$reqClass] = $wgJSAutoloadClasses[$reqClass];
212 - $this->rKey.= $reqClass;
 210+ $this->rKey .= $reqClass;
213211 } else {
214 - $this->error_msg.= 'Requested class: ' . htmlspecialchars( $reqClass ) . ' not found' . "\n";
 212+ $this->error_msg .= 'Requested class: ' . htmlspecialchars( $reqClass ) . ' not found' . "\n";
215213 }
216214 }
217215 }
218216 }
219217
220 - // check for requested files if enabled:
221 - if( $wgEnableScriptLoaderJsFile ){
222 - if( isset( $_GET['files'] ) ){
 218+ // Check for requested files, if enabled
 219+ if ( $wgEnableScriptLoaderJsFile ) {
 220+ if ( isset( $_GET['files'] ) ) {
223221 $reqFileList = explode( ',', isset( $_GET['files'] ) );
224 - // clean the file list and populate jsFileList
225 - foreach( $reqFileList as $reqFile ){
226 - // no jumping dirs:
 222+ // Clean the file list and populate jsFileList
 223+ foreach ( $reqFileList as $reqFile ) {
 224+ // No jumping dirs
227225 $reqFile = str_replace( '../', '', $reqFile );
228 - // only allow alphanumeric underscores periods and ending with .js
 226+ // Only allow alphanumeric underscores periods and ending with .js
229227 $reqFile = ereg_replace( "[^A-Za-z0-9_\-\/\.]", '', $reqFile );
230 - if( substr( $reqFile, -3 ) == '.js' ){
231 - // don't add it twice:
232 - if( !in_array( $reqFile, $jsFileList ) ) {
 228+ if ( substr( $reqFile, - 3 ) == '.js' ) {
 229+ // Don't add it twice:
 230+ if ( !in_array( $reqFile, $jsFileList ) ) {
233231 $this->jsFileList[] = $IP . $reqFile;
234 - $this->rKey.= $reqFile;
 232+ $this->rKey .= $reqFile;
235233 }
236234 } else {
237 - $this->error_msg.= 'Not valid requsted JavaScript file' . "\n";
 235+ $this->error_msg .= 'Not valid requsted JavaScript file' . "\n";
238236 }
239237 }
240238 }
241239 }
242240
243 - // add the language code to the rKey:
 241+ // Add the language code to the rKey:
244242 $this->rKey .= '_' . $wgContLanguageCode;
245243
246 - // add the unique rid to the rKey
 244+ // Add the unique rid
247245 $this->rKey .= $this->urid;
248246
249 - // add a min flag:
250 - if( $wgEnableScriptMinify ){
251 - $this->rKey.= '_min';
 247+ // Add a minify flag
 248+ if ( $wgEnableScriptMinify ) {
 249+ $this->rKey .= '_min';
252250 }
253251 }
254252
255 - function doProccessJsFile( $file_name ){
 253+ function doProcessJsFile( $file_name ) {
256254 global $IP, $wgEnableScriptLocalization, $IP;
257255
258 - // load the file:
 256+ // Load the file
259257 $str = @file_get_contents( "{$IP}/{$file_name}" );
260258
261 - if( $str === false ){
262 - // @@todo check php error level (don't want to expose paths if errors are hidden)
263 - $this->error_msg.= 'Requested File: ' . htmlspecialchars( $file_name ) . ' could not be read' . "\n";
 259+ if ( $str === false ) {
 260+ // @@todo check PHP error level. Don't want to expose paths if errors are hidden.
 261+ $this->error_msg .= 'Requested File: ' . htmlspecialchars( $file_name ) . ' could not be read' . "\n";
264262 return '';
265263 }
266264 $this->cur_file = $file_name;
267265
268 - // strip out js_log debug lines not much luck with this regExp yet:
269 - //if( !$this->debug )
 266+ // Strip out js_log debug lines. Not much luck with this regExp yet:
 267+ // if( !$this->debug )
270268 // $str = preg_replace('/\n\s*js_log\s*\([^\)]([^;]|\n])*;/', "\n", $str);
271269
272 - // do language swap
273 - if( $wgEnableScriptLocalization )
 270+ // Do language swap
 271+ if ( $wgEnableScriptLocalization )
274272 $str = preg_replace_callback(
275 - '/loadGM\s*\(\s*{(.*)}\s*\)\s*/siU', // @@todo fix: will break down if someone does }) in their msg text
 273+ // @@todo fix: will break down if someone does }) in their msg text
 274+ '/loadGM\s*\(\s*{(.*)}\s*\)\s*/siU',
276275 array( $this, 'languageMsgReplace' ),
277276 $str
278277 );
@@ -279,28 +278,28 @@
280279 return $str;
281280 }
282281
283 - function languageMsgReplace( $jvar ){
284 - if( !isset( $jvar[1] ) )
 282+ function languageMsgReplace( $jvar ) {
 283+ if ( !isset( $jvar[1] ) )
285284 return;
286285
287286 $jmsg = json_decode( '{' . $jvar[1] . '}', true );
288 - // do the language lookup:
289 - if( $jmsg ){
290 - foreach( $jmsg as $msgKey => $default_en_value ){
 287+ // Do the language lookup
 288+ if ( $jmsg ) {
 289+ foreach ( $jmsg as $msgKey => $default_en_value ) {
291290 $jmsg[$msgKey] = wfMsgNoTrans( $msgKey );
292291 }
293 - //return the updated loadGM json with fixed new lines:
 292+ // Return the updated loadGM JSON with fixed new lines
294293 return 'loadGM( ' . json_encode( $jmsg ) . ')';
295294 } else {
296 - $this->error_msg.= "Could not parse JSON language msg in File:\n" .
 295+ $this->error_msg .= "Could not parse JSON language msg in File:\n" .
297296 htmlspecialchars ( $this->cur_file ) . "\n";
298297 }
299 - // could not parse json (throw error?)
 298+ // Could not parse JSON (throw error?)
300299 return $jvar[0];
301300 }
302301 }
303302
304 -//a simple version of HTMLFileCache (@@todo abstract shared pieces)
 303+// A simple version of HTMLFileCache (@@todo abstract shared pieces)
305304 class simpleFileCache {
306305 var $mFileCache;
307306 var $filename = null;
@@ -308,12 +307,12 @@
309308
310309 public function __construct( &$rKey ) {
311310 $this->rKey = $rKey;
312 - $this->filename = $this->fileCacheName(); // init name
 311+ $this->filename = $this->fileCacheName();
313312 }
314313
315314 public function fileCacheName() {
316315 global $wgUseGzip;
317 - if( !$this->mFileCache ) {
 316+ if ( !$this->mFileCache ) {
318317 global $wgFileCacheDirectory;
319318
320319 $hash = md5( $this->rKey );
@@ -324,7 +323,7 @@
325324 $hash2 = substr( $hash, 0, 2 );
326325 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$this->rKey}.js";
327326
328 - if( $wgUseGzip )
 327+ if ( $wgUseGzip )
329328 $this->mFileCache .= '.gz';
330329
331330 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
@@ -336,50 +335,50 @@
337336 return file_exists( $this->filename );
338337 }
339338
340 - public function outputFromFileCache(){
 339+ public function outputFromFileCache() {
341340 global $wgUseGzip;
342 - if( $wgUseGzip ) {
343 - if( wfClientAcceptsGzip() ) {
 341+ if ( $wgUseGzip ) {
 342+ if ( wfClientAcceptsGzip() ) {
344343 header( 'Content-Encoding: gzip' );
345344 readfile( $this->filename );
346345 } else {
347 - /* Send uncompressed (check if fileCache is in compressed state (ends with .gz)
348 - * (unlikely to execute this since $wgUseGzip would have created a new file above.. but just in case:
 346+ /* Send uncompressed. Check if fileCache is in compressed state (ends with .gz)
 347+ * We're unlikely to execute this since $wgUseGzip would have created a new file
 348+ * above, but just in case.
349349 */
350 - if( substr( $this->filename, -3 ) == '.gz' ){
 350+ if ( substr( $this->filename, - 3 ) == '.gz' ) {
351351 readgzfile( $this->filename );
352352 } else {
353353 readfile( $this->filename );
354354 }
355355 }
356356 } else {
357 - // just output the file
 357+ // Just output the file
358358 readfile( $this->filename );
359359 }
360 - //return true
361360 return true;
362361 }
363362
364363 public function saveToFileCache( &$text ) {
365364 global $wgUseFileCache, $wgUseGzip;
366 - if( !$wgUseFileCache ) {
 365+ if ( !$wgUseFileCache ) {
367366 return 'Error: Called saveToFileCache with $wgUseFileCache off';
368367 }
369 - if( strcmp( $text, '' ) == 0 ) return 'saveToFileCache: empty output file';
 368+ if ( strcmp( $text, '' ) == 0 ) return 'saveToFileCache: empty output file';
370369
371 - // check the directories if we could not create them error out:
 370+ // Check the directories. If we could not create them, error out.
372371 $status = $this->checkCacheDirs();
373372
374 - if( $wgUseGzip ){
 373+ if ( $wgUseGzip ) {
375374 $outputText = gzencode( trim( $text ) );
376375 } else {
377376 $outputText = trim( $text );
378377 }
379378
380 - if( $status !== true )
 379+ if ( $status !== true )
381380 return $status;
382381 $f = fopen( $this->filename, 'w' );
383 - if( $f ) {
 382+ if ( $f ) {
384383 fwrite( $f, $outputText );
385384 fclose( $f );
386385 } else {
@@ -392,10 +391,10 @@
393392 $mydir2 = substr( $this->filename, 0, strrpos( $this->filename, '/' ) ); # subdirectory level 2
394393 $mydir1 = substr( $mydir2, 0, strrpos( $mydir2, '/' ) ); # subdirectory level 1
395394
396 - if( wfMkdirParents( $mydir1 ) === false || wfMkdirParents( $mydir2 ) === false ){
 395+ if ( wfMkdirParents( $mydir1 ) === false || wfMkdirParents( $mydir2 ) === false ) {
397396 return 'Could not create cache directory. Check your cache directory permissions?';
398397 } else {
399398 return true;
400399 }
401400 }
402 -}
\ No newline at end of file
 401+}
Index: trunk/phase3/js2/remoteMwEmbed.js
@@ -1,81 +1,81 @@
2 -/*
3 - * this file exposes some of the functionality of mwEmbed to wikis
 2+/*
 3+ * this file exposes some of the functionality of mwEmbed to wikis
44 * that are not yet running the new-upload branch
55 */
66
77
8 -var urlparts = getRemoteEmbedPath();
9 -var mwEmbedHostPath =urlparts[0];
10 -var reqAguments =urlparts[1];
 8+var urlparts = getRemoteEmbedPath();
 9+var mwEmbedHostPath = urlparts[0];
 10+var reqAguments = urlparts[1];
1111
12 -//check if mvEmbed is already loaded (ie the js2 branch is active) in which case do nothing
13 -if( typeof MV_EMBED_VERSION == 'undefined' ){
 12+// Check if mvEmbed is already loaded (ie the js2 branch is active) in which case do nothing
 13+if( typeof MV_EMBED_VERSION == 'undefined' ) {
1414 doPageSpecificRewrite();
15 -}
 15+}
1616
17 -function doPageSpecificRewrite(){
18 - //add media wizard:
19 - if( wgAction == 'edit' || wgAction == 'submit' ){
20 - load_mv_embed( function(){
21 - importScriptURI(mwEmbedHostPath + '/editPage.js' + reqAguments);
 17+function doPageSpecificRewrite() {
 18+ // Add media wizard
 19+ if( wgAction == 'edit' || wgAction == 'submit' ) {
 20+ load_mv_embed( function() {
 21+ importScriptURI( mwEmbedHostPath + '/editPage.js' + reqAguments );
2222 });
2323 }
24 -
25 - //firefogg integration:
26 - if( wgPageName== "Special:Upload" ){
27 - load_mv_embed( function(){
28 - importScriptURI(mwEmbedHostPath + '/uploadPage.js' +reqAguments);
 24+
 25+ // Firefogg integration
 26+ if( wgPageName == "Special:Upload" ){
 27+ load_mv_embed( function() {
 28+ importScriptURI( mwEmbedHostPath + '/uploadPage.js' + reqAguments );
2929 });
3030 }
31 -
32 - //oggHandler rewrite:
33 - var vidIdList = [];
34 - var divs = document.getElementsByTagName('div');
35 - for(var i = 0; i < divs.length; i++){
36 - if( divs[i].id && divs[i].id.substring(0,11) == 'ogg_player_'){
37 - vidIdList.push( divs[i].getAttribute("id") );
38 - }
39 - }
40 - if( vidIdList.length > 0){
41 - load_mv_embed( function(){
42 - mvJsLoader.embedVideoCheck(function(){
43 - //do utilty rewrite of oggHanlder content:
44 - rewrite_for_oggHanlder( vidIdList );
 31+
 32+ // OggHandler rewrite
 33+ var vidIdList = [];
 34+ var divs = document.getElementsByTagName( 'div' );
 35+ for( var i = 0; i < divs.length; i++ ) {
 36+ if( divs[i].id && divs[i].id.substring( 0, 11 ) == 'ogg_player_' ) {
 37+ vidIdList.push( divs[i].getAttribute( "id" ) );
 38+ }
 39+ }
 40+ if( vidIdList.length > 0 ) {
 41+ load_mv_embed( function() {
 42+ mvJsLoader.embedVideoCheck( function() {
 43+ // Do utilty rewrite of OggHandler content:
 44+ rewrite_for_OggHandler( vidIdList );
4545 });
4646 });
4747 }
4848 }
49 -function getRemoteEmbedPath(){
50 - for(var i=0; i < document.getElementsByTagName('script').length; i++){
51 - var s = document.getElementsByTagName('script')[i];
52 - if( s.src.indexOf('remoteMwEmbed.js') != -1 ){
53 - var reqStr='';
54 - var scriptPath='';
55 - if( s.src.indexOf('?') != -1){
56 - reqStr = s.src.substr( s.src.indexOf('?') );
57 - scriptPath = s.src.substr(0, s.src.indexOf('?')).replace('remoteMwEmbed.js', '');
58 - }else{
59 - scriptPath = s.src.replace('remoteMwEmbed.js', '')
60 - }
61 - //use the external_media_wizard path:
 49+function getRemoteEmbedPath() {
 50+ for( var i = 0; i < document.getElementsByTagName( 'script' ).length; i++ ) {
 51+ var s = document.getElementsByTagName( 'script' )[i];
 52+ if( s.src.indexOf( 'remoteMwEmbed.js' ) != -1 ) {
 53+ var reqStr = '';
 54+ var scriptPath = '';
 55+ if( s.src.indexOf( '?' ) != -1) {
 56+ reqStr = s.src.substr( s.src.indexOf( '?' ) );
 57+ scriptPath = s.src.substr( 0, s.src.indexOf( '?' ) ).replace( 'remoteMwEmbed.js', '' );
 58+ } else {
 59+ scriptPath = s.src.replace( 'remoteMwEmbed.js', '' )
 60+ }
 61+ // Use the external_media_wizard path:
6262 return [scriptPath, reqStr];
6363 }
64 - }
 64+ }
6565 }
6666
67 -function load_mv_embed( callback ){
68 - //inject mv_embed if needed:
69 - if( typeof mvEmbed == 'undefined'){
70 - importScriptURI(mwEmbedHostPath +'/mwEmbed/mv_embed.js' + reqAguments);
71 - check_for_mv_embed( callback );
72 - }else{
 67+function load_mv_embed( callback ) {
 68+ // Inject mv_embed if needed
 69+ if( typeof mvEmbed == 'undefined' ) {
 70+ importScriptURI( mwEmbedHostPath + '/mwEmbed/mv_embed.js' + reqAguments );
7371 check_for_mv_embed( callback );
74 - }
 72+ } else {
 73+ check_for_mv_embed( callback );
 74+ }
7575 }
76 -function check_for_mv_embed( callback ){
77 - if( typeof MV_EMBED_VERSION == 'undefined'){
78 - setTimeout('check_for_mv_embed( ' + callback +');', 25);
79 - }else{
 76+function check_for_mv_embed( callback ) {
 77+ if( typeof MV_EMBED_VERSION == 'undefined' ) {
 78+ setTimeout( 'check_for_mv_embed( ' + callback + ');', 25 );
 79+ } else {
8080 callback();
8181 }
8282 }
Index: trunk/phase3/js2/uploadPage.js
@@ -1,136 +1,139 @@
22 /*
3 - * uploadPage.js to be run on specialUpload page.
4 - * controls the invocation of the mvUploader class based on local config.
 3+ * This script is run on [[Special:Upload]].
 4+ * It controls the invocation of the mvUploader class based on local config.
55 */
6 -js2AddOnloadHook( function(){
 6+js2AddOnloadHook( function() {
77 mwUploadHelper.init();
88 });
99 var mwUploadFormTarget = '#mw-upload-form';
10 -//set up the upoload form bindings once all dom manipluation is done
11 -var mwUploadHelper = {
12 - init:function(){
 10+// Set up the upload form bindings once all DOM manipulation is done
 11+var mwUploadHelper = {
 12+ init: function() {
1313 var _this = this;
14 - //if not boolean false set to true:
15 - if(typeof wgEnableFirefogg == 'undefined')
 14+ // If wgEnableFirefogg is not boolean false, set to true
 15+ if( typeof wgEnableFirefogg == 'undefined' )
1616 wgEnableFirefogg = true;
1717
18 - if( wgEnableFirefogg ){
19 - //setup the upload handler to firefogg (supports our upload proccess) (should work with the http uploads too)
20 - $j('#wpUploadFile').firefogg({
21 - //an api url (we won't submit directly to action of the form)
22 - 'api_url' : wgServer + wgScriptPath + '/api.php',
 18+ if( wgEnableFirefogg ) {
 19+ // Set up the upload handler to Firefogg. Should work with the HTTP uploads too.
 20+ $j( '#wpUploadFile' ).firefogg( {
 21+ // An API URL (we won't submit directly to action of the form)
 22+ 'api_url': wgServer + wgScriptPath + '/api.php',
2323 'form_rewrite': true,
24 - 'target_edit_from' : mwUploadFormTarget,
25 - 'new_source_cb' : function( orgFilename, oggName ){
26 - if($j('#wpDestFile').val() == "")
27 - $j('#wpDestFile').val( oggName );
28 - $j('#wpDestFile').doDestCheck({
29 - 'warn_target':'#wpDestFile-warning'
 24+ 'target_edit_from': mwUploadFormTarget,
 25+ 'new_source_cb': function( orgFilename, oggName ) {
 26+ if( $j( '#wpDestFile' ).val() == "" )
 27+ $j( '#wpDestFile' ).val( oggName );
 28+ $j( '#wpDestFile' ).doDestCheck({
 29+ 'warn_target': '#wpDestFile-warning'
3030 });
31 - }
32 - });
33 - }else{
34 - //Add basic upload profile support ( http status monitoring, progress box for browsers that support it etc.)
35 - if($j('#wpUploadFileURL').length != 0){
36 - $j('#wpUploadFileURL').baseUploadInterface({
37 - 'api_url' : wgServer + wgScriptPath + '/api.php',
38 - 'target_edit_from' : mwUploadFormTarget
 31+ }
 32+ });
 33+ } else {
 34+ // Add basic upload profile support ( http status monitoring, progress box for
 35+ // browsers that support it, etc.)
 36+ if( $j( '#wpUploadFileURL' ).length != 0 ) {
 37+ $j( '#wpUploadFileURL' ).baseUploadInterface( {
 38+ 'api_url': wgServer + wgScriptPath + '/api.php',
 39+ 'target_edit_from': mwUploadFormTarget
3940 });
4041 }
4142 }
4243
43 - if( wgAjaxUploadDestCheck ){
44 - //do destination check:
45 - $j('#wpDestFile').change(function(){
46 - $j('#wpDestFile').doDestCheck({
 44+ if( wgAjaxUploadDestCheck ) {
 45+ // Do destination check
 46+ $j( '#wpDestFile' ).change( function() {
 47+ $j( '#wpDestFile' ).doDestCheck({
4748 'warn_target':'#wpDestFile-warning'
4849 });
4950 });
5051 }
5152
52 - //check if we have http enabled & setup enable/disable toggle:
53 - if($j('#wpUploadFileURL').length != 0){
54 - //set the initial toggleUpType
55 - _this.toggleUpType(true);
 53+ // Check if we have HTTP enabled & setup enable/disable toggle:
 54+ if( $j( '#wpUploadFileURL' ).length != 0 ) {
 55+ // Set the initial toggleUpType
 56+ _this.toggleUpType( true );
5657
57 - $j("input[name='wpSourceType']").click(function(){
 58+ $j( "input[name='wpSourceType']" ).click( function() {
5859 _this.toggleUpType( this.id == 'wpSourceTypeFile' );
5960 });
6061 }
61 - $j('#wpUploadFile,#wpUploadFileURL').focus(function(){
62 - _this.toggleUpType( this.id == 'wpUploadFile' );
63 - }).change(function(){ //also setup the onChange event binding:
64 - if ( wgUploadAutoFill ) {
65 - mwUploadHelper.doDestinationFill( this );
66 - }
67 - });
 62+ $j( '#wpUploadFile,#wpUploadFileURL' )
 63+ .focus( function() {
 64+ _this.toggleUpType( this.id == 'wpUploadFile' );
 65+ })
 66+ // Also setup the onChange event binding:
 67+ .change( function() {
 68+ if ( wgUploadAutoFill ) {
 69+ mwUploadHelper.doDestinationFill( this );
 70+ }
 71+ });
6872 },
6973 /**
70 - * toggleUpType sets the upload radio buttons
 74+ * Set the upload radio buttons
7175 *
7276 * boolean set
7377 */
74 - toggleUpType:function( set ){
75 - $j('#wpSourceTypeFile').attr('checked', set);
76 - $j('#wpUploadFile').attr('disabled', !set);
 78+ toggleUpType: function( set ) {
 79+ $j( '#wpSourceTypeFile' ).attr( 'checked', set );
 80+ $j( '#wpUploadFile' ).attr( 'disabled', !set );
7781
78 - $j('#wpSourceTypeURL').attr('checked', !set);
79 - $j('#wpUploadFileURL').attr('disabled', set);
 82+ $j( '#wpSourceTypeURL' ).attr( 'checked', !set );
 83+ $j( '#wpUploadFileURL' ).attr( 'disabled', set );
8084
81 - //if firefogg is enbaled: toggle action per form select of http upload vs firefogg upload
82 - if( wgEnableFirefogg ){
83 - $j('#wpUploadFile').firefogg({
84 - 'firefogg_form_action': $j('#wpSourceTypeFile').attr('checked')
 85+ // If Firefogg is enabled, toggle action according to wpSourceTypeFile selection
 86+ if( wgEnableFirefogg ) {
 87+ $j( '#wpUploadFile' ).firefogg({
 88+ 'firefogg_form_action': $j( '#wpSourceTypeFile' ).attr( 'checked' )
8589 });
8690 }
87 - },
 91+ },
8892 /**
89 - * doDestinationFill fills in a destination file-name based on a source asset name.
 93+ * Fill in a destination file-name based on a source asset name.
9094 */
91 - doDestinationFill : function( targetElm ){
92 - js_log("doDestinationFill")
93 - //remove any previously flagged errors
94 - $j('#mw-upload-permitted,#mw-upload-prohibited').hide();
 95+ doDestinationFill: function( targetElm ) {
 96+ js_log( "doDestinationFill" )
 97+ // Remove any previously flagged errors
 98+ $j( '#mw-upload-permitted,#mw-upload-prohibited' ).hide();
9599
96 - var path = $j(targetElm).val();
 100+ var path = $j( targetElm ).val();
97101 // Find trailing part
98 - var slash = path.lastIndexOf('/');
99 - var backslash = path.lastIndexOf('\\');
 102+ var slash = path.lastIndexOf( '/' );
 103+ var backslash = path.lastIndexOf( '\\' );
100104 var fname;
101 - if (slash == -1 && backslash == -1) {
 105+ if ( slash == -1 && backslash == -1 ) {
102106 fname = path;
103 - } else if (slash > backslash) {
104 - fname = path.substring(slash+1, 10000);
 107+ } else if ( slash > backslash ) {
 108+ fname = path.substring( slash+1, 10000 );
105109 } else {
106 - fname = path.substring(backslash+1, 10000);
 110+ fname = path.substring( backslash+1, 10000 );
107111 }
108 - //urls are less likely to have a usefull extension don't include them in the extention check
109 - if( wgFileExtensions && $j(targetElm).attr('id') != 'wpUploadFileURL' ){
 112+ // URLs are less likely to have a useful extension. Don't include them in the extension check.
 113+ if( wgFileExtensions && $j( targetElm ).attr( 'id' ) != 'wpUploadFileURL' ) {
110114 var found = false;
111 - if( fname.lastIndexOf('.')!=-1 ){
112 - var ext = fname.substr( fname.lastIndexOf('.')+1 );
113 - for(var i=0; i < wgFileExtensions.length; i++){
114 - if( wgFileExtensions[i].toLowerCase() == ext.toLowerCase() )
 115+ if( fname.lastIndexOf( '.' ) != -1 ) {
 116+ var ext = fname.substr( fname.lastIndexOf( '.' ) + 1 );
 117+ for( var i = 0; i < wgFileExtensions.length; i++ ) {
 118+ if( wgFileExtensions[i].toLowerCase() == ext.toLowerCase() )
115119 found = true;
116120 }
117121 }
118 - if(!found){
119 - //clear the upload set mw-upload-permitted to error
120 - $j(targetElm).val('');
121 - $j('#mw-upload-permitted,#mw-upload-prohibited').show().addClass('error');
122 - //clear the wpDestFile as well:
123 - $j('#wpDestFile').val('');
 122+ if( !found ) {
 123+ // Clear the upload. Set mw-upload-permitted to error.
 124+ $j( targetElm ).val( '' );
 125+ $j( '#mw-upload-permitted,#mw-upload-prohibited' ).show().addClass( 'error' );
 126+ $j( '#wpDestFile' ).val( '' );
124127 return false;
125128 }
126129 }
127130 // Capitalise first letter and replace spaces by underscores
128 - fname = fname.charAt(0).toUpperCase().concat(fname.substring(1,10000)).replace(/ /g, '_');
 131+ fname = fname.charAt( 0 ).toUpperCase().concat( fname.substring( 1, 10000 ) ).replace( / /g, '_' );
129132 // Output result
130 - $j('#wpDestFile').val( fname );
 133+ $j( '#wpDestFile' ).val( fname );
131134
132 - //do a destination check
133 - $j('#wpDestFile').doDestCheck({
134 - 'warn_target':'#wpDestFile-warning'
 135+ // Do a destination check
 136+ $j( '#wpDestFile' ).doDestCheck({
 137+ 'warn_target': '#wpDestFile-warning'
135138 });
136139 }
137140 }
Index: trunk/phase3/js2/editPage.js
@@ -1,48 +1,50 @@
22 /*
3 - * js2 style replacement for mediaWiki edit.js
 3+ * JS2-style replacement for MediaWiki edit.js
 4+ * @todo port the rest of it to here
45 */
5 -//setup configuration vars:
6 -if(!mwAddMediaConfig)
 6+
 7+// Setup configuration vars
 8+if( !mwAddMediaConfig )
79 var mwAddMediaConfig = {
8 - 'profile':'mediawiki_edit',
9 - 'target_textbox': '#wpTextbox1',
10 - //note selections in the textbox will take over the default query
 10+ 'profile': 'mediawiki_edit',
 11+ 'target_textbox': '#wpTextbox1',
 12+ // Note: selections in the textbox will take over the default query
1113 'default_query': wgTitle,
12 - 'target_title':wgPageName,
13 - //here we can setup the conten provider overides
14 - 'cpconfig': {},
15 -
16 - //the local wiki api url:
 14+ 'target_title': wgPageName,
 15+ // Here we can setup the content provider overrides
 16+ 'cpconfig': {},
 17+ // The local wiki API URL:
1718 'local_wiki_api_url': wgServer + wgScriptPath + '/api.php'
1819 };
1920
2021
21 -js2AddOnloadHook( function(){
22 - mwEditPageHelper.init();
 22+js2AddOnloadHook( function() {
 23+ mwEditPageHelper.init();
2324 });
24 -var mwEditPageHelper = {
25 - init:function(){
 25+var mwEditPageHelper = {
 26+ init: function() {
2627 var _this = this;
27 - //@@todo check for new version of toolbar and via toolbar api:
28 -
29 - //kind of tricky would be nice to use a "loader" call here to avoid concurancy issues.
30 - if( typeof $j.wikiEditor != 'undefined' ){
31 - setTimeout(function(){
32 - $j('.wikiEditor-ui [rel=file]').unbind().addMediaWiz(
33 - mwAddMediaConfig
34 - );
35 - },100 );
36 - }else{
37 - //add the add-media-wizard button for old toolbar:
38 - $j('#toolbar').append('<img style="cursor:pointer" id="btn-add-media-wiz" src="' + mv_skin_img_path + 'Button_add_media.png">');
39 - $j('#btn-add-media-wiz').addMediaWiz(
40 - mwAddMediaConfig
41 - );
 28+ //@@todo check for a new version of the toolbar and via toolbar API
 29+
 30+ // Kind of tricky, it would be nice to use a "loader" call here to avoid concurrency issues.
 31+ if( typeof $j.wikiEditor != 'undefined' ) {
 32+ setTimeout( function() {
 33+ $j( '.wikiEditor-ui [rel=file]' ).unbind().addMediaWiz(
 34+ mwAddMediaConfig
 35+ );
 36+ }, 100 );
 37+ } else {
 38+ // Add the add-media-wizard button for old toolbar:
 39+ $j( '#toolbar' ).append( '<img style="cursor:pointer" id="btn-add-media-wiz" src="' +
 40+ mv_skin_img_path + 'Button_add_media.png">' );
 41+ $j( '#btn-add-media-wiz' ).addMediaWiz(
 42+ mwAddMediaConfig
 43+ );
4244 }
43 -
44 - //add to new toolbar (need to use api)
45 - /*$j('[rel=insert] tool-file').addMediaWiz(
46 - mwAddMediaConfig
47 - );*/
 45+
 46+ // Add to new toolbar (need to use api)
 47+ /*$j( '[rel=insert] tool-file' ).addMediaWiz(
 48+ mwAddMediaConfig
 49+ );*/
4850 }
4951 }

Status & tagging log