/*
 * $Id: miscTools.js,v 1.1 2008/02/22 10:44:44 vrusu Exp $
 * $Revision: 1.1 $
 * $Date: 2008/02/22 10:44:44 $
 */
 
// *** COMMON CROSS-BROWSER COMPATIBILITY CODE ***

var isDOM=document.getElementById?1:0;
var isIE=document.all?1:0;
var isNS4=navigator.appName=='Netscape'&&!isDOM?1:0;
var isIE4=isIE&&!isDOM?1:0;
var isOp=window.opera?1:0;
var isDyn=isDOM||isIE||isNS4;


// convert all characters to lowercase to simplify testing
var agt=navigator.userAgent.toLowerCase();

// *** BROWSER VERSION ***
// Note: On IE5, these return 4, so use is_ie5up to detect IE5.
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie3    = (is_ie && (is_major < 4));
var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
var is_ie4up  = (is_ie && (is_major >= 4));
var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie5up  = (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);



/* --------------------------------------------------
	Population automatique des proprietes d'un objet
*/
function addProps(obj, data, names, addNull) {
	for (var i = 0; i < names.length; i++) if(i < data.length || addNull) obj[names[i]] = data[i];
}




/* --------------------------------------------------
	Recherche un objet DHTML d'ID donnee et le renvoit (ou null si inexistant)
*/
function getObj(id) {
	if (isDOM && document.getElementById(id)!=null) {
		return document.getElementById(id);
	}
	
	// on cherche dans document.layers (Netscape)
	if (document.layers && eval("document."+id)!=null) {
		return eval("document."+id);
	}
	
	// on cherche dans document.all
	if (isIE && eval("typeof(document.all[id])")!="undefined") {
		return document.all[id];
	}

	
	// sinon on cherche dans les formulaires
	for(var i=0; i<document.forms.length; i++) {
		if (eval("typeof(document.forms[i]."+id+")")!="undefined")
			return eval("document.forms[i]."+id);
	}

	// sinon on cherche dans les frames
	if (typeof(document.frames)!="undefined") {
		for(var i=0; i<document.frames.length; i++) {
			if (eval("typeof(document.frames[i]."+id+")")!="undefined")
				return eval("document.frames[i]."+id);
		}
	}

	// sinon on cherche dans les images
	for(var i=0; i<document.images.length; i++) {
		if (eval("typeof(document.images[i]."+id+")")!="undefined")
			return eval("document.images[i]."+id);
	}

	// pas trouve !!
	return null;
}

function focusIfExists(id) {
	if (getObj(id) && getObj(id).focus) {
		getObj(id).focus();
	}
}

function focusFieldIfExists(f, name) {
	if (getField(f, name) && getField(f, name).focus) {
		getField(f, name).focus();
	}
}

function getRadioValue(radioButtonOrGroup) {
  var value = null;
  if (radioButtonOrGroup.length) { // group 
    for (var b = 0; b < radioButtonOrGroup.length; b++)
      if (radioButtonOrGroup[b].checked)
        value = radioButtonOrGroup[b].value;
  }
  else if (radioButtonOrGroup.checked)
    value = radioButtonOrGroup.value;
  return value;
}


// Change l'etat de toutes les chechboxes de nom donne
function changeCheckboxesState(form, cbName, state) {
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].name==cbName) {
			form.elements[i].checked = state;
		}
	}	
}


// Change l'etat de toutes les chechboxes dont le nom commence par le prefixe donne
function changeCheckboxesStatePrefix(form, cbNamePrefix, state) {
	for (var i = 0; i < form.elements.length; i++) {
		var elname = form.elements[i].name;
		if (typeof(elname)!="undefined" && elname.indexOf(cbNamePrefix)==0) {
			form.elements[i].checked = state;
		}
	}	
}

// Change l'etat de toutes les chechboxes dont l'id commence par le prefixe donne
function changeCheckboxesStatePrefixId(form, cbNamePrefix, state) {
	for (var i = 0; i < form.elements.length; i++) {
		var elId = form.elements[i].id;
		if (typeof(elId)!="undefined" && elId.indexOf(cbNamePrefix)==0) {
			form.elements[i].checked = state;
		}
	}	
}

/* --------------------------------------------------
	Fonction qui renvoie la taille d'un element si elle est inferieure
	? une taille donnee, ou la taille maximum sinon
*/
function normalizeElementHeight(obj, max) {
	var h = obj.scrollHeight;
	if (h > max)
	 h = max;

	return h+"px";
}


