var languages = Array.from(document.getElementsByClassName('language'));
var xhttp = new XMLHttpRequest();
var langDocument = {};
	
languages.forEach ( function(value, index) 
{
	languages[index].addEventListener ( 'click', function()
		{
			switchLanguage(this.dataset.lang);
		}
	);
}
);

xhttp.onreadystatechange = function()
{
    if ( this.readyState === 4 && this.status === 200 ) 
	{
        langDocument = JSON.parse ( this.responseText );
        processLangDocument ();
    }
};

function switchLanguage ( language )
{ 
	CurrentLanguage = language;
	
    xhttp.open ( "GET", "/eoQUALBootstrap/eoQUAL/i18n/" + language + ".json", true );
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send();

    let elems = document.getElementsByClassName ('language');
    for ( let i=0; i<elems.length; i++ )
    {
    	elems [i].classList.remove ( 'languageImgBorder');
    }

    $('#IdcLanguageImg_'+CurrentLanguage).addClass ( "languageImgBorder");

}

function processLangDocument ()
{
    var tags = document.querySelectorAll ( 'span,img,a,label,legend,li,option,h1,h2,h3,h4,h5,h6,button,div,th,p,input,small' );
    Array.from(tags).forEach ( function(value, index)
	{
        let key = value.dataset.langkey;

        if ( key != undefined )
        {
			if ( langDocument[key] ) 
			{
				value.innerText = langDocument[key];
			}
			else
			{
				// console.log ("Error!!!  key="+key);
			}
		}

		let keyTitle = value.dataset.langkey_title;

		if ( keyTitle != undefined )
        {
			if ( langDocument[keyTitle] ) 
				value.title = langDocument[keyTitle];
        }

        let keyPlaceholder = value.dataset.langkey_placeholder;

		if ( keyPlaceholder != undefined )
        {
			if ( langDocument[keyPlaceholder] ) 
				value.placeholder = langDocument[keyPlaceholder];
        }
    });
}

function Translate ( strInput )
{
	if ( langDocument[strInput] ) 
		return langDocument[strInput];
	else
	{	
		console.log ( "Error !!!  key="+strInput );
		return "";
	}
}
