// -------------------------------
// 				PICKERS
// -------------------------------

var picker = null;

function popupPicker(target, idSelected, inputId, inputDescr, width, height) {
	
	// get the coordinate to display the new window
	var left = (screen.width - width) / 2;
	var top  = (screen.height - height) / 2;

	picker = window.open(target+'?idSelected='+idSelected+'&inputId='+inputId+'&inputDescr='+inputDescr, 'popupPicker', 'top=' + top + ',left=' + left + ',width=' + width +',height=' + height + ',status=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,menubar=no');
}

function popupPickerWithIdCompany(target, idSelected, idCompanySelected, inputId, inputIdCompany, inputDescr, width, height) {
	
	// get the coordinate to display the new window
	var left = (screen.width - width) / 2;
	var top  = (screen.height - height) / 2;

	picker = window.open(target+'?idSelected='+idSelected+'&idCompanySelected='+idCompanySelected+'&inputId='+inputId+'&inputIdCompany='+inputIdCompany+'&inputDescr='+inputDescr, 'popupPicker', 'top=' + top + ',left=' + left + ',width=' + width +',height=' + height + ',status=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,menubar=no');
}


function validatePicking(inputId,inputDescr,idElementSelected) 
{
	var radios = window.document.getElementsByName('picker_radio');

	var elementSelected = false;

	for (var i=0; i < radios.length && !elementSelected; i++)
	{
		if ( radios[i].checked )
		{
			window.opener.document.getElementById(inputId).value = radios[i].value.split('[.]')[0];
			window.opener.document.getElementById(inputDescr).value = radios[i].value.split('[.]')[1];
			window.close();
			elementSelected = true;
			
			// test if selection changed
			if( radios[i].value.split('[.]')[0] != idElementSelected )
			{
				window.opener.document.getElementById('changed').value = 'true';
			}
		}
	}
	// if no element is selected, the opener fields are empty and the popup is closed
	if(!elementSelected)
	{
		window.opener.document.getElementById(inputId).value = '';
		window.opener.document.getElementById(inputDescr).value = '';
		window.close();
		
		// test if selection changed
		if( idElementSelected != '' )
			window.opener.document.getElementById('changed').value = 'true';
	}
}


function validatePickingWithIdCompany(inputId,inputIdCompany,inputDescr,idElementSelected,idCompanyElementSelected) 
{
	var radios = window.document.getElementsByName('picker_radio');

		var elementSelected = false;

		for (var i=0; i < radios.length && !elementSelected; i++)
		{
			if ( radios[i].checked )
			{
				window.opener.document.getElementById(inputId).value = radios[i].value.split('[.]')[0];
				window.opener.document.getElementById(inputIdCompany).value = radios[i].value.split('[.]')[1];
				window.opener.document.getElementById(inputDescr).value = radios[i].value.split('[.]')[2];
				window.close();
				elementSelected = true;
				
				// test if selection changed
				if( (radios[i].value.split('[.]')[0] != idElementSelected) || (radios[i].value.split('[.]')[1] != idCompanyElementSelected) )
				{
					window.opener.document.getElementById('changed').value = 'true';
				}
			}
		}
		// if no element is selected, the opener fields are empty and the popup is closed
		if(!elementSelected)
		{
			window.opener.document.getElementById(inputId).value = '';
			window.opener.document.getElementById(inputIdCompany).value = '';
			window.opener.document.getElementById(inputDescr).value = '';
			window.close();
			
			// test if selection changed
			if( (idElementSelected != '') || (idCompanyElementSelected !=  '') )
				window.opener.document.getElementById('changed').value = 'true';
		}
}

function selectRadio(valueToSelect) 
{
	var radios = window.document.getElementsByName('picker_radio');
	
	var stop = false;
	for (var i=0; i < radios.length && !stop; i++)
	{
		if (radios[i].value == valueToSelect)
		{
			radios[i].checked = true;
			stop = true;
		}
	}
}


function emptySelection() 
{
	var radios = window.document.getElementsByName('picker_radio');

	for (var i=0; i < radios.length; i++)
	{
		radios[i].checked = false;
	}
}


// -------------------------------
// 	Gestion des textpopup
// -------------------------------
function PopupTextReadOnly (text,width,height)
{
	// get the coordinate to display the new window
	var left = (screen.width - width) / 2;
	var top  = (screen.height - height) / 2;
	
	var my_popup_image = window.open("","popupText","top=" + top + ",left=" + left + ",width=" + width + ",height=" + height + ",toolbar=no,resizable=yes");
	my_popup_image.document.open();
	my_popup_image.document.writeln("<textarea style='width:100%; height:100%; font-size: 10pt' readonly>"+text+"</textarea>");
	my_popup_image.document.close();
	
	return true;
} // PopupImage


// -------------------------------
// 		 Gestion des images
// -------------------------------

///////////////////////////////////////////////////////////////////////////////////
// PopupImage : Display a image on a pupup
// Parameters : 
//		- imageDiv : the id of the image div
///////////////////////////////////////////////////////////////////////////////////
function PopupImage (imageDiv)
{
	var my_popup_image=window.document.getElementById(imageDiv);
	if(my_popup_image.style.visibility=="visible" && my_popup_image.style.display=="block")
	{
		my_popup_image.style.visibility="hidden";
		my_popup_image.style.display="none";
	}
	else
	{
		my_popup_image.style.visibility="visible";
		my_popup_image.style.display="block";
	}
	
	return true;
} // PopupImage


