// VALIDATION FUNCTIONS

function CheckPassword( val, param )
{
	if( ( val != null ) && ( val.length == 0 ) )
	{
		return true;
	}
	
	if( param > 0 )
	{
		var params = param.split( ":" );
		if( params.length == 2 )
		{
			//alert( parseInt( params[ 0 ] ) );
			//alert( parseInt( params[ 1 ] ) );
			// interval
			if( ( val.length >= parseInt( params[ 0 ] ) ) && ( val.length <= parseInt( params[ 1 ] ) ) )
				return true;
		}	
		else
		{
			//alert( parseInt( params[ 0 ] ) );
			// minimum value
			if ( val.length >= parseInt( params[ 0 ] ) )
				return true;
		}
		return false;
	}

	return true;
}

function ComparePasswords( val, param, doc )
{
	if( doc == null )
		var doc = document;
	var passwd2 = doc.getElementById( param );
	
	if( ( val.length == 0 ) && ( passwd2.value.length == 0 ) )
		return true;
	if( val == passwd2.value )
		return true;
		
	return false;
}

function MM_findObj(n, docum) //, d) 
{ //v4.0

  var p,i,x;  
  var doc;
  
  if ( docum != null )
  {
	doc = docum;
  }
  else
  {
	  try{
		doc = document;
	  }
	catch( Exception )
	{
		doc = document;
	}
  }
  //alert( "Getting control by name: " + n );
  try{
	x = doc.getElementById( n ); 
  }
  catch( Exception )
  {
	x = null;
  }
  if( x == null )
  {
	try{
		//alert( "testing controls" );
		for( i = 0; i < doc.forms[ 0 ].elements.length; i++ )
		{
			//alert( "testing -- " + doc.forms[ 0 ].elements[ i ].name );
			if( doc.forms[ 0 ].elements[ i ].name == n )
			{
				x = doc.forms[ 0 ].elements[ i ];
				break;
			}
		}
	}
	catch( Exception )
	{
		x = null;
	}
  }
  return x;
}

//Check if we have selected checkboxes
function isCheckboxSelected(form1 , checkBoxName)
{
	var form;
	if(form1 == null){
		form = document.frmMain;
	}
	else
	{
		form = form1;
	}

	for( i=0; i<form.elements.length; i++)
	{
		if( ( form.elements[i].type == "checkbox" )&&
			( form.elements[i].name	== checkBoxName ) &&
			( form.elements[i].checked )
		  )
		{
			return true;
		}
	}
	return false;
}

function isNotEmpty(val)
{
  return ((trim(val)).length>0);
}

function isEmail(val)
{
	if((val != null) && (val != "")){
		//var m = val.match(/\w+[.]?\w*@\w+[.]\w+/g);
		var m = val.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i);
		return ((m!=null)&&(m.length>0));
	}
	else{
		return false;
	}
}

function isSmaller( val, maxValue )
{
	if(val.length>0)
	{
		if(isNum(val))
			{
				vmax=eval( maxValue );
				if ( val >= vmax ) return 0;
				return 1;
			} 
		else return 0;
	} 
	else
	{
		return 1;
	}
}

function isGreater( val, minValue )
{
	//alert( "Getting " + val + "  param = " + minValue );
	if(val.length>0)
	{
		if(isNum(val))
			{
				//alert( "Processing " + val + "  param = " + minValue );
				vmin=eval( minValue );
				if ( val <= vmin ) return 0;
				return 1;
			} 
		else return 0;
	} 
	else
	{
		return 1;
	}
}

function isBetween(val,interval)	//inRange
{ 
	if(val.length>0)
	{
		if(isNum(val))
			{
				cpos=interval.indexOf(':');
				vmin=eval(interval.substring(0, cpos));
				vmax=eval(interval.substr(cpos+1));
				if (val<vmin || vmax<val) return 0;
				return 1;
			} 
		else return 0;
	} 
	else
	{
		return 1;
	}
}

function getMin(test)	//helper to isBetween
{
	return test.substring(0,test.indexOf(':'));
}


function getMax(test)	//helper to isBetween
{
	return test.substr(test.indexOf(':')+1);
}