/* --------------------------------------------------
	Fonction qui renvoie un objet contenant la position (x, y) d'un objet
*/
function getDim(el){
	if (typeof(el.offsetLeft)=="undefined")
		return {x:0,y:0};

	for (var lx=0,ly=0;el!=null;
		lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
	return {x:lx,y:ly}
}


/* --------------------------------------------------
	Gestion des actions sur le onload du document
*/
var onLoadActions = new Array();

function addOnLoadAction(action)
{
	if (action!=null && action!="")
		onLoadActions[onLoadActions.length] = action;
}

function executeOnLoadActions()
{
	var i;
	for(i=0; i<onLoadActions.length; i++)
		eval(onLoadActions[i]);
}



var displayWaitMessageOnURLChange = false;

/* --------------------------------------------------
	Simule un clic sur un lien
*/
function goToURL(u, targetName)
{
	if (typeof(u)=="undefined" || u==null || u=="")
		return true;

	if (u.indexOf("javascript:")==0)
	{
		var jscode = u.substring(11);
		if (eval(jscode))
			return true;
		else
			return false;
	}

	if (typeof(targetName)!="undefined" && targetName!=null){
		var w = window.open(u, targetName);
		w.focus();
  }
  else{
  		if (displayWaitMessageOnURLChange)
  			displayWaitMessage();

    	window.location.href=u;
   }
}


/* ---------------------------------------
	Ouverture d'un lien dans la fenetre parente
*/
function goToURLOpener(u) {
	top.opener.goToURL(u);
	top.opener.focus();
}

/* --------------------------------------------------
	Soumission d'un formulaire en javascript
	(avec appel du callback onsubmit)
*/
function submitForm(f) {
	var result = true;

	if (typeof(f.onsubmit)!="undefined" && f.onsubmit!=null)
		result = f.onsubmit();

	try {
	if (result)
		f.submit();
	}
	catch(e) {}

	return result;
}




/* --------------------------------------------------
	Callback appele sur onKeyPressed pour executer une action JSsi ENTER est tapee
*/
function executeOnEnter(action, event) {
	var key = event.keyCode;

	if (key == 13) {
		eval(action);
		return false;
	}

	return true;
}



/* --------------------------------------------------
	Callback appelee sur onKeyPressed pour soumettre le formulaire si ENTER est tapee
	obj : objet DHTML du champ text (typiquement : this)
	beforeSubmitAction : action facultative a executer avant le submit
						 Dans ce cas le submit n'a lieu que si l'action retourne vrai ou rien.
						 Sil elle retoute faux, le submit n'a pas lieu.
*/
function submitOwnerFormOnEnter(obj, beforeSubmitAction) {
    var key = event.keyCode;

	if (key == 13) {
		var result = true;
		if (typeof(beforeSubmitAction)!="undefined" && beforeSubmitAction!=null && beforeSubmitAction!="")
			result = eval(beforeSubmitAction);

		if (typeof(result)=="undefined" || result)
		submitForm(obj.form);
		
		return false;
	}

	return true;
}

/* --------------------------------------------------
	Va au champ du formulaire suivant (simule TAB) sur un appui sur ENTER
*/
function tabOnEnter (field, evt) {
	var keyCode = document.layers ? evt.which : document.all ? 
	evt.keyCode : evt.keyCode;
	if (keyCode != 13)
		return true;
	else {
		var nextField = getNextElement(field);
		nextField.focus();
		if (typeof(nextField.select)!="undefined")
			nextField.select();
			
		return false;
	}
}


function getNextElement(field) {
	var fieldFound = false;
	var form = field.form;

	for (var e = 0; e < form.elements.length; e++) {
		if (fieldFound && form.elements[e].type != 'hidden')
			break;
		if (field == form.elements[e])
			fieldFound = true;
	}

	return form.elements[e % form.elements.length];
}




/* --------------------------------------------------
	Ouvre une fenetre de taille donnee, centree sur l'cran
*/
function openCenteredWindow(name, url, w, h, notResizable)
{
	var features = ",directories=no,location=no,status=no,toolbar=no,scrollbars=yes";
	if (notResizable)
		features += ",resizable=no";
	else
		features += ",resizable=yes";
	var win = window.open(url, name, getCenteringWinPos(w,h)+features, true);
	win.focus();
	return win;
}

function getCenteringWinPos(w,h){
    var sW = parseInt(screen.availWidth, 10);
    var sH = parseInt(screen.availHeight, 10);
    if (sW / sH > 2)    // si double ecran
        sW = Math.round(sW/2);

    var x = Math.round((sW - w)/2);
    var y = Math.round((sH - h)/2);

    return "width="+w+",height="+h+",top="+y+",left="+x;
}

function openPopup(url, name) {
	openCenteredWindow(name, url, 600, 450, false);
	return false;
}


/* --------------------------------------------------
	Simule le comportement d'une fenetre modale a partir d'une fenetre
	"fille".
	
	childWindow : objet fenetre fille
	onCloseExpression : expression javascript facultative ? evaluer lorsque la fenetre pseudo-modale sera fermee.
*/
var forceFocusWindow = null;
var simulateModalOnCloseExpression = null;

function simulateModalBehavior(childWindow, onCloseExpression) {
	try {
		forceFocusWindow = childWindow;
		simulateModalOnCloseExpression = onCloseExpression;
		
		window.onfocus=focusChildModal;
		forceFocusUntilClosed();	
	}
	catch(e)  {
	}
}

function forceFocusUntilClosed() {
	try {
		if (typeof(forceFocusWindow)=="undefined" || forceFocusWindow==null)
			return;
			
		if (forceFocusWindow.closed) {
			forceFocusWindow=null;
			window.onfocus=null;
			window.focus();
			
			// Callback
			if (typeof(simulateModalOnCloseExpression)!="undefined" && simulateModalOnCloseExpression!=null && simulateModalOnCloseExpression!="") {
				eval(simulateModalOnCloseExpression);
				simulateModalOnCloseExpression = null;
			}
			return;
		}
		
		setTimeout("forceFocusUntilClosed();", 300);
	}
	catch(e) {
		forceFocusWindow=null;
		try {
			// Callback
			if (typeof(simulateModalOnCloseExpression)!="undefined" && simulateModalOnCloseExpression!=null && simulateModalOnCloseExpression!="") {
				eval(simulateModalOnCloseExpression);
				simulateModalOnCloseExpression = null;
			}
		} catch(e) {
		}
	}
}

function focusChildModal() {
	try {
		if (typeof(forceFocusWindow)=="undefined" || forceFocusWindow==null || forceFocusWindow.closed)
			return;

		forceFocusWindow.focus();
		setTimeout("forceFocusWindow.focus();",50);
	}
	catch(e) {}
	
	return false;
}


function closePopupWindowWhenOpenerClosed() {
	try {
		if (	typeof(window.opener)=="undefined"
			||	window.opener==null
			||	window.opener.closed
			||	window.opener.forceFocusWindow!=window) {
			window.close();
		}
	}
	catch(e) {}
}


/* --------------------------------------------------
	Ouvre une fenetre modale de choix d'elements et retourne le resultat de celle-ci
*/
function openStandardModalSelector(url, parameters) {
	if (typeof(showModalDialog)=="undefined") {
		alert("Attention : impossible de creer une fenetre modale avec ce navigateur !\n");
		return;		
	}
	else
		return showModalDialog(url, parameters, "dialogWidth:350px;dialogHeight:500px;center:yes;scroll:no;status:no;resizable:yes;");
}







/* --------------------------------------------------
	Affiche une fenetre popup contenant l'image e previsualiser
*/
var zoomImgObj;
var zoomImgParameters;

function showPopupImage(imgUrl, imgTitle) {

	zoomImgParameters = { href : imgUrl, title: imgTitle };

	zoomImgObj = new Image();
	zoomImgObj.onload = openPopupImage;
	zoomImgObj.src = imgUrl;
}

function openPopupImage() {	
	var w = zoomImgObj.width + 5;
	var h = zoomImgObj.height + 30;
	
	if (w==0 && h==0) {
		setTimeout("openPopupImage();", 250);
	}

	showModalDialog("zoomImagePopup.htm", zoomImgParameters, "dialogWidth:"+w+"px;dialogHeight:"+h+"px;center:yes;scroll:no;status:no;resizable:yes;");
}




/* ----------------------------------------------------
	Retaille un image e une taille maximum
*/
var imgAutoId = 0;
function autoResizeIfBigger(img, maxW, maxH) {
	var w = img.width;
	var h = img.height;

	if (w==0 && h==0) {
		if (typeof(img.id)=="undefined" || img.id==null || img.id=="") {
			imgAutoId++;
			img.id = "RSIMG"+imgAutoId;
		}
		
		setTimeout("autoResizeIfBigger(getObj('"+img.id+"'),"+maxW+","+maxH+")", 1250);
		return true;
	}
	
	if (w > maxW) {
		h = h*(maxW/w);
		w = maxW;	
	}

	if (h > maxH) {
		w = w*(maxH/h);
		h = maxH;	
	}

	img.width = Math.round(w);
	img.height = Math.round(h);
	
	if (typeof(img.style.visibility)!="undefined")
		img.style.visibility="visible";
	
	return true;
}




// -------------------------
function toDo() {
	alert("Cette action n'est pas encore implementee !")
}



/* ----------------------------------------------------
	Cree dynamiquement un layer
*/
function createLayer(id, position, x, y, w, h, display, visibility) {
	// Cree le layer
	var layer = document.createElement('DIV');
	
	if (typeof(position)!="undefined" && position!=null)
		layer.style.position = position;
		
	if (typeof(x)!="undefined" && x!=null)
		layer.style.left = x+"px";

	if (typeof(y)!="undefined" && y!=null)
		layer.style.top = y+"px";

	if (typeof(w)!="undefined" && w!=null)
		layer.style.width = w+"px";

	if (typeof(h)!="undefined" && h!=null)
		layer.style.height = h+"px";
			
	if (typeof(display)!="undefined" && display!=null)
		layer.style.display = display;

	if (typeof(visibility)!="undefined" && visibility!=null)
		layer.style.visibility = visibility;

	document.body.appendChild(layer);
			
	return layer;
}



// ------------------------------------------------------
function setCookie (cookieName, cookieValue, expires, path, domain, secure) {
	document.cookie = 
		escape(cookieName) + '=' + escape(cookieValue) 
		+ (expires ? '; EXPIRES=' + expires.toGMTString() : '')
		+ (path ? '; PATH=' + path : '')
		+ (domain ? '; DOMAIN=' + domain : '')
		+ (secure ? '; SECURE' : '');
}

//------------------------------------------------------
function getCookie (cookieName) {
	var cookieValue = null;
	var posName = document.cookie.indexOf(escape(cookieName) + '=');
	if (posName != -1) {
		var posValue = posName + (escape(cookieName) + '=').length;
		var endPos = document.cookie.indexOf(';', posValue);
		if (endPos != -1)
			cookieValue = unescape(document.cookie.substring(posValue, endPos));
		else
			cookieValue = unescape(document.cookie.substring(posValue));
	}
	return cookieValue;
}


function parseQueryString (str) {
  str = str ? str : location.search;
  var query = str.charAt(0) == '?' ? str.substring(1) : str;
  var args = new Object();
  if (query) {
	var fields = query.split('&');
	for (var f = 0; f < fields.length; f++) {
	  var field = fields[f].split('=');
	  args[unescape(field[0].replace(/\+/g, ' '))] = unescape(field[1].replace(/\+/g, ' '));
	}
  }
  return args;
}


function getQueryString(str) {
	var pos = str.indexOf("?");
	if (pos<0)
		return "";
	return str.substring(pos+1);
}

function getQueryParameterValue(str, name) {
	var args = parseQueryString(str);
	return args[name];
}

function copyQueryParametersToForm(queryStr, f) {
	if (queryStr==null || queryStr=="")
		return;
	
	// recuperation des parametres	
	var args = parseQueryString(queryStr);
	
	// recopie dans le formulaire
	for(var name in args) {
		var v = args[name];

		var field = getField(f, name);
		if (f==null) {
			// ajout dynamique du champ
			addField(f, "hidden", name, v);
		}
		else
			field.value = v;
	}	
}


/* ------------------------------------------
	Gestion dynamique des formulaires
*/
function addField(form, fieldType, fieldName, fieldValue) {
  if (document.getElementById) {
	var input = document.createElement('INPUT');
	  if (document.all) { // what follows should work 
						  // with NN6 but doesn't in M14
		input.type = fieldType;
		input.name = fieldName;
		input.value = fieldValue;
	  }
	  else if (document.getElementById) { // so here is the
										  // NN6 workaround
		input.setAttribute('type', fieldType);
		input.setAttribute('name', fieldName);
		input.setAttribute('value', fieldValue);
	  }
	form.appendChild(input);
  }
}
function getField (form, fieldName) {
  if (!document.all)
	return form[fieldName];
  else  // IE has a bug not adding dynamically created field 
		// as named properties so we loop through the elements array 
	for (var e = 0; e < form.elements.length; e++)
	  if (form.elements[e].name == fieldName)
		return form.elements[e];
  return null;
}        
function removeField (form, fieldName) {
  var field = getField (form, fieldName);
  if (field && !field.length)
	field.parentNode.removeChild(field);
}
function toggleField (form, fieldName, value) {
  var field = getField (form, fieldName);
  if (field)
	removeField (form, fieldName);
  else
	addField (form, 'hidden', fieldName, value);
}

/*
 * Echange les contenus respectifs de deux lignes de tableau <tr> de meme structure
 */
function swapTrContents(tr1, tr2) {
	for(var i=0; i<tr1.cells.length; i++) {
		var c1 = tr1.cells[i];
		var c2 = tr2.cells[i];
		
		var c1Cont = c1.innerHTML;
		var c2Cont = c2.innerHTML;
		c1.innerHTML = "";
		c2.innerHTML = c1Cont;
		c1.innerHTML = c2Cont;
	}
}



function getSelectValue(field) {
	if (field != null) {
		if (field.selectedIndex<0 || field.options.length<1)
			return null;
			
		return field.options[field.selectedIndex].value;
	}
}

function setSelectValue(field, value, text, force) {
	// on cherche d'abord dans les options existantes
	for(var i=0; i<field.options.length; i++) {
		if (field.options[i].value == value) {
			field.selectedIndex = i;
			return;
		}
	}
	
	if (force) {		
		var opt = new Option(text, value);
		try {
			field.add(opt);
		}
		catch(e) {
			field.options[field.options.length] = opt;
		}
		opt.text = text;
		opt.value = value;			
		field.selectedIndex = field.options.length-1;
	}
}


var showCalendarSelect_hiddenField = null;
var showCalendarSelect_selectField = null;

function showCalendarSelect(selectField, hiddenField, anchorname, format) {
	hiddenField.value = getSelectValue(selectField);
	showCalendarSelect_selectField = selectField;
	showCalendarSelect_hiddenField = hiddenField;
	showCalendar(hiddenField, anchorname, "showCalendarSelect_returnFunction", format);
}

function showCalendarSelect_returnFunction(y, m, d) {
	var dt = new Date(y,m-1,d,0,0,0);
	var val = showCalendarSelect_hiddenField.value = formatDate(dt, window.CalendarPopup_dateFormat);
	setSelectValue(showCalendarSelect_selectField, val, val, true);
	return true;
}


                     
// ----------------------------------------------------------------------------
// Pour memoriser la position du scroll il faut avoir les champs
// coordHolderX et coordHolderY dans le formulaire
// et mettre le nom du formulaire dans la variable Javascript "scrollPosFormId"

var scrollPosFormIds = new Array();
var scrollPosFormTimer = null;

function scrollController_GetCoords()
{
  if (scrollPosFormIds==null || scrollPosFormIds.length==0)
	return;

  var scrollX, scrollY;
  
  if (document.all)
  {
     if (!document.documentElement.scrollLeft)
        scrollX = document.body.scrollLeft;
     else
        scrollX = document.documentElement.scrollLeft;
           
     if (!document.documentElement.scrollTop)
        scrollY = document.body.scrollTop;
     else
        scrollY = document.documentElement.scrollTop;
  }   
  else
  {
     scrollX = window.pageXOffset;
     scrollY = window.pageYOffset;
  }

  for(var i=0; i<scrollPosFormIds.length; i++) {
	  var f = getObj(scrollPosFormIds[i]);
	  f.coordHolderX.value = scrollX;
	  f.coordHolderY.value = scrollY;
  }
  
  return true;  
}

function scrollController_Scroll() {
  if (scrollPosFormIds==null || scrollPosFormIds.length==0)
	return;
	
  var x=0;
  var y=0;
  for(var i=0; i<scrollPosFormIds.length; i++) {
	  var f = getObj(scrollPosFormIds[i]);
	  x = f.coordHolderX.value;
	  y = f.coordHolderY.value;	  
	  if (x!="")
	  	break;
  }
  window.scrollTo(x, y);
  scrollPosFormTimer = setTimeout("window.scrollTo("+x+","+y+")", 50);
  
  return true;
}


function scrollController_clearTimer() {
	if (scrollPosFormTimer!=null) {
		clearTimeout(scrollPosFormTimer);
		scrollPosFormTimer=null;
	}
}

window.onscroll = scrollController_GetCoords;
window.onkeypress = scrollController_GetCoords;
window.onclick = scrollController_GetCoords;
//window.onload = scrollController_Scroll;
addOnLoadAction("scrollController_Scroll();");




/* --------------------------------------------------
	Scrolle la fenetre jusqu'a la position d'un objet
*/
function scrollWindowTo(obj) {
	scrollController_clearTimer();
	window.scrollTo(0, getDim(obj).y);
}



/* --------------------------------------------------
	Scrolle la fenetre jusqu'a la position d'un objet
*/
function scrollWindowToCenter(obj) {
	if (typeof(document.body.clientHeight)=="undefined")
		return;

	var deltaH = Math.max((document.body.clientHeight - obj.clientHeight) / 2, 0);
	window.scrollTo(0, getDim(obj).y - deltaH);
}



// ----------------------------------------------------------------------------

// Formattage d'un nombre + arrondi e nb decimales
function formatteArrondi(origValue, nbDec) {
	var k = Math.pow(10, nbDec);
	
	var value = Math.round(origValue*k)/k;
	if (isNaN(value)) {
		alert("\""+origValue+"\" n'est pas un montant correct !");
		return formatteSeulement(0, nbDec);
	}

	return formatteSeulement(value, nbDec);
}


function formatteSeulement(value, nbDec) {
	value = "" + value;
	var posDot = value.indexOf(".");
	if (posDot<0 && nbDec>0) {
		value+=".";
		for(var i=0; i<nbDec; i++)
			value+="0";
	}
	else {
		var d = value.length - posDot;
		for(var i=0; i<1+nbDec-d; i++)
			value+="0";
	}

	value = value.replace(".", ",");

	return value;
}





///////////////////////////////////////////////////

var normalBodyClassName = null;

function blurBody() {
	var body = getObj('SPpage');
	normalBodyClassName = body.className;
	body.className='blurred';
}


function unblurBody() {
	var body = getObj('SPpage');
	if (normalBodyClassName!=null) {
		body.className=normalBodyClassName;
		normalBodyClassName=null;
	}
}



function displayWaitMessage(htmlContent, imgURL)
{
/*	var img = getObj("WaitAnimation");
	var d = new Date();
	img.src = img.src+"?m="+d.getTime();
*/
	var obj = getObj("DynamicWaitMsg");
	obj.style.visibility = "visible";
	obj.style.display = "block";	
	centerLayer(obj);	
	
//	blurBody();
}

function displayWaitMessage2(htmlContent, imgURL)
{
	var html = '<table border="0" cellspacing="10" cellpadding="0"><tr><td align="center" class="waitMessageText">';
	if (imgURL)
		html += '<img src="'+imgURL+'" alt=""></td><td align="center" class="waitMessageText">';
	html += htmlContent;
	html += '</td></tr></table>';

	var obj = document.all["DynamicWaitMsg"];
	if (obj) {
		obj.innerHTML = html;
	}
	else
		document.body.insertAdjacentHTML('beforeEnd', '<div id="DynamicWaitMsg" class="waitMessageZone" style="position:absolute;z-index:30000; visibility:hidden;">'+html+'</div>');

	var obj = document.all["DynamicWaitMsg"];
	centerLayer(obj);
	obj.style.visibility = "visible";
}


var isCurrentlySubmitting = false;
var isSubmitingOnEnter = false;
var forbidWaitMessage = false;

function hideWaitMessage()
{
	isCurrentlySubmitting = false;
	var obj = getObj("DynamicWaitMsg");
	if (obj) {
		obj.style.display = "none";
		obj.style.visibility = "hidden";
	}
}

function displayWaitOnSubmit() {
	if (forbidWaitMessage)
		return true;

	if (isCurrentlySubmitting) {
		// si deje en train de soumettre => on ne fait rien
		if (!isSubmitingOnEnter)
			alert("Traitement en cours ! Veuillez patienter...");
		// sinon pas de message d'erreur
		
		return false;
	}
	isCurrentlySubmitting = true;

	displayWaitMessage();

	return true;
}


function onClickAndDisplayWaitMessage() {
	var result = this.oldonclick();
	if (typeof(result)!="undefined" && !result)
		return result;

	displayWaitMessage();
	return true;
}

function addShowWaitMessageOnEachLink() {
	var locationTest = location.href+"#";

	for(var i=0; i<document.links.length; i++) {
		var link = document.links[i];
		
		if (typeof(link.href)=="undefined" || link.href=="" || link.href=="#" || link.href=="javascript:" || link.href.indexOf(locationTest)==0)
			continue;			
			
		if (link.target!="" && link.target!="_self")
			continue;
			
//		alert(link.href+" / "+document.href);
			
		if (link.onclick==null) {
			link.onclick = displayWaitMessage;
		}
		else {
			link.oldonclick = link.onclick;
			link.onclick = onClickAndDisplayWaitMessage;
		}
	}
}

/* --------------------------------------------------
	Centre un calque positionne en absolu dans la fenetre
*/
function centerLayer(obj)
{
	initFixing("DynamicWaitMsg", 0.5, 0.6);
}



var Opera = window.opera ? true : false;
var fixedElement, elWidth, elHeight, tid;

function initFixing (id, kx, ky) {
  if (document.layers) {
    fixedElement = document[id];
    elWidth = fixedElement.document.width;
    elHeight = fixedElement.document.height;
  }
  else if (document.getElementById && !Opera) {
    fixedElement = document.getElementById(id);
    elWidth = fixedElement.offsetWidth;
    elHeight = fixedElement.offsetHeight;
  }
  else if (document.all && !Opera) {
    fixedElement = document.all[id];
    elWidth = fixedElement.offsetWidth;
    elHeight = fixedElement.offsetHeight;
  }
  else if (Opera) {
    fixedElement = document.getElementById(id);
    elWidth = fixedElement.style.pixelWidth;
    elHeight = fixedElement.style.pixelHeight;
  }
  fixPosition(kx, ky);
}

function fixPosition(kx, ky) {
  if (document.layers) {
    fixedElement.left = Math.floor(window.pageXOffset + (window.innerWidth - elWidth) * kx);
    fixedElement.top = Math.floor(window.pageYOffset + (window.innerHeight - elHeight) * ky);
  }
  else if (document.all && !Opera) {
    fixedElement.style.pixelLeft = Math.floor(document.body.scrollLeft + (document.body.clientWidth - elWidth) * kx);
    fixedElement.style.pixelTop = Math.floor(document.body.scrollTop + (document.body.clientHeight - elHeight) * ky);
  }
  else if (document.getElementById && !Opera) {
    if (elWidth == 0)  // workaround for bug of NN6 to compute width
      elWidth = fixedElement.offsetWidth;
    fixedElement.style.left = Math.floor(window.pageXOffset + (window.innerWidth - elWidth)* kx) + 'px';
    fixedElement.style.top = Math.floor(window.pageYOffset + (window.innerHeight - elHeight)* ky) + 'px';
  }
  else if (Opera) {
    fixedElement.style.pixelLeft = Math.floor(window.pageXOffset + (window.innerWidth - elWidth)* kx);
    fixedElement.style.pixelTop = Math.floor(window.pageYOffset + (window.innerHeight - elHeight)* ky);
  }
}




function initFixing2(id, x, y) {
  if (document.layers) {
    fixedElement = document[id];
    elWidth = fixedElement.document.width;
    elHeight = fixedElement.document.height;
  }
  else if (document.getElementById && !Opera) {
    fixedElement = document.getElementById(id);
    elWidth = fixedElement.offsetWidth;
    elHeight = fixedElement.offsetHeight;
  }
  else if (document.all && !Opera) {
    fixedElement = document.all[id];
    elWidth = fixedElement.offsetWidth;
    elHeight = fixedElement.offsetHeight;
  }
  else if (Opera) {
    fixedElement = document.getElementById(id);
    elWidth = fixedElement.style.pixelWidth;
    elHeight = fixedElement.style.pixelHeight;
  }
  fixPosition2(x, y);
}

function fixPosition2(x, y) {
  if (document.layers) {
    fixedElement.left = Math.floor(window.pageXOffset + Math.min(x, window.innerWidth - elWidth));
    fixedElement.top = Math.floor(window.pageYOffset + Math.min(y, window.innerHeight - elHeight));
  }
  else if (document.all && !Opera) {
    fixedElement.style.pixelLeft = Math.floor(document.body.scrollLeft + Math.min(x,document.body.scrollWidth - elWidth));
    fixedElement.style.pixelTop = Math.floor(document.body.scrollTop + Math.min(y,document.body.scrollHeight - elHeight));
  }
  else if (document.getElementById && !Opera) {
    if (elWidth == 0)  // workaround for bug of NN6 to compute width
      elWidth = fixedElement.offsetWidth;
    fixedElement.style.left = Math.floor(window.pageXOffset + Math.min(x, window.innerWidth - elWidth)) + 'px';
    fixedElement.style.top = Math.floor(window.pageYOffset + Math.min(y, window.innerHeight - elHeight)) + 'px';
  }
  else if (Opera) {
    fixedElement.style.pixelLeft = Math.floor(window.pageXOffset + Math.min(x, window.innerWidth - elWidth));
    fixedElement.style.pixelTop = Math.floor(window.pageYOffset + Math.min(y, window.innerHeight - elHeight));
  }
}


// --- preload d'images
function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}