///////////////////////////////////////////////////////////////////////////////////
// ClosePopupImage : close the popup image
// Parameters : 
//		- imageDiv : the id of the image div
///////////////////////////////////////////////////////////////////////////////////
function ClosePopupImage (imageDiv)
{
	var my_popup_image=window.document.getElementById(imageDiv);
	my_popup_image.style.visibility="hidden";
	my_popup_image.style.display="none";
	return true;
} // ClosePopupImage

/////////////////////////////////////////////////////////////////////////////
// ResizeImage : Resize an image
// Parameters :
//		- image 		: an HTML IMG tag
//		- height_max	: the max height of the resized image
//		- width_max		: the max width of the resized image
/////////////////////////////////////////////////////////////////////////////
function ResizeImage(image,height_max,width_max)
{
	// save the real size
	var img = new Image();
	img.src=image.src;
	
	if ( img.height > height_max )
	{
		image.width = img.width * ( height_max / img.height );
		image.height = height_max;
	}
	
	if ( img.width > width_max )
	{
		image.height = img.height * ( width_max / img.width );
		image.width = width_max;
	}
	
	return true;
}



///////////////////////////////////////////////////////////////////////////////////
// DisplayImageFromInputFile : Display an Image after user select a new file 
//							   on a input file (works only on IE)
// Parameters : 
//		- image : the id of the image
//		- file	: src for the file loaded
///////////////////////////////////////////////////////////////////////////////////
function DisplayImageFromInputFile (imageId,file)
{
	// save the real size
	var img = new Image();
	img.src="file://"+file;

	// change the src on the resized image
	var image = document.getElementById(imageId);
	image.width=img.width;
	image.height=img.height;
	image.src=img.src;
	
	// change the src on the big image
	var imagePopup = document.getElementById(imageId+"PopupImg");
	imagePopup.width=img.width;
	imagePopup.height=img.height;
	imagePopup.src=img.src;
	
	return true;
} // DisplayImageFromInputFile

/////////////////////////////////////////////////////////////////////////////
// ChangePosition : Change the position of an imageor div
// Parameters :
//		- IdObject 		: an HTML IMG tag
//		- top			: the position from top of page
//		- left			: the position from left of page
/////////////////////////////////////////////////////////////////////////////
function ChangePosition(IdObject,top,left)
{
	var object = document.getElementById(IdObject);
	
	object.pixeltop=top;
	object.pixelleft=left;
	
	return true;
}

/////////////////////////////////////////////////////////////////////////////
// SamePosition : Change the position of an imageor div
// Parameters :
//		- IdObject 		: an HTML IMG tag
//		- IdBase		: an HTML IMG tag (which give position for object)
/////////////////////////////////////////////////////////////////////////////
function SamePosition(IdObject,IdBase)
{
	var base = document.getElementById(IdBase);
	ChangePosition(IdObject,base.pixeltop,base.pixelleft)

	return true;
}


/////////////////////////////////////////////////////////////////////////////
// SameDate : Change Update a date according to an other one if upper
// Parameters :
//		- NameObjectBase 		: an HTML textField tag (which give date)
//		- NameObjectUpdated	: an HTML textField tag 
/////////////////////////////////////////////////////////////////////////////

function GetBaseValue(IdObjectBase,IdObjectUpdated)
{
	var objectBase = document.getElementById(IdObjectBase);
	var objectUpdated = document.getElementById(IdObjectUpdated);
	
	//split date according to format
	// if the 4 first figures are not a number, format = dd#mm#yyyy
	if (isNaN(objectUpdated.value.slice(0,4)))
	{
		start_day 	= objectBase.value.slice(0,2);
		start_month = objectBase.value.slice(3,5);
		start_year	= objectBase.value.slice(6,10);
		end_day 	= objectUpdated.value.slice(0,2);
		end_month 	= objectUpdated.value.slice(3,5);
		end_year	= objectUpdated.value.slice(6,10);	
	}
	// format = yyyy#mm#dd
	else
	{
		start_day 	= objectBase.value.slice(8,10);
		start_month = objectBase.value.slice(5,7);
		start_year	= objectBase.value.slice(0,4);
		end_day 	= objectUpdated.value.slice(8,10);
		end_month 	= objectUpdated.value.slice(5,7);
		end_year	= objectUpdated.value.slice(0,4);	
	}
	
	if((start_year > end_year) || ((start_year == end_year) && (start_month > end_month)) || ((start_year == end_year) && (start_month == end_month) && (start_day > end_day)))
	{
		objectUpdated.value=objectBase.value;
	}
	return true;
}



function setDoNotWarn()
{
	if(document.getElementById('do_not_warn') != null)
		document.getElementById('do_not_warn').value = true;
	
	return true;
}

function changeDecimalSeparator(number) 
{
	return number.replace(/\./,',');
}

function changeCommaToPoint(number) 
{
	return number.replace(',','.').replace(';', '.');
}

//Change the css of the select id in the menu
function LoadPageCSS(menuclick)
{
	//alert('Valeur Id debut :' + menuclick);
	
	if (menuclick == '')
	{
		menuclick = '1'; //for the first connexion ex:accueil
	}

	//we change the class of the id select
	if(document.getElementById(menuclick) != null)
		document.getElementById(menuclick).className  = "menuitemactu";
}
	
	
	