function isNum(val)
{
  if (isNaN(val)) return 0;
  return 1;
}

function isChecked(val)
{
  return val.checked;
}

function isSelected(val)
{
  return val.selectedIndex;
}

function isNotZeroSel(val)
{
	if ( val.selectedIndex == 0 )	
		return false;
	else
		return true;  

}

function isRadioSelected(val)
{
	//alert(val);
	var i;
	var form;
	try{
		form=document.forms[0];
	}
	catch (Exception)
	{
		form=document.forms[0];
	}
	for(i=0;i<form.elements.length;i++)
	{
		if(form.elements[i].name==val)
		{
			if(form.elements[i].checked)
			{
				return true;
			}
		}
	}
	return false;
}

/*{
	var form;
	if(form1 == null){
		form = top.mainFrame.document.frmMain;
	}
	else
	{
		form = form1;
	}

	for( i=0; i<form.elements.length; i++)
	{
		if( ( form.elements[i].type == "checkbox" )&&
			( form.elements[i].name	== checkBoxName ) &&
			( form.elements[i].checked )
		  )
		{
			return true;
		}
	}
	return false;
}*/

function getParamsText(params)
{
	return params.substr(params.indexOf(',')+1);
}

function isDateAfter(objDate1,params)
{
	
	objDate2 = MM_findObj(params.substr(0,params.indexOf(',')));
	valDate1 = objDate1.value;
	valDate2 = objDate2.value;

	if (valDate2 == "") 
		return true;
	else
		return (valDate2>=valDate1)
}

function isValidPhoneChar(c)
{
	if((c == "0")||(c == "1")||(c == "2")||(c == "3")||(c == "4")) return true;
	if((c == "5")||(c == "6")||(c == "7")||(c == "8")||(c == "9")) return true;
	if((c == '/')||(c == '-')||(c == '+')) return true;
	if((c == '(')||(c == ')')||(c == ' ')) return true;
	return false;
}

function isPhoneValid(value)
{
	var i=0;
	var s = new String();
	var c='';
	s = value.toString()
	for(i=0;i<s.length;i++)
	{
		c = s.substring(i,i+1);
		if(!isValidPhoneChar(c))
		{
			return false;
		}
	}
	return true;
}


function isDateBefore(objDate1,params)
{	
	//alert("params = "+params);
	valDate2 = params.substr(0,params.indexOf(','));
	valDate1 = objDate1.value;	
	
	//alert(valDate1+"; "+valDate2);
	
	if (valDate1 == "") 
		return true;
	else
		return (valDate2<=valDate1);
	
}

function isValidFileName(filename)
{
	//alert(filename);
	if(filename.indexOf('<')!=-1) return false;
	if(filename.indexOf('>')!=-1) return false;
	if(filename.indexOf('/')!=-1) return false;
	if(filename.indexOf('?')!=-1) return false;
	//if(filename.indexOf(':')!=-1) return false;
	if(filename.indexOf(';')!=-1) return false;
	if(filename.indexOf('\'')!=-1) return false;
	if(filename.indexOf('\"')!=-1) return false;
	//if(filename.indexOf('\\')!=-1) return false;
	if(filename.indexOf('[')!=-1) return false;
	if(filename.indexOf(']')!=-1) return false;
	if(filename.indexOf('{')!=-1) return false;
	if(filename.indexOf('}')!=-1) return false;
	if(filename.indexOf('|')!=-1) return false;
	if(filename.indexOf('=')!=-1) return false;
	if(filename.indexOf('+')!=-1) return false;
	if(filename.indexOf('*')!=-1) return false;
	if(filename.indexOf('&')!=-1) return false;
	if(filename.indexOf('^')!=-1) return false;
	if(filename.indexOf('%')!=-1) return false;
	if(filename.indexOf('$')!=-1) return false;
	if(filename.indexOf('#')!=-1) return false;
	if(filename.indexOf('@')!=-1) return false;
	if(filename.indexOf('!')!=-1) return false;
	if(filename.indexOf('~')!=-1) return false;
	
	return true;
	
}