// -- select and focus field
var selectFocusFieldObj = null;
function selectFocusField(field) {
	
	if (typeof(field.select)!="undefined")
		field.select();
	if (typeof(field.focus)!="undefined") {
		field.focus();	
	}
	if (selectFocusFieldObj != field) {
		selectFocusFieldObj = field;
		setTimeout("selectFocusField(selectFocusFieldObj)",150);		
	}
	else
		selectFocusFieldObj = null;
}


function showHideBlock(id, show) {
	var obj = getObj(id);

	if (obj==null)
		return;
		
	if (show) {
		obj.style.display = "block";
	}
	else {
		obj.style.display = "none";
	}
}

function showHideInline(id, show) {
	var obj = getObj(id);

	if (obj==null)
		return;
		
	if (show) {
		obj.style.display = "inline";
	}
	else {
		obj.style.display = "none";
	}
}


function showHideTR(id, show) {
	var obj = getObj(id);
	showHideTRObj(obj, show);
}


function showHideTRObj(obj, show) {
	if (obj==null)
		return;
		
	if (show) {
		obj.style.display = isIE ? "inline-block" : "table-row";
	}
	else {
		obj.style.display = "none";
	}
}


function truncateField(field, maxLength, event, leftCharsZoneId) {
	var len = field.value.length;

	if (event!=null) {
		var key = event.keyCode;

		if (len>maxLength) {
			field.value = field.value.substring(0, maxLength);
		}
	}
	
	if (typeof(leftCharsZoneId)!="undefined" && leftCharsZoneId!=null && leftCharsZoneId!="") {
		getObj(leftCharsZoneId).innerHTML = Math.max(0, (maxLength-len));
	}
	
	return true;
}