//check if the parameter "elt" is an integer
//return a boolean 
function isInt(elt){
    var x = new Boolean(isNaN(parseFloat(elt)));
	return x;
}

//check and set float format for the parameter"elt"
//Accept only float user input
function onlyFloat(elt)
{
    var j=0;
	var str="";
	
	for(i=0;i<elt.length;i++)
	{
		str1=elt.substring(i,i+1);
		if ((isInt(str1)==true) && str1!="." && str1!=",")
		{
			str1=""; 
		}
		if (str1==","){str1=".";}
		if (str1=="." && j!=0){str1="";}
		if (str1=="." && j==0){j=1;}
		str=str+str1;
	}
	
	return str;
}
/*check and set float format for the parameter"elt"
*Accept only float user input 
*ex: -1ttt,15.20 ==> -115.20, 1,25,26==> 1.2526
*/
function onlyFloatWithNegative(elt)
{
    var j=0;
	var str="";
	if (elt.indexOf(",")!=-1 && elt.indexOf(".")!=-1) elt = elt.replace(/,/g,"");
	for(i=0;i<elt.length;i++)
	{
		str1=elt.substring(i,i+1);
		if ((isInt(str1)==true) && str1!="." && str1!="," && str1!="-")
		{
			str1=""; 
		}
		if(str1=="-" && i!=0){str1="";}
		if (str1==","){str1=".";}
		if (str1=="." && j!=0){str1="";}
		if (str1=="." && j==0){j=1;}
		str=str+str1;
	}
	
	return str;
}
/**
 * Extract a number within a string literal, remove all noises
 * @param elementId
 * @return apply to the element id the new value
 * */
function extractNumberWithinLitteral(elementId)
{
	if($(elementId) != null)
	{
		FormatUtil.extractNumberWithinString($(elementId).value, function(reply)
		{
			$(elementId).value = reply;
		});
	}
}



//Get the entry and return the extracted number
/*function returnDecimal(elt)
{
	var reg = new RegExp("(\+|-)?([1-9]\d*|0|\.)","gi");
	for()
}*/

//Tween the element with transition
//@param div/span element to be display 
/**function divOnExpand(divId){
	
	alert(divId);
	$('#'+divId).toggle('blind');
	// Always sets the duration of the tween to 1000 ms and a bouncing transition
	// And then tweens the height of the element
	/*$('myOtherElement').set('tween', {
	duration: 700
	}).tween('height', (document.getElementById('formDivHeightId').offsetTop - 120));
  document.getElementById('activateButton_xxc1234456').style.display='none';
  document.getElementById('inactivateButton_xxc1234456').style.display='';
 
}

//Tween the element with transition
//@param div/span element to be hide 
function divOnReduce(divId){
	$('#'+divId).toggle('blind');
	
	// Always sets the duration of the tween to 1000 ms and a bouncing transition
	// And then tweens the height of the element
	/*$(divId).set('tween', {
	duration: 700
	}).tween('height', 21);
	document.getElementById('inactivateButton_xxc1234456').style.display='none';
    document.getElementById('activateButton_xxc1234456').style.display='';
    
}*/



/**
Hide the element with transition
@param div/span element to be hidden
@param theButtonId the button id to be clicked for action display/hidden 
	convention: theButtonId_0 hide
				theButtonId_1 display
**/
function divOnReduce(divId, theButtonId, divHeightId){
	// Always sets the duration of the tween to 1000 ms and a bouncing transition
	// And then tweens the height of the element
	//alert(document.getElementById(divId).style.height);
	if($(divId) != null)
	{
		//Save to the httpSession the div height
		AllDwrFunction.setAttributeValueFromRequest(divId, $(divId).offsetHeight);
			
		$(divId).set('tween', {
		duration: 700
		}).tween('height', divHeightId);
		
		//Display hide the action button function to the current state
		for(var i=0;i<2; i++)
		{
			var theButtonIdDisplayHide = theButtonId + '_'+i;
			document.getElementById(theButtonIdDisplayHide).style.display!=null?
				document.getElementById(theButtonIdDisplayHide).style.display == 'none'?
					document.getElementById(theButtonIdDisplayHide).style.display = '':
						document.getElementById(theButtonIdDisplayHide).style.display == ''?document.getElementById(theButtonIdDisplayHide).style.display = 'none':'':'';
		}
    }
}


/**
Tween the element with transition
@param div/span element to be hidden
@param theButtonId the button id to be clicked for action display/hidden 
	convention: theButtonId_0 hide
				theButtonId_1 display
**/
function divOnToggleExpand(divId, theButtonId){
	// Always sets the duration of the tween to 1000 ms and a bouncing transition
	// And then tweens the height of the element
	//alert(document.getElementById(divId).style.height);
	$('#'+divId).toggle('blind');
	
	/*if($(divId) != null)
	{
		//Save to the httpSession the div height
		AllDwrFunction.dwrGetAttributeValueFromRequest(divId, function(reply) {
				//Reply = null this is not a saved value, take the one define in the paramter
				divHeightFromRequest = reply;
				$(divId).set('tween', {
					duration: 700
					}).tween('height', divHeightFromRequest);
				  
				  	//Display hide the action button function to the current state
					for(var i=0;i<2; i++)
					{
						var theButtonIdDisplayHide = theButtonId + '_'+i;
						document.getElementById(theButtonIdDisplayHide).style.display!=null?
							document.getElementById(theButtonIdDisplayHide).style.display == 'none'?
								document.getElementById(theButtonIdDisplayHide).style.display = '':
									document.getElementById(theButtonIdDisplayHide).style.display == ''?document.getElementById(theButtonIdDisplayHide).style.display = 'none':'':'';
					}
			});
			
		//alert(divHeightFromRequest);
	}*/
}



