/**
*
* Library "Client side control"
*
* @author	Escape
* @version	2.0
* @updated	27/10/1999
*
*/

// Declare structure for required fields controlling
var requiredFormFields = new Array ();
var requiredFormFieldsCondition = new Array ();
var requiredFormFieldsAlertText = new Array ();

// Confirmation messages
var msgDelete   = 'Voulez-vous supprimer cette fiche ?';
var msgSave   = 'Désirez-vous enregistrer les modifications ?';
var msgSaveRequiered   = 'Aucune modification ne doit être en attente d\'enregistrement pour pouvoir effectuer cette action !';

var check  = false;		// flag for "running required fields checking" (non-reentrance)
var change = false;		// when true, means that the form has been modified
var theChildWindow;		// Handle to a child window

/**
*
* @function	submitForm()
*
* @param	theTypeAction 	: The action type code.
* @param	saveRequiered	: (optional) indicateur de validation préalable obligatoire
* @param	formObj 		: (optional) the form to submit
* @return	(boolean) 		: true for submit the form, false to stop.
*
*/

function submitForm( theTypeAction, saveRequiered, doSubmit, formObj ) {

	//---------------------------------
	// Traitement des paramètres passés

	if (null == theTypeAction) return false;
	theTypeAction = theTypeAction.toLowerCase();

	if (null == saveRequiered) saveRequiered = false;

	// Changement FP du 04/02/2000 bug sur le submit sur type="Image"
	if (null == doSubmit) doSubmit = false;

	if (null == formObj) formObj = document.forms[0];
	if (null == formObj) {
		alert ("Attention, formulaire invalide !!!!");
		return false;
	}

	//----------------------------------------------
	// Gestion de l'enregistrement obligatoire avant
	// l'appel de certains types d'action

	if (saveRequiered && change) {
		alert( msgSaveRequiered );
		return false;
	}

	//-----------------------
	// Traitement des actions

	if ( theTypeAction == 'enregistrer' ) {

		if (!checkForm(formObj)) {			// Checking required fields
			return false;
		}
	}

	if ( theTypeAction == 'supprimer') {

		if (!confirm( msgDelete ) )			// Prompt for save before continue ?
			return false;
	}

	if ( theTypeAction == 'ajouter' ) {

		if ( change ) {
			if ( confirm( msgSave ) ) {
				return submitForm( 'enregistrer', saveRequiered, doSubmit, formObj );
			}
		}
	}

	// Mémorisation du type d'action
	formObj.action.value = theTypeAction;

	if (doSubmit) {
		formObj.submit();
		return false;
	}

	return true;
}

/**
*
* @function	checkForm()
*
* Check for empty required form's fiels.
*
* @param	formObj : the HTML form to check.
* @return	(boolean) true, if all the required fields are filled, false if not.
*
* @remark	By including, your own client-side file defining the arrays "requiredFormFields",
*			"requiredFormFieldsCondition", "requiredFormFieldsAlertText", in your HTML page you can define :
*			the required fields list for an HTML file, the specific required condition for
*			each field and a personalized error message for each one.
*
* @example
*
*		// Scripts client
*
*		requiredFormFields = new Array ( 'code',
*								'libelle',
*								'reference',
*								'taux');
*
*		requiredFormFieldsCondition = new Array ( 'true',
*								'true',
*								'(document.fiche.ancreference.value.length == 0)',
*								'true');
*
*		requiredFormFieldsAlertText = new Array ( 'Le code est obligatoire.',
*								'Le libellé est obligatoire.',
*								'Le sélection d\'une photographie est obligatoire.',
*								'Le taux de TVA est obligatoire.');
*
*/

/************************************
	Utility functions
************************************/

function rTrim( theSource ) {

	if (null == theSource ) return "";

	while (theSource.charAt( theSource.length - 1 ) == " " ) {

		theSource = theSource.substring( 0, theSource.length - 1 );

		if (theSource.length == 0)
			return "";
	}

	return theSource;
}


