// &amp; OK
//	Rosette-scripts.js : Rosette basic functions in JavaScript.
//	Leader : C.Roy
//	Rosette versions : 2.1 and 3.0

// Copyright (c) 2006-2009 Rosette - by Vincent Euverte - August 2006 - extended October 2007

var nouvelleFenetre = ''; var editorPalette = '';

//  test AJAX -------------------------------------------------------------

//
function ajaxEditorEnvrt( insertionDebutMdc )
	{
	var Text, fontbase0, Font, orientation, direction,widthOrHeightMax,withPositionNbr,analysis,motsAffiches,sample,option;

	if( !insertionDebutMdc ) insertionDebutMdc='';	
	Text = encodeURIComponent( insertionDebutMdc + document.chain_input.Text.value );
	fontbase0 = document.chain_input.fontbase0.value;
	if( document.getElementById('parameter' ) == null )
		Font = 1;
	else
		Font = document.getElementById('parameter' ).Font.value;
	orientation = (document.getElementById('ori2').checked)?'V':'H';
	direction = (document.getElementById('dirdir2').checked)?1:0;
	var pureTextCoef = document.chain_input.pureTextCoef.value;
	widthOrHeightMax = document.chain_input.widthOrHeightMax.value;
	withPositionNbr = (document.chain_input.pos_num.checked)?1:0;
	analysis = (document.chain_input.analysis.checked)?1:0;
	var listeBtn = document.getElementsByName('mots');
	for(var i=0; i < listeBtn.length; i++)
		{
		if(listeBtn[i].checked)
			{
			var valeur=listeBtn[i].value;
			break;
			}
		}
	if( valeur=='tous' )
		motsAffiches=-1;
	else if( document.getElementById('premMot') )
		motsAffiches=document.getElementById('premMot').value+','+document.getElementById('dernMot').value;
	else
		motsAffiches=-1;
	sample = document.chain_input.sample.value;
	document.chain_input.currentSample.value = sample;
	option = document.getElementById( 'ongletActif' ).value;
	//option = document.chain_input.option.value;
	return 'Text=' + Text + '&fontbase0=' + fontbase0
		+ '&Font=' + Font + '&orientation=' + orientation + '&direction=' + direction
		+ '&pureTextCoef=' + pureTextCoef + '&widthOrHeightMax=' + widthOrHeightMax + '&withPositionNbr=' + withPositionNbr
		+ '&analysis=' + analysis + '&mots=' + motsAffiches
		+ '&sample=' + sample + '&option=' + option;
	}
//
function ajaxEditorLaunch(  )
	{
	var divAttente = document.getElementById( 'divAttente' );
	centreElement(divAttente,0);
	divAttente.style.visibility="visible";

	ajaxEditor( ajaxEditorEnvrt() );
	document.getElementById( 'hieros' ).innerHTML = _ajaxAnswer;
//console.log("========"+_ajaxAnswer);
	document.getElementById( 'hieros').style.width = "auto";	//document.getElementById( 'content' ).style.width;
	document.getElementById( 'hieros').style.height = "auto";
	positionneImages( 'hieros' );

	divAttente.style.visibility="hidden";
	}
    
/**
*   calcul image hiéroglyphes pour éditeur de groupe
*/
function ajaxEditorLaunchEditGroupe(  )
	{
// ajout opérateur /S
//	ajaxEditor( ajaxEditorEnvrt( '..*' ) );
	ajaxEditor( ajaxEditorEnvrt( '' ) );
//    var reponse = '<img onload="dimensionne();" ' + _ajaxAnswer.substr(5,_ajaxAnswer.length-5)
    var reponse = '<img ' + _ajaxAnswer.substr(5,_ajaxAnswer.length-5)
	document.getElementById( 'hieros' ).innerHTML = reponse;
	document.getElementById( 'hieros').style.width = "auto";	//document.getElementById( 'content' ).style.width;
	document.getElementById( 'hieros').style.height = "auto";
	positionneImages( 'hieros' );
	}

/**
*	taille de la fenêtre
*/
function returnSize()
	{
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' )
		{	//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
		}
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
		{	//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
		}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
		{	//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
		}
	var result = new Array(myWidth,myHeight);
	return result;
	}

/**
*
*/
function centreElement(element,pourIphone)
	{
	var tailleFenetre = returnSize( );
	var myWidth=tailleFenetre[0];
	var myHeight=tailleFenetre[1];
    var elementWidth=0;
    var elementHeight=0;
    if( element.offsetWidth != null )
        {
        var elementWidth=element.offsetWidth;
        var elementHeight=element.offsetHeight;
        }
	var myScrollLeft=document.documentElement.scrollLeft;
	var myScrollTop=document.documentElement.scrollTop;
	var posX=myScrollLeft+myWidth-myWidth/2-elementWidth/2
	var posY=myScrollTop+myHeight-myHeight/2-elementHeight/2;
	element.style.left=posX+"px";
	element.style.top=posY+"px";
	}