/**
Show_hide column belonging to the given table id
@param id_of_table the id of the given table
@param col_no the number of column to be hidden
@param show_hide true|false
*/
function show_hide_column(id_of_table, class_accessor_of_table, col_no, show_hide)
{
	//Retrieve current idSrv
	var idCurrentSrv = $('#currentIdSrv').val();
	var idUserOfSession = $('#idUserOfSession').val();
	//Retrieve user preferences to the session
	AllDwrFunction.dwrGetUserPreferences(function(reply){
		var myStruct = reply;
		if(myStruct != null)
		{
			myStruct = JSON.parse(myStruct);
		}
		var theTable  = document.getElementById(id_of_table);
		//Don't take subcolumns
		$('#'+id_of_table).children().children(':not([class="header1"])').children('td:nth-child('+col_no+')').css("display", show_hide?'':'none');
		var result = $.addCol(myStruct, idUserOfSession, idCurrentSrv, class_accessor_of_table, 'col' + col_no , show_hide);
		//alert(JSON.stringify(result));
		//Save the cookie new value
		//$.cookie('PREF', JSON.stringify(result), {expires: 999, path: '/'});
		
		AllDwrFunction.dwrUpdateUserPreferences(JSON.stringify(result));
	});
	
	return;
}


/**
Show_hide column belonging to the given table id
@param id_of_table the id of the given table
@param col_no the number of column to be hidden
@param show_hide true|false
*/
function doExecuteShowOrHideCols(idCurrentSrv, idUserOfSession, userPrefColsAndFilters)
{
	//alert($('td.form_border').find('table').length);
	//alert($.cookie('PREF'));
	//alert(userPrefColsAndFilters);
	//{"eureciadbf9905319cdd2910119e14f98d31ecd":{"eureciabarem":{"cols":{"tab_list":{"cols3":false}},"filters":{}},"eurecia402880830d361c57010d362eb4350026":{"filters":{},"cols":{"tab_displayedAccumulationInformationList":{"cols1":true,"cols2":true,"cols3":true,"cols4":true}}}}}
	if(userPrefColsAndFilters != null)
	{
		var myStruct = JSON.parse(userPrefColsAndFilters);
		
		//$('.form_border').find('table').children().children().children('td:nth-child('+(col_no+1)+')').css("display", show_hide?'':'none');
		var i = 1;
		
		var colsStruct =  $.getCols(myStruct, idUserOfSession, idCurrentSrv);
		/*alert(JSON.stringify(myStruct));
		return; */
    	for(classAccessorOfTable in colsStruct)
		{
			//alert('doExecuteShowOrHideCols 1 ' + classAccessorOfTable);
			var encoded = $.toJSON(myStruct);
			colsValue = eval('$.evalJSON(encoded).' + idUserOfSession + '.' + idCurrentSrv + '.cols.' + classAccessorOfTable);
			//If this table already registered, exists in the structure
			if(typeof(colsValue) != 'undefined')
	    	{
	    		//alert('doExecuteShowOrHideCols 2 ' + JSON.stringify(colsValue));
				for(col in colsValue)
				{
					//Get the table and set display or not the column
					//alert('doExecuteShowOrHideCols 3 ' + col);
					colValue = eval('$.evalJSON(encoded).' + idUserOfSession + '.' + idCurrentSrv + '.cols.' + classAccessorOfTable + '.' + col);
					//For example col1 or col12
					col = col.substring(col.length, col.length>4?col.length-2:col.length-1);
					//alert('doExecuteShowOrHideCols 4 ' + col);
					//alert('doExecuteShowOrHideCols 5 ' + colValue);
					//Update the col display
					$('#'+classAccessorOfTable+'_'+col).attr('checked', colValue);
					//$('.' + classAccessorOfTable).find('.form_border').find('div').children('input[type="CHECKBOX"]:eq(' + (col-2) + ')').attr('checked', colValue);
					//alert($('.' + classAccessorOfTable).find('td.form_border').find('table:eq(0)').attr('class'));
					//Don't take subcolumns
					$('.' + classAccessorOfTable).find('td.form_border').find('table:eq(0)').children().children(':not([class="header1"])').children('td:nth-child('+col+')').css('display', colValue?'':'none');
				}
	    	}
			
		}
	}
	return true;
}

/**
Show_hide filter zone belonging to the given table id
@param id_of_table the id of the given table
@param col_no the number of column to be hidden
@param show_hide true|false
*/
function show_hide_filter (filterName)
{
	//Retrieve current idSrv
	var idCurrentSrv = $('#currentIdSrv').val();
	var idUserOfSession = $('#idUserOfSession').val();
	//Get filter number
	var filter_no = filterName.substring(filterName.lastIndexOf("_")+1, filterName.lastIndexOf("_") + 3);
	
	$('tr.'+filterName+'_child').fadeToggle('fast', function(){
		var show_hide = $(this).is(':visible');
		$('#'+filterName).find('img').attr('src', show_hide?'fw/global/image/app/filter_section_down_7_13.png':'fw/global/image/app/filter_section_right_7_13.png');
		//Retrieve old user preferences	
		AllDwrFunction.dwrGetUserPreferences(function(reply){
			var myStruct = reply;
			if(myStruct != null)
			{
				myStruct = JSON.parse(myStruct);
			}

			var result = $.addFilter(myStruct, idUserOfSession, idCurrentSrv, filterName , show_hide);
			AllDwrFunction.dwrUpdateUserPreferences(JSON.stringify(result));
		});
	}); 
	
	return true;
}

