// -------------------------------------------------------------------
/*

Copyright (c) 2008, Rainer Blome

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

- Neither the name(s) of the copyright holder(s), nor the names of any
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

// -------------------------------------------------------------------
/**

TODO

o Make it work in IE without Script errors.

o Internationalize the page titles.

o Use something else that's better than document.write()?
  At least wrap it in a call like i18n.write("msg %1\$s blah").

o Prefer to generate HTML.  Then gettext() should be sufficient.

o My attempted (but under IE failing) abuse of the anchor tag (< a
  id="Transparency" >) should be replaced by uses of "span", whose
  innnerHTML can be replaced in both IE and Mozilla.

o Determine preferred content language as set in the user's
  preferences or browser's options, or use the language set by
  util.js/langselect.js.

o Is it OK to use JSON format for the translation tables or are
  there strong reasons to use PO files?

o Make it work with different character sets.
  Currently, I used HTML/entities to get non-ASCII characters,
  but this does not work with texts displayed in list boxes (why not?).

  Would utf-8 be the right way to go?
  Is it a good idea to look at the source of http://www.wikipedia.org/
  and try to learn from it?

o Specify the encoding of the .js files.
  Is this possible at all?
  Is this necessary?
  Maybe not, since it already works UTF-8-encoded i18n.js.
  Do .js files inherit their encoding from the parent document?
  Or is the browser's encoding setting used?

o Encode the .js files using UTF-8.

o Move the translation tables to separate files.

o Load only the needed translation table(s).

o For the language selection box:  Write each
  language name (the first name in each item) the way it is written in
  the language itself, in the native script of
  the language.  For example:

  Catalan
  English
  Français

  (ordered by the language-tag)

  Code or data for such a list should already exist on the web, somewhere.

o Optional: To each language selection item, add the name as
  translated to the current language. For example, when the current
  language is English, format the French item like this: "Français
  (French)".

o Mark all keys that are reused (used in more than one place).

o Internationalize further html pages and code.

o Decide whether the language selection dialog should switch the
  UI language in synchrony with the desired results language.

o Support positional message parameters.

o Create tar file that runs locally out of the box.

o Support right to left writing (direction: rtl) .

o Support top to bottom writing direction (block-progression: rl).

o Scale, localize for more languages.

DONE

o Make results page work locally.

o Internationalized: index.html, header.js, search.html, main.js,
  ui.js, hist.js, expand_ma.js.

o Determine browser's language setting. Unfortunately under my Firefox,
  the value of navigator.language is always "en-US", no matter which
  languages I have configured under Tools-> Options-> Advanced->
  General-> Languages-> Choose...

o Make element modification work on IE - using "<span id="msgkey"></span>"
  and calling xlate("msgkey") works for IE.

*/

// -------------------------------------------------------------------
// FIXME: How do I switch the navigator.language of my browser?

function browser_language()
{
	return undefined != navigator.userLanguage ? navigator.userLanguage
	: undefined != navigator.language ? navigator.language
	: undefined != navigator.browserLanguage ? navigator.browserLanguage
	: undefined != navigator.systemLanguage ? navigator.systemLanguage
	: (alert("Could not determine language to use"), undefined);
}

// -------------------------------------------------------------------
i18n.debugtext= function()
{
	var text= "";

	text= text+
	' lang='    +navigator.language
	//for netscape flavored browsers
	//+' appName=' +navigator.appName
	//for IE
	+' usrLang=' +navigator.userLanguage
	+' brwsLang='+navigator.browserLanguage
	+' sysLang=' +navigator.systemLanguage
	;
	text= "[For debugging: Langs: Effective="+i18n.language_name
	+" &nbsp; "+text+"]";
	text= text+" Browser=: "+browser_language();

	return text;
}

// -------------------------------------------------------------------
/** Sets the global translation table (i18n.language) to the translation
    table with the given name (looked up in the i18n object). If no
    matching translation table was found, the global translation table
    is not changed.  */

i18n.setlanguage= function(newlangname) {
	var newlang= i18n[newlangname];
	// If not found, try matching just the first two chars
	if (undefined == newlang) {
		newlangname= newlangname.substring(0,2).toLowerCase();
		newlang= i18n[newlangname];
	}
	if (undefined != newlang) {
		i18n.language_name= newlangname;
		i18n.language= newlang;
	}
	else i18n.language = undefined;
}

// -------------------------------------------------------------------
// param added by jeff to only display spans, etc on pages that allow changing lang
// dont need all the extra stuff if not changeable
i18n.canChange=false;
// -------------------------------------------------------------------


// -------------------------------------------------------------------
// FIXME: This should be set based on the user's preferences,
// initially indicated by the browser.