//	appel depuis corpus (corpus.php)
//	
//	le MdC à traiter est transmis par la variable de session 'corpusText' (pour ne pas dépasser la longuer max d'URI)
function ajaxEditorLaunchCorpus2( textId, ancesters, lineIndex, optSize, mode, orientation, direction, grid, widthOrHeightMax, pourIphone )
	{
    if( !pourIphone ) pourIphone = 0;
	var divAttente = document.getElementById( 'divAttente' );
	centreElement(divAttente,pourIphone);
	divAttente.style.visibility="visible";
	var Font = 1;
	if( document.getElementById('parameter' ) != null )
		Font = document.getElementById('parameter' ).Font.value;
	var params = 'Text=session' + lineIndex + '&fontbase0=' + optSize
		+ '&textId=' + textId + '&ancesters=' + ancesters
		+ '&Font=' + Font + '&orientation=' + orientation + '&direction=' + direction
		+ '&pureTextCoef=0.5&widthOrHeightMax=' + widthOrHeightMax + '&withPositionNbr=0'
		+ '&analysis=0&sample=0&option=0'
		+ '&corpusMode=' + mode;
	if( grid )
		params = params + '&corpusGrid';
	//	appel asynchrone
	var xhr = null;

	xhr = getXMLHTTP( );

	var targetDiv = 'hieros' + lineIndex;
    xhr.onreadystatechange  = function( )
		{ 
		if( xhr.readyState  == 4 )
			{
			if( xhr.status  == 200 )
				{
				document.getElementById( this.targetDiv ).innerHTML = this.responseText;
				positionneImages( this.targetDiv );
				if( document.getElementById( 'iphHieros' ) )
					{
					var hauteur = parseInt( document.getElementById( 'hieros1' ).style.height ) + 33;
					document.getElementById( 'iphHieros' ).style.height= hauteur + 'px';
					var largeur = parseInt( document.getElementById( 'hieros1' ).style.width );
                    largeur = Math.max( largeur, 100 );
					document.getElementById( 'iphHieros' ).style.width=largeur + 'px';
					document.getElementById( 'iphHierosFleches' ).style.width=largeur + 'px';
					}
				}
			else if( xhr.status  == 500 )
				{
				document.getElementById( this.targetDiv ).innerHTML = this.responseText;
				}
			else
				{
				alert('xhr.status '+xhr.status+'...'+xhr.responseText);
				document.ajax.dyn ="Error code " + xhr.status;
				}
            divAttente.style.visibility="hidden";
			}
		}; 

	var _adresseCible = 'scripts/ajaxEditor.php';
	xhr.open( 'GET', _adresseCible + '?' + params, true );
xhr.targetDiv = targetDiv;
	xhr.send( null );

return xhr;
	}

function dimensionnePhoto( lineIndex )
	{
	var targetDiv = 'hieros' + lineIndex;
	var imageId = 'photo' + lineIndex;
	document.getElementById( imageId ).style.height = document.getElementById( targetDiv ).style.height;
	}

//	appel depuis éditeur lignes corpus (admin_Text_line.php)
//	
//	le MdC à traiter est transmis par la variable de session 'corpusText' (pour ne pas dépasser la longuer max d'URI)
function ajaxEditorLaunchCorpus3( textAreaId, targetDiv, size, police, insertionDebutMdc  )
	{
	if( !size ) size = 35;
	if( !police ) police = 1;
    if( !insertionDebutMdc ) insertionDebutMdc='';
	var theText = encodeURIComponent( insertionDebutMdc + document.getElementById( textAreaId ).value );
//	if( textAreaId == 'Translit' )
//		theText = '"' + theText + '"/zt';
	var params = 'Text=' + theText + '&fontbase0=' + size
			+ '&Font=' + police + '&orientation=H&direction=0'
			+ '&pureTextCoef=0.5&widthOrHeightMax=-1&withPositionNbr=0'
			+ '&analysis=0&sample=0&option=0&area=' + textAreaId;
	ajaxEditor( params );
	document.getElementById( targetDiv ).innerHTML = _ajaxAnswer;
	//positionneImages( targetDiv );
	}

//	appel depuis depuis corpus pour initialisation des variables
//	
//	le MdC à traiter est transmis par la variable de session 'corpusText' (pour ne pas dépasser la longuer max d'URI)
function XXXajaxEditorLaunchCorpus4( textId, optSize )
	{
	//alert( 'ajaxEditorLaunchCorpus4');
	var params = 'Text=session0' + '&fontbase0=' + optSize
			+ '&textId=' + textId
			+ '&Font=1&orientation=H&direction=0'
			+ '&pureTextCoef=0.5&widthOrHeightMax=-1&withPositionNbr=0'
			+ '&analysis=0&sample=0&option=0&ancesters';
	ajaxEditor( params );
	}


function ajaxMET( rubrique, langue, selected, idMenu, module )
	{
//alert('ajaxMET...'+idMenu+'...'+module);
	if( selected == null ) selected = -1;
	if( idMenu == null ) idMenu = 'Id1';
	if( module == null ) module = '';	// la liste contiendra ttes les sous-rubriques de la rubrique
		//	si ce paramètre = 'Corpus', la liste ne contiendra que les sous-rubriques déjà utilisées/allouées pour ce module
	var idxSelected = -1;
	
	var Font = 1;
	if( document.getElementById('parameter' ) != null )
		Font = document.getElementById('parameter' ).Font.value;
	var params = 'rubric=' + rubrique + '&language=' + langue + '&module=' + module;
	//	appel asynchrone
	var xhr = null;

	xhr = getXMLHTTP();
    xhr.onreadystatechange  = function( )
		{ 
		if( xhr.readyState  == 4 )
			{
			if( xhr.status  == 200 )
				{
				var elSel = document.getElementById( idMenu );
				//	suppression options existantes
				for( i=elSel.length-1; i>=0; i-- )
					elSel.remove( 0 );
				//	création nouvelles
				var lesOptions = xhr.responseText.split( '---' );
				for( i=0; i<lesOptions.length; i++ )
					{
					var elOptNew = document.createElement( 'option' );
					var lesSegs = lesOptions[ i ].split( '@olgdv' );
					var reg=new RegExp( '&nbsp;&nbsp;&nbsp;', 'g' );
					elOptNew.text = lesSegs[ 1 ].replace( reg, '\u00a0\u00a0\u00a0' );
					elOptNew.value = lesSegs[ 0 ];
					try
						{ elSel.add(elOptNew, null); }
					catch(ex)
						{ elSel.add(elOptNew);}	
					if( selected != -1 && selected == lesSegs[ 0 ] )
						idxSelected = i;
					}
				if( idxSelected != -1 )
					elSel.selectedIndex = idxSelected;
				}
			else 
				alert( 'ERREUR ajaxMET(...code ' + xhr.status );
			}
		}; 

	var _adresseCible = 'scripts/ajaxMET.php';
	xhr.open( 'GET', _adresseCible + '?' + params, true );
	xhr.send( null );
	}



