Bug 21156: Add plural translation capabilities to JS files
authorJulian Maurice <julian.maurice@biblibre.com>
Mon, 4 Jan 2016 20:08:29 +0000 (21:08 +0100)
committerMartin Renvoize <martin.renvoize@ptfs-europe.com>
Mon, 10 Feb 2020 10:14:46 +0000 (10:14 +0000)
It adds Javascript equivalent of Koha::I18N's exported subroutines, and
they are used the same way.

String extraction is done only on *.js files and require gettext 0.19
(available in Debian jessie, and also in wheezy-backports)

It adds Javascript library Gettext.js for handling translation and a
Perl script po2json to transform PO file into JSON.

Gettext.js and po2json both come from Locale::Simple.
There are several tools named po2json. It's simpler to integrate this
one into Koha than to check if the good one is installed on the system.
Locale::Simple is not needed.

To avoid polluting the global namespace too much, this patch also
introduce a global JS object named Koha and add some stuff in Koha.i18n

Test plan:
1. Add a translatable string in a JS file. For example, add this:
     alert(__nx("There is one item", "There are {count} items", 3,
     {count: 3}));
   to staff-global.js
2. cd misc/translator && ./translate update fr-FR
3. Open misc/translator/po/fr-FR-messages-js.po, verify that your
   string is present, and translate it
4. cd misc/translator && ./translate install fr-FR
5. (Optional) Verify that
   koha-tmpl/intranet-tmpl/prog/fr-FR/js/locale_data.js exists and
   contains your translation
6. Open your browser on the staff main page, change language and verify
   that the message is translated
7. Repeat 1-6 on OPAC side

Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Signed-off-by: Bernardo Gonzalez Kriegel <bgkriegel@gmail.com>
Works well, translation is OK and test message is displayed correctly.
Current qa-tool error is a false positive.
Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>

C4/Installer/PerlDependencies.pm
koha-tmpl/intranet-tmpl/js/Gettext.js [new file with mode: 0644]
koha-tmpl/intranet-tmpl/js/i18n.js [new file with mode: 0644]
koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-close.inc
koha-tmpl/opac-tmpl/bootstrap/js/Gettext.js [new file with mode: 0644]
koha-tmpl/opac-tmpl/bootstrap/js/i18n.js [new file with mode: 0644]
misc/translator/LangInstaller.pm
misc/translator/po2json [new file with mode: 0755]