function isAlphaCharacters( chars )
{
	var alpha = new RegExp( "^[a-zA-Z0-9]*$" );
	var res = alpha.exec( chars );
	if( ( res != null ) )
	{
		return true;
	}
	else
	{
		return false;
	}
}

function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}



function validateForm(paramList,doc) { //v4.0
  var i,p,q,nm,test,display, params, num,min,max,errors='',args=validateForm.arguments;
  for (i=0; i<(paramList.length-3); i+=4) 
  { 
	if(paramList[i]!=" ")
	{
		ctrl=MM_findObj(paramList[i]);		
	}
	
	display=paramList[i+1];
	
    test=paramList[i+2];
    //alert('test:' + test);
    params=paramList[i+3]; 

		/******************************* ENGLISH	*/
		// FIELD MUST NOT BE EMPTY ---- FOR SPAN/DIV
		if(test.indexOf('REQ1')>-1)
		{
			if (!isNotEmpty(ctrl.innerHTML)) 
				errors+='- Vous devez completer le champ "'+display+'";\n';
		}		
		else{
			// FIELD MUST NOT BE EMPTY
			if(test.indexOf('REQ')>-1) {if (!isNotEmpty(ctrl.value)) errors+='- Vous devez completer le champ  "'+display+'";\n'};
		}
		// FIELD MUST BE AN EMAIL ADDRESS
		if(test.indexOf('EML')>-1) {if (!isEmail(ctrl.value)) errors+='- Le champ "'+display+'" doit contenir un adresse email correcte;\n'};
		// FIELD MUST BE A NUMBER ---- FOR SPAN/DIV
		if(test.indexOf('NUM1')>-1) 
		{
			if (!isNum(ctrl.innerHTML)) 
				errors+='- Le champ "'+display+'" doit contenir une valeur numerique;\n';
		}
		else{
			// FIELD MUST BE A NUMBER
			if(test.indexOf('NUM')>-1) {if (!isNum(ctrl.value)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique;\n'};
		}
		// FIELD MUST CONTAIN A NUMERIC VALUE GREATER THAN GIVEN ONE
		if(test.indexOf('ATL')>-1) {if (!isGreater(ctrl.value,params)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique superieure ou egale a ' + params + ';\n'};
		// FIELD MUST CONTAIN A NUMERIC VALUE SMALLER THAN GIVEN ONE
		if(test.indexOf('ATM')>-1) {if (!isSmaller(ctrl.value,params)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique inferieure a ' + params + ';\n'};
		// FIELD MUST CONTAIN A NUMERIC VALUE BETWEEN TWO LIMITS
		if(test.indexOf('BTW')>-1) {if (!isBetween(ctrl.value,params)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique comprise entre ' + getMin(params) + ' et ' + getMax(params) + ';\n'};
		// THERE SHOULD BE AT LEAST ONE OPTION CHECKED ( CHECKBOX ) (1)
		if(test.indexOf('CHK')>-1) {if (!isChecked(ctrl)) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'};
		// THERE SHOULD BE AT LEAST ONE OPTION SELECTED ( LISTBOX )
		if(test.indexOf('SSL')>-1) {if (!isSelected(ctrl)) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'}; 
		// THERE SHOULD BE AT LEAST ONE OPTION SELECTED ( DROPDOWNLIST )	
		if(test.indexOf('SL0')>-1) {
		                             if (!isNotZeroSel(ctrl))
		                             { 
		                                errors+='- Vous devez selectionner une option pour "'+display+'" ;\n';
		                             }
		                            } 
		// THERE SHOULD BE AN OPTION SELECTED ( RADIOBUTTON LIST )
		if(test.indexOf('RSL')>-1) {if (!isRadioSelected(paramList[i])) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'};
		// THERE SHOULD BE AT LEAST ONE OPTION CHECKED IN ONE CHECKBOX ( CHECKBOX ) (2)	
		if(test.indexOf('CKL')>-1) {if (!isCheckboxSelected(null , paramList[ i ])) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'};
		// DUNNOW ( DATE related )
		if(test.indexOf('AFT')>-1) {if (!isDateAfter(ctrl,params)) errors+='- "'+getParamsText(params)+'" doit etre ulterieure a "' + display + '";\n'};
		if(test.indexOf('BEF')>-1) {if (!isDateBefore(ctrl,params)) errors+='- "' + display + '" doit etre anterieure a "'+getParamsText(params)+'";\n'};
		if(test.indexOf('PHN')>-1) {if (!isPhoneValid(ctrl.value)) errors+='- Le champ "'+display+'" doit contenir un numero de telephone correct;\n'};
		// THE FIELD SHOULD CONTAIN A VALID FILE NAME
		if(test.indexOf('FIL')>-1) {if (!isValidFileName(ctrl.value)) errors+='- "' + display + '" doit contenir un nom de fichier correct;\n'};
		// THE FIELD SHOULD CONTAIN VALID ALPHA CHARS
		if( test.indexOf('ALF')>-1) { if( !isAlphaCharacters( ctrl.value ) ) errors += ' - "' + display + '" doit contenir des caracteres alphanumeriques;\n'};

		// comparing two fields
		if( test.indexOf( 'PWDC' ) > -1 ){ if( !ComparePasswords( ctrl.value, params.split(',')[ 0 ] ) ) errors += '- Le champ "' + params.split( ',' )[ 1 ] + '" doit correspondre au champ "' + display + '";\n'};
		// testing for required number of chars
		if( test.indexOf('PWD')>-1) 
		{ 
			if( !CheckPassword( ctrl.value, params, document ) ) 
			{
				if( paramList[ i ].length > 0 )
					var p = params.split( ":" );
				else
					var p = "";
				if( params.length == 1 )
					errors += '- Le champ "' + display + '" doit contenir au moins ' + params + ' caracteres;\n';
				else
				{
					if( params.length == 2 )
						errors += '- Le champ "' + display + '" doit contenir au moins ' + p[ 0 ] + ' caracteres et au plus ' + p[ 1 ] + ' caracteres;\n';
				}
			}
		}
		

  }
	
  if (errors)
  {
		displayAlertPopup( 'Le formulaire n\'est pas entierement complete:\n'+errors, "Erreurs de validation" );
		//alert('The form is not fully completed:\n'+errors);
  }
  //document.IsValidated = 
  if(errors == '')
	return true;
  else
	return false;
	
}

function getValidationError(paramList, doc) { //v4.0
	
  var i,p,q,nm,test,display, params, num,min,max,errors='',args=validateForm.arguments;
  for (i=0; i<(paramList.length-3); i+=4) 
  { 
	if(paramList[i]!=" ")
	{
		ctrl=MM_findObj(paramList[i]);		
	}
	
	display=paramList[i+1];
	
    test=paramList[i+2];
    //alert('test:' + test);
    params=paramList[i+3]; 

	var ctrlValue = null;
	try{
		ctrlValue = ctrl.value;
	}
	catch( Exception )
	{
		ctrlValue = ctrl.innerHTML;
	}

		/******************************* ENGLISH	*/
		// FIELD MUST NOT BE EMPTY
		if(test.indexOf('REQ')>-1) {if (!isNotEmpty(ctrl.value)) errors+='- Vous devez completer le champ "'+display+'";\n'};
		// FIELD MUST BE AN EMAIL ADDRESS
		if(test.indexOf('EML')>-1) {if (!isEmail(ctrl.value)) errors+='- Le champ "'+display+'" doit contenir un adresse email correcte;\n'};
		// FIELD MUST BE A NUMBER
		if(test.indexOf('NUM')>-1) {if (!isNum(ctrl.value)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique;\n'};
		// FIELD MUST CONTAIN A NUMERIC VALUE GREATER THAN GIVEN ONE
		if(test.indexOf('ATL')>-1) {if (!isGreater(ctrl.value,params)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique superieure ou egale a ' + params + ';\n'};
		// FIELD MUST CONTAIN A NUMERIC VALUE SMALLER THAN GIVEN ONE
		if(test.indexOf('ATM')>-1) {if (!isSmaller(ctrl.value,params)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique inferieure a ' + params + ';\n'};
		// FIELD MUST CONTAIN A NUMERIC VALUE BETWEEN TWO LIMITS
		if(test.indexOf('BTW')>-1) {if (!isBetween(ctrl.value,params)) errors+='- Le champ "'+display+'" doit contenir une valeur numerique comprise entre ' + getMin(params) + ' et ' + getMax(params) + ';\n'};
		// THERE SHOULD BE AT LEAST ONE OPTION CHECKED ( CHECKBOX ) (1)
		if(test.indexOf('CHK')>-1) {if (!isChecked(ctrl)) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'};
		// THERE SHOULD BE AT LEAST ONE OPTION SELECTED ( LISTBOX )
		if(test.indexOf('SSL')>-1) {if (!isSelected(ctrl)) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'}; 
		// THERE SHOULD BE AT LEAST ONE OPTION SELECTED ( DROPDOWNLIST )	
		if(test.indexOf('SL0')>-1) {   if (!isNotZeroSel(ctrl)) errors+='- Vous devez selectionner une option pour "'+display+'" ;\n'}; 
		// THERE SHOULD BE AN OPTION SELECTED ( RADIOBUTTON LIST )
		if(test.indexOf('RSL')>-1) {if (!isRadioSelected(paramList[i])) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'};
		// THERE SHOULD BE AT LEAST ONE OPTION CHECKED IN ONE CHECKBOX ( CHECKBOX ) (2)	
		if(test.indexOf('CKL')>-1) {if (!isCheckboxSelected(doc.forms[ 0 ] , paramList[ i ])) errors+='- Dans le champ "'+display+'" vous devez selectionner au moins une option;\n'};
		// DUNNOW ( DATE related )
		if(test.indexOf('AFT')>-1) {if (!isDateAfter(ctrl,params)) errors+='- "'+getParamsText(params)+'" doit etre ulterieure a "' + display + '";\n'};
		if(test.indexOf('BEF')>-1) {if (!isDateBefore(ctrl,params)) errors+='- "' + display + '" doit etre anterieure a "'+getParamsText(params)+'";\n'};
		if(test.indexOf('PHN')>-1) {if (!isPhoneValid(ctrl.value)) errors+='- "'+display+'" doit contenir un numero de telephone correct;\n'};
		// THE FIELD SHOULD CONTAIN A VALID FILE NAME
		if(test.indexOf('FIL')>-1) {if (!isValidFileName(ctrl.value)) errors+='- "' + display + '" doit contenir un nom de fichier correct;\n'};

		// comparing two fields
		if( test.indexOf( 'PWDC' ) > -1 ){ if( !ComparePasswords( ctrl.value, params.split(',')[ 0 ] ) ) errors += ' - Le champ "' + params.split( ',' )[ 1 ] + '" doit correspondre au champ "' + display + '";\n'};
		// testing for required number of chars
		if( test.indexOf('PWD')>-1) 
		{ 
			if( !CheckPassword( ctrl.value, params, document ) ) 
			{
				if( paramList[ i ].length > 0 )
					var p = params.split( ":" );
				else
					var p = "";
				if( params.length == 1 )
					errors += ' - Le champ "' + display + '" doit contenir au moins ' + params + ' caracteres;\n';
				else
				{
					if( params.length == 2 )
						errors += ' - Le champ "' + display + '" doit contenir au moins ' + p[ 0 ] + ' caracteres et au plus ' + p[ 1 ] + ' caracteres;\n';
				}
			}
		}
  }
	
  if (errors)
  {
		return errors;
	
	//	alert('The form is not fully completed:\n'+errors);
  }
  
  else
  {
		return "";
}
	
}

function doSave( form ) {	

	var doc;
	
	if ( form == null ) {
		form = document.frmMain;
	}
	
	var needsValidation;
	try {
		if ( form.hNeedsValidation.value == "true" ) {
			needsValidation = true;
		} else {	
			needsValidation = false;
		}
	}
	catch( Exception ) {
		needsValidation = false;
	}
	
	if( needsValidation ) {
		var paramList;		
		var paramArray;

		paramList=form.hValidParams.value.toString();
		paramArray=paramList.split(", ");

		if(validateForm(paramArray,doc)) {
			form.submit();
		}
	} else {	
		form.submit();		
	}	
}
