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 AddLanguages ( defaultLanguage )
{
	let filesList = GetFilesInServerFolder ( '/eoDACSBootstrap/eoDACS/i18n/', false );

	let tmp = '';
	for ( let i=0; i<filesList.length; i++ )
	{
		if ( defaultLanguage == filesList [i] )
			eoDACS.CurrentLanguage = defaultLanguage;

		tmp += '<div class="col-auto">';
		tmp +=		'<img id="IdcLanguageImg_'+filesList [i]+'" src="SubFW/bmp/flag-'+filesList [i]+'.png" class="language imgclickable d-inline m-0 p-0 ps-1 pe-1" height="24" data-lang="fr" onclick="switchLanguage ( \''+filesList [i]+'\' );"/>';
		tmp +=	'</div>';
	}

	document.getElementById ('IdcLanguageDiv').innerHTML = tmp;
}

function switchLanguage ( language )
{
	eoDACS.CurrentLanguage = language;
	
    xhttp.open ( "GET", "/eoDACSBootstrap/eoDACS/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_'+eoDACS.CurrentLanguage).addClass ( "languageImgBorder");

	return language;
}

function processLangDocument ()
{
    var tags = document.querySelectorAll ( 'span,img,a,label,legend,li,option,h1,h2,h3,h4,h5,h6,button,div,th,td,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];
			/*
			else
				console.log ("Error!!!  keyTitle="+keyTitle);
			*/
        }

        let keyPlaceholder = value.dataset.langkey_placeholder;

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

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