function strReplaceAll ( theSource, toFind, replaceWith ) {

	if (null == theSource ) return "";

	li_pos = theSource.indexOf( toFind );

	while (li_pos != -1)
	{
		if (li_pos < theSource.length -1 )
			theSource = theSource.substring(0, li_pos ) + replaceWith + theSource.substring(li_pos+1, theSource.length);
		else
			theSource = theSource.substring(0, li_pos );

		li_pos = theSource.indexOf( toFind, li_pos + replaceWith.length );
	}

	return theSource;
}

function getFieldNameRoot( theFieldName ) {

	lastInd = theFieldName.lastIndexOf("_");

	if ( isNaN( theFieldName.substring( lastInd + 1, theFieldName.length )) )
		return theFieldName;

	return theFieldName.substring( 0, lastInd + 1 )+"#";
}

function checkForm( formObj )
{
	if (check) {
		return false;
	}

	check = true;

	var foundComplete = false;
	var foundRoot = false;
	var fieldRoot;
	var theCondition;
	var brequired;

	for(i = 0 ; i < formObj.elements.length; i++) {

		if ( formObj.elements[i].type != "submit"
			&& formObj.elements[i].type != "reset"
			&& formObj.elements[i].type != "hidden"
			&& formObj.elements[i].type != "button"
			&& formObj.elements[i].type != "checkbox")
		{

			// Ajout du trim de tous les champs texte
			// FP - 20/01/2000
			if ( formObj.elements[i].type == "text" || formObj.elements[i].type == "textarea" ) {
				formObj.elements[i].value = rTrim( formObj.elements[i].value );
			}

			fieldRoot = getFieldNameRoot( formObj.elements[i].name );

			for (j=0 ; j < requiredFormFields.length; j++ )
			{
				foundComplete = ( formObj.elements[i].name == requiredFormFields[ j ] );
				foundRoot = ( foundComplete ) ? false : ( fieldRoot == requiredFormFields[ j ] );

				// alert( formObj.elements[i].name+"\r\n"+fieldRoot+"\r\n"+foundComplete+"\r\n"+foundRoot );

				if ( foundComplete || foundRoot ) {

					theCondition = eval( 'requiredFormFieldsCondition['+j+']' );
					if ( foundRoot ) {
						theCondition = strReplaceAll( theCondition, "#", formObj.elements[i].name.substring( fieldRoot.length - 1, formObj.elements[i].name.length ));
					}

					//-------------------------------------------------------
					// Traitement du type de champ obligatoire en deux temps
					// car Netscape ne s'arrête pas après l'évaluation à faux
					// d'une première condition. Il évalue la totalité

					if ( formObj.elements[i].type.substring(0, 6) == "select" )
						brequired = ( eval( theCondition ) );
					else
						brequired = (( formObj.elements[i].value.length == 0 ) && eval( theCondition ))

					if (brequired) {

						var theAlertText = requiredFormFieldsAlertText[ j ];

						alert( ( null != theAlertText ) ? theAlertText : 'Ce champ est obligatoire.' );

						change = true;
						formObj.elements[i].focus();

						check = false;
						return false;
					}

					break;
				}
			}
		}
	}

	check = false;
	return true;
}

/**
*
* @function	focusForm()
*
* Set the focus on the first, focus enable field of the form
*
* @param	formObj : HTML form
* @return	None
*
* @remark	This function has to be called on the "onLoad" event of the page.
*
*/

function focusForm(formObj)
{
	for(i = 0 ; i < formObj.elements.length; i++)
	{
		if ( formObj.elements[i].type != "submit" && formObj.elements[i].type != "reset" && formObj.elements[i].type != "hidden"
			&& formObj.elements[i].type != "button" && formObj.elements[i].type != "checkbox")
		{
			if (!formObj.elements[i].disabled) {
				formObj.elements[i].focus();
				return true;
			}
		}
	}
	return true;
}