index c2e5ebf..9f1db97 100644 (file)
@@ -142,7 +142,7 @@ our $PERL_DEPS = {
     'Locale::PO' => {
         'usage'    => 'Core',
         'required' => '1',
-        'min_ver'  => '0.17'
+        'min_ver'  => '0.24'
     },
     'LWP::Simple' => {
         'usage'    => 'Core',
diff --git a/koha-tmpl/intranet-tmpl/js/Gettext.js b/koha-tmpl/intranet-tmpl/js/Gettext.js
new file mode 100644 (file)
index 0000000..ce6bf96
--- /dev/null
@@ -0,0 +1,1264 @@
+/*
+Pure Javascript implementation of Uniforum message translation.
+Copyright (C) 2008 Joshua I. Miller <unrtst@cpan.org>, all rights reserved
+
+This program is free software; you can redistribute it and/or modify it
+under the terms of the GNU Library General Public License as published
+by the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+USA.
+
+=head1 NAME
+
+Javascript Gettext - Javascript implemenation of GNU Gettext API.
+
+=head1 SYNOPSIS
+
+ // //////////////////////////////////////////////////////////
+ // Optimum caching way
+ <script language="javascript" src="/path/LC_MESSAGES/myDomain.json"></script>
+ <script language="javascript" src="/path/Gettext.js'></script>
+
+ // assuming myDomain.json defines variable json_locale_data
+ var params = {  "domain" : "myDomain",
+                 "locale_data" : json_locale_data
+              };
+ var gt = new Gettext(params);
+ // create a shortcut if you'd like
+ function _ (msgid) { return gt.gettext(msgid); }
+ alert(_("some string"));
+ // or use fully named method
+ alert(gt.gettext("some string"));
+ // change to use a different "domain"
+ gt.textdomain("anotherDomain");
+ alert(gt.gettext("some string"));
+
+
+ // //////////////////////////////////////////////////////////
+ // The other way to load the language lookup is a "link" tag
+ // Downside is that not all browsers cache XMLHttpRequests the
+ // same way, so caching of the language data isn't guarenteed
+ // across page loads.
+ // Upside is that it's easy to specify multiple files
+ <link rel="gettext" href="/path/LC_MESSAGES/myDomain.json" />
+ <script language="javascript" src="/path/Gettext.js'></script>
+
+ var gt = new Gettext({ "domain" : "myDomain" });
+ // rest is the same
+
+
+ // //////////////////////////////////////////////////////////
+ // The reson the shortcuts aren't exported by default is because they'd be
+ // glued to the single domain you created. So, if you're adding i18n support
+ // to some js library, you should use it as so:
+
+ if (typeof(MyNamespace) == 'undefined') MyNamespace = {};
+ MyNamespace.MyClass = function () {
+     var gtParms = { "domain" : 'MyNamespace_MyClass' };
+     this.gt = new Gettext(gtParams);
+     return this;
+ };
+ MyNamespace.MyClass.prototype._ = function (msgid) {
+     return this.gt.gettext(msgid);
+ };
+ MyNamespace.MyClass.prototype.something = function () {
+     var myString = this._("this will get translated");
+ };
+
+ // //////////////////////////////////////////////////////////
+ // Adding the shortcuts to a global scope is easier. If that's
+ // ok in your app, this is certainly easier.
+ var myGettext = new Gettext({ 'domain' : 'myDomain' });
+ function _ (msgid) {
+     return myGettext.gettext(msgid);
+ }
+ alert( _("text") );
+
+ // //////////////////////////////////////////////////////////
+ // Data structure of the json data
+ // NOTE: if you're loading via the <script> tag, you can only
+ // load one file, but it can contain multiple domains.
+ var json_locale_data = {
+     "MyDomain" : {
+         "" : {
+             "header_key" : "header value",
+             "header_key" : "header value",
+         "msgid" : [ "msgid_plural", "msgstr", "msgstr_plural", "msgstr_pluralN" ],
+         "msgctxt\004msgid" : [ null, "msgstr" ],
+         },
+     "AnotherDomain" : {
+         },
+     }
+
+=head1 DESCRIPTION
+
+This is a javascript implementation of GNU Gettext, providing internationalization support for javascript. It differs from existing javascript implementations in that it will support all current Gettext features (ex. plural and context support), and will also support loading language catalogs from .mo, .po, or preprocessed json files (converter included).
+
+The locale initialization differs from that of GNU Gettext / POSIX. Rather than setting the category, domain, and paths, and letting the libs find the right file, you must explicitly load the file at some point. The "domain" will still be honored. Future versions may be expanded to include support for set_locale like features.
+
+
+=head1 INSTALL
+
+To install this module, simply copy the file lib/Gettext.js to a web accessable location, and reference it from your application.
+
+
+=head1 CONFIGURATION
+
+Configure in one of two ways:
+
+=over
+
+=item 1. Optimal. Load language definition from statically defined json data.
+
+    <script language="javascript" src="/path/locale/domain.json"></script>
+
+    // in domain.json
+    json_locale_data = {
+        "mydomain" : {
+            // po header fields
+            "" : {
+                "plural-forms" : "...",
+                "lang" : "en",
+                },
+            // all the msgid strings and translations
+            "msgid" : [ "msgid_plural", "translation", "plural_translation" ],
+        },
+    };
+    // please see the included bin/po2json script for the details on this format
+
+This method also allows you to use unsupported file formats, so long as you can parse them into the above format.
+
+=item 2. Use AJAX to load language file.
+
+Use XMLHttpRequest (actually, SJAX - syncronous) to load an external resource.
+
+Supported external formats are:
+
+=over
+
+=item * Javascript Object Notation (.json)
+
+(see bin/po2json)
+
+    type=application/json
+
+=item * Uniforum Portable Object (.po)
+
+(see GNU Gettext's xgettext)
+
+    type=application/x-po
+
+=item * Machine Object (compiled .po) (.mo)
+
+NOTE: .mo format isn't actually supported just yet, but support is planned.
+
+(see GNU Gettext's msgfmt)
+
+    type=application/x-mo
+
+=back
+
+=back
+
+=head1 METHODS
+
+The following methods are implemented:
+
+  new Gettext(args)
+  textdomain  (domain)
+  gettext     (msgid)
+  dgettext    (domainname, msgid)
+  dcgettext   (domainname, msgid, LC_MESSAGES)
+  ngettext    (msgid, msgid_plural, count)
+  dngettext   (domainname, msgid, msgid_plural, count)
+  dcngettext  (domainname, msgid, msgid_plural, count, LC_MESSAGES)
+  pgettext    (msgctxt, msgid)
+  dpgettext   (domainname, msgctxt, msgid)
+  dcpgettext  (domainname, msgctxt, msgid, LC_MESSAGES)
+  npgettext   (msgctxt, msgid, msgid_plural, count)
+  dnpgettext  (domainname, msgctxt, msgid, msgid_plural, count)
+  dcnpgettext (domainname, msgctxt, msgid, msgid_plural, count, LC_MESSAGES)
+  strargs     (string, args_array)
+
+
+=head2 new Gettext (args)
+
+Several methods of loading locale data are included. You may specify a plugin or alternative method of loading data by passing the data in as the "locale_data" option. For example:
+
+    var get_locale_data = function () {
+        // plugin does whatever to populate locale_data
+        return locale_data;
+    };
+    var gt = new Gettext( 'domain' : 'messages',
+                          'locale_data' : get_locale_data() );
+
+The above can also be used if locale data is specified in a statically included <SCRIPT> tag. Just specify the variable name in the call to new. Ex:
+
+    var gt = new Gettext( 'domain' : 'messages',
+                          'locale_data' : json_locale_data_variable );
+
+Finally, you may load the locale data by referencing it in a <LINK> tag. Simply exclude the 'locale_data' option, and all <LINK rel="gettext" ...> items will be tried. The <LINK> should be specified as:
+
+    <link rel="gettext" type="application/json" href="/path/to/file.json">
+    <link rel="gettext" type="text/javascript"  href="/path/to/file.json">
+    <link rel="gettext" type="application/x-po" href="/path/to/file.po">
+    <link rel="gettext" type="application/x-mo" href="/path/to/file.mo">
+
+args:
+
+=over
+
+=item domain
+
+The Gettext domain, not www.whatev.com. It's usually your applications basename. If the .po file was "myapp.po", this would be "myapp".
+
+=item locale_data
+
+Raw locale data (in json structure). If specified, from_link data will be ignored.
+
+=back
+
+=cut
+
+*/
+
+Gettext = function (args) {
+    this.domain         = 'messages';
+    // locale_data will be populated from <link...> if not specified in args
+    this.locale_data    = undefined;
+
+    // set options
+    var options = [ "domain", "locale_data" ];
+    if (this.isValidObject(args)) {
+        for (var i in args) {
+            for (var j=0; j<options.length; j++) {
+                if (i == options[j]) {
+                    // don't set it if it's null or undefined
+                    if (this.isValidObject(args[i]))
+                        this[i] = args[i];
+                }
+            }
+        }
+    }
+
+
+    // try to load the lang file from somewhere
+    this.try_load_lang();
+
+    return this;
+}
+
+Gettext.context_glue = "\004";
+Gettext._locale_data = {};
+
+Gettext.prototype.try_load_lang = function() {
+    // check to see if language is statically included
+    if (typeof(this.locale_data) != 'undefined') {
+        // we're going to reformat it, and overwrite the variable
+        var locale_copy = this.locale_data;
+        this.locale_data = undefined;
+        this.parse_locale_data(locale_copy);
+
+        if (typeof(Gettext._locale_data[this.domain]) == 'undefined') {
+            throw new Error("Error: Gettext 'locale_data' does not contain the domain '"+this.domain+"'");
+        }
+    }
+
+
+    // try loading from JSON
+    // get lang links
+    var lang_link = this.get_lang_refs();
+
+    if (typeof(lang_link) == 'object' && lang_link.length > 0) {
+        // NOTE: there will be a delay here, as this is async.
+        // So, any i18n calls made right after page load may not
+        // get translated.
+        // XXX: we may want to see if we can "fix" this behavior
+        for (var i=0; i<lang_link.length; i++) {
+            var link = lang_link[i];
+            if (link.type == 'application/json') {
+                if (! this.try_load_lang_json(link.href) ) {
+                    throw new Error("Error: Gettext 'try_load_lang_json' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
+                }
+            } else if (link.type == 'application/x-po') {
+                if (! this.try_load_lang_po(link.href) ) {
+                    throw new Error("Error: Gettext 'try_load_lang_po' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
+                }
+            } else {
+                // TODO: implement the other types (.mo)
+                throw new Error("TODO: link type ["+link.type+"] found, and support is planned, but not implemented at this time.");
+            }
+        }
+    }
+};
+
+// This takes the bin/po2json'd data, and moves it into an internal form
+// for use in our lib, and puts it in our object as:
+//  Gettext._locale_data = {
+//      domain : {
+//          head : { headfield : headvalue },
+//          msgs : {
+//              msgid : [ msgid_plural, msgstr, msgstr_plural ],
+//          },
+Gettext.prototype.parse_locale_data = function(locale_data) {
+    if (typeof(Gettext._locale_data) == 'undefined') {
+        Gettext._locale_data = { };
+    }
+
+    // suck in every domain defined in the supplied data
+    for (var domain in locale_data) {
+        // skip empty specs (flexibly)
+        if ((! locale_data.hasOwnProperty(domain)) || (! this.isValidObject(locale_data[domain])))
+            continue;
+        // skip if it has no msgid's
+        var has_msgids = false;
+        for (var msgid in locale_data[domain]) {
+            has_msgids = true;
+            break;
+        }
+        if (! has_msgids) continue;
+
+        // grab shortcut to data
+        var data = locale_data[domain];
+
+        // if they specifcy a blank domain, default to "messages"
+        if (domain == "") domain = "messages";
+        // init the data structure
+        if (! this.isValidObject(Gettext._locale_data[domain]) )
+            Gettext._locale_data[domain] = { };
+        if (! this.isValidObject(Gettext._locale_data[domain].head) )
+            Gettext._locale_data[domain].head = { };
+        if (! this.isValidObject(Gettext._locale_data[domain].msgs) )
+            Gettext._locale_data[domain].msgs = { };
+
+        for (var key in data) {
+            if (key == "") {
+                var header = data[key];
+                for (var head in header) {
+                    var h = head.toLowerCase();
+                    Gettext._locale_data[domain].head[h] = header[head];
+                }
+            } else {
+                Gettext._locale_data[domain].msgs[key] = data[key];
+            }
+        }
+    }
+
+    // build the plural forms function
+    for (var domain in Gettext._locale_data) {
+        if (this.isValidObject(Gettext._locale_data[domain].head['plural-forms']) &&
+            typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
+            // untaint data
+            var plural_forms = Gettext._locale_data[domain].head['plural-forms'];
+            var pf_re = new RegExp('^(\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;a-zA-Z0-9_\(\)])+)', 'm');
+            if (pf_re.test(plural_forms)) {
+                //ex english: "Plural-Forms: nplurals=2; plural=(n != 1);\n"
+                //pf = "nplurals=2; plural=(n != 1);";
+                //ex russian: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)
+                //pf = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)";
+
+                var pf = Gettext._locale_data[domain].head['plural-forms'];
+                if (! /;\s*$/.test(pf)) pf = pf.concat(';');
+                /* We used to use eval, but it seems IE has issues with it.
+                 * We now use "new Function", though it carries a slightly
+                 * bigger performance hit.
+                var code = 'function (n) { var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) }; };';
+                Gettext._locale_data[domain].head.plural_func = eval("("+code+")");
+                */
+                var code = 'var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) };';
+                Gettext._locale_data[domain].head.plural_func = new Function("n", code);
+            } else {
+                throw new Error("Syntax error in language file. Plural-Forms header is invalid ["+plural_forms+"]");
+            }
+
+        // default to english plural form
+        } else if (typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
+            Gettext._locale_data[domain].head.plural_func = function (n) {
+                var p = (n != 1) ? 1 : 0;
+                return { 'nplural' : 2, 'plural' : p };
+                };
+        } // else, plural_func already created
+    }
+
+    return;
+};
+
+
+// try_load_lang_po : do an ajaxy call to load in the .po lang defs
+Gettext.prototype.try_load_lang_po = function(uri) {
+    var data = this.sjax(uri);
+    if (! data) return;
+
+    var domain = this.uri_basename(uri);
+    var parsed = this.parse_po(data);
+
+    var rv = {};
+    // munge domain into/outof header
+    if (parsed) {
+        if (! parsed[""]) parsed[""] = {};
+        if (! parsed[""]["domain"]) parsed[""]["domain"] = domain;
+        domain = parsed[""]["domain"];
+        rv[domain] = parsed;
+
+        this.parse_locale_data(rv);
+    }
+
+    return 1;
+};
+
+Gettext.prototype.uri_basename = function(uri) {
+    var rv;
+    if (rv = uri.match(/^(.*\/)?(.*)/)) {
+        var ext_strip;
+        if (ext_strip = rv[2].match(/^(.*)\..+$/))
+            return ext_strip[1];
+        else
+            return rv[2];
+    } else {
+        return "";
+    }
+};
+
+Gettext.prototype.parse_po = function(data) {
+    var rv = {};
+    var buffer = {};
+    var lastbuffer = "";
+    var errors = [];
+    var lines = data.split("\n");
+    for (var i=0; i<lines.length; i++) {
+        // chomp
+        lines[i] = lines[i].replace(/(\n|\r)+$/, '');
+
+        var match;
+
+        // Empty line / End of an entry.
+        if (/^$/.test(lines[i])) {
+            if (typeof(buffer['msgid']) != 'undefined') {
+                var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
+                                   buffer['msgctxt'].length) ?
+                                  buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
+                                  buffer['msgid'];
+                var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
+                                    buffer['msgid_plural'].length) ?
+                                   buffer['msgid_plural'] :
+                                   null;
+
+                // find msgstr_* translations and push them on
+                var trans = [];
+                for (var str in buffer) {
+                    var match;
+                    if (match = str.match(/^msgstr_(\d+)/))
+                        trans[parseInt(match[1])] = buffer[str];
+                }
+                trans.unshift(msgid_plural);
+
+                // only add it if we've got a translation
+                // NOTE: this doesn't conform to msgfmt specs
+                if (trans.length > 1) rv[msg_ctxt_id] = trans;
+
+                buffer = {};
+                lastbuffer = "";
+            }
+
+        // comments
+        } else if (/^#/.test(lines[i])) {
+            continue;
+
+        // msgctxt
+        } else if (match = lines[i].match(/^msgctxt\s+(.*)/)) {
+            lastbuffer = 'msgctxt';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgid
+        } else if (match = lines[i].match(/^msgid\s+(.*)/)) {
+            lastbuffer = 'msgid';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgid_plural
+        } else if (match = lines[i].match(/^msgid_plural\s+(.*)/)) {
+            lastbuffer = 'msgid_plural';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgstr
+        } else if (match = lines[i].match(/^msgstr\s+(.*)/)) {
+            lastbuffer = 'msgstr_0';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgstr[0] (treak like msgstr)
+        } else if (match = lines[i].match(/^msgstr\[0\]\s+(.*)/)) {
+            lastbuffer = 'msgstr_0';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgstr[n]
+        } else if (match = lines[i].match(/^msgstr\[(\d+)\]\s+(.*)/)) {
+            lastbuffer = 'msgstr_'+match[1];
+            buffer[lastbuffer] = this.parse_po_dequote(match[2]);
+
+        // continued string
+        } else if (/^"/.test(lines[i])) {
+            buffer[lastbuffer] += this.parse_po_dequote(lines[i]);
+
+        // something strange
+        } else {
+            errors.push("Strange line ["+i+"] : "+lines[i]);
+        }
+    }
+
+
+    // handle the final entry
+    if (typeof(buffer['msgid']) != 'undefined') {
+        var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
+                           buffer['msgctxt'].length) ?
+                          buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
+                          buffer['msgid'];
+        var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
+                            buffer['msgid_plural'].length) ?
+                           buffer['msgid_plural'] :
+                           null;
+
+        // find msgstr_* translations and push them on
+        var trans = [];
+        for (var str in buffer) {
+            var match;
+            if (match = str.match(/^msgstr_(\d+)/))
+                trans[parseInt(match[1])] = buffer[str];
+        }
+        trans.unshift(msgid_plural);
+
+        // only add it if we've got a translation
+        // NOTE: this doesn't conform to msgfmt specs
+        if (trans.length > 1) rv[msg_ctxt_id] = trans;
+
+        buffer = {};
+        lastbuffer = "";
+    }
+
+
+    // parse out the header
+    if (rv[""] && rv[""][1]) {
+        var cur = {};
+        var hlines = rv[""][1].split(/\\n/);
+        for (var i=0; i<hlines.length; i++) {
+            if (! hlines.length) continue;
+
+            var pos = hlines[i].indexOf(':', 0);
+            if (pos != -1) {
+                var key = hlines[i].substring(0, pos);
+                var val = hlines[i].substring(pos +1);
+                var keylow = key.toLowerCase();
+
+                if (cur[keylow] && cur[keylow].length) {
+                    errors.push("SKIPPING DUPLICATE HEADER LINE: "+hlines[i]);
+                } else if (/#-#-#-#-#/.test(keylow)) {
+                    errors.push("SKIPPING ERROR MARKER IN HEADER: "+hlines[i]);
+                } else {
+                    // remove begining spaces if any
+                    val = val.replace(/^\s+/, '');
+                    cur[keylow] = val;
+                }
+
+            } else {
+                errors.push("PROBLEM LINE IN HEADER: "+hlines[i]);
+                cur[hlines[i]] = '';
+            }
+        }
+
+        // replace header string with assoc array
+        rv[""] = cur;
+    } else {
+        rv[""] = {};
+    }
+
+    // TODO: XXX: if there are errors parsing, what do we want to do?
+    // GNU Gettext silently ignores errors. So will we.
+    // alert( "Errors parsing po file:\n" + errors.join("\n") );
+
+    return rv;
+};
+
+
+Gettext.prototype.parse_po_dequote = function(str) {
+    var match;
+    if (match = str.match(/^"(.*)"/)) {
+        str = match[1];
+    }
+    // unescale all embedded quotes (fixes bug #17504)
+    str = str.replace(/\\"/g, "\"");
+    return str;
+};
+
+
+// try_load_lang_json : do an ajaxy call to load in the lang defs
+Gettext.prototype.try_load_lang_json = function(uri) {
+    var data = this.sjax(uri);
+    if (! data) return;
+
+    var rv = this.JSON(data);
+    this.parse_locale_data(rv);
+
+    return 1;
+};
+
+// this finds all <link> tags, filters out ones that match our
+// specs, and returns a list of hashes of those
+Gettext.prototype.get_lang_refs = function() {
+    var langs = new Array();
+    var links = document.getElementsByTagName("link");
+    // find all <link> tags in dom; filter ours
+    for (var i=0; i<links.length; i++) {
+        if (links[i].rel == 'gettext' && links[i].href) {
+            if (typeof(links[i].type) == 'undefined' ||
+                links[i].type == '') {
+                if (/\.json$/i.test(links[i].href)) {
+                    links[i].type = 'application/json';
+                } else if (/\.js$/i.test(links[i].href)) {
+                    links[i].type = 'application/json';
+                } else if (/\.po$/i.test(links[i].href)) {
+                    links[i].type = 'application/x-po';
+                } else if (/\.mo$/i.test(links[i].href)) {
+                    links[i].type = 'application/x-mo';
+                } else {
+                    throw new Error("LINK tag with rel=gettext found, but the type and extension are unrecognized.");
+                }
+            }
+
+            links[i].type = links[i].type.toLowerCase();
+            if (links[i].type == 'application/json') {
+                links[i].type = 'application/json';
+            } else if (links[i].type == 'text/javascript') {
+                links[i].type = 'application/json';
+            } else if (links[i].type == 'application/x-po') {
+                links[i].type = 'application/x-po';
+            } else if (links[i].type == 'application/x-mo') {
+                links[i].type = 'application/x-mo';
+            } else {
+                throw new Error("LINK tag with rel=gettext found, but the type attribute ["+links[i].type+"] is unrecognized.");
+            }
+
+            langs.push(links[i]);
+        }
+    }
+    return langs;
+};
+
+
+/*
+
+=head2 textdomain( domain )
+
+Set domain for future gettext() calls
+
+A  message  domain  is  a  set of translatable msgid messages. Usually,
+every software package has its own message domain. The domain  name  is
+used to determine the message catalog where a translation is looked up;
+it must be a non-empty string.
+
+The current message domain is used by the gettext, ngettext, pgettext,
+npgettext functions, and by the dgettext, dcgettext, dngettext, dcngettext,
+dpgettext, dcpgettext, dnpgettext and dcnpgettext functions when called
+with a NULL domainname argument.
+
+If domainname is not NULL, the current message domain is set to
+domainname.
+
+If domainname is undefined, null, or empty string, the function returns
+the current message domain.
+
+If  successful,  the  textdomain  function  returns the current message
+domain, after possibly changing it. (ie. if you set a new domain, the
+value returned will NOT be the previous domain).
+
+=cut
+
+*/
+Gettext.prototype.textdomain = function (domain) {
+    if (domain && domain.length) this.domain = domain;
+    return this.domain;
+}
+
+/*
+
+=head2 gettext( MSGID )
+
+Returns the translation for B<MSGID>.  Example:
+
+    alert( gt.gettext("Hello World!\n") );
+
+If no translation can be found, the unmodified B<MSGID> is returned,
+i. e. the function can I<never> fail, and will I<never> mess up your
+original message.
+
+One common mistake is to interpolate a variable into the string like this:
+
+  var translated = gt.gettext("Hello " + full_name);
+
+The interpolation will happen before it's passed to gettext, and it's
+unlikely you'll have a translation for every "Hello Tom" and "Hello Dick"
+and "Hellow Harry" that may arise.
+
+Use C<strargs()> (see below) to solve this problem:
+
+  var translated = Gettext.strargs( gt.gettext("Hello %1"), [full_name] );
+
+This is espeically useful when multiple replacements are needed, as they
+may not appear in the same order within the translation. As an English to
+French example:
+
+  Expected result: "This is the red ball"
+  English: "This is the %1 %2"
+  French:  "C'est le %2 %1"
+  Code: Gettext.strargs( gt.gettext("This is the %1 %2"), ["red", "ball"] );
+
+(The example is stupid because neither color nor thing will get
+translated here ...).
+
+=head2 dgettext( TEXTDOMAIN, MSGID )
+
+Like gettext(), but retrieves the message for the specified
+B<TEXTDOMAIN> instead of the default domain.  In case you wonder what
+a textdomain is, see above section on the textdomain() call.
+
+=head2 dcgettext( TEXTDOMAIN, MSGID, CATEGORY )
+
+Like dgettext() but retrieves the message from the specified B<CATEGORY>
+instead of the default category C<LC_MESSAGES>.
+
+NOTE: the categories are really useless in javascript context. This is
+here for GNU Gettext API compatability. In practice, you'll never need
+to use this. This applies to all the calls including the B<CATEGORY>.
+
+
+=head2 ngettext( MSGID, MSGID_PLURAL, COUNT )
+
+Retrieves the correct translation for B<COUNT> items.  In legacy software
+you will often find something like:
+
+    alert( count + " file(s) deleted.\n" );
+
+or
+
+    printf(count + " file%s deleted.\n", $count == 1 ? '' : 's');
+
+I<NOTE: javascript lacks a builtin printf, so the above isn't a working example>
+
+The first example looks awkward, the second will only work in English
+and languages with similar plural rules.  Before ngettext() was introduced,
+the best practice for internationalized programs was:
+
+    if (count == 1) {
+        alert( gettext("One file deleted.\n") );
+    } else {
+        printf( gettext("%d files deleted.\n"), count );
+    }
+
+This is a nuisance for the programmer and often still not sufficient
+for an adequate translation.  Many languages have completely different
+ideas on numerals.  Some (French, Italian, ...) treat 0 and 1 alike,
+others make no distinction at all (Japanese, Korean, Chinese, ...),
+others have two or more plural forms (Russian, Latvian, Czech,
+Polish, ...).  The solution is:
+
+    printf( ngettext("One file deleted.\n",
+                     "%d files deleted.\n",
+                     count), // argument to ngettext!
+            count);          // argument to printf!
+
+In English, or if no translation can be found, the first argument
+(B<MSGID>) is picked if C<count> is one, the second one otherwise.
+For other languages, the correct plural form (of 1, 2, 3, 4, ...)
+is automatically picked, too.  You don't have to know anything about
+the plural rules in the target language, ngettext() will take care
+of that.
+
+This is most of the time sufficient but you will have to prove your
+creativity in cases like
+
+    "%d file(s) deleted, and %d file(s) created.\n"
+
+That said, javascript lacks C<printf()> support. Supplied with Gettext.js
+is the C<strargs()> method, which can be used for these cases:
+
+    Gettext.strargs( gt.ngettext( "One file deleted.\n",
+                                  "%d files deleted.\n",
+                                  count), // argument to ngettext!
+                     count); // argument to strargs!
+
+NOTE: the variable replacement isn't done for you, so you must
+do it yourself as in the above.
+
+=head2 dngettext( TEXTDOMAIN, MSGID, MSGID_PLURAL, COUNT )
+
+Like ngettext() but retrieves the translation from the specified
+textdomain instead of the default domain.
+
+=head2 dcngettext( TEXTDOMAIN, MSGID, MSGID_PLURAL, COUNT, CATEGORY )
+
+Like dngettext() but retrieves the translation from the specified
+category, instead of the default category C<LC_MESSAGES>.
+
+
+=head2 pgettext( MSGCTXT, MSGID )
+
+Returns the translation of MSGID, given the context of MSGCTXT.
+
+Both items are used as a unique key into the message catalog.
+
+This allows the translator to have two entries for words that may
+translate to different foreign words based on their context. For
+example, the word "View" may be a noun or a verb, which may be
+used in a menu as File->View or View->Source.
+
+    alert( pgettext( "Verb: To View", "View" ) );
+    alert( pgettext( "Noun: A View", "View"  ) );
+
+The above will both lookup different entries in the message catalog.
+
+In English, or if no translation can be found, the second argument
+(B<MSGID>) is returned.
+
+=head2 dpgettext( TEXTDOMAIN, MSGCTXT, MSGID )
+
+Like pgettext(), but retrieves the message for the specified
+B<TEXTDOMAIN> instead of the default domain.
+
+=head2 dcpgettext( TEXTDOMAIN, MSGCTXT, MSGID, CATEGORY )
+
+Like dpgettext() but retrieves the message from the specified B<CATEGORY>
+instead of the default category C<LC_MESSAGES>.
+
+
+=head2 npgettext( MSGCTXT, MSGID, MSGID_PLURAL, COUNT )
+
+Like ngettext() with the addition of context as in pgettext().
+
+In English, or if no translation can be found, the second argument
+(MSGID) is picked if B<COUNT> is one, the third one otherwise.
+
+=head2 dnpgettext( TEXTDOMAIN, MSGCTXT, MSGID, MSGID_PLURAL, COUNT )
+
+Like npgettext() but retrieves the translation from the specified
+textdomain instead of the default domain.
+
+=head2 dcnpgettext( TEXTDOMAIN, MSGCTXT, MSGID, MSGID_PLURAL, COUNT, CATEGORY )
+
+Like dnpgettext() but retrieves the translation from the specified
+category, instead of the default category C<LC_MESSAGES>.
+
+=cut
+
+*/
+
+// gettext
+Gettext.prototype.gettext = function (msgid) {
+    var msgctxt;
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dgettext = function (domain, msgid) {
+    var msgctxt;
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dcgettext = function (domain, msgid, category) {
+    var msgctxt;
+    var msgid_plural;
+    var n;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+// ngettext
+Gettext.prototype.ngettext = function (msgid, msgid_plural, n) {
+    var msgctxt;
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dngettext = function (domain, msgid, msgid_plural, n) {
+    var msgctxt;
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dcngettext = function (domain, msgid, msgid_plural, n, category) {
+    var msgctxt;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category, category);
+};
+
+// pgettext
+Gettext.prototype.pgettext = function (msgctxt, msgid) {
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dpgettext = function (domain, msgctxt, msgid) {
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dcpgettext = function (domain, msgctxt, msgid, category) {
+    var msgid_plural;
+    var n;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+// npgettext
+Gettext.prototype.npgettext = function (msgctxt, msgid, msgid_plural, n) {
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dnpgettext = function (domain, msgctxt, msgid, msgid_plural, n) {
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+// this has all the options, so we use it for all of them.
+Gettext.prototype.dcnpgettext = function (domain, msgctxt, msgid, msgid_plural, n, category) {
+    if (! this.isValidObject(msgid)) return '';
+
+    var plural = this.isValidObject(msgid_plural);
+    var msg_ctxt_id = this.isValidObject(msgctxt) ? msgctxt+Gettext.context_glue+msgid : msgid;
+
+    var domainname = this.isValidObject(domain)      ? domain :
+                     this.isValidObject(this.domain) ? this.domain :
+                                                       'messages';
+
+    // category is always LC_MESSAGES. We ignore all else
+    var category_name = 'LC_MESSAGES';
+    var category = 5;
+
+    var locale_data = new Array();
+    if (typeof(Gettext._locale_data) != 'undefined' &&
+        this.isValidObject(Gettext._locale_data[domainname])) {
+        locale_data.push( Gettext._locale_data[domainname] );
+
+    } else if (typeof(Gettext._locale_data) != 'undefined') {
+        // didn't find domain we're looking for. Search all of them.
+        for (var dom in Gettext._locale_data) {
+            locale_data.push( Gettext._locale_data[dom] );
+        }
+    }
+
+    var trans = [];
+    var found = false;
+    var domain_used; // so we can find plural-forms if needed
+    if (locale_data.length) {
+        for (var i=0; i<locale_data.length; i++) {
+            var locale = locale_data[i];
+            if (this.isValidObject(locale.msgs[msg_ctxt_id])) {
+                // make copy of that array (cause we'll be destructive)
+                for (var j=0; j<locale.msgs[msg_ctxt_id].length; j++) {
+                    trans[j] = locale.msgs[msg_ctxt_id][j];
+                }
+                trans.shift(); // throw away the msgid_plural
+                domain_used = locale;
+                found = true;
+                // only break if found translation actually has a translation.
+                if ( trans.length > 0 && trans[0].length != 0 )
+                    break;
+            }
+        }
+    }
+
+    // default to english if we lack a match, or match has zero length
+    if ( trans.length == 0 || trans[0].length == 0 ) {
+        trans = [ msgid, msgid_plural ];
+    }
+
+    var translation = trans[0];
+    if (plural) {
+        var p;
+        if (found && this.isValidObject(domain_used.head.plural_func) ) {
+            var rv = domain_used.head.plural_func(n);
+            if (! rv.plural) rv.plural = 0;
+            if (! rv.nplural) rv.nplural = 0;
+            // if plurals returned is out of bound for total plural forms
+            if (rv.nplural <= rv.plural) rv.plural = 0;
+            p = rv.plural;
+        } else {
+            p = (n != 1) ? 1 : 0;
+        }
+        if (this.isValidObject(trans[p]))
+            translation = trans[p];
+    }
+
+    return translation;
+};
+
+
+/*
+
+=head2 strargs (string, argument_array)
+
+  string : a string that potentially contains formatting characters.
+  argument_array : an array of positional replacement values
+
+This is a utility method to provide some way to support positional parameters within a string, as javascript lacks a printf() method.
+
+The format is similar to printf(), but greatly simplified (ie. fewer features).
+
+Any percent signs followed by numbers are replaced with the corrosponding item from the B<argument_array>.
+
+Example:
+
+    var string = "%2 roses are red, %1 violets are blue";
+    var args   = new Array("10", "15");
+    var result = Gettext.strargs(string, args);
+    // result is "15 roses are red, 10 violets are blue"
+
+The format numbers are 1 based, so the first itme is %1.
+
+A lone percent sign may be escaped by preceeding it with another percent sign.
+
+A percent sign followed by anything other than a number or another percent sign will be passed through as is.
+
+Some more examples should clear up any abmiguity. The following were called with the orig string, and the array as Array("[one]", "[two]") :
+
+  orig string "blah" becomes "blah"
+  orig string "" becomes ""
+  orig string "%%" becomes "%"
+  orig string "%%%" becomes "%%"
+  orig string "%%%%" becomes "%%"
+  orig string "%%%%%" becomes "%%%"
+  orig string "tom%%dick" becomes "tom%dick"
+  orig string "thing%1bob" becomes "thing[one]bob"
+  orig string "thing%1%2bob" becomes "thing[one][two]bob"
+  orig string "thing%1asdf%2asdf" becomes "thing[one]asdf[two]asdf"
+  orig string "%1%2%3" becomes "[one][two]"
+  orig string "tom%1%%2%aDick" becomes "tom[one]%2%aDick"
+
+This is especially useful when using plurals, as the string will nearly always contain the number.
+
+It's also useful in translated strings where the translator may have needed to move the position of the parameters.
+
+For example:
+
+  var count = 14;
+  Gettext.strargs( gt.ngettext('one banana', '%1 bananas', count), [count] );
+
+NOTE: this may be called as an instance method, or as a class method.
+
+  // instance method:
+  var gt = new Gettext(params);
+  gt.strargs(string, args);
+
+  // class method:
+  Gettext.strargs(string, args);
+
+=cut
+
+*/
+/* utility method, since javascript lacks a printf */
+Gettext.strargs = function (str, args) {
+    // make sure args is an array
+    if ( null == args ||
+         'undefined' == typeof(args) ) {
+        args = [];
+    } else if (args.constructor != Array) {
+        args = [args];
+    }
+
+    // NOTE: javascript lacks support for zero length negative look-behind
+    // in regex, so we must step through w/ index.
+    // The perl equiv would simply be:
+    //    $string =~ s/(?<!\%)\%([0-9]+)/$args[$1]/g;
+    //    $string =~ s/\%\%/\%/g; # restore escaped percent signs
+
+    var newstr = "";
+    while (true) {
+        var i = str.indexOf('%');
+        var match_n;
+
+        // no more found. Append whatever remains
+        if (i == -1) {
+            newstr += str;
+            break;
+        }
+
+        // we found it, append everything up to that
+        newstr += str.substr(0, i);
+
+        // check for escpaed %%
+        if (str.substr(i, 2) == '%%') {
+            newstr += '%';
+            str = str.substr((i+2));
+
+        // % followed by number
+        } else if ( match_n = str.substr(i).match(/^%(\d+)/) ) {
+            var arg_n = parseInt(match_n[1]);
+            var length_n = match_n[1].length;
+            if ( arg_n > 0 && args[arg_n -1] != null && typeof(args[arg_n -1]) != 'undefined' )
+                newstr += args[arg_n -1];
+            str = str.substr( (i + 1 + length_n) );
+
+        // % followed by some other garbage - just remove the %
+        } else {
+            newstr += '%';
+            str = str.substr((i+1));
+        }
+    }
+
+    return newstr;
+}
+
+/* instance method wrapper of strargs */
+Gettext.prototype.strargs = function (str, args) {
+    return Gettext.strargs(str, args);
+}
+
+/* verify that something is an array */
+Gettext.prototype.isArray = function (thisObject) {
+    return this.isValidObject(thisObject) && thisObject.constructor == Array;
+};
+
+/* verify that an object exists and is valid */
+Gettext.prototype.isValidObject = function (thisObject) {
+    if (null == thisObject) {
+        return false;
+    } else if ('undefined' == typeof(thisObject) ) {
+        return false;
+    } else {
+        return true;
+    }
+};
+
+Gettext.prototype.sjax = function (uri) {
+    var xmlhttp;
+    if (window.XMLHttpRequest) {
+        xmlhttp = new XMLHttpRequest();
+    } else if (navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) {
+        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
+    } else {
+        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
+    }
+
+    if (! xmlhttp)
+        throw new Error("Your browser doesn't do Ajax. Unable to support external language files.");
+
+    xmlhttp.open('GET', uri, false);
+    try { xmlhttp.send(null); }
+    catch (e) { return; }
+
+    // we consider status 200 and 0 as ok.
+    // 0 happens when we request local file, allowing this to run on local files
+    var sjax_status = xmlhttp.status;
+    if (sjax_status == 200 || sjax_status == 0) {
+        return xmlhttp.responseText;
+    } else {
+        var error = xmlhttp.statusText + " (Error " + xmlhttp.status + ")";
+        if (xmlhttp.responseText.length) {
+            error += "\n" + xmlhttp.responseText;
+        }
+        alert(error);
+        return;
+    }
+}
+
+Gettext.prototype.JSON = function (data) {
+    return eval('(' + data + ')');
+}
+
+
+/*
+
+=head1 NOTES
+
+These are some notes on the internals
+
+=over
+
+=item LOCALE CACHING
+
+Loaded locale data is currently cached class-wide. This means that if two scripts are both using Gettext.js, and both share the same gettext domain, that domain will only be loaded once. This will allow you to grab a new object many times from different places, utilize the same domain, and share a single translation file. The downside is that a domain won't be RE-loaded if a new object is instantiated on a domain that had already been instantiated.
+
+=back
+
+=head1 BUGS / TODO
+
+=over
+
+=item error handling
+
+Currently, there are several places that throw errors. In GNU Gettext, there are no fatal errors, which allows text to still be displayed regardless of how broken the environment becomes. We should evaluate and determine where we want to stand on that issue.
+
+=item syncronous only support (no ajax support)
+
+Currently, fetching language data is done purely syncronous, which means the page will halt while those files are fetched/loaded.
+
+This is often what you want, as then following translation requests will actually be translated. However, if all your calls are done dynamically (ie. error handling only or something), loading in the background may be more adventagous.
+
+It's still recommended to use the statically defined <script ...> method, which should have the same delay, but it will cache the result.
+
+=item domain support
+
+domain support while using shortcut methods like C<_('string')> or C<i18n('string')>.
+
+Under normal apps, the domain is usually set globally to the app, and a single language file is used. Under javascript, you may have multiple libraries or applications needing translation support, but the namespace is essentially global.
+
+It's recommended that your app initialize it's own shortcut with it's own domain.  (See examples/wrapper/i18n.js for an example.)
+
+Basically, you'll want to accomplish something like this:
+
+    // in some other .js file that needs i18n
+    this.i18nObj = new i18n;
+    this.i18n = this.i18nObj.init('domain');
+    // do translation
+    alert( this.i18n("string") );
+
+If you use this raw Gettext object, then this is all handled for you, as you have your own object then, and will be calling C<myGettextObject.gettext('string')> and such.
+
+
+=item encoding
+
+May want to add encoding/reencoding stuff. See GNU iconv, or the perl module Locale::Recode from libintl-perl.
+
+=back
+
+
+=head1 COMPATABILITY
+
+This has been tested on the following browsers. It may work on others, but these are all those to which I have access.
+
+    FF1.5, FF2, FF3, IE6, IE7, Opera9, Opera10, Safari3.1, Chrome
+
+    *FF = Firefox
+    *IE = Internet Explorer
+
+
+=head1 REQUIRES
+
+bin/po2json requires perl, and the perl modules Locale::PO and JSON.
+
+=head1 SEE ALSO
+
+bin/po2json (included),
+examples/normal/index.html,
+examples/wrapper/i18n.html, examples/wrapper/i18n.js,
+Locale::gettext_pp(3pm), POSIX(3pm), gettext(1), gettext(3)
+
+=head1 AUTHOR
+
+Copyright (C) 2008, Joshua I. Miller E<lt>unrtst@cpan.orgE<gt>, all rights reserved. See the source code for details.
+
+=cut
+
+*/
diff --git a/koha-tmpl/intranet-tmpl/js/i18n.js b/koha-tmpl/intranet-tmpl/js/i18n.js
new file mode 100644 (file)
index 0000000..4c2df9a
--- /dev/null
@@ -0,0 +1,51 @@
+(function() {
+  var params = {
+    "domain": "Koha"
+  };
+  if (typeof json_locale_data !== 'undefined') {
+    params.locale_data = json_locale_data;
+  }
+
+  Koha.i18n = {
+    gt: new Gettext(params),
+
+    expand: function(text, vars) {
+      var replace_callback = function(match, name) {
+        return name in vars ? vars[name] : match;
+      };
+      return text.replace(/\{(.*?)\}/g, replace_callback);
+    }
+  };
+})();
+
+function __(msgid) {
+  return Koha.i18n.gt.gettext(msgid);
+}
+
+function __x(msgid, vars) {
+  return Koha.i18n.expand(__(msgid), vars);
+}
+
+function __n(msgid, msgid_plural, count) {
+  return Koha.i18n.gt.ngettext(msgid, msgid_plural, count);
+}
+
+function __nx(msgid, msgid_plural, count, vars) {
+  return Koha.i18n.expand(__n(msgid, msgid_plural, count), vars);
+}
+
+function __p(msgctxt, msgid) {
+  return Koha.i18n.gt.pgettext(msgctxt, msgid);
+}
+
+function __px(msgctxt, msgid, vars) {
+  return Koha.i18n.expand(__p(msgctxt, msgid), vars);
+}
+
+function __np(msgctxt, msgid, msgid_plural, count) {
+  return Koha.i18n.gt.npgettext(msgctxt, msgid, msgid_plural, count);
+}
+
+function __npx(msgctxt, msgid, msgid_plural, count, vars) {
+  return Koha.i18n.expand(__np(msgctxt, msgid, msgid_plural, count), vars);
+}
index 6fe8c15..0b04200 100644 (file)
 [% INCLUDE intranetstylesheet.inc %]
 [% IF ( bidi ) %][% Asset.css("css/right-to-left.css") | $raw %][% END %]
 
+<script>
+var Koha = {};
+</script>
+
+<script src="[% themelang %]/js/locale_data.js"></script>
+<script src="[% interface %]/js/Gettext.js"></script>
+<script src="[% interface %]/js/i18n.js"></script>
+
 [% IF ( login ) %]
     [% Asset.css("css/login.css") | $raw %]
 [% END %]
diff --git a/koha-tmpl/opac-tmpl/bootstrap/js/Gettext.js b/koha-tmpl/opac-tmpl/bootstrap/js/Gettext.js
new file mode 100644 (file)
index 0000000..ce6bf96
--- /dev/null
@@ -0,0 +1,1264 @@
+/*
+Pure Javascript implementation of Uniforum message translation.
+Copyright (C) 2008 Joshua I. Miller <unrtst@cpan.org>, all rights reserved
+
+This program is free software; you can redistribute it and/or modify it
+under the terms of the GNU Library General Public License as published
+by the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+USA.
+
+=head1 NAME
+
+Javascript Gettext - Javascript implemenation of GNU Gettext API.
+
+=head1 SYNOPSIS
+
+ // //////////////////////////////////////////////////////////
+ // Optimum caching way
+ <script language="javascript" src="/path/LC_MESSAGES/myDomain.json"></script>
+ <script language="javascript" src="/path/Gettext.js'></script>
+
+ // assuming myDomain.json defines variable json_locale_data
+ var params = {  "domain" : "myDomain",
+                 "locale_data" : json_locale_data
+              };
+ var gt = new Gettext(params);
+ // create a shortcut if you'd like
+ function _ (msgid) { return gt.gettext(msgid); }
+ alert(_("some string"));
+ // or use fully named method
+ alert(gt.gettext("some string"));
+ // change to use a different "domain"
+ gt.textdomain("anotherDomain");
+ alert(gt.gettext("some string"));
+
+
+ // //////////////////////////////////////////////////////////
+ // The other way to load the language lookup is a "link" tag
+ // Downside is that not all browsers cache XMLHttpRequests the
+ // same way, so caching of the language data isn't guarenteed
+ // across page loads.
+ // Upside is that it's easy to specify multiple files
+ <link rel="gettext" href="/path/LC_MESSAGES/myDomain.json" />
+ <script language="javascript" src="/path/Gettext.js'></script>
+
+ var gt = new Gettext({ "domain" : "myDomain" });
+ // rest is the same
+
+
+ // //////////////////////////////////////////////////////////
+ // The reson the shortcuts aren't exported by default is because they'd be
+ // glued to the single domain you created. So, if you're adding i18n support
+ // to some js library, you should use it as so:
+
+ if (typeof(MyNamespace) == 'undefined') MyNamespace = {};
+ MyNamespace.MyClass = function () {
+     var gtParms = { "domain" : 'MyNamespace_MyClass' };
+     this.gt = new Gettext(gtParams);
+     return this;
+ };
+ MyNamespace.MyClass.prototype._ = function (msgid) {
+     return this.gt.gettext(msgid);
+ };
+ MyNamespace.MyClass.prototype.something = function () {
+     var myString = this._("this will get translated");
+ };
+
+ // //////////////////////////////////////////////////////////
+ // Adding the shortcuts to a global scope is easier. If that's
+ // ok in your app, this is certainly easier.
+ var myGettext = new Gettext({ 'domain' : 'myDomain' });
+ function _ (msgid) {
+     return myGettext.gettext(msgid);
+ }
+ alert( _("text") );
+
+ // //////////////////////////////////////////////////////////
+ // Data structure of the json data
+ // NOTE: if you're loading via the <script> tag, you can only
+ // load one file, but it can contain multiple domains.
+ var json_locale_data = {
+     "MyDomain" : {
+         "" : {
+             "header_key" : "header value",
+             "header_key" : "header value",
+         "msgid" : [ "msgid_plural", "msgstr", "msgstr_plural", "msgstr_pluralN" ],
+         "msgctxt\004msgid" : [ null, "msgstr" ],
+         },
+     "AnotherDomain" : {
+         },
+     }
+
+=head1 DESCRIPTION
+
+This is a javascript implementation of GNU Gettext, providing internationalization support for javascript. It differs from existing javascript implementations in that it will support all current Gettext features (ex. plural and context support), and will also support loading language catalogs from .mo, .po, or preprocessed json files (converter included).
+
+The locale initialization differs from that of GNU Gettext / POSIX. Rather than setting the category, domain, and paths, and letting the libs find the right file, you must explicitly load the file at some point. The "domain" will still be honored. Future versions may be expanded to include support for set_locale like features.
+
+
+=head1 INSTALL
+
+To install this module, simply copy the file lib/Gettext.js to a web accessable location, and reference it from your application.
+
+
+=head1 CONFIGURATION
+
+Configure in one of two ways:
+
+=over
+
+=item 1. Optimal. Load language definition from statically defined json data.
+
+    <script language="javascript" src="/path/locale/domain.json"></script>
+
+    // in domain.json
+    json_locale_data = {
+        "mydomain" : {
+            // po header fields
+            "" : {
+                "plural-forms" : "...",
+                "lang" : "en",
+                },
+            // all the msgid strings and translations
+            "msgid" : [ "msgid_plural", "translation", "plural_translation" ],
+        },
+    };
+    // please see the included bin/po2json script for the details on this format
+
+This method also allows you to use unsupported file formats, so long as you can parse them into the above format.
+
+=item 2. Use AJAX to load language file.
+
+Use XMLHttpRequest (actually, SJAX - syncronous) to load an external resource.
+
+Supported external formats are:
+
+=over
+
+=item * Javascript Object Notation (.json)
+
+(see bin/po2json)
+
+    type=application/json
+
+=item * Uniforum Portable Object (.po)
+
+(see GNU Gettext's xgettext)
+
+    type=application/x-po
+
+=item * Machine Object (compiled .po) (.mo)
+
+NOTE: .mo format isn't actually supported just yet, but support is planned.
+
+(see GNU Gettext's msgfmt)
+
+    type=application/x-mo
+
+=back
+
+=back
+
+=head1 METHODS
+
+The following methods are implemented:
+
+  new Gettext(args)
+  textdomain  (domain)
+  gettext     (msgid)
+  dgettext    (domainname, msgid)
+  dcgettext   (domainname, msgid, LC_MESSAGES)
+  ngettext    (msgid, msgid_plural, count)
+  dngettext   (domainname, msgid, msgid_plural, count)
+  dcngettext  (domainname, msgid, msgid_plural, count, LC_MESSAGES)
+  pgettext    (msgctxt, msgid)
+  dpgettext   (domainname, msgctxt, msgid)
+  dcpgettext  (domainname, msgctxt, msgid, LC_MESSAGES)
+  npgettext   (msgctxt, msgid, msgid_plural, count)
+  dnpgettext  (domainname, msgctxt, msgid, msgid_plural, count)
+  dcnpgettext (domainname, msgctxt, msgid, msgid_plural, count, LC_MESSAGES)
+  strargs     (string, args_array)
+
+
+=head2 new Gettext (args)
+
+Several methods of loading locale data are included. You may specify a plugin or alternative method of loading data by passing the data in as the "locale_data" option. For example:
+
+    var get_locale_data = function () {
+        // plugin does whatever to populate locale_data
+        return locale_data;
+    };
+    var gt = new Gettext( 'domain' : 'messages',
+                          'locale_data' : get_locale_data() );
+
+The above can also be used if locale data is specified in a statically included <SCRIPT> tag. Just specify the variable name in the call to new. Ex:
+
+    var gt = new Gettext( 'domain' : 'messages',
+                          'locale_data' : json_locale_data_variable );
+
+Finally, you may load the locale data by referencing it in a <LINK> tag. Simply exclude the 'locale_data' option, and all <LINK rel="gettext" ...> items will be tried. The <LINK> should be specified as:
+
+    <link rel="gettext" type="application/json" href="/path/to/file.json">
+    <link rel="gettext" type="text/javascript"  href="/path/to/file.json">
+    <link rel="gettext" type="application/x-po" href="/path/to/file.po">
+    <link rel="gettext" type="application/x-mo" href="/path/to/file.mo">
+
+args:
+
+=over
+
+=item domain
+
+The Gettext domain, not www.whatev.com. It's usually your applications basename. If the .po file was "myapp.po", this would be "myapp".
+
+=item locale_data
+
+Raw locale data (in json structure). If specified, from_link data will be ignored.
+
+=back
+
+=cut
+
+*/
+
+Gettext = function (args) {
+    this.domain         = 'messages';
+    // locale_data will be populated from <link...> if not specified in args
+    this.locale_data    = undefined;
+
+    // set options
+    var options = [ "domain", "locale_data" ];
+    if (this.isValidObject(args)) {
+        for (var i in args) {
+            for (var j=0; j<options.length; j++) {
+                if (i == options[j]) {
+                    // don't set it if it's null or undefined
+                    if (this.isValidObject(args[i]))
+                        this[i] = args[i];
+                }
+            }
+        }
+    }
+
+
+    // try to load the lang file from somewhere
+    this.try_load_lang();
+
+    return this;
+}
+
+Gettext.context_glue = "\004";
+Gettext._locale_data = {};
+
+Gettext.prototype.try_load_lang = function() {
+    // check to see if language is statically included
+    if (typeof(this.locale_data) != 'undefined') {
+        // we're going to reformat it, and overwrite the variable
+        var locale_copy = this.locale_data;
+        this.locale_data = undefined;
+        this.parse_locale_data(locale_copy);
+
+        if (typeof(Gettext._locale_data[this.domain]) == 'undefined') {
+            throw new Error("Error: Gettext 'locale_data' does not contain the domain '"+this.domain+"'");
+        }
+    }
+
+
+    // try loading from JSON
+    // get lang links
+    var lang_link = this.get_lang_refs();
+
+    if (typeof(lang_link) == 'object' && lang_link.length > 0) {
+        // NOTE: there will be a delay here, as this is async.
+        // So, any i18n calls made right after page load may not
+        // get translated.
+        // XXX: we may want to see if we can "fix" this behavior
+        for (var i=0; i<lang_link.length; i++) {
+            var link = lang_link[i];
+            if (link.type == 'application/json') {
+                if (! this.try_load_lang_json(link.href) ) {
+                    throw new Error("Error: Gettext 'try_load_lang_json' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
+                }
+            } else if (link.type == 'application/x-po') {
+                if (! this.try_load_lang_po(link.href) ) {
+                    throw new Error("Error: Gettext 'try_load_lang_po' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
+                }
+            } else {
+                // TODO: implement the other types (.mo)
+                throw new Error("TODO: link type ["+link.type+"] found, and support is planned, but not implemented at this time.");
+            }
+        }
+    }
+};
+
+// This takes the bin/po2json'd data, and moves it into an internal form
+// for use in our lib, and puts it in our object as:
+//  Gettext._locale_data = {
+//      domain : {
+//          head : { headfield : headvalue },
+//          msgs : {
+//              msgid : [ msgid_plural, msgstr, msgstr_plural ],
+//          },
+Gettext.prototype.parse_locale_data = function(locale_data) {
+    if (typeof(Gettext._locale_data) == 'undefined') {
+        Gettext._locale_data = { };
+    }
+
+    // suck in every domain defined in the supplied data
+    for (var domain in locale_data) {
+        // skip empty specs (flexibly)
+        if ((! locale_data.hasOwnProperty(domain)) || (! this.isValidObject(locale_data[domain])))
+            continue;
+        // skip if it has no msgid's
+        var has_msgids = false;
+        for (var msgid in locale_data[domain]) {
+            has_msgids = true;
+            break;
+        }
+        if (! has_msgids) continue;
+
+        // grab shortcut to data
+        var data = locale_data[domain];
+
+        // if they specifcy a blank domain, default to "messages"
+        if (domain == "") domain = "messages";
+        // init the data structure
+        if (! this.isValidObject(Gettext._locale_data[domain]) )
+            Gettext._locale_data[domain] = { };
+        if (! this.isValidObject(Gettext._locale_data[domain].head) )
+            Gettext._locale_data[domain].head = { };
+        if (! this.isValidObject(Gettext._locale_data[domain].msgs) )
+            Gettext._locale_data[domain].msgs = { };
+
+        for (var key in data) {
+            if (key == "") {
+                var header = data[key];
+                for (var head in header) {
+                    var h = head.toLowerCase();
+                    Gettext._locale_data[domain].head[h] = header[head];
+                }
+            } else {
+                Gettext._locale_data[domain].msgs[key] = data[key];
+            }
+        }
+    }
+
+    // build the plural forms function
+    for (var domain in Gettext._locale_data) {
+        if (this.isValidObject(Gettext._locale_data[domain].head['plural-forms']) &&
+            typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
+            // untaint data
+            var plural_forms = Gettext._locale_data[domain].head['plural-forms'];
+            var pf_re = new RegExp('^(\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;a-zA-Z0-9_\(\)])+)', 'm');
+            if (pf_re.test(plural_forms)) {
+                //ex english: "Plural-Forms: nplurals=2; plural=(n != 1);\n"
+                //pf = "nplurals=2; plural=(n != 1);";
+                //ex russian: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)
+                //pf = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)";
+
+                var pf = Gettext._locale_data[domain].head['plural-forms'];
+                if (! /;\s*$/.test(pf)) pf = pf.concat(';');
+                /* We used to use eval, but it seems IE has issues with it.
+                 * We now use "new Function", though it carries a slightly
+                 * bigger performance hit.
+                var code = 'function (n) { var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) }; };';
+                Gettext._locale_data[domain].head.plural_func = eval("("+code+")");
+                */
+                var code = 'var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) };';
+                Gettext._locale_data[domain].head.plural_func = new Function("n", code);
+            } else {
+                throw new Error("Syntax error in language file. Plural-Forms header is invalid ["+plural_forms+"]");
+            }
+
+        // default to english plural form
+        } else if (typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
+            Gettext._locale_data[domain].head.plural_func = function (n) {
+                var p = (n != 1) ? 1 : 0;
+                return { 'nplural' : 2, 'plural' : p };
+                };
+        } // else, plural_func already created
+    }
+
+    return;
+};
+
+
+// try_load_lang_po : do an ajaxy call to load in the .po lang defs
+Gettext.prototype.try_load_lang_po = function(uri) {
+    var data = this.sjax(uri);
+    if (! data) return;
+
+    var domain = this.uri_basename(uri);
+    var parsed = this.parse_po(data);
+
+    var rv = {};
+    // munge domain into/outof header
+    if (parsed) {
+        if (! parsed[""]) parsed[""] = {};
+        if (! parsed[""]["domain"]) parsed[""]["domain"] = domain;
+        domain = parsed[""]["domain"];
+        rv[domain] = parsed;
+
+        this.parse_locale_data(rv);
+    }
+
+    return 1;
+};
+
+Gettext.prototype.uri_basename = function(uri) {
+    var rv;
+    if (rv = uri.match(/^(.*\/)?(.*)/)) {
+        var ext_strip;
+        if (ext_strip = rv[2].match(/^(.*)\..+$/))
+            return ext_strip[1];
+        else
+            return rv[2];
+    } else {
+        return "";
+    }
+};
+
+Gettext.prototype.parse_po = function(data) {
+    var rv = {};
+    var buffer = {};
+    var lastbuffer = "";
+    var errors = [];
+    var lines = data.split("\n");
+    for (var i=0; i<lines.length; i++) {
+        // chomp
+        lines[i] = lines[i].replace(/(\n|\r)+$/, '');
+
+        var match;
+
+        // Empty line / End of an entry.
+        if (/^$/.test(lines[i])) {
+            if (typeof(buffer['msgid']) != 'undefined') {
+                var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
+                                   buffer['msgctxt'].length) ?
+                                  buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
+                                  buffer['msgid'];
+                var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
+                                    buffer['msgid_plural'].length) ?
+                                   buffer['msgid_plural'] :
+                                   null;
+
+                // find msgstr_* translations and push them on
+                var trans = [];
+                for (var str in buffer) {
+                    var match;
+                    if (match = str.match(/^msgstr_(\d+)/))
+                        trans[parseInt(match[1])] = buffer[str];
+                }
+                trans.unshift(msgid_plural);
+
+                // only add it if we've got a translation
+                // NOTE: this doesn't conform to msgfmt specs
+                if (trans.length > 1) rv[msg_ctxt_id] = trans;
+
+                buffer = {};
+                lastbuffer = "";
+            }
+
+        // comments
+        } else if (/^#/.test(lines[i])) {
+            continue;
+
+        // msgctxt
+        } else if (match = lines[i].match(/^msgctxt\s+(.*)/)) {
+            lastbuffer = 'msgctxt';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgid
+        } else if (match = lines[i].match(/^msgid\s+(.*)/)) {
+            lastbuffer = 'msgid';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgid_plural
+        } else if (match = lines[i].match(/^msgid_plural\s+(.*)/)) {
+            lastbuffer = 'msgid_plural';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgstr
+        } else if (match = lines[i].match(/^msgstr\s+(.*)/)) {
+            lastbuffer = 'msgstr_0';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgstr[0] (treak like msgstr)
+        } else if (match = lines[i].match(/^msgstr\[0\]\s+(.*)/)) {
+            lastbuffer = 'msgstr_0';
+            buffer[lastbuffer] = this.parse_po_dequote(match[1]);
+
+        // msgstr[n]
+        } else if (match = lines[i].match(/^msgstr\[(\d+)\]\s+(.*)/)) {
+            lastbuffer = 'msgstr_'+match[1];
+            buffer[lastbuffer] = this.parse_po_dequote(match[2]);
+
+        // continued string
+        } else if (/^"/.test(lines[i])) {
+            buffer[lastbuffer] += this.parse_po_dequote(lines[i]);
+
+        // something strange
+        } else {
+            errors.push("Strange line ["+i+"] : "+lines[i]);
+        }
+    }
+
+
+    // handle the final entry
+    if (typeof(buffer['msgid']) != 'undefined') {
+        var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
+                           buffer['msgctxt'].length) ?
+                          buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
+                          buffer['msgid'];
+        var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
+                            buffer['msgid_plural'].length) ?
+                           buffer['msgid_plural'] :
+                           null;
+
+        // find msgstr_* translations and push them on
+        var trans = [];
+        for (var str in buffer) {
+            var match;
+            if (match = str.match(/^msgstr_(\d+)/))
+                trans[parseInt(match[1])] = buffer[str];
+        }
+        trans.unshift(msgid_plural);
+
+        // only add it if we've got a translation
+        // NOTE: this doesn't conform to msgfmt specs
+        if (trans.length > 1) rv[msg_ctxt_id] = trans;
+
+        buffer = {};
+        lastbuffer = "";
+    }
+
+
+    // parse out the header
+    if (rv[""] && rv[""][1]) {
+        var cur = {};
+        var hlines = rv[""][1].split(/\\n/);
+        for (var i=0; i<hlines.length; i++) {
+            if (! hlines.length) continue;
+
+            var pos = hlines[i].indexOf(':', 0);
+            if (pos != -1) {
+                var key = hlines[i].substring(0, pos);
+                var val = hlines[i].substring(pos +1);
+                var keylow = key.toLowerCase();
+
+                if (cur[keylow] && cur[keylow].length) {
+                    errors.push("SKIPPING DUPLICATE HEADER LINE: "+hlines[i]);
+                } else if (/#-#-#-#-#/.test(keylow)) {
+                    errors.push("SKIPPING ERROR MARKER IN HEADER: "+hlines[i]);
+                } else {
+                    // remove begining spaces if any
+                    val = val.replace(/^\s+/, '');
+                    cur[keylow] = val;
+                }
+
+            } else {
+                errors.push("PROBLEM LINE IN HEADER: "+hlines[i]);
+                cur[hlines[i]] = '';
+            }
+        }
+
+        // replace header string with assoc array
+        rv[""] = cur;
+    } else {
+        rv[""] = {};
+    }
+
+    // TODO: XXX: if there are errors parsing, what do we want to do?
+    // GNU Gettext silently ignores errors. So will we.
+    // alert( "Errors parsing po file:\n" + errors.join("\n") );
+
+    return rv;
+};
+
+
+Gettext.prototype.parse_po_dequote = function(str) {
+    var match;
+    if (match = str.match(/^"(.*)"/)) {
+        str = match[1];
+    }
+    // unescale all embedded quotes (fixes bug #17504)
+    str = str.replace(/\\"/g, "\"");
+    return str;
+};
+
+
+// try_load_lang_json : do an ajaxy call to load in the lang defs
+Gettext.prototype.try_load_lang_json = function(uri) {
+    var data = this.sjax(uri);
+    if (! data) return;
+
+    var rv = this.JSON(data);
+    this.parse_locale_data(rv);
+
+    return 1;
+};
+
+// this finds all <link> tags, filters out ones that match our
+// specs, and returns a list of hashes of those
+Gettext.prototype.get_lang_refs = function() {
+    var langs = new Array();
+    var links = document.getElementsByTagName("link");
+    // find all <link> tags in dom; filter ours
+    for (var i=0; i<links.length; i++) {
+        if (links[i].rel == 'gettext' && links[i].href) {
+            if (typeof(links[i].type) == 'undefined' ||
+                links[i].type == '') {
+                if (/\.json$/i.test(links[i].href)) {
+                    links[i].type = 'application/json';
+                } else if (/\.js$/i.test(links[i].href)) {
+                    links[i].type = 'application/json';
+                } else if (/\.po$/i.test(links[i].href)) {
+                    links[i].type = 'application/x-po';
+                } else if (/\.mo$/i.test(links[i].href)) {
+                    links[i].type = 'application/x-mo';
+                } else {
+                    throw new Error("LINK tag with rel=gettext found, but the type and extension are unrecognized.");
+                }
+            }
+
+            links[i].type = links[i].type.toLowerCase();
+            if (links[i].type == 'application/json') {
+                links[i].type = 'application/json';
+            } else if (links[i].type == 'text/javascript') {
+                links[i].type = 'application/json';
+            } else if (links[i].type == 'application/x-po') {
+                links[i].type = 'application/x-po';
+            } else if (links[i].type == 'application/x-mo') {
+                links[i].type = 'application/x-mo';
+            } else {
+                throw new Error("LINK tag with rel=gettext found, but the type attribute ["+links[i].type+"] is unrecognized.");
+            }
+
+            langs.push(links[i]);
+        }
+    }
+    return langs;
+};
+
+
+/*
+
+=head2 textdomain( domain )
+
+Set domain for future gettext() calls
+
+A  message  domain  is  a  set of translatable msgid messages. Usually,
+every software package has its own message domain. The domain  name  is
+used to determine the message catalog where a translation is looked up;
+it must be a non-empty string.
+
+The current message domain is used by the gettext, ngettext, pgettext,
+npgettext functions, and by the dgettext, dcgettext, dngettext, dcngettext,
+dpgettext, dcpgettext, dnpgettext and dcnpgettext functions when called
+with a NULL domainname argument.
+
+If domainname is not NULL, the current message domain is set to
+domainname.
+
+If domainname is undefined, null, or empty string, the function returns
+the current message domain.
+
+If  successful,  the  textdomain  function  returns the current message
+domain, after possibly changing it. (ie. if you set a new domain, the
+value returned will NOT be the previous domain).
+
+=cut
+
+*/
+Gettext.prototype.textdomain = function (domain) {
+    if (domain && domain.length) this.domain = domain;
+    return this.domain;
+}
+
+/*
+
+=head2 gettext( MSGID )
+
+Returns the translation for B<MSGID>.  Example:
+
+    alert( gt.gettext("Hello World!\n") );
+
+If no translation can be found, the unmodified B<MSGID> is returned,
+i. e. the function can I<never> fail, and will I<never> mess up your
+original message.
+
+One common mistake is to interpolate a variable into the string like this:
+
+  var translated = gt.gettext("Hello " + full_name);
+
+The interpolation will happen before it's passed to gettext, and it's
+unlikely you'll have a translation for every "Hello Tom" and "Hello Dick"
+and "Hellow Harry" that may arise.
+
+Use C<strargs()> (see below) to solve this problem:
+
+  var translated = Gettext.strargs( gt.gettext("Hello %1"), [full_name] );
+
+This is espeically useful when multiple replacements are needed, as they
+may not appear in the same order within the translation. As an English to
+French example:
+
+  Expected result: "This is the red ball"
+  English: "This is the %1 %2"
+  French:  "C'est le %2 %1"
+  Code: Gettext.strargs( gt.gettext("This is the %1 %2"), ["red", "ball"] );
+
+(The example is stupid because neither color nor thing will get
+translated here ...).
+
+=head2 dgettext( TEXTDOMAIN, MSGID )
+
+Like gettext(), but retrieves the message for the specified
+B<TEXTDOMAIN> instead of the default domain.  In case you wonder what
+a textdomain is, see above section on the textdomain() call.
+
+=head2 dcgettext( TEXTDOMAIN, MSGID, CATEGORY )
+
+Like dgettext() but retrieves the message from the specified B<CATEGORY>
+instead of the default category C<LC_MESSAGES>.
+
+NOTE: the categories are really useless in javascript context. This is
+here for GNU Gettext API compatability. In practice, you'll never need
+to use this. This applies to all the calls including the B<CATEGORY>.
+
+
+=head2 ngettext( MSGID, MSGID_PLURAL, COUNT )
+
+Retrieves the correct translation for B<COUNT> items.  In legacy software
+you will often find something like:
+
+    alert( count + " file(s) deleted.\n" );
+
+or
+
+    printf(count + " file%s deleted.\n", $count == 1 ? '' : 's');
+
+I<NOTE: javascript lacks a builtin printf, so the above isn't a working example>
+
+The first example looks awkward, the second will only work in English
+and languages with similar plural rules.  Before ngettext() was introduced,
+the best practice for internationalized programs was:
+
+    if (count == 1) {
+        alert( gettext("One file deleted.\n") );
+    } else {
+        printf( gettext("%d files deleted.\n"), count );
+    }
+
+This is a nuisance for the programmer and often still not sufficient
+for an adequate translation.  Many languages have completely different
+ideas on numerals.  Some (French, Italian, ...) treat 0 and 1 alike,
+others make no distinction at all (Japanese, Korean, Chinese, ...),
+others have two or more plural forms (Russian, Latvian, Czech,
+Polish, ...).  The solution is:
+
+    printf( ngettext("One file deleted.\n",
+                     "%d files deleted.\n",
+                     count), // argument to ngettext!
+            count);          // argument to printf!
+
+In English, or if no translation can be found, the first argument
+(B<MSGID>) is picked if C<count> is one, the second one otherwise.
+For other languages, the correct plural form (of 1, 2, 3, 4, ...)
+is automatically picked, too.  You don't have to know anything about
+the plural rules in the target language, ngettext() will take care
+of that.
+
+This is most of the time sufficient but you will have to prove your
+creativity in cases like
+
+    "%d file(s) deleted, and %d file(s) created.\n"
+
+That said, javascript lacks C<printf()> support. Supplied with Gettext.js
+is the C<strargs()> method, which can be used for these cases:
+
+    Gettext.strargs( gt.ngettext( "One file deleted.\n",
+                                  "%d files deleted.\n",
+                                  count), // argument to ngettext!
+                     count); // argument to strargs!
+
+NOTE: the variable replacement isn't done for you, so you must
+do it yourself as in the above.
+
+=head2 dngettext( TEXTDOMAIN, MSGID, MSGID_PLURAL, COUNT )
+
+Like ngettext() but retrieves the translation from the specified
+textdomain instead of the default domain.
+
+=head2 dcngettext( TEXTDOMAIN, MSGID, MSGID_PLURAL, COUNT, CATEGORY )
+
+Like dngettext() but retrieves the translation from the specified
+category, instead of the default category C<LC_MESSAGES>.
+
+
+=head2 pgettext( MSGCTXT, MSGID )
+
+Returns the translation of MSGID, given the context of MSGCTXT.
+
+Both items are used as a unique key into the message catalog.
+
+This allows the translator to have two entries for words that may
+translate to different foreign words based on their context. For
+example, the word "View" may be a noun or a verb, which may be
+used in a menu as File->View or View->Source.
+
+    alert( pgettext( "Verb: To View", "View" ) );
+    alert( pgettext( "Noun: A View", "View"  ) );
+
+The above will both lookup different entries in the message catalog.
+
+In English, or if no translation can be found, the second argument
+(B<MSGID>) is returned.
+
+=head2 dpgettext( TEXTDOMAIN, MSGCTXT, MSGID )
+
+Like pgettext(), but retrieves the message for the specified
+B<TEXTDOMAIN> instead of the default domain.
+
+=head2 dcpgettext( TEXTDOMAIN, MSGCTXT, MSGID, CATEGORY )
+
+Like dpgettext() but retrieves the message from the specified B<CATEGORY>
+instead of the default category C<LC_MESSAGES>.
+
+
+=head2 npgettext( MSGCTXT, MSGID, MSGID_PLURAL, COUNT )
+
+Like ngettext() with the addition of context as in pgettext().
+
+In English, or if no translation can be found, the second argument
+(MSGID) is picked if B<COUNT> is one, the third one otherwise.
+
+=head2 dnpgettext( TEXTDOMAIN, MSGCTXT, MSGID, MSGID_PLURAL, COUNT )
+
+Like npgettext() but retrieves the translation from the specified
+textdomain instead of the default domain.
+
+=head2 dcnpgettext( TEXTDOMAIN, MSGCTXT, MSGID, MSGID_PLURAL, COUNT, CATEGORY )
+
+Like dnpgettext() but retrieves the translation from the specified
+category, instead of the default category C<LC_MESSAGES>.
+
+=cut
+
+*/
+
+// gettext
+Gettext.prototype.gettext = function (msgid) {
+    var msgctxt;
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dgettext = function (domain, msgid) {
+    var msgctxt;
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dcgettext = function (domain, msgid, category) {
+    var msgctxt;
+    var msgid_plural;
+    var n;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+// ngettext
+Gettext.prototype.ngettext = function (msgid, msgid_plural, n) {
+    var msgctxt;
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dngettext = function (domain, msgid, msgid_plural, n) {
+    var msgctxt;
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dcngettext = function (domain, msgid, msgid_plural, n, category) {
+    var msgctxt;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category, category);
+};
+
+// pgettext
+Gettext.prototype.pgettext = function (msgctxt, msgid) {
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dpgettext = function (domain, msgctxt, msgid) {
+    var msgid_plural;
+    var n;
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dcpgettext = function (domain, msgctxt, msgid, category) {
+    var msgid_plural;
+    var n;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+// npgettext
+Gettext.prototype.npgettext = function (msgctxt, msgid, msgid_plural, n) {
+    var category;
+    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
+};
+
+Gettext.prototype.dnpgettext = function (domain, msgctxt, msgid, msgid_plural, n) {
+    var category;
+    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
+};
+
+// this has all the options, so we use it for all of them.
+Gettext.prototype.dcnpgettext = function (domain, msgctxt, msgid, msgid_plural, n, category) {
+    if (! this.isValidObject(msgid)) return '';
+
+    var plural = this.isValidObject(msgid_plural);
+    var msg_ctxt_id = this.isValidObject(msgctxt) ? msgctxt+Gettext.context_glue+msgid : msgid;
+
+    var domainname = this.isValidObject(domain)      ? domain :
+                     this.isValidObject(this.domain) ? this.domain :
+                                                       'messages';
+
+    // category is always LC_MESSAGES. We ignore all else
+    var category_name = 'LC_MESSAGES';
+    var category = 5;
+
+    var locale_data = new Array();
+    if (typeof(Gettext._locale_data) != 'undefined' &&
+        this.isValidObject(Gettext._locale_data[domainname])) {
+        locale_data.push( Gettext._locale_data[domainname] );
+
+    } else if (typeof(Gettext._locale_data) != 'undefined') {
+        // didn't find domain we're looking for. Search all of them.
+        for (var dom in Gettext._locale_data) {
+            locale_data.push( Gettext._locale_data[dom] );
+        }
+    }
+
+    var trans = [];
+    var found = false;
+    var domain_used; // so we can find plural-forms if needed
+    if (locale_data.length) {
+        for (var i=0; i<locale_data.length; i++) {
+            var locale = locale_data[i];
+            if (this.isValidObject(locale.msgs[msg_ctxt_id])) {
+                // make copy of that array (cause we'll be destructive)
+                for (var j=0; j<locale.msgs[msg_ctxt_id].length; j++) {
+                    trans[j] = locale.msgs[msg_ctxt_id][j];
+                }
+                trans.shift(); // throw away the msgid_plural
+                domain_used = locale;
+                found = true;
+                // only break if found translation actually has a translation.
+                if ( trans.length > 0 && trans[0].length != 0 )
+                    break;
+            }
+        }
+    }
+
+    // default to english if we lack a match, or match has zero length
+    if ( trans.length == 0 || trans[0].length == 0 ) {
+        trans = [ msgid, msgid_plural ];
+    }
+
+    var translation = trans[0];
+    if (plural) {
+        var p;
+        if (found && this.isValidObject(domain_used.head.plural_func) ) {
+            var rv = domain_used.head.plural_func(n);
+            if (! rv.plural) rv.plural = 0;
+            if (! rv.nplural) rv.nplural = 0;
+            // if plurals returned is out of bound for total plural forms
+            if (rv.nplural <= rv.plural) rv.plural = 0;
+            p = rv.plural;
+        } else {
+            p = (n != 1) ? 1 : 0;
+        }
+        if (this.isValidObject(trans[p]))
+            translation = trans[p];
+    }
+
+    return translation;
+};
+
+
+/*
+
+=head2 strargs (string, argument_array)
+
+  string : a string that potentially contains formatting characters.
+  argument_array : an array of positional replacement values
+
+This is a utility method to provide some way to support positional parameters within a string, as javascript lacks a printf() method.
+
+The format is similar to printf(), but greatly simplified (ie. fewer features).
+
+Any percent signs followed by numbers are replaced with the corrosponding item from the B<argument_array>.
+
+Example:
+
+    var string = "%2 roses are red, %1 violets are blue";
+    var args   = new Array("10", "15");
+    var result = Gettext.strargs(string, args);
+    // result is "15 roses are red, 10 violets are blue"
+
+The format numbers are 1 based, so the first itme is %1.
+
+A lone percent sign may be escaped by preceeding it with another percent sign.
+
+A percent sign followed by anything other than a number or another percent sign will be passed through as is.
+
+Some more examples should clear up any abmiguity. The following were called with the orig string, and the array as Array("[one]", "[two]") :
+
+  orig string "blah" becomes "blah"
+  orig string "" becomes ""
+  orig string "%%" becomes "%"
+  orig string "%%%" becomes "%%"
+  orig string "%%%%" becomes "%%"
+  orig string "%%%%%" becomes "%%%"
+  orig string "tom%%dick" becomes "tom%dick"
+  orig string "thing%1bob" becomes "thing[one]bob"
+  orig string "thing%1%2bob" becomes "thing[one][two]bob"
+  orig string "thing%1asdf%2asdf" becomes "thing[one]asdf[two]asdf"
+  orig string "%1%2%3" becomes "[one][two]"
+  orig string "tom%1%%2%aDick" becomes "tom[one]%2%aDick"
+
+This is especially useful when using plurals, as the string will nearly always contain the number.
+
+It's also useful in translated strings where the translator may have needed to move the position of the parameters.
+
+For example:
+
+  var count = 14;
+  Gettext.strargs( gt.ngettext('one banana', '%1 bananas', count), [count] );
+
+NOTE: this may be called as an instance method, or as a class method.
+
+  // instance method:
+  var gt = new Gettext(params);
+  gt.strargs(string, args);
+
+  // class method:
+  Gettext.strargs(string, args);
+
+=cut
+
+*/
+/* utility method, since javascript lacks a printf */
+Gettext.strargs = function (str, args) {
+    // make sure args is an array
+    if ( null == args ||
+         'undefined' == typeof(args) ) {
+        args = [];
+    } else if (args.constructor != Array) {
+        args = [args];
+    }
+
+    // NOTE: javascript lacks support for zero length negative look-behind
+    // in regex, so we must step through w/ index.
+    // The perl equiv would simply be:
+    //    $string =~ s/(?<!\%)\%([0-9]+)/$args[$1]/g;
+    //    $string =~ s/\%\%/\%/g; # restore escaped percent signs
+
+    var newstr = "";
+    while (true) {
+        var i = str.indexOf('%');
+        var match_n;
+
+        // no more found. Append whatever remains
+        if (i == -1) {
+            newstr += str;
+            break;
+        }
+
+        // we found it, append everything up to that
+        newstr += str.substr(0, i);
+
+        // check for escpaed %%
+        if (str.substr(i, 2) == '%%') {
+            newstr += '%';
+            str = str.substr((i+2));
+
+        // % followed by number
+        } else if ( match_n = str.substr(i).match(/^%(\d+)/) ) {
+            var arg_n = parseInt(match_n[1]);
+            var length_n = match_n[1].length;
+            if ( arg_n > 0 && args[arg_n -1] != null && typeof(args[arg_n -1]) != 'undefined' )
+                newstr += args[arg_n -1];
+            str = str.substr( (i + 1 + length_n) );
+
+        // % followed by some other garbage - just remove the %
+        } else {
+            newstr += '%';
+            str = str.substr((i+1));
+        }
+    }
+
+    return newstr;
+}
+
+/* instance method wrapper of strargs */
+Gettext.prototype.strargs = function (str, args) {
+    return Gettext.strargs(str, args);
+}
+
+/* verify that something is an array */
+Gettext.prototype.isArray = function (thisObject) {
+    return this.isValidObject(thisObject) && thisObject.constructor == Array;
+};
+
+/* verify that an object exists and is valid */
+Gettext.prototype.isValidObject = function (thisObject) {
+    if (null == thisObject) {
+        return false;
+    } else if ('undefined' == typeof(thisObject) ) {
+        return false;
+    } else {
+        return true;
+    }
+};
+
+Gettext.prototype.sjax = function (uri) {
+    var xmlhttp;
+    if (window.XMLHttpRequest) {
+        xmlhttp = new XMLHttpRequest();
+    } else if (navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) {
+        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
+    } else {
+        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
+    }
+
+    if (! xmlhttp)
+        throw new Error("Your browser doesn't do Ajax. Unable to support external language files.");
+
+    xmlhttp.open('GET', uri, false);
+    try { xmlhttp.send(null); }
+    catch (e) { return; }
+
+    // we consider status 200 and 0 as ok.
+    // 0 happens when we request local file, allowing this to run on local files
+    var sjax_status = xmlhttp.status;
+    if (sjax_status == 200 || sjax_status == 0) {
+        return xmlhttp.responseText;
+    } else {
+        var error = xmlhttp.statusText + " (Error " + xmlhttp.status + ")";
+        if (xmlhttp.responseText.length) {
+            error += "\n" + xmlhttp.responseText;
+        }
+        alert(error);
+        return;
+    }
+}
+
+Gettext.prototype.JSON = function (data) {
+    return eval('(' + data + ')');
+}
+
+
+/*
+
+=head1 NOTES
+
+These are some notes on the internals
+
+=over
+
+=item LOCALE CACHING
+
+Loaded locale data is currently cached class-wide. This means that if two scripts are both using Gettext.js, and both share the same gettext domain, that domain will only be loaded once. This will allow you to grab a new object many times from different places, utilize the same domain, and share a single translation file. The downside is that a domain won't be RE-loaded if a new object is instantiated on a domain that had already been instantiated.
+
+=back
+
+=head1 BUGS / TODO
+
+=over
+
+=item error handling
+
+Currently, there are several places that throw errors. In GNU Gettext, there are no fatal errors, which allows text to still be displayed regardless of how broken the environment becomes. We should evaluate and determine where we want to stand on that issue.
+
+=item syncronous only support (no ajax support)
+
+Currently, fetching language data is done purely syncronous, which means the page will halt while those files are fetched/loaded.
+
+This is often what you want, as then following translation requests will actually be translated. However, if all your calls are done dynamically (ie. error handling only or something), loading in the background may be more adventagous.
+
+It's still recommended to use the statically defined <script ...> method, which should have the same delay, but it will cache the result.
+
+=item domain support
+
+domain support while using shortcut methods like C<_('string')> or C<i18n('string')>.
+
+Under normal apps, the domain is usually set globally to the app, and a single language file is used. Under javascript, you may have multiple libraries or applications needing translation support, but the namespace is essentially global.
+
+It's recommended that your app initialize it's own shortcut with it's own domain.  (See examples/wrapper/i18n.js for an example.)
+
+Basically, you'll want to accomplish something like this:
+
+    // in some other .js file that needs i18n
+    this.i18nObj = new i18n;
+    this.i18n = this.i18nObj.init('domain');
+    // do translation
+    alert( this.i18n("string") );
+
+If you use this raw Gettext object, then this is all handled for you, as you have your own object then, and will be calling C<myGettextObject.gettext('string')> and such.
+
+
+=item encoding
+
+May want to add encoding/reencoding stuff. See GNU iconv, or the perl module Locale::Recode from libintl-perl.
+
+=back
+
+
+=head1 COMPATABILITY
+
+This has been tested on the following browsers. It may work on others, but these are all those to which I have access.
+
+    FF1.5, FF2, FF3, IE6, IE7, Opera9, Opera10, Safari3.1, Chrome
+
+    *FF = Firefox
+    *IE = Internet Explorer
+
+
+=head1 REQUIRES
+
+bin/po2json requires perl, and the perl modules Locale::PO and JSON.
+
+=head1 SEE ALSO
+
+bin/po2json (included),
+examples/normal/index.html,
+examples/wrapper/i18n.html, examples/wrapper/i18n.js,
+Locale::gettext_pp(3pm), POSIX(3pm), gettext(1), gettext(3)
+
+=head1 AUTHOR
+
+Copyright (C) 2008, Joshua I. Miller E<lt>unrtst@cpan.orgE<gt>, all rights reserved. See the source code for details.
+
+=cut
+
+*/
diff --git a/koha-tmpl/opac-tmpl/bootstrap/js/i18n.js b/koha-tmpl/opac-tmpl/bootstrap/js/i18n.js
new file mode 100644 (file)
index 0000000..4c2df9a
--- /dev/null
@@ -0,0 +1,51 @@
+(function() {
+  var params = {
+    "domain": "Koha"
+  };
+  if (typeof json_locale_data !== 'undefined') {
+    params.locale_data = json_locale_data;
+  }
+
+  Koha.i18n = {
+    gt: new Gettext(params),
+
+    expand: function(text, vars) {
+      var replace_callback = function(match, name) {
+        return name in vars ? vars[name] : match;
+      };
+      return text.replace(/\{(.*?)\}/g, replace_callback);
+    }
+  };
+})();
+
+function __(msgid) {
+  return Koha.i18n.gt.gettext(msgid);
+}
+
+function __x(msgid, vars) {
+  return Koha.i18n.expand(__(msgid), vars);
+}
+
+function __n(msgid, msgid_plural, count) {
+  return Koha.i18n.gt.ngettext(msgid, msgid_plural, count);
+}
+
+function __nx(msgid, msgid_plural, count, vars) {
+  return Koha.i18n.expand(__n(msgid, msgid_plural, count), vars);
+}
+
+function __p(msgctxt, msgid) {
+  return Koha.i18n.gt.pgettext(msgctxt, msgid);
+}
+
+function __px(msgctxt, msgid, vars) {
+  return Koha.i18n.expand(__p(msgctxt, msgid), vars);
+}
+
+function __np(msgctxt, msgid, msgid_plural, count) {
+  return Koha.i18n.gt.npgettext(msgctxt, msgid, msgid_plural, count);
+}
+
+function __npx(msgctxt, msgid, msgid_plural, count, vars) {
+  return Koha.i18n.expand(__np(msgctxt, msgid, msgid_plural, count), vars);
+}
index 3da23a8..2b1e26c 100644 (file)
@@ -81,6 +81,7 @@ sub new {
     $self->{msginit}         = `which msginit`;
     $self->{xgettext}        = `which xgettext`;
     $self->{sed}             = `which sed`;
+    $self->{po2json}         = "$Bin/po2json";
     chomp $self->{cp};
     chomp $self->{msgmerge};
     chomp $self->{msgfmt};
@@ -486,8 +487,10 @@ sub create_messages {
 
     my $pot = "$Bin/$self->{domain}.pot";
     my $po = "$self->{path_po}/$self->{lang}-messages.po";
+    my $js_pot = "$self->{domain}-js.pot";
+    my $js_po = "$self->{path_po}/$self->{lang}-messages-js.po";
 
-    unless ( -f $pot ) {
+    unless ( -f $pot && -f $js_pot ) {
         $self->extract_messages();
     }
 
@@ -495,10 +498,13 @@ sub create_messages {
     my $locale = $self->locale_name();
     system "$self->{msginit} -i $pot -o $po -l $locale --no-translator 2> /dev/null";
     warn "Problems creating $pot ".$? if ( $? == -1 );
+    system "$self->{msginit} -i $js_pot -o $js_po -l $locale --no-translator 2> /dev/null";
+    warn "Problems creating $js_pot ".$? if ( $? == -1 );
 
     # If msginit failed to correctly set Plural-Forms, set a default one
-    system "$self->{sed} --in-place $po "
-        . "--expression='s/Plural-Forms: nplurals=INTEGER; plural=EXPRESSION/Plural-Forms: nplurals=2; plural=(n != 1)/'";
+    system "$self->{sed} --in-place "
+        . "--expression='s/Plural-Forms: nplurals=INTEGER; plural=EXPRESSION/Plural-Forms: nplurals=2; plural=(n != 1)/' "
+        . "$po $js_po";
 }
 
 sub update_messages {
@@ -506,14 +512,17 @@ sub update_messages {
 
     my $pot = "$Bin/$self->{domain}.pot";
     my $po = "$self->{path_po}/$self->{lang}-messages.po";
+    my $js_pot = "$self->{domain}-js.pot";
+    my $js_po = "$self->{path_po}/$self->{lang}-messages-js.po";
 
-    unless ( -f $pot ) {
+    unless ( -f $pot && -f $js_pot ) {
         $self->extract_messages();
     }
 
-    if ( -f $po ) {
+    if ( -f $po && -f $js_pot ) {
         say "Update messages ($self->{lang})" if $self->{verbose};
         system "$self->{msgmerge} --backup=off --quiet -U $po $pot";
+        system "$self->{msgmerge} --backup=off --quiet -U $js_po $js_pot";
     } else {
         $self->create_messages();
     }
@@ -674,11 +683,12 @@ sub extract_messages {
 
     push @files_to_scan, @tt_files;
 
-    my $xgettext_cmd = "$self->{xgettext} --force-po -L Perl --from-code=UTF-8 "
+    my $xgettext_common_args = "--force-po --from-code=UTF-8 "
         . "--package-name=Koha --package-version='' "
         . "-k -k__ -k__x -k__n:1,2 -k__nx:1,2 -k__xn:1,2 -k__p:1c,2 "
         . "-k__px:1c,2 -k__np:1c,2,3 -k__npx:1c,2,3 -kN__ -kN__n:1,2 "
-        . "-kN__p:1c,2 -kN__np:1c,2,3 "
+        . "-kN__p:1c,2 -kN__np:1c,2,3 ";
+    my $xgettext_cmd = "$self->{xgettext} -L Perl $xgettext_common_args "
         . "-o $Bin/$self->{domain}.pot -D $tempdir -D $basedir";
     $xgettext_cmd .= " $_" foreach (@files_to_scan);
 
@@ -686,9 +696,31 @@ sub extract_messages {
         die "system call failed: $xgettext_cmd";
     }
 
+    my @js_dirs = (
+        "$intranetdir/koha-tmpl/intranet-tmpl/prog/js",
+        "$intranetdir/koha-tmpl/opac-tmpl/bootstrap/js",
+    );
+
+    my @js_files;
+    find(sub {
+        if ($_ =~ m/\.js$/) {
+            my $filename = $File::Find::name;
+            $filename =~ s|^$intranetdir/||;
+            push @js_files, $filename;
+        }
+    }, @js_dirs);
+
+    $xgettext_cmd = "$self->{xgettext} -L JavaScript $xgettext_common_args "
+        . "-o $Bin/$self->{domain}-js.pot -D $intranetdir";
+    $xgettext_cmd .= " $_" foreach (@js_files);
+
+    if (system($xgettext_cmd) != 0) {
+        die "system call failed: $xgettext_cmd";
+    }
+
     my $replace_charset_cmd = "$self->{sed} --in-place " .
-        "$Bin/$self->{domain}.pot " .
-        "--expression='s/charset=CHARSET/charset=UTF-8/'";
+        "--expression='s/charset=CHARSET/charset=UTF-8/' " .
+        "$Bin/$self->{domain}.pot $Bin/$self->{domain}-js.pot";
     if (system($replace_charset_cmd) != 0) {
         die "system call failed: $replace_charset_cmd";
     }
@@ -701,19 +733,37 @@ sub install_messages {
     my $modir = "$self->{path_po}/$locale/LC_MESSAGES";
     my $pofile = "$self->{path_po}/$self->{lang}-messages.po";
     my $mofile = "$modir/$self->{domain}.mo";
+    my $js_pofile = "$self->{path_po}/$self->{lang}-messages-js.po";
 
-    if ( not -f $pofile ) {
+    unless ( -f $pofile && -f $js_pofile ) {
         $self->create_messages();
     }
     say "Install messages ($locale)" if $self->{verbose};
     make_path($modir);
     system "$self->{msgfmt} -o $mofile $pofile";
+
+    my $js_locale_data = 'var json_locale_data = {"Koha":' . `$self->{po2json} $js_pofile` . '};';
+    my $progdir = $self->{context}->config('intrahtdocs') . '/prog';
+    mkdir "$progdir/$self->{lang}/js";
+    open my $fh, '>', "$progdir/$self->{lang}/js/locale_data.js";
+    print $fh $js_locale_data;
+    close $fh;
+
+    my $opachtdocs = $self->{context}->config('opachtdocs');
+    opendir(my $dh, $opachtdocs);
+    for my $theme ( grep { not /^\.|lib|xslt/ } readdir($dh) ) {
+        mkdir "$opachtdocs/$theme/$self->{lang}/js";
+        open my $fh, '>', "$opachtdocs/$theme/$self->{lang}/js/locale_data.js";
+        print $fh $js_locale_data;
+        close $fh;
+    }
 }
 
 sub remove_pot {
     my $self = shift;
 
     unlink "$Bin/$self->{domain}.pot";
+    unlink "$Bin/$self->{domain}-js.pot";
 }
 
 sub install {
diff --git a/misc/translator/po2json b/misc/translator/po2json
new file mode 100755 (executable)
index 0000000..2f534be
--- /dev/null
@@ -0,0 +1,249 @@
+#!/usr/bin/env perl
+# PODNAME: po2json
+# ABSTRACT: Command line tool for converting a po file into a Gettext.js compatible json dataset
+
+# Copyright (C) 2008, Joshua I. Miller E<lt>unrtst@cpan.orgE<gt>, all
+# rights reserved.
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Library General Public License as published
+# by the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Library General Public License for more details.
+#
+# You should have received a copy of the GNU Library General Public
+# License along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+# USA.
+
+
+use strict;
+use JSON 2.53;
+use Locale::PO 0.24;
+use File::Basename qw(basename);
+
+my $gettext_context_glue = "\004";
+
+sub usage {
+    return "$0 {-p} {file.po} > {outputfile.json}
+    -p  : do pretty-printing of json data\n";
+}
+
+&main;
+
+sub main
+{
+    my ($src_fh, $src);
+
+    my $pretty = 0;
+    if ($ARGV[0] =~ /^--?p$/) {
+        shift @ARGV;
+        $pretty = 1;
+    }
+
+    if (length($ARGV[0]))
+    {
+        if ($ARGV[0] =~ /^-h/) {
+            print &usage;
+            exit 1;
+        }
+
+        unless (-r $ARGV[0]) {
+            print "ERROR: Unable to read file [$ARGV[0]]\n";
+            die &usage;
+        }
+
+        $src = $ARGV[0];
+    } else {
+        die &usage;
+    }
+
+    # we'll be building this data struct
+    my $json = {};
+
+    my $plural_form_count;
+    # get po object stack
+    my $pos = Locale::PO->load_file_asarray($src) or die "Can't parse po file [$src].";
+
+
+    foreach my $po (@$pos)
+    {
+        my $qmsgid1 = $po->msgid;
+        my $msgid1 = $po->dequote( $qmsgid1 );
+
+        # on the header
+        if (length($msgid1) == 0)
+        {
+            my $qmsgstr = $po->msgstr;
+            my $cur = $po->dequote( $qmsgstr );
+            my %cur;
+            foreach my $h (split(/\n/, $cur))
+            {
+                next unless length($h);
+                my @h = split(':', $h, 2);
+
+                if (length($cur{$h[0]})) {
+                    warn "SKIPPING DUPLICATE HEADER LINE: $h\n";
+                } elsif ($h[0] =~ /#-#-#-#-#/) {
+                    warn "SKIPPING ERROR MARKER IN HEADER: $h\n";
+                } elsif (@h == 2) {
+                    $cur{$h[0]} = $h[1];
+                } else {
+                    warn "PROBLEM LINE IN HEADER: $h\n";
+                    $cur{$h} = '';
+                }
+            }
+
+            # init header ref
+            $$json{''} ||= {};
+
+            # populate header ref
+            foreach my $key (keys %cur) {
+                $$json{''}{$key} = length($cur{$key}) ? $cur{$key} : '';
+            }
+
+            # save plural form count
+            if ($$json{''}{'Plural-Forms'}) {
+                my $t = $$json{''}{'Plural-Forms'};
+                $t =~ s/^\s*//;
+                if ($t =~ /nplurals=(\d+)/) {
+                    $plural_form_count = $1;
+                } else {
+                    die "ERROR parsing plural forms header [$t]\n";
+                }
+            } else {
+                warn "NO PLURAL FORM HEADER FOUND - DEFAULTING TO 2\n";
+                # just default to 2
+                $plural_form_count = 2;
+            }
+
+        # on a normal msgid
+        } else {
+            my $qmsgctxt = $po->msgctxt;
+            my $msgctxt = $po->dequote($qmsgctxt) if $qmsgctxt;
+
+            # build the new msgid key
+            my $msg_ctxt_id = defined($msgctxt) ? join($gettext_context_glue, ($msgctxt, $msgid1)) : $msgid1;
+
+            # build translation side
+            my @trans;
+
+            # msgid plural side
+            my $qmsgid_plural = $po->msgid_plural;
+            my $msgid2 = $po->dequote( $qmsgid_plural ) if $qmsgid_plural;
+            push(@trans, $msgid2);
+
+            # translated string
+            # this shows up different if we're plural
+            if (defined($msgid2) && length($msgid2))
+            {
+                my $plurals = $po->msgstr_n;
+                for (my $i=0; $i<$plural_form_count; $i++)
+                {
+                    my $qstr = ref($plurals) ? $$plurals{$i} : undef;
+                    my $str  = $po->dequote( $qstr ) if $qstr;
+                    push(@trans, $str);
+                }
+
+            # singular
+            } else {
+                my $qmsgstr = $po->msgstr;
+                my $msgstr = $po->dequote( $qmsgstr ) if $qmsgstr;
+                push(@trans, $msgstr);
+            }
+
+            $$json{$msg_ctxt_id} = \@trans;
+        }
+    }
+
+
+    my $jsonobj = new JSON;
+    my $basename = basename($src);
+    $basename =~ s/\.pot?$//;
+    if ($pretty)
+    {
+        print $jsonobj->pretty->encode( { $basename => $json });
+    } else {
+        print $jsonobj->encode($json);
+    }
+}
+
+__END__
+
+=pod
+
+=head1 NAME
+
+po2json - Command line tool for converting a po file into a Gettext.js compatible json dataset
+
+=head1 VERSION
+
+version 0.019
+
+=head1 SYNOPSIS
+
+ po2json /path/to/domain.po > domain.json
+
+=head1 DESCRIPTION
+
+This takes a PO file, as is created from GNU Gettext's xgettext, and converts it into a JSON file.
+
+The output is an annonymous associative array. So, if you plan to load this via a <script> tag, more processing will be require (the output from this program must be assigned to a named javascript variable). For example:
+
+    echo -n "var json_locale_data = " > domain.json
+    po2json /path/to/domain.po >> domain.json
+    echo ";" >> domain.json
+
+=head1 NAME
+
+po2json - Convert a Uniforum format portable object file to javascript object notation.
+
+=head1 OPTIONS
+
+ -p : pretty-print the output. Makes the output more human-readable.
+
+=head1 BUGS
+
+Locale::PO has a potential bug (I don't know if this actually causes a problem or not). Given a .po file with an entry like:
+
+    msgid ""
+    "some string"
+    msgstr ""
+
+When $po->dump is run on that entry, it will output:
+
+    msgid "some string"
+    msgstr ""
+
+The above is removing the first linebreak. I don't know if that is significant. If so, we'll have to rewrite using a different parser (or include our own parser).
+
+=head1 REQUIRES
+
+ Locale::PO
+ JSON
+
+=head1 SEE ALSO
+
+ Locale::PO
+ Gettext.js
+
+=head1 AUTHOR
+
+Copyright (C) 2008, Joshua I. Miller E<lt>unrtst@cpan.orgE<gt>, all rights reserved. See the source code for details.
+
+=head1 AUTHOR
+
+Torsten Raudssus <torsten@raudss.us>
+
+=head1 COPYRIGHT AND LICENSE
+
+This software is copyright (c) 2012 by DuckDuckGo, Inc. L<http://duckduckgo.com/>, Torsten Raudssus <torsten@raudss.us>.
+
+This is free software; you can redistribute it and/or modify it under
+the same terms as the Perl 5 programming language system itself.
+
+=cut