msb protocol synch change
[msb/apigateway.git] / msb-core / apiroute / apiroute-service / src / main / resources / iui-route / js / jquery.i18n / jquery.i18n.properties-1.0.9.js
1
2 /******************************************************************************
3  * jquery.i18n.properties
4  * 
5  * Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
6  * MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
7  * 
8  * @version     1.0.x
9  * @author      Nuno Fernandes
10  * @url         www.codingwithcoffee.com
11  * @inspiration Localisation assistance for jQuery (http://keith-wood.name/localisation.html)
12  *              by Keith Wood (kbwood{at}iinet.com.au) June 2007
13  * 
14  *****************************************************************************/
15
16 (function($) {
17 $.i18n = {};
18
19 /** Map holding bundle keys (if mode: 'map') */
20 $.i18n.map = {};
21     
22 /**
23  * Load and parse message bundle files (.properties),
24  * making bundles keys available as javascript variables.
25  * 
26  * i18n files are named <name>.js, or <name>_<language>.js or <name>_<language>_<country>.js
27  * Where:
28  *      The <language> argument is a valid ISO Language Code. These codes are the lower-case, 
29  *      two-letter codes as defined by ISO-639. You can find a full list of these codes at a 
30  *      number of sites, such as: http://www.loc.gov/standards/iso639-2/englangn.html
31  *      The <country> argument is a valid ISO Country Code. These codes are the upper-case,
32  *      two-letter codes as defined by ISO-3166. You can find a full list of these codes at a
33  *      number of sites, such as: http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
34  * 
35  * Sample usage for a bundles/Messages.properties bundle:
36  * $.i18n.properties({
37  *      name:      'Messages', 
38  *      language:  'en_US',
39  *      path:      'bundles'
40  * });
41  * @param  name                 (string/string[], optional) names of file to load (eg, 'Messages' or ['Msg1','Msg2']). Defaults to "Messages"
42  * @param  language             (string, optional) language/country code (eg, 'en', 'en_US', 'pt_PT'). if not specified, language reported by the browser will be used instead.
43  * @param  path                 (string, optional) path of directory that contains file to load
44  * @param  mode                 (string, optional) whether bundles keys are available as JavaScript variables/functions or as a map (eg, 'vars' or 'map')
45  * @param  cache        (boolean, optional) whether bundles should be cached by the browser, or forcibly reloaded on each page load. Defaults to false (i.e. forcibly reloaded)
46  * @param  encoding     (string, optional) the encoding to request for bundles. Property file resource bundles are specified to be in ISO-8859-1 format. Defaults to UTF-8 for backward compatibility.
47  * @param  callback     (function, optional) callback function to be called after script is terminated
48  */
49 $.i18n.properties = function(settings) {
50         // set up settings
51     var defaults = {
52         name:           'Messages',
53         language:       '',
54         path:           '',  
55         mode:           'vars',
56         cache:                  false,
57         encoding:       'UTF-8',
58         callback:       null
59     };
60     settings = $.extend(defaults, settings);    
61     if(settings.language === null || settings.language == '') {
62            settings.language = $.i18n.browserLang();
63         }
64         if(settings.language === null) {settings.language='';}
65         
66         // load and parse bundle files
67         var files = getFiles(settings.name);
68         for(i=0; i<files.length; i++) {
69                 // 1. load base (eg, Messages.properties)
70                 //loadAndParseFile(settings.path + files[i] + '.properties', settings);
71         // 2. with language code (eg, Messages_pt.properties)
72                 //if(settings.language.length >= 2) {
73         //    loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
74                 //}
75                 // 3. with language code and country code (eg, Messages_pt_PT.properties)
76                 // 将寻找资源文件的顺序倒置
77         if(settings.language.length >= 5) {
78             loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 5) +'.properties', settings);
79         } else if(settings.language.length >= 2) {
80             loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
81                 } else {
82                         loadAndParseFile(settings.path + files[i] + '.properties', settings);
83                 }
84         }
85         
86         // call callback
87         if(settings.callback){ settings.callback(); }
88 };
89
90
91 /**
92  * When configured with mode: 'map', allows access to bundle values by specifying its key.
93  * Eg, jQuery.i18n.prop('com.company.bundles.menu_add')
94  */
95 $.i18n.prop = function(key /* Add parameters as function arguments as necessary  */) {
96         var value = $.i18n.map[key];
97         if (value == null)
98                 return '[' + key + ']';
99         
100 //      if(arguments.length < 2) // No arguments.
101 //    //if(key == 'spv.lbl.modified') {alert(value);}
102 //              return value;
103         
104 //      if (!$.isArray(placeHolderValues)) {
105 //              // If placeHolderValues is not an array, make it into one.
106 //              placeHolderValues = [placeHolderValues];
107 //              for (var i=2; i<arguments.length; i++)
108 //                      placeHolderValues.push(arguments[i]);
109 //      }
110
111         // Place holder replacement
112         /**
113          * Tested with:
114          *   test.t1=asdf ''{0}''
115          *   test.t2=asdf '{0}' '{1}'{1}'zxcv
116          *   test.t3=This is \"a quote" 'a''{0}''s'd{fgh{ij'
117          *   test.t4="'''{'0}''" {0}{a}
118          *   test.t5="'''{0}'''" {1}
119          *   test.t6=a {1} b {0} c
120          *   test.t7=a 'quoted \\ s\ttringy' \t\t x
121          *
122          * Produces:
123          *   test.t1, p1 ==> asdf 'p1'
124          *   test.t2, p1 ==> asdf {0} {1}{1}zxcv
125          *   test.t3, p1 ==> This is "a quote" a'{0}'sd{fgh{ij
126          *   test.t4, p1 ==> "'{0}'" p1{a}
127          *   test.t5, p1 ==> "'{0}'" {1}
128          *   test.t6, p1 ==> a {1} b p1 c
129          *   test.t6, p1, p2 ==> a p2 b p1 c
130          *   test.t6, p1, p2, p3 ==> a p2 b p1 c
131          *   test.t7 ==> a quoted \ s   tringy           x
132          */
133         
134         var i;
135         if (typeof(value) == 'string') {
136         // Handle escape characters. Done separately from the tokenizing loop below because escape characters are 
137                 // active in quoted strings.
138         i = 0;
139         while ((i = value.indexOf('\\', i)) != -1) {
140                    if (value[i+1] == 't')
141                            value = value.substring(0, i) + '\t' + value.substring((i++) + 2); // tab
142                    else if (value[i+1] == 'r')
143                            value = value.substring(0, i) + '\r' + value.substring((i++) + 2); // return
144                    else if (value[i+1] == 'n')
145                            value = value.substring(0, i) + '\n' + value.substring((i++) + 2); // line feed
146                    else if (value[i+1] == 'f')
147                            value = value.substring(0, i) + '\f' + value.substring((i++) + 2); // form feed
148                    else if (value[i+1] == '\\')
149                            value = value.substring(0, i) + '\\' + value.substring((i++) + 2); // \
150                    else
151                            value = value.substring(0, i) + value.substring(i+1); // Quietly drop the character
152         }
153                 
154                 // Lazily convert the string to a list of tokens.
155                 var arr = [], j, index;
156                 i = 0;
157                 while (i < value.length) {
158                         if (value[i] == '\'') {
159                                 // Handle quotes
160                                 if (i == value.length-1)
161                                         value = value.substring(0, i); // Silently drop the trailing quote
162                                 else if (value[i+1] == '\'')
163                                         value = value.substring(0, i) + value.substring(++i); // Escaped quote
164                                 else {
165                                         // Quoted string
166                                         j = i + 2;
167                                         while ((j = value.indexOf('\'', j)) != -1) {
168                                                 if (j == value.length-1 || value[j+1] != '\'') {
169                                                         // Found start and end quotes. Remove them
170                                                         value = value.substring(0,i) + value.substring(i+1, j) + value.substring(j+1);
171                                                         i = j - 1;
172                                                         break;
173                                                 }
174                                                 else {
175                                                         // Found a double quote, reduce to a single quote.
176                                                         value = value.substring(0,j) + value.substring(++j);
177                                                 }
178                                         }
179                                         
180                                         if (j == -1) {
181                                                 // There is no end quote. Drop the start quote
182                                                 value = value.substring(0,i) + value.substring(i+1);
183                                         }
184                                 }
185                         }
186                         else if (value[i] == '{') {
187                                 // Beginning of an unquoted place holder.
188                                 j = value.indexOf('}', i+1);
189                                 if (j == -1)
190                                         i++; // No end. Process the rest of the line. Java would throw an exception
191                                 else {
192                                         // Add 1 to the index so that it aligns with the function arguments.
193                                         index = parseInt(value.substring(i+1, j));
194                                         if (!isNaN(index) && index >= 0) {
195                                                 // Put the line thus far (if it isn't empty) into the array
196                                                 var s = value.substring(0, i);
197                                                 if (s != "")
198                                                         arr.push(s);
199                                                 // Put the parameter reference into the array
200                                                 arr.push(index);
201                                                 // Start the processing over again starting from the rest of the line.
202                                                 i = 0;
203                                                 value = value.substring(j+1);
204                                         }
205                                         else
206                                                 i = j + 1; // Invalid parameter. Leave as is.
207                                 }
208                         }
209                         else
210                                 i++;
211                 }
212                 
213                 // Put the remainder of the no-empty line into the array.
214                 if (value != "")
215                         arr.push(value);
216                 value = arr;
217                 
218                 // Make the array the value for the entry.
219                 $.i18n.map[key] = arr;
220         }
221         
222         if (value.length == 0)
223                 return "";
224         if (value.lengh == 1 && typeof(value[0]) == "string")
225                 return value[0];
226         
227         var s = "";
228         for (i=0; i<value.length; i++) {
229                 if (typeof(value[i]) == "string")
230                         s += value[i];
231                 // Must be a number
232                 else if (value[i] + 1 < arguments.length)
233                         s += arguments[value[i] + 1];
234                 else
235                         s += "{"+ value[i] +"}";
236         }
237         
238         return s;
239 };
240
241 /** Language reported by browser, normalized code */
242 $.i18n.browserLang = function() {
243         return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
244 }
245
246
247 /** Load and parse .properties files */
248 function loadAndParseFile(filename, settings) {
249         $.ajax({
250         url:        filename,
251         async:      false,
252         cache:          settings.cache,
253         contentType:'text/plain;charset='+ settings.encoding,
254         dataType:   'text',
255         success:    function(data, status) {
256                                         parseData(data, settings.mode); 
257                                         }
258     });
259 }
260
261 /** Parse .properties files */
262 function parseData(data, mode) {
263    var parsed = '';
264    var parameters = data.split( /\n/ );
265    var regPlaceHolder = /(\{\d+\})/g;
266    var regRepPlaceHolder = /\{(\d+)\}/g;
267    var unicodeRE = /(\\u.{4})/ig;
268    for(var i=0; i<parameters.length; i++ ) {
269        parameters[i] = parameters[i].replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
270        if(parameters[i].length > 0 && parameters[i].match("^#")!="#") { // skip comments
271            var pair = parameters[i].split('=');
272            if(pair.length > 0) {
273                /** Process key & value */
274                var name = unescape(pair[0]).replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
275                var value = pair.length == 1 ? "" : pair[1];
276                // process multi-line values
277                while(value.match(/\\$/)=="\\") {
278                         value = value.substring(0, value.length - 1);
279                         value += parameters[++i].replace( /\s\s*$/, '' ); // right trim
280                }               
281                // Put values with embedded '='s back together
282                for(var s=2;s<pair.length;s++){ value +='=' + pair[s]; }
283                value = value.replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
284                
285                /** Mode: bundle keys in a map */
286                if(mode == 'map' || mode == 'both') {
287                    // handle unicode chars possibly left out
288                    var unicodeMatches = value.match(unicodeRE);
289                    if(unicodeMatches) {
290                      for(var u=0; u<unicodeMatches.length; u++) {
291                         value = value.replace( unicodeMatches[u], unescapeUnicode(unicodeMatches[u]));
292                      }
293                    }
294                    // add to map
295                    $.i18n.map[name] = value;
296                }
297                
298                /** Mode: bundle keys as vars/functions */
299                if(mode == 'vars' || mode == 'both') {
300                    value = value.replace( /"/g, '\\"' ); // escape quotation mark (")
301                    
302                    // make sure namespaced key exists (eg, 'some.key') 
303                    checkKeyNamespace(name);
304                    
305                    // value with variable substitutions
306                    if(regPlaceHolder.test(value)) {
307                        var parts = value.split(regPlaceHolder);
308                        // process function args
309                        var first = true;
310                        var fnArgs = '';
311                        var usedArgs = [];
312                        for(var p=0; p<parts.length; p++) {
313                            if(regPlaceHolder.test(parts[p]) && (usedArgs.length == 0 || usedArgs.indexOf(parts[p]) == -1)) {
314                                if(!first) {fnArgs += ',';}
315                                fnArgs += parts[p].replace(regRepPlaceHolder, 'v$1');
316                                usedArgs.push(parts[p]);
317                                first = false;
318                            }
319                        }
320                        parsed += name + '=function(' + fnArgs + '){';
321                        // process function body
322                        var fnExpr = '"' + value.replace(regRepPlaceHolder, '"+v$1+"') + '"';
323                        parsed += 'return ' + fnExpr + ';' + '};';
324                        
325                    // simple value
326                    }else{
327                        parsed += name+'="'+value+'";';
328                    }
329                } // END: Mode: bundle keys as vars/functions
330            } // END: if(pair.length > 0)
331        } // END: skip comments
332    }
333    eval(parsed);
334 }
335
336 /** Make sure namespace exists (for keys with dots in name) */
337 // TODO key parts that start with numbers quietly fail. i.e. month.short.1=Jan
338 function checkKeyNamespace(key) {
339         var regDot = /\./;
340         if(regDot.test(key)) {
341                 var fullname = '';
342                 var names = key.split( /\./ );
343                 for(var i=0; i<names.length; i++) {
344                         if(i>0) {fullname += '.';}
345                         fullname += names[i];
346                         if(eval('typeof '+fullname+' == "undefined"')) {
347                                 eval(fullname + '={};');
348                         }
349                 }
350         }
351 }
352
353 /** Make sure filename is an array */
354 function getFiles(names) {
355         return (names && names.constructor == Array) ? names : [names];
356 }
357
358 /** Ensure language code is in the format aa_AA. */
359 function normaliseLanguageCode(lang) {
360     lang = lang.toLowerCase();
361     if(lang.length > 3) {
362         lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
363     }
364     return lang;
365 }
366
367 /** Unescape unicode chars ('\u00e3') */
368 function unescapeUnicode(str) {
369   // unescape unicode codes
370   var codes = [];
371   var code = parseInt(str.substr(2), 16);
372   if (code >= 0 && code < Math.pow(2, 16)) {
373      codes.push(code);
374   }
375   // convert codes to text
376   var unescaped = '';
377   for (var i = 0; i < codes.length; ++i) {
378     unescaped += String.fromCharCode(codes[i]);
379   }
380   return unescaped;
381 }
382
383 /* Cross-Browser Split 1.0.1
384 (c) Steven Levithan <stevenlevithan.com>; MIT License
385 An ECMA-compliant, uniform cross-browser split method */
386 var cbSplit;
387 // avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
388 if (!cbSplit) {    
389   cbSplit = function(str, separator, limit) {
390       // if `separator` is not a regex, use the native `split`
391       if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
392         if(typeof cbSplit._nativeSplit == "undefined")
393           return str.split(separator, limit);
394         else
395           return cbSplit._nativeSplit.call(str, separator, limit);
396       }
397   
398       var output = [],
399           lastLastIndex = 0,
400           flags = (separator.ignoreCase ? "i" : "") +
401                   (separator.multiline  ? "m" : "") +
402                   (separator.sticky     ? "y" : ""),
403           separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
404           separator2, match, lastIndex, lastLength;
405   
406       str = str + ""; // type conversion
407       if (!cbSplit._compliantExecNpcg) {
408           separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
409       }
410   
411       /* behavior for `limit`: if it's...
412       - `undefined`: no limit.
413       - `NaN` or zero: return an empty array.
414       - a positive number: use `Math.floor(limit)`.
415       - a negative number: no limit.
416       - other: type-convert, then use the above rules. */
417       if (limit === undefined || +limit < 0) {
418           limit = Infinity;
419       } else {
420           limit = Math.floor(+limit);
421           if (!limit) {
422               return [];
423           }
424       }
425   
426       while (match = separator.exec(str)) {
427           lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
428   
429           if (lastIndex > lastLastIndex) {
430               output.push(str.slice(lastLastIndex, match.index));
431   
432               // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
433               if (!cbSplit._compliantExecNpcg && match.length > 1) {
434                   match[0].replace(separator2, function () {
435                       for (var i = 1; i < arguments.length - 2; i++) {
436                           if (arguments[i] === undefined) {
437                               match[i] = undefined;
438                           }
439                       }
440                   });
441               }
442   
443               if (match.length > 1 && match.index < str.length) {
444                   Array.prototype.push.apply(output, match.slice(1));
445               }
446   
447               lastLength = match[0].length;
448               lastLastIndex = lastIndex;
449   
450               if (output.length >= limit) {
451                   break;
452               }
453           }
454   
455           if (separator.lastIndex === match.index) {
456               separator.lastIndex++; // avoid an infinite loop
457           }
458       }
459   
460       if (lastLastIndex === str.length) {
461           if (lastLength || !separator.test("")) {
462               output.push("");
463           }
464       } else {
465           output.push(str.slice(lastLastIndex));
466       }
467   
468       return output.length > limit ? output.slice(0, limit) : output;
469   };
470   
471   cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
472   cbSplit._nativeSplit = String.prototype.split;
473
474 } // end `if (!cbSplit)`
475 String.prototype.split = function (separator, limit) {
476     return cbSplit(this, separator, limit);
477 };
478
479 })(jQuery);
480