/**
*
* @function	checkDate()
*
* Check the validity of an "date" field value.
*
* @param	dateField  : HTML form's field containing a date data
* @param	vText (optional) : message to show in the case of an invalid date has been entered
* @return	(boolean) true if the value is a valid date.
*
* @remark	the date must be enter following one of this format : "dd/mm/yyyy" ou "ddmmyyyy".
*
* @example	<input type="text" name="dateapplication" size="12" maxlength="10" value="<%=dateapplication%>"
* 			onKeyPress="checkOnKeyPressDate();" onFocus="select(this);" onChange="change = true;"
*			onBlur="checkDate(this);" >
*
*/

function checkDate( dateField, vText ) {

	var sValue = dateField.value;
	var dDate;

	if ( sValue.length == 0)
		return true;

	if ( sValue.length == 8)
		sValue = sValue.substr(0,2) + '/' + sValue.substr(2,2) + '/' + sValue.substr(4,4);

	if ( sValue.length != 10 || sValue.substr(2,1) !='/' || sValue.substr(5,1) !='/' )
	{
		alert( "Cette date doit être saisie au format JJ/MM/AAAA ou JJMMAAAA." );
		dateField.value = '';
		dateField.focus();
		return false;
	}

	dDate = new Date( parseInt( sValue.substr(6, 4), 10), parseInt( sValue.substr(3, 2) - 1, 10 ), parseInt( sValue.substr(0, 2), 10 ) );

	if ( dDate.getMonth() + 1 != parseInt( sValue.substr(3, 2), 10) | dDate.getDate() != parseInt( sValue.substr(0, 2), 10 ) )
	{
		if ( vText == null )
		{
			vText = "La valeur saisie n'est pas une date valide.";
		}
		alert( vText );

		//dateField.value = '';

		dateField.focus();
		return false;
	}

	dateField.value = sValue;
	return true;
}

/**
*
* @function	checkTime()
*
* Check the validity of an "time" field value.
*
* @param	dateField  : HTML form's field containing a time data
* @param	vText (optional) : message to show in the case of an invalid time has been entered
* @return	(boolean) true if the value is a valid time.
*
* @remark	the date must be enter following one of this format : "hh:mm" ou "hhmm".
*
* @example	<input type="text" name="currenttime" size="6" maxlength="5" value="<%= currentTime %>"
* 			onKeyPress="checkOnKeyPressTime();" onFocus="select(this);" onChange="change = true;"
*			onBlur="checkTime( this, 'this'is not a correct time value !' );" >
*
*/

function checkTime( dataField, vText)
{
	var sValue = dataField.value;

	if ( sValue.length == 0 )
		return true;

	if ( sValue.length == 4 )
		sValue = sValue.substr(0,2) + ':' + sValue.substr(2,2);

	var table = sValue.split(':');

	if ( sValue.length != 5 || table.length != 2)
	{
		alert( "Cette heure doit être saisie au format HH:MM ou HHMM." );
		dataField.value = '';
		dataField.focus();
		return false;
	}

	if (( parseInt(table[0], 10) > 24 || parseInt(table[0], 10) < 0 || isNaN(parseInt(table[0], 10)) ||
		 parseInt(table[1], 10) > 59 || parseInt(table[1], 10) < 0 || isNaN(parseInt(table[1], 10)) ) ||
		 ( parseInt(table[0], 10) == 24 ))
	{
		if ( vText == null )
		{
			vText = "La valeur saisie n'est pas une heure valide.";
		}
		alert( vText );
		dataField.value = '';
		dataField.focus();
		return false;
	}

	dataField.value = sValue;
	return true;
}

/**
*
* @function	checkOnKeyPress() and derived functions...
*
* Limit the input to a limited list of chars.
* Check if the input char is correct depending on the type of targeted value
*
* @param	numeric : true, if you ask for numeric value (number from 0 to 9)
* @param	incorrect : a string containing the list of disallowed inputs
* @return	(boolean) : true, to allow the input
*
* @remark	this function blocks any invalid character before it has been displayed by the browser.
*
* @example	<input type="text" name="currenttime" size="6" maxlength="5" value="<%= currentTime %>"
* 			onKeyPress="checkOnKeyPressTime();" onFocus="select(this);" onChange="change = true;"
*			onBlur="checkTime( this, 'this'is not a correct time value !' );" >
*
*/

