// -------------------------------
// 				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;
}

/**
 * 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){
	// 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){
	// 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='';
    
}**/

//Tween the element with transition
//@param  idEmement
function displayHideUserPreferences(idEmement){
SessionEurecia.dwrGetUserPreferences(idEmement, function(reply){
					 if( $('myOtherElement')!=null){
						  //alert(reply);
						  if (reply=="hide")
						  {
							$('myOtherElement').set('height', 21);
							document.getElementById('myOtherElement').style.height='21px';
							var tab = document.getElementsByName('displayFilterZoneButton');
							//id contains 0 hide
							//id contains 1 display
							if(tab[0] !== undefined )
								if(tab[0].id.contains('_1'))
								{
									var displayId = tab[0].id;
								}	
								else
									var hideId = tab[0].id;
								
							
							if(tab[1] !== undefined )
								if(tab[1].id.contains('_1'))
								{
									var displayId = tab[1].id;
								}
								else
									var hideId = tab[1].id;
								
								
							//alert(hideId);
							//alert(displayId);
							if(hideId != null && document.getElementById(hideId) != null)
								document.getElementById(hideId).style.display='none';
							
							if(displayId != null && document.getElementById(displayId) != null)
								document.getElementById(displayId).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
		DwrHelper.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 divOnExpand(divId, theButtonId, divHeight){
	// 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);
	divHeightFromRequest = 0;
	if($(divId) != null)
	{
		//Save to the httpSession the div height
		DwrHelper.getAttributeValueFromRequest(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);
	}
}

/**
Shoo_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, col_no, show_hide) {

	var stl;
	//alert(col_no);			
	if (show_hide) 
		stl = ''
	else
		stl = 'none';
						
	var theTable  = document.getElementById(id_of_table);
	var rows = theTable.getElementsByTagName('tr');
	//For each rows
	for (var i=0; i<rows.length;i++) {
	  var cels = rows[i].getElementsByTagName('td')
	  
	  if(cels[col_no] != null){
		cels[col_no].style.display=stl;
	  	cels[col_no].set=show_hide?"show":"hide";
	  }
	}
	//alert(col_no);
	
}




  /**
  * 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);
	
	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 )
	OpenTimeSheetAction.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.contains(impOrder))
			{	
				if(document.getElementById(nextElementId) != null )
					updateSelect(null, nextElementId);
					
				//Set all following axis
				//Set following axis
				for(followingAxeNumber=impOrder+1; followingAxeNumber<6; followingAxeNumber++)
				{
				 	//Is the current axe contains any sub elements which conditions other elements
				 	if(allAxesContainingConditionsElement.contains(followingAxeNumber))
				 	{
				 		//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
			if(allAxesContainingConditionsElement != '' && allAxesContainingConditionsElement.contains(impOrder))
			{
				//alert(nextElementId);
				//alert(document.getElementById(nextElementId));
			  	if(document.getElementById(nextElementId) != null )
			  	{
				  	//CallBack server method
				  	OpenTimeSheetAction.dwrGetImputationStructureLinkedOptionList(document.getElementById('idUserForListValueHidden').value, document.getElementById(currentItemId).value, impOrder, beanIndex, allAxesContainingConditionsElement, function(reply)
				  	{
					 	//Update next select
					 	updateSelect(reply, nextElementId);
					 	
					 	
					 	//Set following axis
					 	for(followingAxeNumber=impOrder+1; followingAxeNumber<6; followingAxeNumber++)
					 	{
					 	 	//Is the current axe contains any sub elements which conditions other elements
					 	 	if(allAxesContainingConditionsElement.contains(followingAxeNumber))
					 	 	{
					 	 		//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 funtion
				 }//END if
			}//END if 
		}//END else
	});//END function dwrIsTheGivenElementSelectable
  }
  
  
/**
* 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();
					SessionEurecia.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();
					SessionEurecia.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, password, favoriteName) 
{ 
		if (window.sidebar && window.sidebar.addPanel)
		{ // Firefox 
			window.sidebar.addPanel(favoriteName, httpRoot+"login.do?email="+email+"&password="+password,"");
		} 
		else if ( document.all ) 
		{ // IE Favorite
			window.external.AddFavorite(httpRoot+"login.do?email="+email+"&password="+password,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');
		}
		  
}