function addToArray(arr, value) {
	arr[arr.length] = value;
}

function selectAllOptions(obj, val) {
	var allOptions = obj.options;
	for ( var i = 0; i < allOptions.length; i++ ) {
		allOptions.selected = val;
	}
}

// -------------------------------------------------
// check that at leat one checkbox is chekced. 
// 
// f : the form
// prefix : the prefix of the checkbox name
// -------------------------------------------------
function checkCheckboxes(f, prefix) {
	var atLeastOne = false;
	for (i=0 ; i < f.elements.length ; i++) {
		var elname = f.elements[i].name;
		if (typeof(elname)!="undefined" && elname.indexOf(prefix)==0) {
			if (f.elements[i].checked) {
				atLeastOne = true;
			}
		}
	}
	return atLeastOne;
}



/*
	Return all elements which name is eltName and attrName attribute value is attrValue.
*/
function getElementsByAttributeValue(eltName, attrName, attrValue) {
	var elts = document.getElementsByTagName(eltName);
	var results = new Array();
	
	// Attribute filter
	for(var i=0; i<elts.length; i++) {
		var elt = elts[i];
		
		var eltAttrValue = elt.getAttribute(attrName);
		if (typeof(eltAttrValue)=="undefined" || eltAttrValue==null)
			continue;
			
		if (eltAttrValue != attrValue)
			continue;
			
		results[results.length] = elt;
	}
	
	return results;
}