function checkOnKeyPress( numeric, incorrect ){

	var lnumeric = new String('0123456789');

	if (numeric) {
		if ( lnumeric.indexOf( String.fromCharCode(window.event.keyCode) ) == -1 ) {
			window.event.keyCode = null;
			return false;
		}
	}

	if ( incorrect.indexOf( String.fromCharCode(window.event.keyCode) ) > -1 ) {
		window.event.keyCode = null;
		return false;
	}

	return true;
}

function checkOnKeyPressValid( valide ){
	if ( valide.indexOf( String.fromCharCode(window.event.keyCode) ) == -1 ) {
			window.event.keyCode = null;
			return false;
		}

	return true;
}

function checkOnKeyPressInvalid( nonvalide ){
	if ( nonvalide.indexOf( String.fromCharCode(window.event.keyCode) ) != -1 ) {
			window.event.keyCode = null;
			return false;
		}

	return true;
}

function checkOnKeyPressDate(){
	return checkOnKeyPressValid('0123456789/');
}

function checkOnKeyPressNum( decimalpart, negativenum ){
	decimalpart = ( null == decimalpart ) ? false : decimalpart ;
	negativenum = ( null == negativenum ) ? false : negativenum ;
	return checkOnKeyPressValid('0123456789'+ ( ( decimalpart ) ? '.' : '' )+ ( ( negativenum ) ? '-' : '' ));
}

function checkOnKeyPressTime(){
	return checkOnKeyPressValid('0123456789:');
}

function checkOnKeyPressAlpha(){
	return checkOnKeyPressInvalid('&');
}

/**
*
* @function	checkOnBlur(), and the following ones
*
* Check the validity of an input field when the user try to leave it.
*
* @param	numeric : true, if you ask for numeric value (number from 0 to 9)
* @param	incorrect : a string containing the list of disallowed inputs
* @param	champ : the input field being checked
* @param	decimalpart : the number of numeric characters allowed after the decimal point.
* @param	negativenum : are the negative numbers allowed ?
* @return	(boolean) true, if the input is valid
*
* @remark
*
* @example	<input type="text" name="taux" size="10" maxlength="8" value="<%= taux %>"
*				onKeyPress="checkOnKeyPressNum( true, false );"
*				onFocus="select(this);" onChange="change = true;"
*				onBlur="checkNumeric( this, 2, false );">
*
*/

function checkOnBlur( numeric, incorrect, champ, decimalpart, negativenum ){

	decimalpart = ( null == decimalpart ) ? 0 : decimalpart ;
	negativenum = ( null == negativenum ) ? false : negativenum ;
	var cptDecSep = 0;

	var lnumeric = new String('0123456789'+ ( ( decimalpart > 0) ? '.' : '' )+ ( ( negativenum ) ? '-' : '' ) );

	for( var i=0; i < champ.value.length; i++){

		charvalue = champ.value.substring(i,i+1)

		if (numeric) {
			if ( lnumeric.indexOf( charvalue ) == -1 ) {
				alert( "La valeur saisie n'est pas un numérique." );
				champ.focus();
				return false;
			}
			if ( negativenum && charvalue == '-' && i != 0 ) {
				alert( "La valeur numérique saisie n'est pas valide." );
				champ.focus();
				return false;
			}
			if ( decimalpart > 0 && charvalue == '.' ) {
				if ( cptDecSep != 0 ) {
					alert( "La valeur numérique saisie n'est pas valide." );
					champ.focus();
					return false;
				}
				else
					cptDecSep = 1;
			}
		}

		if ( incorrect.indexOf( charvalue ) > -1 ) {
			alert( "La valeur saisie n'est pas valide." );
			champ.focus();
			return false;
		}
	}

	return true;
}

