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