/**
Show_hide filters belonging to the given table id
@param id_of_table the id of the given table
@param col_no the number of column to be hidden
@param show_hide true|false
*/
function doExecuteShowOrHideFilters(idCurrentSrv, idUserOfSession, userPrefColsAndFilters)
{
	//alert($('td.form_border').find('table').length);
	//alert($.cookie('PREF'));
	//alert(userPrefColsAndFilters);
	//{"eureciadbf9905319cdd2910119e14f98d31ecd":{"eureciabarem":{"cols":{"tab_list":{"cols3":false}},"filters":{}},"eurecia402880830d361c57010d362eb4350026":{"filters":{},"cols":{"tab_displayedAccumulationInformationList":{"cols1":true,"cols2":true,"cols3":true,"cols4":true}}}}}
	if(userPrefColsAndFilters != null)
	{
		var myStruct = JSON.parse(userPrefColsAndFilters);
		var encoded = $.toJSON(myStruct);
		
		//$('.form_border').find('table').children().children().children('td:nth-child('+(col_no+1)+')').css("display", show_hide?'':'none');
		var filtersStruct =  $.getFilters(myStruct, idUserOfSession, idCurrentSrv);
		//Fetch filters structure
		for(filterName in filtersStruct)
		{
			//Retrieve to the structure the filter value
			var filterValue = eval('$.evalJSON(encoded).' + idUserOfSession + '.' + idCurrentSrv + '.filters.' + filterName);
			if(!filterValue)
			{
				$('tr.'+filterName+'_child').css('display', 'none');
				$('#'+filterName).find('img').attr('src', 'fw/global/image/app/filter_section_down_7_13.png');
			}
		}
	}
}



/**
 * Fill fromSelectId to toSelectId options
 * @param fromSelectId select object
 * @param toSelectId select object
 * @return update fromSelectId to toSelectId options
 */
 function fillSelect(fromSelectId , toSelectId)
 {
	//The list of all the users (User list)
	  var data = document.getElementById (fromSelectId).options;
	  var optionTab = new Array();
	  var option  = new Array();
	  var i = 0;
	  for(i; data != null && (i< data.length); i++)
		{
		 
			    option[i] =  [{name:'', id:''}];
			  	option[i][0] = data[i].value;
			  	option[i][1] = data[i].text;
				optionTab[i] = option[i];
		  
		}
	  //Update the select compment
	  updateSelect (optionTab, toSelectId);
	}


  /**
  * Update the toSelect with the fromSelect options::List<Object[value,descr]>, erase the remaining elements of toSelect
  * @param fromSelectListOption List<Object[value, descr]>
  * @param toSelectId
  * @return update toSelect object with the fromSelectListOption; 
  *	if the fromSelectListOption is null, erase the toSelect elements
  */
  function updateSelect(fromSelectListOption, toSelectId)
  {
  	
	var toSelectObject = document.getElementById(toSelectId);
	var toSelectObjectSize = toSelectObject.options.length;
	var i = 0;
	
	//Erase all datas
	dwr.util.removeAllOptions(toSelectId);
	//If we will remove all the options, add an option with ('','') to modify the value (imputationitem id) to null
	if(fromSelectListOption == null)
	{
		var option  = new Array();
		option[0] =  [{name:'', id:''}];
		option[0][0] = '';
		option[0][1] = '';
	 	var data =  [{name:option[0][1], id:option[0][0]}];
	 	dwr.util.addOptions(toSelectId, data, 'id', 'name');
	}
	//END If 
	for(i; fromSelectListOption != null && (i< fromSelectListOption.length); i++)
	{
	 	var data =  [{name:fromSelectListOption[i][1], id:fromSelectListOption[i][0]}];
	 	dwr.util.addOptions(toSelectId, data, 'id', 'name');
	}	
	
	//Reset the value
	document.getElementById(toSelectId).value = null;

   }
  
  /**
  * Update for each following axis the options value dynamicly if needed
  * Make those loaded dynamicly or not
  */
  function updateNextImputationStrutureOptionList(currentItemId, impOrder, beanIndex)
  {
	//Get all axe containing elements which conditions other elements
	var allAxesContainingConditionsElement = document.getElementById('numberAxeContainsElementConditions').value;
	//alert(currentItemId);
	//Get next axe/element/select
	//21 = imputationStructureId.length
	var nextElement = currentItemId.substring(0, 21);
	//alert(nextElement);
	var nextElementId = nextElement + (impOrder+1) + "_" + beanIndex;
	//alert(nextElementId);
	//alert(document.getElementById(currentItemId).value);
	if(document.getElementById(currentItemId) != null )
	
		AllDwrFunction.dwrIsTheGivenElementSelectable(document.getElementById(currentItemId).value, function(isForbidden){
		if(!isForbidden)
		{
			//Get the concerned select
			select = document.getElementById(currentItemId);
			//Modify the selectedIndex, set the first one for example
			select.selectedIndex = 0;
			
			//Reset the following axis
			if(allAxesContainingConditionsElement != '' && allAxesContainingConditionsElement.indexOf(impOrder) != -1)
			{	
				if(document.getElementById(nextElementId) != null )
				{
					updateSelect(null, nextElementId);
					
				}
					
				//Set all following axis
				//Set following axis
				for(followingAxeNumber=impOrder+1; followingAxeNumber<6; followingAxeNumber++)
				{
					alert(impOrder);
				 	//Is the current axe contains any sub elements which conditions other elements
				 	if(allAxesContainingConditionsElement.indexOf(followingAxeNumber) != -1)
				 	{
				 		//If so, get the following one
				 		var followingAxeId = nextElement + (followingAxeNumber+1) + "_" + beanIndex;
				 		//alert(followingAxe);
				 	
				 		if(document.getElementById(followingAxeId) != null)
				 		{
				 			//alert(document.getElementById(followingAxe).value);
				 			//alert(followingAxe);
				 			document.getElementById(followingAxeId).value=null;
				 			//alert(document.getElementById(followingAxe).options[document.getElementById(followingAxe).selectedIndex].text);
				 			updateSelect(null, followingAxeId);
				 		
				 			//alert(document.getElementById(followingAxe).value);
				 		}
				 	}
				}
			}//End resetting following axis
			alert(messageFobiddenAccount);
			return false;
		}
		else 
		{ 
			//DO JOB
			
				//alert(nextElementId);
				//alert(document.getElementById(nextElementId));
				if(document.getElementById(nextElementId) != null )
				{
					getImputationStructureLinkedOptionList(document.getElementById('idUserForListValueHidden').value, currentItemId, impOrder, beanIndex, allAxesContainingConditionsElement, nextElement, nextElementId);
				 } // END if
			
			//If the item is a vacation , init the nbdays, bnHours, nbMinutes
			var selectedItem = document.getElementById(currentItemId).value;
			if (selectedItem.indexOf("vacation")!=-1)
			{
			var date = document.getElementById('dateActivite_' + beanIndex).innerHTML;
			AllDwrFunction.dwrInitTimeWorkedForVacationType(selectedItem, date, function(reply){	

					if(document.getElementById('imputationStructureUnit').value == 'days')
						document.getElementById('daysWorked_' + beanIndex).value = reply[0];
					else
					{
						document.getElementById('timeWorked_Hours_' + beanIndex).value = reply[1];
						document.getElementById('text_timeWorked_Hours_' + beanIndex).value = reply[1];
						document.getElementById('timeWorked_Minutes_' + beanIndex).value = reply[2];
						document.getElementById('text_timeWorked_Minutes_' + beanIndex).value = reply[2];
					}
				});
			}

		}//END else
	});//END function dwrIsTheGivenElementSelectable
	
  }
  