// FIXME: Allow interactive switching of language.

i18n.init= function()
{
    if (undefined == i18n.language)
    {
	var lang= getCookie("ws_lang");
	if (undefined == lang || false == lang) {
	    lang=browser_language();
	}
	i18n.setlanguage(lang);
    }
    // i dont like the way i did this, but right now it works for testing
    try{if(location.href.indexOf("search.html") > -1 || location.href.indexOf("profile.html") >-1 || location.href.indexOf("index.html") >-1 || location.href.indexOf("translate.html") >-1) {i18n.canChange = true;}else {i18n.canChange = false;}}catch(sl_ex){}
}
i18n.init();


// -------------------------------------------------------------------
/**  Jeff adding vars/function to translate on the fly when language is changed
	20080624
*/

var i18n_arr = new Array();
var i18n_timer=false;

function xlateOnFly(lang) {
	// FIXME: When the translation table is changed on the fly, we
	// need to format newly translated messages using the original
	// sprintf call.  One way to achieve this is to move the
	// sprintf call into a closure and pass that closure to
	// getspan.
	
	for (var ii=0; ii<i18n_arr.length; ii++) {
	    var e= i18n_arr[ii];
	    if (!e.i_args) {
		if (document.getElementById("i18n_"+ii)) {
		    document.getElementById("i18n_"+ii).innerHTML = gettextonfly(e.i_id, lang);
		}
	    }
	    else {
		var args= e.i_args;
		if (args.id && args.param) {
		    if (document.getElementById(args.id)) {
			eval("document.getElementById('" + args.id + "')." +
			     args.param + "='"+(args.pre ? args.pre : "")+"'"+
			     "+gettextonfly(e.i_id, lang)+"+
			     "'"+(args.post ? args.post : "")+"'");
		    }
		}
	    }
	}
}

function gettextonfly(id, lang) {
	var text= id;
	var langExists = eval("i18n." + lang);
	if (langExists) {
		text= langExists[id];
		if (undefined == text) { text= id; }
	}

	return text;
}

// -------------------------------------------------------------------
/** In the current translation table (value of i18n.language), looks up
    the message with the given id.

    @return the message text, if a matching message is found.
    Otherwise returns the id.

    @param id - a key identifying the message, usually the message text
    in the default language, for example English.

    FIXME: This is currently not implemented, args are ignored:
    Formats the message using the given arguments.
*/

function gettext(id, args_ignored) {
	var text= id;
	if (undefined != i18n.language) {
		text= i18n.language[id];
		if (undefined == text) { text= id; }
	}
	
	return text;
}

// -------------------------------------------------------------------
/** CAUTION: This function produces a new span every time it is
    called, even if the call has been already made for the call
    location. Call this only for persistent elements, such as in a
    frame. Prefer not to call this for transient elements such as menu
    entries or list elements that are recreated every time that they
    become visible.  Alternatively, store the mementos in a table
    instead of in an array and use id and arguments as the key instead
    of simply the array index.  */
function getspan(id, args) {
	var text= ("function" === typeof(id)) ? id() : gettext(id, args);
	if (i18n.canChange) {
		if (!args) {
			text = "<span id='i18n_" + i18n_arr.length + "'>" + text + "</span>";
			var id_obj = {i_id:id, i_args:false};
		}                                                             
		else var id_obj = {i_id:id, i_args:args};
		i18n_arr.push(id_obj);
	}
	return text;
}

// -------------------------------------------------------------------
/** In the current translation table, looks up the message with the
    given id.  If one is found, replaces the content of the element
    with the given id with the translated message.

    FIXME: This is currently not implemented, args are ignored:
    Formats the message using the given arguments.
*/

function xlate(id, args) {
	var text= getspan(id, args);

	
	// If the replacement is the same as the id, this means that
	// either there was no translation found, in which case we
	// leave the element content as it is, or that the translation is the
	// same as the id, in which case there is no need to replace
	// the content either.
	//if (id != text) { document.getElementById(id).innerHTML = text; }

	// For now, we unconditionally set the innerHTML.  This allows
	// us to leave the tag's contents empty in the HTML file.
	var elt= document.getElementById(id);
	if (undefined == elt) { alert("Could not find element with id '"+id+"'."); }
	else { elt.innerHTML = text; }
}

// -------------------------------------------------------------------
/*
Other ways of changing document text to check out:
var form_elements = document.getElementById(which_div).getElementsByTagName("textarea");
document.getElementById("json-script-output").innerHTML =
 "<div id=\"json-error-message\">" + json_profile.message + "</div>";
*/

// -------------------------------------------------------------------
// EOF