function ajaxEditorCheck( langue, mdc, displayCode, divOut )
	{
	if( divOut == null ) divOut = 'hieros';
	document.getElementById(divOut).innerHTML = '';

	var lesParams= 'Lang=' + langue
		+'&Text=' + encodeURIComponent( document.getElementsByName(mdc)[0].value );
	//alert(lesParams );
	ajaxCheck( lesParams );
	
	var errorMet, resultat, reponse;

var i = _ajaxAnswer.indexOf( '---NOK---', 0 );
//	if( _ajaxAnswer.substring( 0, 2 ) == 'OK' )
	if( i == -1 )
		{	//	validation OK
		show = displayCode;
		errorMet = false;
		reponse = _ajaxAnswer.replace( '---OK---', 'Code normalisé :<div style="margin-left:20px;">' );	//, _ajaxAnswer.length-2 );
		}
	else
		{
		show = true;
		errorMet = true;
		reponse = _ajaxAnswer.replace( '---NOK---', '' );	//, _ajaxAnswer.length-2 );
		}
	if( show )
		{
		if( errorMet )
			resultat = '<div style="margin-left:20px;color:red;">';
		else
			resultat = '';
		resultat += reponse + '</div>';
		}
	else
		resultat = 'OK';
	document.getElementById(divOut).style.width = "auto";	//document.getElementById( 'content' ).style.width;
	document.getElementById(divOut).style.height = "auto";
	document.getElementById(divOut).innerHTML = resultat.replace(/\n/g, '<br/>');
	}

// retourne un objet xmlHttpRequest.
// méthode compatible entre tous les navigateurs (IE/Firefox/Opera)
function getXMLHTTP()
	{
	var xhr=null;
if( true )
	{
	try
		{
		xhr = new XMLHttpRequest(); 
		}
	catch(e)
		{ 
		try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } 
		catch (e2)
			{ 
			try
				{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } 
			catch (e)
				{ alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); }
			}
		}
	}
else
	{
	if(window.XMLHttpRequest) // Firefox et autres
		xhr = new XMLHttpRequest();
	else if(window.ActiveXObject)
		{ // Internet Explorer
		try
			{xhr = new ActiveXObject("Msxml2.XMLHTTP");}
		catch (e)
			{
			try
				{xhr = new ActiveXObject("Microsoft.XMLHTTP");}
			catch (e1)
				{xhr = null;}
			}
		}
	else // XMLHttpRequest non support¬é par le navigateur
		alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
	}
	return xhr;
	}

var _xmlHttp = null; //l'objet xmlHttpRequest utilis¬é pour contacter le serveur
var	_ajaxAnswer='';

function ajaxTraiteXmlAnswer( xmlDoc )
	{
	var options = xmlDoc.getElementsByTagName('option');
	var optionsListe = new Array();
	for( var i=0; i < options.length; ++i )
		optionsListe.push(options[i].firstChild.data);
	return optionsListe;
	}

function ajaxPopup( popupId, action )
	{
	var _adresseCible = "scripts/ajax.php" //l'adresse ¬à interroger pour trouver les suggestions
	if(_xmlHttp&&_xmlHttp.readyState!=0)
		_xmlHttp.abort();
	_xmlHttp = getXMLHTTP();
	if(_xmlHttp)
		{	//appel SYNCHRONE ¬à l'url distante
		_xmlHttp.open( 'GET', _adresseCible + '?popupId=' + popupId + '&action=' + action, false );
		// envoi de la requête
		_xmlHttp.send( null );
		liste = ajaxTraiteXmlAnswer( _xmlHttp.responseXML );
		_ajaxAnswer = liste[0];
		}
	}

function ajaxEditor( params )
	{
	var _adresseCible = 'scripts/ajaxEditor.php';
	if( _xmlHttp && _xmlHttp.readyState!=0)
		_xmlHttp.abort();
	_xmlHttp = getXMLHTTP();

	if(_xmlHttp)
		{	//appel SYNCHRONE ¬à l'url distante
		_xmlHttp.open( 'GET', _adresseCible + '?' + params, false );
		// envoi de la requ¬ête
		_xmlHttp.send( null );
		if( _xmlHttp.status == 200 || _xmlHttp.status  == 500 )
			_ajaxAnswer = _xmlHttp.responseText;
		else
			{
			alert( 'ERREUR _xmlHttp.status : ' + _xmlHttp.status );
			_ajaxAnswer = '';
			}
		}
	}

function ajaxTailleImages( listeFichiers )
	{
	var params = 'listeImages=' + encodeURIComponent( listeFichiers );
	var _adresseCible = 'scripts/ajaxTailleImages.php';
	if( _xmlHttp && _xmlHttp.readyState!=0)
		_xmlHttp.abort();
	_xmlHttp = getXMLHTTP();
	if(_xmlHttp)
		{	//appel SYNCHRONE ¬à l'url distante
		_xmlHttp.open( 'GET', _adresseCible + '?' + params, false );
		// envoi de la requ¬ête
		_xmlHttp.send( null );
		if( _xmlHttp.status == 200 )
			_ajaxAnswer = _xmlHttp.responseText;
		else
			{
			alert( '_xmlHttp.status : ' + _xmlHttp.status );
			_ajaxAnswer = '';
			}
		}
	}

