﻿var xmlHttp = function ()
{
	function createObject()
	{
		var factories = [
			function () { return new XMLHttpRequest() },
			function () { return new ActiveXObject('Msxml2.XMLHTTP') },
			function () { return new ActiveXObject('Msxml3.XMLHTTP') },
			function () { return new ActiveXObject('Microsoft.XMLHTTP') }
		];

		for (var i in factories)
			try { return factories[i](); }
			catch (e) {}

		return false;
	}

	return {
		Request: function (url, postData)
		{
			var req = createObject();

			if (req)
			{
				req.open(postData ? 'POST' : 'GET', url, false);

				req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');

				if (postData)
					req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

				req.send(postData);
				
				return req.responseText;
			}
		}
	};
}();

var cookie = function ()
{
	function ExpiryDate(/*seconds*/ lifetime)
	{
		var d = new Date();

		d.setTime(d.getTime() + lifetime * 1000);

		return '; expires=' + d.toGMTString();
	}

	return {
		Set: function (name, value, /*seconds*/ lifetime, path, domain, secure)
		{
			var cookieStr = name + '=' + escape(value);

			if (lifetime)
				cookieStr += ExpiryDate(lifetime);

			if (path)
				cookieStr += '; path=' + escape(path);

			if (domain)
				cookieStr += '; domain=' + escape(domain);

			if (secure)
				cookieStr += '; secure';

			document.cookie = cookieStr;
		},

		Get: function (/*string*/ name)
		{
			var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)');

			return results ? unescape(results[2]) : null;
		},
		
		Delete: function (/*string*/ name)
		{
			document.cookie = name += '=' + ExpiryDate(-1);
		}
	};
}();

var lng = function ()
{
	var comboData = [
		{ langId: 'en', name: 'Interface in English'  },
		{ langId: 'es', name: 'La interfaz en español'  },
		{ langId: 'fr', name: 'L\'interface en français' },
		{ langId: 'it', name: 'L\'interfaccia in italiano' },
		{ langId: 'pt', name: 'A interface em português' },
		{ langId: 'ru', name: 'Русскоязычный интерфейс' },
		{ langId: 'uk', name: 'Український інтерфейс' }
	];

	var cookieName = 'langId';
	var curLangId  = 'en';
	var dictIds;
	var lookup;
	var sep;

	function LangIdIndex(langId)
	{
		var i = 'en|es|fr|it|pt|ru|uk|'.indexOf(langId + '|');
		
		return i >= 0 ? i / 3 : -1;
	}

	function Set(/*string*/ langId)
	{
		// If language specified and its already selected or its not specified and none has been selected
		if (curLangId == langId)
			return;

		// Build a list of dictionary IDs used in this document

		dictIds	= '';
		lookup	= {};
		sep		= '';

		Traverse(document.firstChild);

		if (!dictIds)
			return;

		// Get translations from the server

		var replies	= xmlHttp.Request('http://www.ooltra.net/DictLookup.php', 'l=' + langId + '&' + dictIds).split('|');
		var i		= 0;

		// Add them to the lookup table

		for (var l in lookup)
			lookup[l] = replies[i++];

		curLangId = langId;
		cookie.Set(cookieName, langId, 2419200 /*28 days*/, '/');

		// Now traverse the document again substituting the translations

		Traverse2(document.firstChild);
	}

	function Traverse(e)
	{
		while (e)
		{
			if (e.nodeType == 1)	// Element
			{
				var dictId = e.getAttribute('dictid');

				if (dictId && lookup[dictId] == null)
				{
					dictIds += sep + dictId + '=';	// Add it to the XMLRequest string...
					sep = '&';
					lookup[dictId] = '';			// and to the lookup table
				}
				else
					Traverse(e.firstChild);
			}

			e = e.nextSibling;
		}
	}

	function Traverse2(e)
	{
		while (e)
		{
			if (e.nodeType == 1)	// Element
			{
				var dictId	= e.getAttribute('dictid');
				var trav	= true;

				if (dictId)
				{
					e.firstChild.nodeValue = lookup[dictId];
					trav = false;
				}

				if (e.nodeName == 'A')
				{
					// Fix the language parameter in anchor tags.

					var href = e.getAttribute('href');

					// FireFox has a relative path, IE is absolute.
					if (href && (href.substring(0, 5) != 'http:' || href.substring(0, 22) == 'http://www.ooltra.net/') && href.indexOf('.php') > 0)
					{
						var lpar = href.indexOf('?l=');

						if (lpar < 0)
							lpar = href.indexOf('&l=');

						if (lpar < 0)
						{
							if (curLangId != 'en')
								href = href + (href.indexOf('?') < 0 ? '?l=' : '&l=') + curLangId;
						}
						else
						{
							var parEnd = href.indexOf('&', lpar + 3);

							href =
								curLangId != 'en' ?
								href.substring(0, lpar + 3) + curLangId + (parEnd < 0 ? '' : href.substring(parEnd)) :
								(parEnd < 0 ? href.substring(0, lpar) : href.substring(0, lpar + 1) + href.substring(parEnd + 1));
						}

						e.setAttribute('href', href);
					}

					trav = false;
				}

				if (trav)
					Traverse2(e.firstChild);
			}

			e = e.nextSibling;
		}
	}

	return {
		OnLoad: function ()
		{
			var langId = location.search;

			if (langId && (langId = langId.match('(\\?|&)l=([^&]*)')))
				if (LangIdIndex(langId = langId[2]) >= 0)
					curLangId = langId;
				else
					langId = null;

			if (!langId)
				langId = cookie.Get(cookieName);

			if (!langId)
			{
				langId = navigator.language;	// FireFox

				if (!langId)
					langId = navigator.userLanguage;

				langId = langId.substr(0, 2).toLowerCase();

				if (LangIdIndex(langId) < 0)
					langId = null;
			}

			var combo = document.getElementById('langCombo');

			if (langId)
			{
				combo.selectedIndex = LangIdIndex(langId);
				Set(langId);
			}
			else
				Set(comboData[combo.selectedIndex].langId);
		},

		AddCombo: function ()
		{
			document.write('<select class="combo" id="langCombo" size="1" onchange="lng.OnChange(this)">');

			for (var i in comboData)
				document.write('<option>' + comboData[i].name + '</option>');

			document.write('</select>');
		},
		
		Changed: function() {},
		
		OnChange: function (combo)
		{
			var pageLangId = comboData[combo.selectedIndex].langId;

			Set(pageLangId);
			this.Changed();
		},
		
		CurLangId: function () { return curLangId; },
		
		lParam: function ()
		{
			return curLangId != 'en' ? '&l=' + curLangId : '';
		}
	};
}();