/*
	Return the first element which name is eltName and attrName attribute value is attrValue.
*/
function getElementByAttributeValue(eltName, attrName, attrValue) {
	var results = getElementsByAttributeValue(eltName, attrName, attrValue);
	if (results==null || results.length<1)
		return null;
		
	return results[0];
}


/*
	Button highlight.
*/
function highlightButton(id, state) {
	if (getObj(id)){
		if (state == 'true') {
			// getObj(id).className = "button highligh";
			getObj(id).style.color = "red";
			getObj(id).style.border = "1px solid red";
		} else {
			// getObj(id).className = "button";
		}
	}
}

var buttonsToHighlight = new Array();

function addModificationDetection(form, modifiedFlagInput, buttonId) {
	addToArray(buttonsToHighlight, new Array(buttonId, modifiedFlagInput, true));
	highlightModificationButtons();
	addOnChangeCallbackToFormInputs(form, setSomethingModified);
}

function addButtonToHighlight(form, modifiedFlagInput, buttonId) {
	addToArray(buttonsToHighlight, new Array(buttonId, modifiedFlagInput, false));
	highlightModificationButtons();
}

function setSomethingModified(event) {
	//FIXME ne modifier que le champ lie a la callback
	for(var i=0; i < buttonsToHighlight.length; i++) {
		if (!buttonsToHighlight[i][2])	// if one cannot modify
			continue;
		var modifiedFlagInput = buttonsToHighlight[i][1];
		modifiedFlagInput.value = "true";
	}
	highlightModificationButtons();
}