function ajaxLoadSample( withRendering )
	{
	var _adresseCible = 'scripts/ajaxEditorLoad.php' //l'adresse ¬à interroger pour charger le sample

	var sample = document.chain_input.sample.value;
	var params = ajaxEditorEnvrt();
	if(_xmlHttp&&_xmlHttp.readyState!=0)
		_xmlHttp.abort();
	_xmlHttp = getXMLHTTP();
	if(_xmlHttp)
		{	//appel SYNCHRONE ¬à l'url distante
		_xmlHttp.open( 'GET', _adresseCible + '?' + params, false );
		// envoi de la requ¬ête
		_xmlHttp.send( null );
		_ajaxAnswer = _xmlHttp.responseText;
		document.chain_input.Text.value = _ajaxAnswer;
		if( withRendering )
			ajaxEditorLaunch( );
		}
	}

function ajaxCheck( params )
	{
	var _adresseCible = "scripts/ajaxCheck.php" //l'adresse ¬à interroger pour trouver les suggestions
	if(_xmlHttp&&_xmlHttp.readyState!=0)
		_xmlHttp.abort();
	_xmlHttp = getXMLHTTP();
	if(_xmlHttp)
		{	//appel SYNCHRONE ¬à l'url distante
		_xmlHttp.open( 'GET', _adresseCible + '?' + params, false );
		// envoi de la requ¬ête
		_xmlHttp.send( null );
		_ajaxAnswer = _xmlHttp.responseText;
		}
	}

//	positionne les images et les textes contenues dans une div
//
//	La position de chaque image est déterminée par l'attribut "position" de la balise <img correspondante
//	Cet attribut contient une (left et top) ou deux (left puis top) valeurs numériques séparées par une virgule.
//	Ces deux valeurs définissent la distance en pixels du coin sup./gauche de l'image par rapport au 
//	coin sup. gauche de la div.
//	Les paddings de la div sont pris en compte.
//
//	L'élément DOM juste au dessus de la div doit contenir position:relative dans son style
//var maxY = 0;
//var maxX = 0;
//var textDiv = false;
//var imageDiv = false;

//	positionneImages appelle récursivement positionneImages2
function positionneImages2( m, maxX, maxY, textDiv, imageDiv )
	{
	var paddings;
	var dimensions;
	//var message='';
	var img;
	var idxChild = 0;

	if( m.style.padding != '' )
		paddings = m.style.padding.split(' ');
	else
		paddings = Array( 0, 0, 0, 0 );
	var i = 0;
	for( ; i<4; i++ )		//	for each pas dispo avec Safari
		paddings[i] = parseInt(paddings[i]);

if( document.getElementById('iphHieros0' ) )
    {   //  calcul du coef pour ....
	while( (img = m.childNodes[ idxChild ] ) )		//	for each pas dispo avec Safari
		{	//	loop on nodes in container div
		if( img.nodeType != null && img.nodeType == 1 )
			{
			if( img.nodeName == 'IMG' )
				{	// repositionnement image
				var dimensions = img.getAttribute("dimensions");
//console.log('dimensions==='+dimensions);
				if(dimensions)
					{
					dimensions = dimensions.split( ',' );		// x,y,w,h
					for( i=0; i<4; i++ )
						dimensions[i] = parseInt( dimensions[i] );
					//img.style.position = "absolute";	//"absolute";
					//img.style.left = coef*( paddings[3] + dimensions[0] ) + "px";
					//img.style.top = coef*( paddings[0] + dimensions[1] ) + "px";
                    //img.style.width = (coef*dimensions[2]) + 'px';
					//maxY = Math.max( maxY, coef*( dimensions[1] + dimensions[3] ) );
					maxX = Math.max( maxX, dimensions[0] + dimensions[2] );
					//imageDiv = true;
					//img.removeAttribute( "dimensions" );
					}
				}
			else if( false && img.nodeName == 'DIV' )
				{	//	repositionnement div
				var increment = textDiv?0:10;
				img.style.position = 'absolute';
				img.style.top = ( increment + paddings[0] + maxY ) + "px";
				img.style.width = '100%';
				maxY = increment + maxY + img.offsetHeight;
				textDiv = true;
				}
			else if( false && img.nodeName == 'A' )
				{	//	appel  récursif pour images éventuelles dans <a>...</a>
				positionneImages2( img, maxX, maxY );
				}
			}
		idxChild++;
		}
var coef=(document.body.scrollWidth - 20 ) / maxX;
//console.log('======'+coef+'==='+maxX);
    }
else
    var coef = 1;
coef=1;
    idxChild = 0;
	while( (img = m.childNodes[ idxChild ] ) )		//	for each pas dispo avec Safari
		{	//	loop on nodes in container div
		if( img.nodeType != null && img.nodeType == 1 )
			{
			if( img.nodeName == 'IMG' )
				{	// repositionnement image
				var dimensions = img.getAttribute("dimensions");
				if(dimensions)
					{
					dimensions = dimensions.split( ',' );		// x,y,w,h
					for( i=0; i<4; i++ )
						dimensions[i] = parseInt( dimensions[i] );
					img.style.position = "absolute";	//"absolute";
					img.style.left = coef*( paddings[3] + dimensions[0] ) + "px";
					img.style.top = coef*( paddings[0] + dimensions[1] ) + "px";
                    img.style.width = (coef*dimensions[2]) + 'px';
					maxY = Math.max( maxY, coef*( dimensions[1] + dimensions[3] ) );
					maxX = Math.max( maxX, coef*( dimensions[0] + dimensions[2] ) );
					imageDiv = true;
					img.removeAttribute( "dimensions" );
					}
				}
			else if( img.nodeName == 'DIV' )
				{	//	repositionnement div
				var increment = textDiv?0:10;
				img.style.position = 'absolute';
				img.style.top = ( increment + paddings[0] + maxY ) + "px";
				img.style.width = '100%';
				maxY = increment + maxY + img.offsetHeight;
				textDiv = true;
				}
			else if( img.nodeName == 'A' )
				{	//	appel  récursif pour images éventuelles dans <a>...</a>
				positionneImages2( img, maxX, maxY );
				}
			}
		idxChild++;
		}
	return[ maxX, maxY, textDiv, imageDiv ];
	}