function checkNumeric(field, decpart, negative ) {

	if ( field.value.length == 0 ) return true;

	if ( !checkOnBlur( true, '', field, decpart, negative )) return false;

	if ( decpart > 0 ) {
		if ( field.value.indexOf('.') != -1 && field.value.indexOf('.') < field.value.length - decpart - 1 )
		{
			alert( "La valeur numérique à saisir est limitée à "+decpart+" décimale(s)." );
			field.focus();
			return false;
		}
	}

	return true;
}

function checkMois(field) {

	if ( field.value.length == 0 ) return true;

	if ( !checkOnBlur( true, '', field)) return false;

	if ( field.value > 12 || field.value < 1 )
	{
		alert( "Le mois n'est pas valide." );
		field.value = '';
		field.focus();
		return false;
	}

	return true;
}

function checkAnnee(field) {

	if ( field.value.length == 0 ) return true;

	if ( !checkOnBlur( true, '', field)) return false;

	if ( field.value < 1900 )
	{
		alert( "L'année n'est pas valide." );
		field.value = '';
		field.focus();
		return false;
	}
	return true;
}

function checkOnBlurNumDebut( num_debut, num_fin ) {

	var sValueDebut = num_debut.value;

	var sValueFin = num_fin.value;

 	if ( sValueDebut.length == 0 || sValueFin.length == 0 ) return true;

	sValueDebut = 1 * num_debut.value;

	sValueFin = 1 * num_fin.value;

	if ( sValueDebut > sValueFin ) {

		alert( 'La valeur minimale "'+sValueDebut+'" est supérieure à la valeur maximale "'+sValueFin+'".' );

		num_debut.value = "";

		num_debut.focus();

		return false;
	}

	return true;
}

function checkOnBlurNumFin( num_debut, num_fin ) {

	var sValueDebut = num_debut.value;

	var sValueFin = num_fin.value;

 	if ( sValueDebut.length == 0 || sValueFin.length == 0 ) return true;

	sValueDebut = 1 * num_debut.value;

	sValueFin = 1 * num_fin.value;

	if ( sValueDebut > sValueFin ){

		alert( 'La valeur maximale "'+sValueFin+'" est inférieure à la valeur minimale "'+sValueDebut+'".' );

		num_fin.value = "";

		num_fin.focus();

		return false;
	}

	return true;
}



function checkOnBlurDebut( dt_debut, dt_fin ) {

	var dDateDebut, dDateFin;

	if ( !checkDate(dt_debut, null) ) return false;

	var sValueDebut = dt_debut.value;
	var sValueFin = dt_fin.value;

	if ( sValueDebut.length == 0 || sValueFin.length == 0 ) return true;

	dDateDebut = new Date( parseInt( sValueDebut.substr(6, 4), 10), parseInt( sValueDebut.substr(3, 2) - 1, 10 ), parseInt( sValueDebut.substr(0, 2), 10 ) );
	dDateFin = new Date( parseInt( sValueFin.substr(6, 4), 10), parseInt( sValueFin.substr(3, 2) - 1, 10 ), parseInt( sValueFin.substr(0, 2), 10 ) );

	if ( dDateDebut > dDateFin ){
		alert( 'La date de début saisie "'+sValueDebut+'" est supérieure à la date de fin "'+sValueFin+'".' );
		dt_debut.value = '';
		dt_debut.focus();
		return false;
	}

	return true;
}

function checkOnBlurFin( dt_debut, dt_fin ) {

	var dDateDebut, dDateFin;

	if ( !checkDate(dt_fin, null) ) return false;

	var sValueDebut = dt_debut.value;
	var sValueFin = dt_fin.value;

	if ( sValueDebut.length == 0 || sValueFin.length == 0 ) return true;

	dDateDebut = new Date( parseInt( sValueDebut.substr(6, 4), 10), parseInt( sValueDebut.substr(3, 2) - 1, 10 ), parseInt( sValueDebut.substr(0, 2), 10 ) );
	dDateFin = new Date( parseInt( sValueFin.substr(6, 4), 10), parseInt( sValueFin.substr(3, 2) - 1, 10 ), parseInt( sValueFin.substr(0, 2), 10 ) );

	if ( dDateDebut > dDateFin ){
		alert( 'La date de fin saisie "'+sValueFin+'" est inférieure à la date de début "'+sValueDebut+'".' );
		dt_fin.value = '';
		dt_fin.focus();
		return false;
	}
	return true;
}