function highlightModificationButtons() {
	for(var i=0; i < buttonsToHighlight.length; i++) {
		var buttonId = buttonsToHighlight[i][0];
		var modifiedFlagInput = buttonsToHighlight[i][1];
		var modified = modifiedFlagInput.value;
		/*
		alert(buttonId.name);
		alert(modifiedFlagInput.name);
		alert(modified);
		*/
		
		highlightButton(buttonId, (modified || modified=="true"));
	}
}

function addOnChangeCallbackToFormInputs(form, callback) {
	var addonchange, addonclick, addonkeypress;

	for (var i = 0; i < form.elements.length; i++) {
		var elt = form.elements[i];
		if (typeof(elt.type)=="undefined")
			continue;

		addonchange=false;
		addonclick=false;
		addonkeypress=false;

		switch(elt.type) {
			case "text":
			case "password":
			case "textarea":
			case "file":
				addonchange = true;
				addonkeypress = true;
				break;

			case "select-one":
			case "select-multiple":
				addonchange = true;
				addonkeypress = true;
				break;
				
				
			case "radio":
			case "checkbox":
				addonchange = true;
				addonclick = true;
				break;				
			
			case "hidden":			
			default:
				// nothing to do!
		}
		
		// onkeypress callback
		if (addonkeypress) {
			if (typeof(elt.onkeypress)!="undefined" && elt.onkeypress!=null && elt.onkeypress!="") {
				if (typeof(elt.onkeypresses)=="undefined")
					elt.onkeypresses = new Array( elt.onkeypress );
				addToArray(elt.onkeypresses, callback);
				elt.onkeypress = executeMultipleOnKeyPresses;
			}
			else {
				elt.onkeypress = callback;
			}
		}
		
		// onchange callback
		if (addonchange) {
			if (typeof(elt.onchange)!="undefined" && elt.onchange!=null && elt.onchange!="") {
				if (typeof(elt.onchanges)=="undefined")
					elt.onchanges = new Array( elt.onchange );
				addToArray(elt.onchanges, callback);
				elt.onchange = executeMultipleOnChanges;
			}
			else {
				elt.onchange = callback;
			}
		}
		
		// onclick callback
		if (addonclick) {
			if (typeof(elt.onclick)!="undefined" && elt.onclick!=null && elt.onclick!="") {
				if (typeof(elt.onclicks)=="undefined")
					elt.onclicks = new Array( elt.onclick );
				addToArray(elt.onclicks, callback);
				elt.onclick = executeMultipleOnClicks;
			}
			else {
				elt.onclick = callback;
			}
		}
	}	
}