function positionneImages( divName )
	{
    var maxY = 0;
    var maxX = 0;
    var textDiv = false;
    var imageDiv = false;
	
	var redimensionnerContainer = true;
	if( arguments.length > 1 )
		redimensionnerContainer = arguments[1];
	var m = document.getElementById( divName );
	//	paddings de la div --> paddings[]
	var paddings;
	if( m.style.padding != '' )
		paddings = m.style.padding.split(' ');
	else
		paddings = Array( 0, 0, 0, 0 );
	var i = 0;
	for( ; i<4; i++ )		//	for each pas dispo avec Safari
		paddings[i] = parseInt(paddings[i]);
	
	if( false )
		{	// affiche hiérarchie de positionnement DOM
		n=m;
		mes=m.id + ' offsetTop ' + m.offsetTop + String.fromCharCode(10);
		while( n.offsetParent != null )
			{
			mes += '<' + n.offsetParent.id +'-'+ n.offsetParent.nodeName+'-'+n.offsetParent.nodeType+'-'+n.offsetParent.hasLayout;
			n = n.offsetParent;
			}
		alert( mes );
		}

	var resultats = positionneImages2( m, maxX, maxY, textDiv, imageDiv );
	maxX = resultats[ 0 ];
	maxY = resultats[ 1 ];
	textDiv = resultats[ 2 ];
	imageDiv = resultats[ 3 ];
	
	if( redimensionnerContainer && ( imageDiv || textDiv ) )
		{	//	ajustement taille div container
		var hauteur = maxY + paddings[2];
		if( textDiv ) hauteur += 40;
		m.style.height = hauteur + "px";
		if( divName.length > 6 && maxX > 0 )
			//	on vient  du corpus
			m.style.width = ( maxX + paddings[1] ) + "px";
		}
	}

/**
* putInEditor : place le contenu de laChaine dans l'elt d'id inputZoneName
*	de la fenetre ayant ouvert la popup en cours.
*/
function putInEditor( laChaine, inputZoneName, remplacerTout )
	{
	var lesSegs = inputZoneName.split( '.' );
	if( lesSegs.length == 2 )
		lObj = window.opener.document.getElementById( lesSegs[ 1 ] );
	else
		lObj = window.opener.document.getElementById( inputZoneName );
	if( laChaine == 'return' ) laChaine = String.fromCharCode( 13 );
	if( remplacerTout )
		lObj.value = laChaine;
	else
		insertAtCursor( lObj, laChaine );
	//var start = lObj.selectionStart;
	//var end = lObj.selectionEnd;
	//lObj.value = lObj.value.substr(0, start) + laChaine + lObj.value.substr(end);
	}

function insertAtCursor( myField, myValue) 
	{
	if ( window.opener.document.selection )
		{	//IE support
		//alert('IE');
		myField.focus();
		sel = window.opener.document.selection.createRange();
		var temp = sel.text.length;
		sel.text = myValue;
		if( myValue.length == 0 )
			{
			sel.moveStart( 'character', myValue.length );
			sel.moveEnd( 'character', myValue.length );
			}
		else
			sel.moveStart( 'character', -myValue.length + temp );
		}
	else if( myField.selectionStart || myField.selectionStart == '0' )
		{	//MOZILLA/NETSCAPE support
		//alert('mozilla');
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring( 0, startPos )
			+ myValue
			+ myField.value.substring( endPos, myField.value.length );
		myField.focus();
		myField.selectionStart = startPos + myValue.length;
		myField.selectionEnd = startPos + myValue.length;
		//alert( startPos + '.' + myValue.length + '.' + myField.selectionStart );
		}
	else
		{
		//alert('else');
		myField.value += myValue;
		myField.focus();
		}
	}

//	function to confirm an operation
function confirmOperation( text, url )
	{
	if( confirm( text ) )
		window.location.href = url;
	}

//	functions checking an email address
function check_email( address )
	{
	if ( address.trim() == "")
		{
		alert("Vous avez oubli¬é de renseigner la rubrique ADRESSE ELECTRONIQUE.");
		document.formulaire.Email.focus();
		return false;
		}
	posAt = address.indexOf('@',0);
	posDot = address.indexOf('.',posAt+2);
	posPipe = address.indexOf('|',0);
	posStar = address.indexOf('*',0);		
	if( posStar != -1 || posPipe != -1 || posAt == -1 || posDot == -1 || (address.length - posDot < 3))
		{
		alert("L'ADRESSE ELECTRONIQUE que vous avez saisie n'est pas valide");
		document.formulaire.Email.focus();
		return false; 		
		}
	return true;
	}
	
//	function called from editor_menu
function askPdf( script, orientation )
	{
	params = '?text=' + document.getElementById("theText").value
				+ '&files=' + document.getElementById("tempFiles").value
				+ '&size=' + document.getElementById("optSize").value
				+ '&orientation=' + orientation;
	window.location = 'scripts/' + script + params;
	}