/**
*
* @function	checkSize()
*
* Check an textarea HTML field to verify if the maximum size has been reached
*
* @param	field : the textarea field
* @param	maxSize :  the maximum contains size
* @param	fieldName : the name of the textarea to personalize the message
* @return	(boolean) true if the maximum size has not been reached
*
* @example	<textarea name="descriptif" cols="55" rows="13" onChange="change = true;"
*			onFocus="select(this);" onBlur="checkSize(this, 2000, 'Descriptif');"><%= descriptif %></textarea>
*
*/

function checkSize( field, maxSize, fieldName ) {

	if ( field.value.length <= maxSize ) return true;

	if (null == fieldName) fieldName = 'Commentaire';
	alert( 'Le champ '+fieldName+' ne peut pas comporter plus de ' + maxSize + ' caractères.' );
	field.value = field.value.substr(0, maxSize );
	field.focus();
	return false;
}

/**
*
* @function	checkIsEmail()
*
* Check if the input can be a valid e-mail address (check just the syntax)
*
* @param	field :  the input field
* @param	text : the error message to show if needed.
* @return	(boolean) true if correct
*
*/

function checkIsEmail(field, text) {

	var sValue = field.value;
  	var ln = sValue.length;

  	if (ln != 0) {
  		if (sValue.indexOf('@') != -1) {
  		 	// Contient le '@'
  		 	if ((sValue.charAt(ln-4)=='.') || (sValue.charAt(ln-3)=='.')) {
  			 	// teste l'extension .fr .com
	  		 	return true;
	  	 	}
	  	}

		if (text == null)
			alert("L'adresse email doit être de la forme utilisateur@serveur.xx(x)");
		else
			alert(text);

		field.value = '';
		field.focus();
		return false;
 	}
  return true;
}

/**
*
* @function	toUpper(), toLower(), toCapitalize()
*
* Convert the input in the appropriated mode
*
* @param	field : the input field to be converted
* @return 	(boolean) true.
*
* @example	<input type="text" name="libelle" size="32" maxlength="30" value="<%= libelle %>"
*			onFocus="select(this);" onChange="change = true;" onBlur="toLower( this );">
*
*/

// Mettre en Majuscule un champ
function toUpper(field) {
	field.value = field.value.toUpperCase();
	return true;
}

// Mettre en Minuscule un champ
function toLower(field) {
	field.value = field.value.toLowerCase();
	return true;
}

// Mettre en la première lettre d'un champ en majuscule
function toCapitalize( field ) {

	var buffer   = field.value.substring( 1, field.value.length ).toLowerCase();
	var resultat = field.value.substring( 0, 1).toUpperCase();
	var posDeb = -1;

	while ( (posDeb = buffer.indexOf( "-" )) != -1 ) {
		resultat += buffer.substring( 0, posDeb + 1 ) + buffer.substring( posDeb + 1, posDeb + 2 ).toUpperCase();
		buffer = buffer.substring( posDeb + 2, buffer.length );
	}

	resultat += buffer;

	field.value = resultat;
	return true;
}

/**
*
* @function	openUnderWin() and closeUnderWin()
*
* function to manage a child window.
*
* @param	theURL :  the URL of the HTML page to display inside the child window
* @param	name :  the window name
* @param	param : some open parameters if necessary
* @return	None.
*
*/

function openUnderWin( theURL, name, param, posX, posY ) {

	if ( null == posX ) posX = 5;
	if ( null == posY ) posY = 5;
	if ( null == param ) param = "";

	// A vérifier
	param += (("" == param) ? "" : ",")+"x="+posX+",y="+posY;

	theChildWindow = window.open( theURL, name, param, true );

	if (theChildWindow != null){

		theChildWindow.moveTo( posX,posY );
		theChildWindow.focus();
	}
}

function closeUnderWin() {

	if (theChildWindow != null){
		theChildWindow.close();
	}

}