function getImputationStructureLinkedOptionList(idUserForListValue, currentItemId, impOrder, beanIndex, allAxesContainingConditionsElement, nextElement, nextElementId)
{ 
	
	AllDwrFunction.dwrGetImputationStructureLinkedOptionList(idUserForListValue, document.getElementById(currentItemId).value, impOrder, beanIndex, allAxesContainingConditionsElement, function(reply)
	{
		if(document.getElementById(currentItemId).value != '' && reply != null && reply[3])
		{
			CCUtility.crtCtrla(document.getElementById(nextElementId), 'activities=GenerateActivityItemForRepartitionKey='+document.getElementById(currentItemId).value+'='+impOrder+'=row_'+ beanIndex, null, null);
		}
		else
		{
			if(document.getElementById(nextElementId) != null)
			{
			 	//Update next select
			 	updateSelect(reply[1], nextElementId);
			 	
			 	document.getElementById(nextElementId).value = reply[2];
 	
	 			//Set following axis
			 	for(followingAxeNumber=impOrder+1; followingAxeNumber<6; followingAxeNumber++)
				{
	 		 		//Is the current axe contains any sub elements which conditions other elements
					if(allAxesContainingConditionsElement.indexOf(followingAxeNumber) != -1)
 	 				{
						//If so, get the following one
 	 					var followingAxeId = nextElement + (followingAxeNumber+1) + "_" + beanIndex;
		 	 			//alert(followingAxe);
 			 	
 	 					if(document.getElementById(followingAxeId) != null)
 	 					{
							//alert(document.getElementById(followingAxe).value);
 	 						//alert(followingAxe);
			 	 			document.getElementById(followingAxeId).value=null;
			 	 			//alert(document.getElementById(followingAxe).options[document.getElementById(followingAxe).selectedIndex].text);
	 			 			updateSelect(null, followingAxeId);
	 			 		
	 	 					//alert(document.getElementById(followingAxe).value);
	 	 				}
					}
				}
				impOrder = impOrder +1;
	 			if(reply[0] && impOrder < 5)
				{
			 		currentItemId = nextElementId;
				 	nextElementId = nextElement + (impOrder+1) + "_" + beanIndex;
			 		getImputationStructureLinkedOptionList(idUserForListValue, currentItemId, impOrder, beanIndex, allAxesContainingConditionsElement, nextElement, nextElementId);
				}
			}
		}
	});//END funtion
}
  