/*
*	popitup : ouverture d'une popup
*
*	fenetre nom de la fenêtre : si commence par 'new ' ==> ouvrir une popup en plus
*		autrement remplacer popup existante si existe ou ouvrir nouvelle
*/
function popitup( url, fenetre, param, event, urlSpeciale )
	{	//	param est optionnel et peut ¬être 'pleinEcran'
	if( event != null )
		// appel avec argt exlicite pour changer comportement du click si shift appuyé
		comportement = event.shiftKey?'nonStandard':'std';
	else
		comportement = 'std';
	
	if( comportement == 'std' )
		{
		if( fenetre == 'editorPalette' )
			{
			//	ask to server if popup open
			ajaxPopup( 1003, 'statut' );
			if( _ajaxAnswer == 'open' && window.editorPalette != '' )
				; // palette window active and opened by the current window
			else
				{
				if( arguments.length < 3 )
					param = 'top=10,left=10,width=580,height=540,scrollbars=yes';
				else if( param == 'pleinEcran' )
					param = 'fullsize,scrollbar,top=10,left=10,width=' + screen.width + ',height=' + screen.height;
				editorPalette=window.open( url, fenetre, param);
				//	pour voir barre adresse : ajouter location=yes
				if (!editorPalette.opener) editorPalette.opener = self;
				}
			if(window.focus) { editorPalette.focus() }
			}
		else
			{
//var forcerNouvellePopup = fenetre.substr(0,4) == 'new ';
//if( !forcerNouvellePopup && window.nouvelleFenetre != '' && !nouvelleFenetre.closed && nouvelleFenetre.location )
			if( window.nouvelleFenetre != '' && !nouvelleFenetre.closed && nouvelleFenetre.location )
				//	une popup ouverte ==> on la remplace
				nouvelleFenetre.location.href = url;
			else
				{	//	on ouvre une nouvelle fenetre
				if( arguments.length < 3 )
					param = 'top=0,left=0,width=580,height=540,scrollbars=yes';
				else if( param == 'pleinEcran' )
					param = 'fullsize,scrollbar,top=0,left=0,width=' + screen.width + ',height=' + screen.height;
fenetre = 'azerty';		//	IE8 n'accepte pas les espaces dans ce param
//fenetre.replace( ' ', '_' );
				nouvelleFenetre = window.open( url, fenetre, param );
				//	pour voir barre adresse : ajouter location=yes
				if( !nouvelleFenetre.opener ) nouvelleFenetre.opener = self;
				}
			if(window.focus) { nouvelleFenetre.focus() }
			}
		}
	else
		alert( 'comportement non std : ' + urlSpeciale + '>>>' + event.target );
	return false;
	}

function returnFromPopup( nbr )
	{
	theW = window.opener;
	
	theSel = "";
	for( i=0; i<nbr; i++ )
		{
		if( document.getElementById( "chk" + i ).checked )
			{
			theSel = theSel + i;
			//if( i < nbr-1 ) theSel= theSel  + ",";
			theSel= theSel  + ",";
			}
		}
	if( theSel.length > 0 ) theSel = theSel.substring( 0, theSel.length-1 );

	theRef = theW.location.href;
	var i = (theRef+'').indexOf( "&colChooser", 0 );
	if( i != -1 )
		{
		var j = (theRef+'').indexOf( "&", i+1 );

		theRef2 = theRef.substring(0, i);
		if( j != -1 )
			theRef2 = theRef2+ theRef.substring( j, theRef.length );
		theRef = theRef2;
		}
	theW.location.href = theRef + "&colChooser=" + theSel;
	window.close();
	}

function TAinsr( mdc1, mdc2 )
	{		//insert text within the same window
	var TA = document.chain_input.Text;
	TAinsr0(mdc1,mdc2,TA);
	}

function TAinsr2( mdc1, mdc2 ) 
	{		//insert in Text area from a popup window
	var TA = window.opener.document.getElementsByName("Text")[0];
	TAinsr0( mdc1, mdc2, TA );
	}

function TASave( ) 
	{		//insert in Text area from a popup window
	var TA = document.getElementsByName("Text")[0];

	window.open( 'scripts/editor_download.php?text=' + encodeURIComponent( TA.value ) );
	}

function TAinsr1(mdc1,mdc2)
	{		//Rosette editor - management of the frame flags
	if (mdc1.substring(0,1) == "<") { // frame opening
		if(document.getElementById("bastion").checked) { // rounded bastion flag is set
			if (mdc1 == "<F") {mdc1 = "<F1";}
			if (mdc1 == "<G") {mdc1 = "<G1";}
			if (mdc2 == "F>") {mdc2 = "F1>";}
			if (mdc2 == "G>") {mdc2 = "G1>";}
			}
		if(document.getElementById("nobeg").checked) { // no beginning flag is set
			switch (mdc1.substr(1,1)) {
				case "F" : mdc1 = "<F0"; break;
				case "G" : mdc1 = "<G0"; break;
				case "H" : mdc1 = "<H0"; break;
				case "S" : mdc1 = "<S0"; break;
				default : mdc1 = "<0";
			}	}
		if(document.getElementById("noline").checked) {mdc1 += '/n';} // no line flag is set
		if(document.getElementById("noend").checked) { // no ending flag is set
			switch (mdc2.substr(0,1)) {
				case "F" : mdc2 = "F0>"; break; 
				case "G" : mdc2 = "G0>"; break;
				case "H" : mdc2 = "H0>"; break;
				case "S" : mdc2 = "S0>"; break;
				default : mdc2 = "0>";
			}	}
		for(i=0;i<3;i++){ // include the separator, acording tothe separator option
			if (document.chain_input.separator[i].checked) {
				mdc1 = mdc1 + document.chain_input.separator[i].value;
				mdc2 = document.chain_input.separator[i].value + mdc2 + document.chain_input.separator[i].value;
		}	}	}
	TAinsr(mdc1,mdc2);	
	} 
		