function executeMultipleOnChanges(event) {
	for(i=0; i<this.onchanges.length; i++) {	
		this.tmponchange = this.onchanges[i];
		var returnVal = this.tmponchange(event);
		if (typeof(returnVal)!="undefined" && !returnVal)
			break;
	}
}

function executeMultipleOnKeyPresses(event) {
	for(i=0; i<this.onkeypresses.length; i++) {	
		this.tmponkeypress = this.onkeypresses[i];
		var returnVal = this.tmponkeypress(event);
		if (typeof(returnVal)!="undefined" && !returnVal)
			break;
	}
}

function executeMultipleOnClicks(event) {
	for(i=0; i<this.onclicks.length; i++) {	
		this.tmponclick = this.onclicks[i];
		var returnVal = this.tmponclick(event);
		if (typeof(returnVal)!="undefined" && !returnVal)
			break;
	}
}

// Trim whitespace from left and right sides of s.
function trim(s) {
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

// -- Clear display table parameters
function handlePagination(f, tableId, url) {
	eval("var toNames = typeof("+tableId+"_parameters);");
	if (toNames!="undefined") {
		eval("var names = "+tableId+"_parameters;");
		var anchor = '';
		var anchorPosition = url.indexOf('#');
		if(anchorPosition != -1) {
			anchor = (url.substr(anchorPosition, url.length));
			url = url.substr(0, anchorPosition);
		}	
		for(var i=0; i<names.length; i++) {
			url += '&'+names[i]+'='+f[names[i]].value;
		}
		url += '&displayTableId=' + tableId;
		// Must come last
		if(anchor != '') {
			url += anchor;
		}
	}
	return url;
}

