// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// EUROPEAN COMMISSION "WEBSERVICE"
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 30/06/08 - Minify and add euXXX function
// 22/10/08 - Update correctly position popup
// 26/11/08 - Format correctly url ("?rid")
// 01/12/08 - Update ModalWindow
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// ---------------------------------------------
// PREDEFINE VAR
// ---------------------------------------------

var euPopup			= null;
var euPopupWidth 	= 160;
var euDocType		= (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
var euMouse			= {x:0,y:0};
var euScroll		= {x:0,y:0};
var euMouse			= {x:0,y:0};
var euWindow		= {w:0,h:0};		

// ---------------------------------------------
// AVOID OVERIDE EVENT HANDLERS
// ---------------------------------------------
// o : element object
// e : event type (mouseover,click,load...)
// f : bind function
// ---------------------------------------------

function euAddEvent(o,e,f)
{
	if(o.addEventListener)
	{
		o.addEventListener(e,f,false);
	}
	else if(o.attachEvent)
	{
		o.attachEvent('on'+e,f);
	}
}

// ---------------------------------------------
// GET EVENT "INFORMATION" 
// ---------------------------------------------
// e : capture event
// ---------------------------------------------

function euGetPosition(e)
{
	if(!e){e=window.event;} // IE
	
	euDocType	= (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
	
	euScroll.x	= document.all ? euDocType.scrollLeft : pageXOffset;
	euScroll.y	= document.all ? euDocType.scrollTop : pageYOffset;
	euMouse.x 	= e.clientX+euScroll.x;
	euMouse.y 	= e.clientY+euScroll.y;
	euWindow.w 	= euDocType.clientWidth+euScroll.x;
	euWindow.h 	= euDocType.clientHeight+euScroll.y;
}

// ---------------------------------------------
// CREATE "POPUP"
// ---------------------------------------------
// i : innerHTML
// c : className
// ---------------------------------------------

function euCreatePopup(i,c)
{	
	if( euPopup == null )
	{
		euPopup				= document.createElement("div");
		euPopup.className	= "euPopup";
		euPopup.id			= "euPopup";
		document.body.appendChild(euPopup);
	}	
	
	euPopup					= document.getElementById("euPopup");
	euPopup.style.width		= euPopupWidth+"px";
	euPopup.className		= (c=='euPopupError') ? "euPoPupError" : "euPopup";
	euPopup.style.display 	= "";
	
	i = i.replace(/\r?\n?\t?/ig,''); // IE break line !GRR
	
	i = i.replace(/class="alIco"/ig,'');
	
	euPopup.style.visibility	= "hidden";
	euPopup.innerHTML 		= "<table id='euPopupIn' cellspacing='0' cellmargin='0' border='0'><tr><td>"+i+"</td></tr></table>";	
	
	setTimeout(function(){
		
		euPopup.style.left  	= (euMouse.x-2)+"px";
		euPopup.style.top   	= (euMouse.y-15)+"px";
		
		euPopup.style.visibility	= "visible";
		euPopup.style.display		= "block";
		euPopup.style.position		= "absolute";
		
		euPopupZ 				= document.getElementById("euPopupIn");
		euPopupW				= euPopupZ.offsetWidth;
		euPopupH				= euPopupZ.offsetHeight;
	
		euPopup.style.width		= euPopupW+"px";
		
		if((euMouse.x+euPopupW)>euWindow.w)
		{
			euPopup.style.left=(euWindow.w-euPopupW)-5+"px";
		}
		if((euMouse.y+euPopupH)>euWindow.h)
		{
			euPopup.style.top=(euWindow.h-euPopupH)-5+"px";
		}
		
	},100);
}

euAddEvent(document,"click",function(){
	if( euPopup != null )
	{
		euPopup.style.display="none";
	}
});
		
// ---------------------------------------------
// BUILD LIST LANGUAGE AND DISPLAY POPUP
// ---------------------------------------------
// w : webservice
// l : languages
// ---------------------------------------------

function euShowPopupLangs(w,l)
{
	lst = "";
	for(index=0;index<l.length;index++)
	{
		ths = l[index];
		lng = ths.lang;
		lab = ths.label;
		typ = ths.type;
		hrf = ths.href;
		tag = (w.target) ? 'target="'+w.target+'"' : '';
		lst+= '<a href="'+hrf+'" lang="'+lng+'" hreflang="'+lng+'" title="'+lab+'" '+tag+'><img src="/wel/images/languages/lang_'+lng+'.gif" alt="'+lab+'" border="0"/></a>'+"\n";
	}
	if(lst!='')
	{
		euCreatePopup(lst);
	}
}

// ---------------------------------------------
// ALLOW MULTIPLE ONLOAD EVENT PAGE
// ---------------------------------------------
// f : function onload
// ---------------------------------------------

function euOnload(f){if(euOnload.loaded){f();}else{euOnload.funcs.push(f);}}
function euOnloadRun(){var i;if(euOnload.loaded){return;};for(i=0;i<euOnload.funcs.length;i++){try{euOnload.funcs[i]();}catch(e){}};euOnload.loaded=true;delete euOnload.funcs;}

euOnload.funcs	= [];
euOnload.loaded	= false;

euAddEvent(window,"load",euOnloadRun);

// ---------------------------------------------
// "FORMAT" LINK/SPAN TO DISPLAY LANGUAGE POPUP 
// ---------------------------------------------

function euInit()		
{
	if(!document.getElementsByTagName){return;}
	
	// ---------------------------------------
	// FOR EACH LINK
	// ---------------------------------------
	// normaly the best way is onclick event !
	// ---------------------------------------
	
	var a = document.getElementsByTagName("a");
							
	for(i=0;i<a.length;i++)
	{
		// ---------------------------------------
		// WEBSERVICE (euWsHide) Without ZZ link
		// ---------------------------------------
		
		if( a[i].className == "euWsHide" )
		{
			a[i].href			= "javascript://";
			//a[i].style.display	= "inline";
			a[i].onclick 		= function(evt)
			{ 
				euGetPosition(evt);
							
				ws 		  = new webservice("Language.Coverage.Popup",this.name,processLanguageCoverage,true);
				ws.target = ( ( this.target == "undefined" ) || ( this.target == null ) ) ? "_self" : this.target;
				ws.send();
							
				return false;
			
			};
		}
	}
	
	// ---------------------------------------
	// FOR EACH SPAN
	// ---------------------------------------
	
	var s = document.getElementsByTagName("span");
	var sm = [];	// source innerHTML euModalWindow
	
	for(i=0;i<s.length;i++)
	{
		// ---------------------------------------
		// MODAL WINDOW
		// ---------------------------------------
	
		if( s[i].className == "euModalWindow" )
		{
			si 				= "sm_"+i;
			sm[si] 			= s[i].innerHTML;
			s[i].innerHTML	= '<b>.</b>';
			s[i].id			= si;
			s[i].className 	= "euModalWindowButton";
			s[i].onclick 	= function(evt)
			{ 
				euGetPosition(evt);
				euCreatePopup(sm[this.id]);
			}
		}
	}
}

// ----------------------------------------------------
// INIT ONLOAD ... "DomReady" next release ;-)
// ----------------------------------------------------

euOnload(function(){euInit();});

// ----------------------------------------------------
// ORIGINAL SCRIPT
// ----------------------------------------------------

var runningWebservices 			= new Array();
var iFrameHashmap 				= new Object();
var READYSTATE_UNINITIALISED 	= 0;
var READYSTATE_LOADING 			= 1;
var READYSTATE_LOADED 			= 2;
var READYSTATE_INTERACTIVE 		= 3;
var READYSTATE_READY 			= 4;
var POLLING_INTERVAL 			= 200;
var HIDDEN_IFRAME_CLASS 		= "iFrameRequest";
var ISO_VAR 					= "%ISO%";
var OFFICIAL_LIST_ID 			= "official";
var UNOFFICIAL_LIST_ID 			= "unofficial";
var LIST_LINK_CLASS 			= "lang";
var LIST_LINK_SELECTED_CLASS 	= "curlang";
var COVERAGE_OPTION 			= "Language.Coverage.Option";
var COVERAGE_POPUP 				= "Language.Coverage.Popup";	
var COVERAGE_LIST 				= "Language.Coverage.List";


/**
 * This script contains a framework to manage
 * simple GET webservices. An example of usage
 * would be:
 * 
 * 	function mycallback(webservice) {		
 *		alert( "Webservice response: " + webservice.request.responseText );
 *	}
 * 
 *	function launcher() {
 *		ws = new webservice( "MyService", "http://www.example.com/myService", mycallback );
 *		ww.send();
 *	}
 *
 * That's all code required to call a GET
 * webservice and makes it very easy not
 * to have to deal with requests, etc...
 *
 * This script use iFrameRequest when
 * the standard Ajax means fail.
 */
 
function processLanguageCoverage(w)
{
	var PMerror = "";
	var xmlDoc 	= w.request.responseXML; // ie return alway [object] <> other => null
	var SrvName	= w.webserviceName;	
	var CheckIE = w.request.responseText; // IE responseXML return alway [object] <> other => null
		
	if( CheckIE.indexOf("500 Internal") == -1 ) // Webservice avalaible
	{
		var l = extractLanguageList( xmlDoc );
			
		if(l.length > 0)
		{
			if ( SrvName == COVERAGE_OPTION )
			{ 
				processCoverageOption(w,l);
			}
			if ( SrvName == COVERAGE_POPUP )
			{
				euShowPopupLangs(w,l);
			}
			if ( SrvName == COVERAGE_LIST )
			{
				processCoverageList(w,l);
			}
		}
		else // no language
		{
			errorZ = extractError( xmlDoc );
			if( errorZ != null )
			{
				PMerror = errorZ.message;
			}
		}
	}
	else // Webservice not avalaible
	{
		PMerror = "Webservice not available";
	}
	if( SrvName == COVERAGE_POPUP && PMerror != "" )
	{
		euCreatePopup(PMerror,"euPopupError");
	}
	
}
function webservice( webserviceName, url, callback, randomize )
{
	if ( ( webserviceName == null ) || ( webserviceName == undefined ) ) {
		return ( null );
	}
	if ( ( url == null ) || ( url == undefined ) ) {
		return ( null );
	}
	if ( ( callback == null ) || ( callback == undefined ) ) {
		return ( null );
	}
	
	// The datamembers
	this.webserviceName = webserviceName;
	
	if ( randomize == true ) {
		
		var ru  = url.split("?");
		var rid = (Math.random() + "").split(".")[1];
		var nu  = ru[0]+"?rid="+rid;
		var tu	= "";
		
		for( i=1; i < ru.length; i++ )
		{
			su = ( i == 1 ) ? "&" : "?";
			tu += su+ru[i];
		}
		
		url = nu+tu;

	}
	
	// Finally assign the (eventually adapted) url
	this.url = url;
	this.request = createRequest( this.url );

	if ( this.request == null ) {
		return ( null );
	}

	// The methods
	this.callback = callback;
	this.send = send;
	this.process = process;
	

	// Register it to the runningWebservices array
	this.index = runningWebservices.length;
	runningWebservices.push( this );
}
function process()
{
	runningWebservices[ this.index ] = null;
	this.callback(this);
}
function send()
{
	this.request.send( null );
}
function createRequest( url )
{
	var request = null;
	try { request = new XMLHttpRequest();}
	catch ( tryMicrosoft ) {
		try { request = new ActiveXObject( "Msxml2.XMLHTTP" ); }
		catch ( tryOtherMicrosoft ) {
			try { request = new ActiveXObject( "Microsoft.XMLHTTP" ); }
			catch ( failed ) {
				request = new iFrameRequest();
			}
		}
	}
	if ( request != null ) {
		request.onreadystatechange = handler;
		request.open( "GET", url, true );
	}
	return ( request );
}
function handler()
{
	var arrayEmpty = true;
	var webservice = null;
	for( var index = 0; index < runningWebservices.length; index++ ) {
		webservice = runningWebservices[ index ];
		if ( webservice != null ) {
			arrayEmpty = false;
			if ( webservice.request.readyState == 4 ) //&& webservice.request.status == 200 ) 
			{
				webservice.process();
			}
		}
	}
	if ( arrayEmpty && ( runningWebservices.length > 0 ) ) {
		runningWebservices = new Array();
	}
}
function loadSelected(id,target)
{
	target = ( ( target == undefined ) || ( target == null ) ) ? "_self" : target;
	open( document.getElementById( id ).value, target );
}
function fillCombo( comboId, errorId, webserviceName, webserviceUrl )
{
	if ( webserviceName == COVERAGE_OPTION ) {
		ws = new webservice(	COVERAGE_OPTION, 
					webserviceUrl,
					processLanguageCoverage,
					true );
		ws.selectId = comboId;
		ws.errorId = errorId;
		ws.send();
	}
}
function processCoverageOption(webservice,languages)
{
	var select = document.getElementById( webservice.selectId );
	if ( select != null ) {
		while( select.length > 0 ) {
			select.remove(0);
		}
		var requestLanguage = extractRequestLanguage( webservice.request.responseXML );
		var option = null;
		for(index=0;index<languages.length;index++) {
			option = languages[index].toOption();
			if ( languages[index].lang == requestLanguage ) {
				option.selected = true;
			}
			try { select.add( option, null ); }
			catch( internetexplorer ) { select.add( option ); } 
		}
	}
}
function processCoverageList(webservice,languages)
{
	var element = document.getElementById( webservice.elementId );
	if ( element != null )
	{
		var hyperlink = null;
		var listItem = null;
		var officialList = document.getElementById( ws.officialListId );
		if (officialList == null)
		{
			officialList = document.createElement( "ul" );
			officialList.id = ws.officialListId;
			element.appendChild( officialList );
		}
		else if ( officialList.hasChildNodes() )
		{
			while ( officialList.childNodes.length >= 1 )
			{
				officialList.removeChild( officialList.firstChild );
			}
		}
		var unofficialList = document.getElementById ( ws.unofficialListId );
		if ( unofficialList == null )
		{
			unofficialList = document.createElement( "ul" ); 
			unofficialList.id = ws.unofficialListId;
			element.appendChild( unofficialList );
		}
		else if ( unofficialList.hasChildNodes() )
		{
			while ( unofficialList.childNodes.length >= 1 )
			{
				unofficialList.removeChild( unofficialList.firstChild );
			}
		}
		var requestLanguage = extractRequestLanguage( webservice.request.responseXML );
		
		for(index=0;index<languages.length;index++)
		{
			hyperlink = languages[index].toHyperlink(true);
			hyperlink.appendChild( document.createTextNode( languages[index].lang ) );

			listItem = document.createElement( "li" );
			listItem.appendChild( hyperlink );

			if ( webservice.linkClass != undefined )
			{
				hyperlink.className = webservice.linkClass;
				if (	( webservice.linkSelectedClass != undefined ) && ( languages[index].lang == requestLanguage  )  )
				{
					hyperlink.className = webservice.linkSelectedClass;
				}
			}
			if ( ( webservice.target != undefined ) && ( webservice.target != null ) )
			{
				hyperlink.target = webservice.target;
			}
			if ( languages[index].isOfficial() )
			{
				officialList.appendChild( listItem );
			}
			else
			{
				unofficialList.appendChild( listItem );
			}
		}
		if ( typeof updateLanguage == 'function' )
		{
			updateLanguage( requestLanguage );
		}
	}
}
function extractLanguageList(xmlDoc)
{
	if ( ( xmlDoc == null ) || ( xmlDoc == undefined ) ) {
		return ( new Array() );
	}
	var documents 		= xmlDoc.getElementsByTagName( "document" );
	var languageList 	= new Array();
	var lang 			= null;
	var label 			= null;
	var type 			= null;
	var url 			= null;
	
	for( index=0; index < documents.length; index++ )
	{
		lang 	= documents[index].attributes[0].nodeValue;
		label 	= documents[index].attributes[1].nodeValue;
		type 	= documents[index].attributes[2].nodeValue;
		href 	= documents[index].attributes[3].nodeValue;
		languageList.push( new language( lang, label, type, href ) );
	}
	return ( languageList );
}
function extractRequestLanguage(xmlDoc)
{
	if ( ( xmlDoc == null ) || ( xmlDoc == undefined ) ) {
		return ( null );
	}
	var languageCoverage = xmlDoc.getElementsByTagName( "language_coverage" );
	if ( ( languageCoverage == null ) || ( languageCoverage == undefined ) ) {
		return ( null );
	}
	var request = languageCoverage[0].attributes[1].nodeValue;
	var regexp = new RegExp( "_[a-z]{2}.", "gm" );
	var matched = request.match( regexp );
	if ( ( matched == undefined ) || ( matched == null ) || ( matched.length == 0 ) ) {
		return ( null );
	}
	return ( matched[ matched.length - 1 ].substring(1,3) );
}
function extractError(xmlDoc)
{
	if ( ( xmlDoc == null ) || ( xmlDoc == undefined ) ) {
		return ( null );
	}
	var code = xmlDoc.getElementsByTagName( "code" )[0];
	if ( ( code == null ) || ( code == undefined ) ) {
		return ( null );
	}
	var message = xmlDoc.getElementsByTagName( "message" )[0];
	if ( ( message == null ) || ( message == undefined ) ) {
		return ( null );
	}
	return ( new error( code.firstChild.nodeValue, message.firstChild.nodeValue ) );
}
function error( code, message )
{
	if ( ( code == null ) || ( code == undefined ) ) {
		return ( null );
	}
	if ( ( message == null ) || ( message == undefined ) ) {
		return ( null );
	}
	this.code = code;
	this.message = message;
}
function iFrameRequest()
{
	var iFrame = document.createElement( 'iframe' );
	var identifier = "iFrame-" + (Math.random() + "").split(".")[1];
	iFrame.id = identifier;
	iFrame.className = HIDDEN_IFRAME_CLASS;
	iFrame.onload = iFrameRequestOnload;
	iFrame.onreadystatechange = iFrameRequestReadyStateChange;
	document.body.appendChild( iFrame );
	this.readystate = READYSTATE_UNINITIALISED;
	this.id = identifier;
	this.iFrame = iFrame;
	this.send = iFrameRequestSend;
	this.open = iFrameRequestOpen;
	this.onreadystatechange = null;
	iFrameHashmap[identifier]=this;
}
function iFrameRequestOpen( method, url )
{
	if ( method.toUpperCase() != "GET"  ) {
		return ( null );
	}
	if ( ( url == null ) || ( url == undefined ) ) {
		return ( null );
	}
	this.readystate = READYSTATE_LOADING;
	this.url = url;
}
function iFrameRequestSend( content )
{
	this.iFrame.src = this.url;
	this.readyState = READYSTATE_LOADING;
}
function iFrameRequestOnload()
{
	var iFrameRequest = iFrameHashmap[this.id];
	if ( ( iFrameRequest != null ) && ( iFrameRequest != undefined ) ) {
		var serializer = new XMLSerializer();
		iFrameRequest.responseXML = this.contentDocument;
		iFrameRequest.responseText = serializer.serializeToString( this.contentDocument ); 
		iFrameRequest.readyState = READYSTATE_READY;
		iFrameHashmap[this.id] = null;
		iFrameRequest.onreadystatechange();
	}
}
function iFrameRequestReadyStateChange()
{
	if ( this.readyState == 'complete' ) {
		var iFrameRequest = iFrameHashmap[this.id];
		if ( ( iFrameRequest != null ) && ( iFrameRequest != undefined ) ) {
			iFrameRequest.responseText = deepCopy( this.contentWindow.document.body.innerText );
			iFrameRequest.responseXML = this.contentWindow.document.XMLDocument;
			iFrameRequest.readyState = READYSTATE_READY;
			iFrameHashmap[this.id] = null;
			if ( ( iFrameRequest.onreadystatechange != null ) && ( iFrameRequest.onreadystatechange != undefined ) ) {
				iFrameRequest.onreadystatechange();
			}
		}
	}	
}
function deepCopy( toCopy )
{
	if ( ( toCopy == undefined ) || ( toCopy == null ) ) { 
		return ( toCopy );
	}
	var targetCopy = "";
	for( var index = 0; index < toCopy.length; index++ ) {
		targetCopy += toCopy.charAt(index);
	}
	return ( targetCopy );
}
function language( lang, label, type, href )
{
	if ( ( lang == null ) || ( lang == undefined ) || ( lang.length != 2 )) {
		return ( null );
	}
	if ( ( label == null ) || ( label == undefined ) ) {
		return ( null );
	}
	if ( ( type != "official" ) && ( type != "non-official" ) ) {
		return ( null );
	}
	if ( ( href == null ) || ( href == undefined ) ) {
		return ( null );
	}

	// The datamembers
	this.lang = lang;
	this.label = label;
	this.type = type;
	this.href = href;
	// The methods
	this.isOfficial = isOfficial;
	this.toHyperlink = toHyperlink;
	this.toOption = toOption;
	this.toImage = toImage;
}
function isOfficial()
{
	return ( this.type == "official" );
}
function toHyperlink(noText)
{
	var hyperlink = document.createElement("a");
	hyperlink.href = this.href;
	hyperlink.title = this.label.substring(0, this.label.indexOf(' (')); 
	hyperlink.hreflang = this.lang;
	hyperlink.lang = this.lang;
	if ( ( noText == undefined ) || ( noText != true ) )
	{
		var hyperlinkText = document.createTextNode( this.label );
		hyperlink.appendChild( hyperlinkText );
	}
	return ( hyperlink );
}
function toOption()
{
	var option = document.createElement("option");
	option.text=this.label;
	option.value=this.href;
	return ( option );
}
function toImage(imagePathTemplate)
{
		if ( ( imagePathTemplate == null ) || ( imagePathTemplate == undefined ) ) {
			return ( null );
		}
		if ( imagePathTemplate.indexOf( ISO_VAR ) == -1 ) {
			return ( null );
		}

		var iconRegExp = new RegExp( ISO_VAR, "g" );
		var image = document.createElement("img");
		image.src = imagePathTemplate.replace( iconRegExp, this.lang );
		image.alt = this.label;
		image.title = this.label;
		return ( image );
}
function fillList( elementId, errorId, webserviceName, webserviceUrl, target, officialListId, unofficialListId )
{
	if( webserviceName == COVERAGE_LIST )
	{
		ws = new webservice( COVERAGE_LIST, webserviceUrl, processLanguageCoverage, true );
		ws.elementId = elementId;
		ws.errorId = errorId;
		ws.linkClass = LIST_LINK_CLASS;
		ws.linkSelectedClass = LIST_LINK_SELECTED_CLASS;
		ws.target = ( target == undefined ) ? null : target;
		ws.officialListId = ( ( officialListId == undefined ) || ( officialListId == null ) ) ? OFFICIAL_LIST_ID : officialListId;
		ws.unofficialListId = ( ( unofficialListId == undefined ) || ( unofficialListId == null ) ) ? UNOFFICIAL_LIST_ID : unofficialListId;
		ws.send();
	}
}