function TAinsr0( mdc1, mdc2, TA) 
	{		//main script, from Aceboard script to add a message
	if (document.selection)
		{
		if ((window.opener) && (window.opener.document))
			{
			TA.focus();
			var str=window.opener.document.selection.createRange().text;			
			var sel=window.opener.document.selection.createRange();
			}
		else
			{
			var str=document.selection.createRange().text;			
			TA.focus();
			var sel=document.selection.createRange();
			}
		if (mdc2!="")
			{
			if (str=="")
				sel.text=sel.text+mdc1+mdc2;
			else
				sel.text=mdc1+sel.text+mdc2;
			}
		else
			sel.text=sel.text+mdc1;
		}
	else if (TA.selectionStart | TA.selectionStart == 0)
		{
		if (TA.selectionEnd > TA.value.length)
			TA.selectionEnd = TA.value.length;
		var firstPos = TA.selectionStart;
		var secondPos = TA.selectionEnd+mdc1.length;
		TA.value=TA.value.slice(0,firstPos)+mdc1+TA.value.slice(firstPos);
		TA.value=TA.value.slice(0,secondPos)+mdc2+TA.value.slice(secondPos);
		TA.selectionStart = firstPos+mdc1.length;
		TA.selectionEnd = secondPos;
		TA.focus();
		}
	else
		{ // Opera
		var sel = document.chain_input.Text;
		var instances = countInstances(mdc1,mdc2);
		if (instances%2 != 0 && mdc2 != ""){
			sel.value = sel.value + mdc2;
		}else{
			sel.value = sel.value + mdc1;
		}
	}
}
		 
function size_adjust(delta)
	{
	document.chain_input.fontbase.value = document.chain_input.fontbase.value - (- delta); }

function go1()
	{
	if (document.chain_input.Section.options[document.chain_input.Section.selectedIndex].value != "none") {
			location = document.chain_input.Section.options[document.chain_input.Section.selectedIndex].value}
	}

function comment(com)
	{
	var descript = document.getElementById("descript");
	descript.expli.value = com;
	}

var w;

function ouvrir(page)
	{
	w=window.open(page, '', 
		'width=800, height=600, scrollbars=yes, left=10, top=10');
	}

function fermer() {if (w.document) w.close();}

function getLeft(MyObject)
//Fonction permettant de connaître la position d'un objet
//par rapport au bord gauche de la page.
//Cet objet peut être à l'intérieur d'un autre objet.
    {
    if( MyObject.offsetParent)
        return (MyObject.offsetLeft + getLeft(MyObject.offsetParent));
    else
        return (MyObject.offsetLeft);
    }

function getTop(MyObject)
//Fonction permettant de connaître la position d'un objet
//par rapport au bord haut de la page.
//Cet objet peut être à l'intérieur d'un autre objet.
    {
    if (MyObject.offsetParent)
        return (MyObject.offsetTop + getTop(MyObject.offsetParent));
    else
        return (MyObject.offsetTop);
    }

/*	pour balise <navigation. Adapté de http://blog.oli-web.com	*/
var curX;
var curY;
var idMenu;

function menuChoix( e, pIdMenu )
	{
	if( e.button == 0  && document.getElementById( 'typeNavF' ).checked )
		{
		if(pIdMenu != '')
			{
			hideMenuChoix();
			idMenu = 'menuChoix' + pIdMenu;
			getCursorPosition(e);
			showMenuChoix();
			}
		}
	else
		hideMenuChoix();
	}

function hideMenuChoix()
	{
	if( ( idMenu != '' ) && ( idMenu != null ) )
		document.getElementById(idMenu).style.display = 'none';
	}

function showMenuChoix()
	{
	if( idMenu != '' && document.getElementById( 'typeNavF' ).checked )
		{
		lObj = document.getElementById(idMenu);
			//	noeud relatif au dessus --> lObjBase
			lObjBase = lObj.parentNode;
			while( lObjBase )
				{
				if( lObjBase.style.position == 'relative' ) break;
				lObjBase = lObj.parentNode;
				};
			//	décalage en fonction position div relative
			curX -= getLeft( lObjBase ) +10;
			curY -= getTop( lObjBase ) +10;
		lObj.style.display = 'block';
		lObj.style.top = curY + 'px';
		lObj.style.left = curX + 'px';
		}
	}

function getCursorPosition( e )
	{
	curX = 0;
	curY = 0;
	if( e.pageX || e.pageY )
		{
		curX = e.pageX;
		curY = e.pageY;
		}
	else if( e.clientX || e.clientY ) 	
		{
		curX = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		curY = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
		}
	}

function hideImgNavigation( rangOnglet )
	{
	document.getElementById( 'tab' + rangOnglet ).className = 'cachediv';
	}

function showImgNavigation( rangOnglet )
	{
	document.getElementById( 'tab' + rangOnglet ).className = '';
	}

// pour afficher ou masquer les onglets de editor_menu
function afficheOnglet( rangOngletActif, refresh )
	{
	//	positionnement objets DOM concernés qui ont pour id :
	//		onglet même : ongletX
	//		dialogue de l'onglet : dialogueOngletX
	//	X étant le rang de l'onglet
	var lObj;
	for( var onglet = 0; onglet<7; onglet++ )
		{
		var nomOnglet = 'onglet' + onglet;
		var nomZoneOnglet = 'dialogueOnglet' + onglet;
		if( onglet == rangOngletActif )
			{
			document.getElementById( nomZoneOnglet ).className = '';
			//lObj = document.getElementById( 'option' );
			//if( lObj != null ) lObj.value = rangOngletActif;
			lObj = document.getElementById( nomOnglet );
			if( lObj != null ) lObj.style.backgroundColor = '#bbbbbb';
			}
		else
			{
			document.getElementById( nomZoneOnglet ).className = 'cachediv';
			lObj = document.getElementById( nomOnglet );
			if( lObj != null ) lObj.style.backgroundColor = '#ffffff';
			}
		}
	//	
	if( refresh )
		{
		var _adresseCible = 'scripts/ajaxEditorResetEnvrt.php'
		if(_xmlHttp&&_xmlHttp.readyState!=0)
			_xmlHttp.abort();
		_xmlHttp = getXMLHTTP();
		if(_xmlHttp)
			{	//appel SYNCHRONE ¬à l'url distante
//			_xmlHttp.open( 'GET', _adresseCible + '?onglet=' + rangOngletActif + '&taille=300', false );
			_xmlHttp.open( 'GET', _adresseCible + '?onglet=' + rangOngletActif, false );
			// envoi de la requête
			_xmlHttp.send( null );
			}
		}
	}