/**
* Historic navigation popup function
* slide the slide object
* buttonId the trigger
* contentId the content to be displayed with effect
* Uses DWR for getting navigation content
*/  
function historicNavigationPopup(slide, buttonId, contentId)
{
				/* for mouseOver, mouseOut $('historicNavigation').addEvent('mouseover', function(e){
					e.stop();
					AllDwrFunction.dwrGetHistoricNavigationContent(function(reply)
					{
						if(reply != null)
						{
							//alert(reply);
							document.getElementById('historicNavigationContent').innerHTML = reply;
							myHorizontalSlide.slideIn();
						}
					})
				});
				$('historicNavigation').addEvent('mouseout', function(e){
					e.stop();
					clearTimeout;
					//Wait 5s
					window.setTimeout('myHorizontalSlide.slideOut()', 4000);
				});*/
				
				$(buttonId).addEvent('click', function(e){
					e.stop();
					AllDwrFunction.dwrGetHistoricNavigationContent(function(reply)
					{
						if(reply != null)
						{
							//alert(reply);
							document.getElementById(contentId).innerHTML = reply;
							//Make it visible, hack IE Bug
							document.getElementById(contentId).style.display = 'block';
							slide.toggle();
						}
					})
				});
}

/**
*Add home page to Browser Favorites
*/
function addHomePageToBrowserFavorite(httpRoot, email, favoriteName) 
{ 
		if (window.sidebar && window.sidebar.addPanel)
		{ // Firefox 
			window.sidebar.addPanel(favoriteName, httpRoot+"login.do?email="+email,"");
		} 
		else if ( document.all ) 
		{ // IE Favorite
			window.external.AddFavorite(httpRoot+"login.do?email="+email,favoriteName); 
		}
		else if (window.opera && window.print) 
		{
		// do nothing
 		}
		else if (navigator.appName=="Netscape") 
		{
			alert('Cliquez sur OK puis appuyez simultan?ment sur les touches <CTRL-D> pour ajouter EURECIA dans vos favoris');
		}
		  
}