function XXXshow( nom, optionRange )
	{
	document.getElementById(nom).className = '';
	lObj = document.getElementById('option');
	if( lObj != null ) lObj.value = optionRange;
	lObj = document.getElementById( 't' + nom );
	if( lObj != null ) lObj.style.backgroundColor = '#bbbbbb';
	}

function XXXhide( nom )
	{
	document.getElementById(nom).className = 'cachediv';
	lObj = document.getElementById( 't' + nom );
	if( lObj != null ) lObj.style.backgroundColor = '#ffffff';
	}

function size_adjust0(delta)
	{
	document.chain_input.fontbase0.value = document.chain_input.fontbase0.value - (- delta);
	}

// Corpus dynamic functions
//	these functions expect the following arrays to be predefined :
//	* nom : the filename of the image ("-r" will be added for the vignette, ".jpg" is assumed)
//	* desc : the label to be displayed either in the infobox or the sidelist
//	* map : center-x, center-y and ray of the circle for the mapping area
//	* loc : x/y coordinates to locate the vignette on the picture
//	* path : relative path where the images are stored (both high resolution and vignette)

function popimage(img)
	{ // concept simplifi√É¬© du site osirisnet.net
	// fonction am√É¬©liorable en limitant le resize selon les tailles de l'√É¬©cran et de l'image
	// les commandes directories=no, status=no, resizable=no ne fonctionnent pas sous FF
	w=open("","image","left=5,top=5,directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=100,height=100");	
	w.document.writeln("<html><head><title>&copy;Projet Rosette</title>");
	w.document.writeln("<script language=javascript>function checksize() {	sw=document.images[0].width+50; sh=document.images[0].height+100; window.resizeTo(sw,sh); window.focus(); }");
    w.document.writeln("</script>");
    w.document.writeln("</head>");
	w.document.writeln("<body onload='checksize()'>");
	w.document.writeln("<a href='javascript:self.close();'><img src='"+img+"' title='fermer/close' alt='fermer/close' border=0></a>");
	w.document.writeln("</body></html>");
	w.document.close();
	}

/**
* 
*/
function extraitImage( formatFichier, divAExtraire )
	{
	var canvas = document.getElementById( "canvas" );
	if( canvas.getContext )
	{
	var ctx = canvas.getContext( "2d" );
	var hieroDiv = document.getElementById( divAExtraire );
	var childCount = hieroDiv.childNodes.length;

	var maxRight = 0;
	var maxBottom = 0;
	for( var childIdx=0; childIdx < childCount; childIdx++ )
		{	// première bcle sur nodes de type IMG pour dimensionner canvas
		var img = hieroDiv.childNodes[childIdx];
		if( img.nodeName == "IMG" )
			{
			if( img.getAttribute( "usemap" ) != null || img.getAttribute( "name" ) == "grid" )
				{
				var xRight = img.offsetLeft + img.offsetWidth;
				var yBottom = img.offsetTop + img.offsetHeight;
				maxRight = Math.max( xRight, maxRight );
				maxBottom = Math.max( yBottom, maxBottom );
				}
			}
		}
		canvas.width = maxRight;
		canvas.height = maxBottom + 15;

		if( formatFichier == 'jpg' )
			{
			ctx.fillStyle = 'rgb(255,255,255)';
			ctx.fillRect(0,0,canvas.width,canvas.height);
			}

		var laDate = new Date(); 
		var copyright = '© ' + laDate.getFullYear() + ' projet Rosette';
		ctx.font='italic 300 10px Unknown Font, sans-serif'; 
		ctx.fillStyle = 'rgb(0,0,0)';
		ctx.fillText(copyright,10,maxBottom+10);

		for( var childIdx=0; childIdx < childCount; childIdx++ )
			{	// seconde bcle sur nodes de type IMG pour tracé final
			var img = hieroDiv.childNodes[childIdx];
			if( img.nodeName == 'IMG' )
				{
				if( img.getAttribute( "usemap" ) != null || img.getAttribute( "name" ) == "grid" )
					ctx.drawImage( img, img.offsetLeft, img.offsetTop );
				}
			}

		if( formatFichier == 'png' )
			Canvas2Image.saveAsPNG( canvas, true );
		else
			Canvas2Image.saveAsJPEG( canvas, true );
		}
	else
		alert("Votre navigateur ne supporte pas cette fonction");
	}

/**
* maps du module graphique
*/
var div = 
		{
		show: function()
			{
			var i = arguments.length-1;
			for( ; i>=0; i-- )
				document.getElementById(arguments[i]).className = 'frameDownSelect';
//alert( '...show( ' + arguments[0] );
			},
		hide: function() 
			{
			var i = arguments.length-1;
			for( ; i>=0; i-- )
				document.getElementById(arguments[i]).className = 'frameDown';
//alert(arguments[0] + '...hide opacity ' + document.getElementById(arguments[0]).style.opacity );
			}
		}

// end of Rosette JS functions -->