/**BEGIN - Convert RGB color to hexadecimal*/
var hexDigits = new Array
("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

function rgb2hex(rgb) {
	//IE return #xxxxxx
	if (rgb.charAt(0) == '#')
		return rgb;
	//Firefox return rgb()
	else
	{
		 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
		 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
	}
}
/**END - Convert RGB color to hexadecimal*/
	
	//Even if can throw exception (no exception has been thrown yet)
	var canThrowException = true;
	/**
	 * Save x and y sroll coord to eureciaSession and re-position them at each page loading
	 * */
	function smartScrollerGetCoords() 
	{
		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;
			}
	
			if(document.getElementById("xCoordHolder") && canThrowException)
			{
				document.getElementById("xCoordHolder").value = scrollX;
				AllDwrFunction.dwrSetxCoordHolder(scrollX);
			}
			
			if(document.getElementById("yCoordHolder") && canThrowException)
			{
				document.getElementById("yCoordHolder").value = scrollY;
				AllDwrFunction.dwrSetyCoordHolder(scrollY);
			}
	}
	
	/**
	 * Set the memorized x and y scroll
	 * */
	function smartScrollerScroll() 
	{
		if(document.getElementById("xCoordHolder"))
			var x = document.getElementById("xCoordHolder").value;
		
		if(document.getElementById("yCoordHolder"))
			var y = document.getElementById("yCoordHolder").value;
		window.scrollTo(x, y);
	}

	window.onload = smartScrollerScroll;
	window.onscroll = smartScrollerGetCoords;
	//window.onkeypress = smartScrollerGetCoords;
	//window.onclick = smartScrollerGetCoords;
	

	/**
	 * Manage check box of browse list, each should have an id like checkBox_n where n={1,2,3,...}
	 * @param isCheck should check them or not
	 * @param nbItems nbItems to be checked or not
	 * @param all, should fetch the list or not
	 * */
	function chkBoxManage(isCheck, nbItems, all)
	{
		//Only one element
		if(!all)
		{
			i = nbItems;
			$('#checkBox_'+i).attr('checked', isCheck);
			$('#checkBoxVal_'+i).val(isCheck);
			if(isCheck)
				$('#checkBoxVal_'+i).parents('tr[class*="even"],[class*="odd"]').addClass('customized_css').find('td').css('background-image', 'none').addClass('customized_css').css('color', '#FFFFFF');
			else
				$('#checkBoxVal_'+i).parents('tr[class*="even"],[class*="odd"]').removeClass('customized_css').find('td').css('background-image', '').removeClass('customized_css').css('color', '');
		}
		else
		{
			for(i=0;i<nbItems;i++)
			{
				$('#checkBox_'+i).attr('checked', isCheck);
				$('#checkBoxVal_'+i).val(isCheck);
				if(isCheck)
					$('#checkBoxVal_'+i).parents('tr[class*="even"],[class*="odd"]').addClass('customized_css').find('td').css('background-image', 'none').addClass('customized_css').css('color', '#FFFFFF');
				else
					$('#checkBoxVal_'+i).parents('tr[class*="even"],[class*="odd"]').removeClass('customized_css').find('td').css('background-image', '').removeClass('customized_css').css('color', '');
			}
		}
	}

	/**
	 * Retrieve key press for the bubble and return if carriage return html code <br>
	 * @param event the key code pressed
	 * @return the html code of carriage return and empty string for others
	 * */
	function getKeyCode(event)
	{
		var touche = window.event ? event.keyCode : event.which;
		if(touche == 13)
		{
			return "<br>";
		}
		else
			return "";
	}
	/**
	 * Display/Hide help bubble function to the concerned user. Different mode existing
	 * @param helpId the helpMessage id, which is too the dom element id
	 * @param typeOfBubble could be a help bubble (Constants.BUBBLE_HELP) or a message resource bubble (Constants.BUBBLE_MESSRESOURCE)
	 * @param isUserAdmin isUserAdmin
	 * Get the message with ajax and display it
	 * */
	function displayHideHelpEditableBubble(helpId, typeOfBubble, isUserAdmin)
	{
		//Create a bubble popup if he doesn't got one
		if(!$('#'+helpId).HasBubblePopup())
		{
			$('#'+helpId).CreateBubblePopup({
				selectable			: isUserAdmin,
				manageMouseEvents 	: false,
				innerHtml			: '<img src="fw/ajax/image/wait.gif" style="border:0px; vertical-align:middle; display:inline;" />',
				innerHtmlStyle		: {color:'#000000', 'text-align':'center'},
				themeName			: 'azure',
				themePath			: 'fw/global/jscript/jquery/jbubble/images/jquerybubblepopup-theme'
			});
		}
		

		//Display hide it function to his status
		if(!($('#'+helpId).IsBubblePopupOpen()))
		{
			//Retrieve the help message 
			AllDwrFunction.dwrBuildHelpMessage(helpId, typeOfBubble, function(helpMessage)
					{
						$('#'+helpId).SetBubblePopupInnerHtml(helpMessage);
						//Show it
						$('#'+helpId).ShowBubblePopup();
						//Move it up
						$('.jquerybubblepopup').css("top", $('.jquerybubblepopup').position().top - 10 );
					});
		}
		else
		{
			//Destroy it to the page, no needed to save it, to ensure the lightness of the html page
			$('#'+helpId).RemoveBubblePopup();
		}
	}
	
	/**
	 * @param helpId the helpMessage id, which is too the dom element id
	 * @param messages array of locale
	 * @param newOne even if new help, if update the help image : replace ... to the good image
	  * @param typeOfBubble could be a help bubble (Constants.BUBBLE_HELP) or a message resource bubble (Constants.BUBBLE_MESSRESOURCE) 
	 * */
	function saveHelpMessages(helpId, messages, newOne, typeOfBubble)
	{
		//Retrieve all messages
		//Fetch the array and save them
		var messagesTab = new Array(10, 2);
		var i = 0;
		$.each(messages, function(key, locale) {
			//Retrieve the message
			helpMessage = $('#' + locale + '_' + helpId).val();
			messagesTab[i++] = locale + '.' + helpMessage;
		});
		//Save it to the session and the db
		AllDwrFunction.dwrSaveHelpMessages(helpId, messagesTab, typeOfBubble, function(reply)
				{
					//If not new one, display message only
					if(!newOne)
					{
						$('#'+helpId + '_divinfo').text(reply).fadeIn();
					}
					else
					{
						//Display message and replace the ... to the help image
						$('#'+helpId + '_divinfo').text(reply).fadeIn();
						//Remove for the given element the existing bubble popup
						$('#'+helpId).RemoveBubblePopup();
						//Replace the old DOM object by the new one, the image and set his onclick action with the old DOM onclick action
						$('#'+helpId).replaceWith(function(){
							return $("<img src='fw/def/image/help.gif' id='"+helpId+"' class='helpLevel0' width='15' height='15'>").bind('click', $(this).attr("onclick"))
						});
					}
				});
	}
	
	/**
	 * Hide the color an object
	 */
	hide = function (ev) {
		if (!isChildOf(ev.data.cal.get(0), ev.target, $('.ibody'))) {
				ev.data.cal.hide();
				$(document).unbind('mousedown', hide);
		}
	}
	/**
	 * Find if el is first the child of container then if not found, find id it is the child of the parentEl
	 * It's stupid to fill container if the container is outside the parent element 
	 *
	 **/
	isChildOf = function(parentEl, el, container) {
		if (parentEl == el) {
			return true;
		}
		if (parentEl.contains) {
			return parentEl.contains(el);
		}
		if ( parentEl.compareDocumentPosition ) {
			return !!(parentEl.compareDocumentPosition(el) & 16);
		}
		var prEl = el.parentNode;
		while(prEl && prEl != container) {
			if (prEl == parentEl)
				return true;
			prEl = prEl.parentNode;
		}
		return false;
	}


	/**
	 * Show the color picker
	 * @param inputId the id of the input where the chosen color will be filled
	 */
	function showColorPicker(inputId)
	{
		//The reply return the html code of the color picker
		AllDwrFunction.dwrGetEureciaColorPicker(inputId, function(reply){
			//Hide the color picker when click outside the color picker
			$(document).bind('mousedown', {cal:$("#"+inputId+"_color")},hide);
			$("#"+inputId+"_color").show();
			$("#"+inputId+"_color").html(reply);
		});
	}
	/**
	 * Function called when the color is chosen
	 * @param inputId the id of the input where the chosen color will be filled
	 * @param color the chosen color
	 */
	function chooseColor(inputId,color)
	{
		$("#"+inputId).css({backgroundColor:color});
		document.getElementById(inputId).value=color;
		$("#"+inputId+"_color").hide();
	} 

	/**
	 * Function to display the overlay
	 */
	function displayOverlay()
	{
		$.ui.dialog.overlay.create();
		CCAjax.waitIndicator(true);
	} 
	
	/**
	 * Function to hide the overlay
	 */
	function hideOverlay()
	{
		$('.ui-widget-overlay').remove();
		CCAjax.waitIndicator(false);
	} 
	
