//associative array that maps the names of the fields that contain dates to 
//the number of fields with the same name that have to be checked
//in this version, all the counts are initialized to 1
//set by dateFields()
//used by checkDateTimeValid()
var dates;

//  fill up hidden field 'HAVE_JS' with "true' if javascript is enabled
//
function checkIfJs(){
    var formElems=document.forms[0].elements;	
    /* check if the form elements exists */
    if (formElems){
	/* check if the field exists */
	if (formElems['HAVE_JS']) {
	    /* fill in the HAVE_JS field  */   
	    // document.myform.HAVE_JS.value ="true";
	    formElems['HAVE_JS'].value="true";
	    /* just a debug remove after tests */
	    // alert ('ok, havejs');
	} 
    }
    
}

function isArray(obj){return(typeof(obj.length)=="undefined")?false:true;}
var bookDebug=false;
//var bookDebug=true;

function checkRoomBookingType( message1 ){
    var formElems=document.forms[0].elements;
    if( message1 ==null || message1==''){
	message1='You cannot share a single room\nPlease select another room type';
    }
     /* check if the form elements exists */
    if (formElems){

	/* check if the field exists
	   First step is to know what the user checked for the sharing, 
	   if he choosed the "no sharing" i set the noSharingIsSelected -> true

	*/

	if (bookDebug){
		alert ("okformElems");
		//alert ("1>>"+formElems['HOTEL_NOT_NEEDED'][1].checked);
		//alert ("0>>"+formElems['HOTEL_NOT_NEEDED'][0].checked);
	}
	if (formElems['HOTEL_NOT_NEEDED']){
	    if (formElems['HOTEL_NOT_NEEDED'][1]){
		if (formElems['HOTEL_NOT_NEEDED'][1].checked){
			if (bookDebug)alert ("no accomoodation, break");
			return true;	
		}	
	    }
	    else {
		if (bookDebug)alert ("no accomoodation, break");
		return true;	
	    }
	}
	
	var noSharingIsSelected=false;
	var isSingleRoom=false

	if (formElems['ROOM_SHARING'] ) {
	    if (bookDebug)alert ("room sharing exist");
	    var myRoomSharing=formElems['ROOM_SHARING'];
	    var myLength=myRoomSharing.length ;
	    //alert (myLength);
	    
	    if (myLength>0){
		if (bookDebug)alert ("myLength="+myLength);
		for (i=0; i<myLength;i++){
		    
			// check the name of the field, I got to check if the "no sharing is checked"
			// I need to use both indexes and values to figure out
		    if (myRoomSharing[i].value=="0"){
			// the "no sharing is checked, it's the only way to book a single room
			noSharingIsSelected =myRoomSharing[i].checked;
			
			
		    }
		    
		    
		}
	    }
	}
	else {
		if (bookDebug)alert ("No Room sharing question, consider no sharing is selected");
		noSharingIsSelected =true;
	
	}

	/*  mode auto booking, the functon will use any of the room selection type, depending if the fields exist*/
	//if (bookDebug)alert ("isArray(singleRoomsArray)="+isArray(singleRoomsArray));
	if (window.singleRoomsArray && formElems['ROOM_TYPE_ID']){
	    var myRtId=formElems['ROOM_TYPE_ID'];
	    var myRtIdidx=formElems['ROOM_TYPE_ID'].selectedIndex;
	    var myRtIdValue=myRtId.options[myRtIdidx].value;
	    // "afficheImage(this.options[this.selectedIndex].value)">
	    if (bookDebug)alert ("myRtIdValue="+myRtIdValue);
	    if (isArray(window.singleRoomsArray)){
		var rsLgt=window.singleRoomsArray.length ;
		if (rsLgt>0){
		    for (i=0; i<rsLgt;i++){
			if (bookDebug)alert ("compare >>"+myRtIdValue+"<< and >>"+window.singleRoomsArray[i]);
			if (myRtIdValue==window.singleRoomsArray[i]){
			    if (bookDebug)alert (" >>"+myRtIdValue+"<< and >>"+window.singleRoomsArray[i]+" SAME SAME !!");
			    // it's a single room !  no sharing possible
			    isSingleRoom=true;

			}
			
		    }
		}
	    }
	    
	    if (bookDebug)alert ("noSharingIsSelected="+noSharingIsSelected+"  isSingleRoom="+isSingleRoom);

	    if (!noSharingIsSelected&&isSingleRoom){
		alert(message1);
		submitcount=0;
		return false;
	    }
	    if (bookDebug){
		alert('book debug, should submit the form');
		submitcount=0;
		return false;
	    }
	    
	}


	/*  mode HOTEL SELECTION, the functon will use any of the room selection type, depending if the fields exist*/
	else if (!window.singleRoomsArray){
	    if (bookDebug)alert ("mode HOTEL SELECTION");
	    /* check if the field exists */
	    if (formElems['ACCOMODATION_TYPE_ID']) {

		var myAccTid=formElems['ACCOMODATION_TYPE_ID'];
		//myAccTid.type.toLowerCase() != "hidden" 
		
		if (bookDebug)alert ("I got a ACCOMODATION_TYPE_ID \nmyAccTid.type.toLowerCase()="+myAccTid.type.toLowerCase());
		if (!noSharingIsSelected && formElems['ACCOMODATION_TYPE_ID'].value=="1" && myAccTid.type.toLowerCase()!="hidden"){
		    alert(message1);
		    submitcount=0;
		    return false;
		}
		else return true;
	    } 
	    else return true;
	}
	return true;
	
    }
    else return true;
}


function addZero(vNumber){ 
    return ((vNumber < 10) ? "0" : "") + vNumber ;
} 
function comparePasswords(){
    var formElems=document.forms[0].elements;
    if (formElems){
	var pass1=formElems["PASSWORD"];
	var pass2=formElems["PASSWORD2"];
	
	//return true;
	if (pass1 && pass2){
	    if(pass1.value!=pass2.value){
		alert("The passwords you entered do not match");
		pass1.value="";
		pass2.value="";
		submitcount=0;
		return false;
	    }
	    if(pass1.value.length < 6 && pass1.value.length>0){
		alert("The password should have 6 characters minimum");
		submitcount=0;
		return false;
	    }
	    return true;
	}
    }
    return true;
}

function formatDateForHotelAutoBooking(origDateAsString){
  // alert ("format "+origDateAsString)
    var tmpArray;
    tmpArray=origDateAsString.split(dtInfo.dateSeparator.charAt(0));

    var day=parseInt(tmpArray[dtInfo.dayPos], 10);
    var month=parseInt(tmpArray[dtInfo.monthPos], 10);
    month =addZero(month);
    day   =addZero(day);

    var year=parseInt(tmpArray[dtInfo.yearPos], 10);
    

    var tmpDate=new Array(3);
    tmpDate[dtInfo.dayPos]=day;
    tmpDate[dtInfo.monthPos]=month;
    tmpDate[dtInfo.yearPos]=year;

    myddateMod=tmpDate[0]+dtInfo.dateSeparator.charAt(0)+tmpDate[1]+dtInfo.dateSeparator.charAt(0)+tmpDate[2];
    //alert ("return "+myddateMod)
	
	
 /*	*/
	
	//myddateMod=origDateAsString;
	
	
    return myddateMod;
    //alreadyalert=true;
    // alert ("myddateMod--"+myddateMod);	
    
}

//called to specify the fields that contain dates
//it saves the names of the fields in the dates array, for later use by checkDateTimeValid()
//usage example: <body onload="dateFields('ARRIVAL_DATE', 'DEPARTURE_DATE')" language=JavaScript>
function dateFields()
	{
	dates=new Array();
	fieldsHelper(dates, dateFields.arguments);
	}
	
//associative array that maps the names of the fields that contain times to 
//the number of fields with the same name that have to be checked
//in this version, all the counts are initialized to 1
//set by timeFields()
//used by checkDateTimeValid()
var times;

//called to specify the fields that contain times
//it saves the names of the fields in the times array, for later use by checkDateTimeValid()
//usage example: <body onload="timeFields('ARRIVAL_TIME', 'DEPARTURE_TIME')" language=JavaScript>
function timeFields()
	{
	times=new Array();
	fieldsHelper(times, timeFields.arguments);
	}



// same for email check...
// usage : <body onload="emailFields('EMAIL', 'EMAIL2')" language=JavaScript>

var emails;
function emailFields()
	{
	emails=new Array();
	fieldsHelper(emails, emailFields.arguments);
	
	}


// same for textarea lenght check...
// usage : <body onload="setTextareaFields('FREE_TEXT_AREA_1', 'FREE_TEXT_AREA_2')" language=JavaScript>
// setTextAreasLenght('250', '512')


var mytextAreas;
function setTextareaFields(){
    mytextAreas=new Array();
    fieldsHelper(mytextAreas, setTextareaFields.arguments);
    
    
}
var textAreasLenght;
function setTextAreasLenght(){
 textAreasLenght=new Array();
 textAreasLenght=setTextAreasLenght.arguments;
 for(i=0; i<textAreasLenght.length; i++){
     //alert (textAreasLenght[i]);
 }
 
}


//helper for dateFields() and timeFields()
function fieldsHelper(fieldsArray, inputArray){
    var i;
    for(i=0; i<inputArray.length; i++){
	fieldsArray[inputArray[i]]=1;
	//alert (inputArray[i]);
    }
}

function similarFields(field1,field2,alertMsg){
    if (field1&&field2){
	var val1=field1.value.trim();
	var val2=field2.value.trim();
	//alert ("val1="+val1+" val1.length£="+val1.length+" val2="+val2+" val2.length£="+val2.length);
	//if (val1.length>0 && val2.length>0 && (val1 != val2)){
	if (val1 != val2){
	    submitcount=0;
	    alert(alertMsg);
	    return false;
	}
    }
    return true;
    
}


//used as an onsubmit handler for the form that contains the fields to be checked
//it's main use is to handle the case when the user presses enter while in a text input field in IE
//it can also be used if the fields have to be checked only once, upon submit, without the validate*() handlers
//usage example: <form method=post action="test.jsp" onsubmit="return(checkDateTimeValid())" language=JavaScript>

function checkDateTimeValid(){
    var myReturnD=false;
    var myReturnT=false;
    
    var formElems=document.forms[0].elements;
    //return checkHelper(dates, formElems, validateDateHelper) && checkHelper(times, formElems, validateTimeHelper);

    var invalidDateMsg="Invalid date";
    if (typeof invalidDateMsgLng!="undefined"){
	invalidDateMsg=invalidDateMsgLng;
    }
    var datesValids=checkDatesHelper(dates, formElems, validateDateHelper);
    if (datesValids=="ok"){
	myReturnD=true;
    }
    else {
	alert (invalidDateMsg+datesValids);
	submitcount=0;
	myReturnD=false;
	
    }
    
    
    var invalidTimeMsg="Invalid time";
    if (typeof invalidTimeMsgLng!="undefined"){
	invalidTimeMsg=invalidTimeMsgLng;
    }
    var timeValids=checkDatesHelper(times, formElems, validateTimeHelper);
    if (timeValids=="ok"){
	myReturnT=true;
    }
    else {
	alert (invalidTimeMsg+timeValids);
	submitcount=0;
	myReturnT=false;
    }
    
    if (myReturnT&&myReturnD){
	return true;
	
    }    
    return false;
    
    //alert( checkDatesHelper(dates, formElems, validateDateHelper));
    
}



function checkDatesHelper(fieldsArray, arrayToScan, validationFunction){
    var allValid=true;
    var tmpArray=new Array();
    var myReturn="";
    var i;
    for(i in fieldsArray){
	tmpArray[i]=fieldsArray[i];
    }
    for(i=0; i<arrayToScan.length; i++){
	var tmpName=arrayToScan[i].name;
	var tmpCount=tmpArray[tmpName];
	if(tmpCount!=null && tmpCount>0){
	    tmpArray[tmpName]--;
	    //alert(arrayToScan[i]+" -- > "+validationFunction(arrayToScan[i]));
	    if(!validationFunction(arrayToScan[i])){
		//      if(debugSumitcout) alert("reset submitcount!");
		submitcount=0;
		allValid=false;
		var lbl=arrayToScan[i].id;
		if (lbl.trim()=="")lbl=arrayToScan[i].name;
		myReturn+="\n"+lbl+": "+arrayToScan[i].value;
		//myReturn+=arrayToScan[i].value+" "+arrayToScan[i].id ;
		//return false;
	    }
	}
    }
    if (allValid)myReturn="ok";
    return myReturn;
}


//used as an onsubmit handler for the form that contains an email to be checked
//work like the dates and times, so don't forget to define the email fields (see function emailFields() )
//usage example: <form method=post action="test.jsp" onsubmit="return(checkEmail())" language=JavaScript>

function checkEmail(){
    var formElems=document.forms[0].elements;
    if( formElems != null ){
	return checkHelper(emails, formElems, checkValidEmail);
    }
    else return true;
}

	
	
	
//used as an onsubmit handler for the form that contains textAreasize
//work like the dates and times, so don't forget to define the textareas fields (see function emailFields() )
//usage example: <form method=post action="test.jsp" onsubmit="return(checkEmail())" language=JavaScript>

function checkTextareas(){
    var formElems=document.forms[0].elements;
    if( formElems != null ){
	//  alert('mytextAreas'+mytextAreas);
	//  	alert('textAreasLenght'+textAreasLenght);
	//  	alert('formElems'+formElems);
      return checkHelperMulti(mytextAreas, textAreasLenght,formElems, checkFieldSize);
      //return checkHelperMulti(mytextAreas,formElems, checkFieldSize);
    }
    else return true;
}



//helper for textAreaLenghtFields()  update of checkHelper() 
// to use 2 dimension array
//scans the array of elements in arrayToScan and applies
//the validation function to the elements that have names in fieldsArray
// with the parameter in paramArray
//returns true if all the validation functions return true, false otherwise



function checkHelperMulti(fieldsArray, paramArray,arrayToScan, validationFunction){
//function checkHelperMulti(fieldsArray,arrayToScan, validationFunction){
  var tmpArray=new Array();
  var i;
  var j=0;
  for(i in fieldsArray){
    tmpArray[i]=fieldsArray[i];
    //alert ('tmpArray[i].name='+tmpArray[i].name);
  }
  for(i=0; i<arrayToScan.length; i++){
    var tmpName=arrayToScan[i].name;
    var tmpCount=tmpArray[tmpName];
    if(tmpCount!=null && tmpCount>0){
      tmpArray[tmpName]--;
     
      //alert ('Validate that crap at i='+i+' and j='+j);
      if(!validationFunction(arrayToScan[i],paramArray[j] )){
	//      if(debugSumitcout) alert("reset submitcount!");
	submitcount=0;
	return false;
      }
      j++;
    }
  }
  return true;
}


//helper for checkDateTimeValid()
//scans the array of elements in arrayToScan and applies
//the validation function to the elements that have names in fieldsArray
//returns true if all the validation functions return true, false otherwise



function checkHelper(fieldsArray, arrayToScan, validationFunction){
    var tmpArray=new Array();
    var i;
    for(i in fieldsArray)
	tmpArray[i]=fieldsArray[i];
    for(i=0; i<arrayToScan.length; i++){
    var tmpName=arrayToScan[i].name;
    var tmpCount=tmpArray[tmpName];
    if(tmpCount!=null && tmpCount>0){
      tmpArray[tmpName]--;
      if(!validationFunction(arrayToScan[i])){
	  //      if(debugSumitcout) alert("reset submitcount!");
	  submitcount=0;
	  return false;
      }
    }
    }
    return true;
}

//contains date and time related information: separators, date format
//used by the validation functions
var dtInfo;

//initializes the dtInfo variable
//must be called before any other of these functions is called
//for example: <body onload="dateTimeInit('/-', 'd/m/y', ':')" language=JavaScript>
//the date separator can be a string of more than one character, which means that any of those 
//characters can act as a separator, but they cannot be mixed in the same date string
//the date format pattern components specify the position of the day, month and year
//patterns like 'ddd / MM / yyyy' or 'date/month/Year' are valid, and have the exact same
//meaning as the first example above. That is:
//-the pattern components only have to begin with the right letter, the rest is ignored
//-the pattern components are case insensitive
//-repeating a specific letter has no special meaning - 'ddd' is the same as 'd'
//-the year has to be specified using 4 digits - 2000, not 00
//-spaces are ignored
//if something is wrong with the date format specified, it is ignored and the date pattern
//is set to the default settings (see below)

function dateTimeInit(dateSeparator, dateFormat, timeSeparator)
	{
	    // that was temporary to fix problem on 18th april 2005
	    //checkIfJs();
	String.prototype.trim=trimSpaces;
	String.prototype.isNumeric=isNumericString;
	dtInfo=new Object();
	dtInfo.dateSeparator=dateSeparator;
	dtInfo.dateFormat=dateFormat.toUpperCase();
	dtInfo.timeSeparator=timeSeparator;
	dtInfo.daysInMonth=new Array(0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var dateFormatArray;
	//find the separator used
	var i;
	for(i=0; i<dtInfo.dateSeparator.length; i++)
		{
		dateFormatArray=dtInfo.dateFormat.split(dtInfo.dateSeparator.charAt(i));
		if(dateFormatArray.length>1)
			break;
		}	
	if(dateFormatArray.length==3)
		{
        var i;
		dtInfo.dayPos=-1;
		dtInfo.monthPos=-1;
		dtInfo.yearPos=-1;
		for(i=0; i<3; i++)
			{
			var dateFormatComp=dateFormatArray[i].trim().charAt(0);
			if(dateFormatComp=="D")
				{
				if(dtInfo.dayPos==-1) dtInfo.dayPos=i;
				else break;
				}
			else if(dateFormatComp=="M")
				{
				if(dtInfo.monthPos==-1) dtInfo.monthPos=i;
				else break;
				}
			else if(dateFormatComp=="Y")
				{
				if(dtInfo.yearPos==-1) dtInfo.yearPos=i;
				else break;
				}
			else
				{
				break;
				}
			}
		if(i==3)//everything OK
			return;
		}
	//if we got here, something is wrong with the dateFormat and dateSeparator; use default
	dtInfo.dateSeparator="/-";
	dtInfo.dateFormat="D/M/Y";
	dtInfo.dayPos=0;
	dtInfo.monthPos=1;
	dtInfo.yearPos=2;
		

	}

//returns true if the date represented by the second argument is after or equal to 
//the date represented by the first argument, false otherwise
//the two fields must contain valid dates, that is, ones that have already been validated 
//and adjusted by the validation functions
//if any of the fields' values is null or an empty string, the function returns true
//the function displays an error message if the dates are not in order
//it is intended to be called from a form's onsubmit handler; usage example:
//<form method=post action="test.jsp" onsubmit="return checkOrderedDates(document.forms[0].elements['ARRIVAL_DATE'], document.forms[0].elements['DEPARTURE_DATE'])" language=JavaScript>

function checkOrderedDates(date1Field, date2Field){
	return 	regisCheckOrderedDates(date1Field, date2Field, "");
}

function regisCheckOrderedDates(date1Field, date2Field, comment){

  if( comment == null){
	comment = "";
  }	

  if( date1Field != null && date2Field != null && !checkOrderedDatesHelper(date1Field.value, date2Field.value)){

    if( date1Field.name.indexOf("TRANSPORT_") > -1 && date2Field.name.indexOf("TRANSPORT_") > -1 ){
      alert("Transportation: Arrival Date cannot be after Departure Date");
    }
    else if( date1Field.name.indexOf("TRANSPORT_") > -1 ||  date2Field.name.indexOf("TRANSPORT_") > -1 ) {
      alert("Transportation: "+ date1Field.name+" cannot be after "+date2Field.name);
    }
    else if(date1Field.name.indexOf("ARRIVAL_DATE") > -1 && date2Field.name.indexOf("DEPARTURE_DATE") > -1){
      alert(comment+"Arrival Date cannot be after Departure Date");
    }
    else{
      alert(comment+date1Field.name+" cannot be after "+date2Field.name);
    }
    // if(debugSumitcout) alert("reset submitcount!");
    submitcount=0;
    return false;
  }
  return true;
}

function checkHotelOrderedDates(date1Field, date2Field){
    return regisCheckOrderedDates(date1Field, date2Field, "HOTEL: ")
}

//helper for checkOrderedDates()
//returns true if the dates are in order or equal, false otherwise
//also returns true if the arguments are null or empty strings

function checkOrderedDatesHelper(date1String, date2String){
	if(date1String==null || date1String.length==0 || date2String==null || date2String.length==0)
		return true;
	var sep=dtInfo.dateSeparator.charAt(0);
	var date1Array=date1String.split(sep);
	var date2Array=date2String.split(sep);
	var year1=parseInt(date1Array[dtInfo.yearPos]);
	var year2=parseInt(date2Array[dtInfo.yearPos]);

	if(year1>year2){
		return false;
	}

	if(year1<year2){
		return true;
	}

	var m1=date1Array[dtInfo.monthPos];
	var m2=date2Array[dtInfo.monthPos];

	var d1=date1Array[dtInfo.dayPos];
	var d2=date2Array[dtInfo.dayPos];

	var month1;
	var month2;
	var day1;
	var day2;
	
	if( m1.indexOf("0") == 0 && m1.length == 2){
	  month1=parseInt(m1.substring(1,2));
	}	
	else{
	  month1=parseInt(m1);
	}
	if( m2.indexOf("0") == 0 && m2.length == 2){
	  month2=parseInt(m2.substring(1,2));
	}	
	else{
	  month2=parseInt(m2);
	}
	if( d1.indexOf("0") == 0 && d1.length == 2){
	  day1=parseInt(d1.substring(1,2));
	}	
	else{
	  day1=parseInt(d1);
	}
	if( d2.indexOf("0") == 0 && d2.length == 2){
	  day2=parseInt(d2.substring(1,2));
	}	
	else{
	  day2=parseInt(d2);
	}
	if(month1>month2){
	  return false;
	}
	if(month1<month2){
	  return true;
	}
	if(day1>day2){
	  return false;
	}
	
	return true;
}

//used by the validate functions, to indicate the time of the last error message display
var lastErrorTime=new Date();

//pops up an error message if the date in inputField is not valid,
//according to the dateSeparator and dateFormat passed to dateTimeInit()
//usage example: <input type=text name="ARRIVAL_DATE" onblur="validateDate(this)" language=JavaScript>
//spaces are ignored around the date elements
//the month and year are optional, i.e. '17' means 'day 17 of the current month and year' 
//and '17/3' means 'March 17th of the current year', if the pattern  is 'd/m/y'
//upon return from the function, the value of the input field is adjusted according to the pattern,
//i.e. spaces trimmed, default elements added, separator set to the first character in the string of separators
function validateDate(inputField){
    var invalidDateMsg="Invalid date";
    if (typeof invalidDateMsgLng!="undefined"){
	invalidDateMsg=invalidDateMsgLng;
    }
    
    if(!validateDateHelper(inputField)){
	    var tmpTime=new Date();
	    if(tmpTime-lastErrorTime>999){
		lastErrorTime=tmpTime;
		var lbl=inputField.id;
		if (lbl.trim()=="")lbl=inputField.name;
		alert(invalidDateMsg+" \n"+lbl+": "+inputField.value);
	    }
	    lastErrorTime=new Date();
	    inputField.focus();
    }
}

//helper for validateDate()
//also used by checkDateTimeValid()
//returns true if the field is OK, false otherwise
//performs all adjustments, if necessary

function validateDateHelper(inputField)
	{
	var inputString=inputField.value.trim();
	if(inputString=="")
		{
		inputField.value=inputString;
		return true;
		}
	var tmpArray;
	//find the separator used
	var i;
	for(i=0; i<dtInfo.dateSeparator.length; i++)
		{
		tmpArray=inputString.split(dtInfo.dateSeparator.charAt(i));
		if(tmpArray.length>1)
			break;
		}
	var compCount=tmpArray.length;
	if(compCount>3)
		return false;
	for(i=0; i<compCount; i++)
		{
		tmpArray[i]=tmpArray[i].trim();
		if(!tmpArray[i].isNumeric())
			return false;
		}
	//if we got here, all components can be parsed to numbers
	var day;
	var month;
	var year;
	if(compCount<3)//handle default values
		{
		var today=new Date();
		year=today.getYear();
		if(year<1900)
			year+=1900;
		if(compCount<2)
			{
			month=today.getMonth()+1;
			day=parseInt(tmpArray[0], 10);
			if(!validateDay(day, month, year))
				return false;
			}
		else
			{
			if(dtInfo.dayPos>dtInfo.monthPos)
				{
				day=parseInt(tmpArray[1], 10);
				month=parseInt(tmpArray[0], 10);
				}
			else
				{
				day=parseInt(tmpArray[0], 10);
				month=parseInt(tmpArray[1], 10);
				}
			if(!validateMonth(month) || !validateDay(day, month, year))
				return false;
			}
		}
	else
		{
		day=parseInt(tmpArray[dtInfo.dayPos], 10);
		month=parseInt(tmpArray[dtInfo.monthPos], 10);
		year=parseInt(tmpArray[dtInfo.yearPos], 10);
		if(!validateYear(year) || !validateMonth(month) || !validateDay(day, month, year))
			return false;
		}
	//if we got here, we have valid values in day, month, year
	//adjust the field value
	var tmpDate=new Array(3);
	tmpDate[dtInfo.dayPos]=day;
	tmpDate[dtInfo.monthPos]=month;
	tmpDate[dtInfo.yearPos]=year;
	inputField.value=tmpDate[0]+dtInfo.dateSeparator.charAt(0)+tmpDate[1]+dtInfo.dateSeparator.charAt(0)+tmpDate[2];
	return true;
	}

//returns true if this is a valid year, false otherwise
//year values should be bigger than 1900
//does not check for NaN, the caller is supposed to do that

function validateYear(year)
	{
	if(year<1900) 
		return false;
	return true;
	}
	
//returns true if this is a valid month, false otherwise
//does not check for NaN, the caller is supposed to do that
function validateMonth(month)
	{
	if(month<1 || month>12)
		return false;
	return true;
	}
	
//returns true if the day is valid in the specified month and year, false otherwise
//the month and year are assumed to be valid
//does not check for NaN, the caller is supposed to do that

function validateDay(day, month, year)
	{
	if(day<1 || day>dtInfo.daysInMonth[month])
		return false;
	if(month==2 && day==29)
		{
		if(year%4!=0 || (year%100==0 && year%400!=0))
			return false;
		}
	return true;
	}

//pops up an error message if the time in inputField is not valid,
//according to the timeSeparator passed to dateTimeInit()
//usage example: <input type=text name="ARRIVAL_TIME" onblur="validateTime(this)" language=JavaScript>
//handles time formats like '5:03pm', '17:03' or '1703'
//spaces are ignored around the time elements
//the AM/PM specifier, if present, is case insensitive
//the minutes value is optional, i.e. '5pm' or '17' means '17:00'
//upon return from the function, the value of the input field is adjusted according to the pattern,
//i.e. spaces trimmed, default elements added

function validateTime(inputField){
    
    
    var invalidTimeMsg="Invalid time";
    if (typeof invalidTimeMsgLng!="undefined"){

	invalidTimeMsg=invalidTimeMsgLng;
    }
    
    if(!validateTimeHelper(inputField)){
	var tmpTime=new Date();
	if(tmpTime-lastErrorTime>999){
	    lastErrorTime=tmpTime;
	    var lbl=inputField.id;
	    if (lbl.trim()=="")lbl=inputField.name;
	    alert(invalidTimeMsg+" \n"+lbl+": "+inputField.value);
	}
	lastErrorTime=new Date();
	inputField.focus();
    }
}

//helper for validateTime()
//also used by checkDateTimeValid()
//returns true if the field is OK, false otherwise
//performs all adjustments, if necessary

function validateTimeHelper(inputField)
	{
	var inputString=inputField.value.trim();
	if(inputString=="")
		{
		inputField.value=inputString;
		return true;
		}
	var amPmSpec=false;
	var pm;
	if(inputString.length>1 && (inputString.charAt(inputString.length-1)=="m" || inputString.charAt(inputString.length-1)=="M"))
		{
		if(inputString.charAt(inputString.length-2)=="a" || inputString.charAt(inputString.length-2)=="A")
			{
			amPmSpec=true;
			pm=false;
			}
		else if(inputString.charAt(inputString.length-2)=="p" || inputString.charAt(inputString.length-2)=="P")
			{
			amPmSpec=true;
			pm=true;
			}
		else
			{
			return false;
			}
		inputString=inputString.substring(0, inputString.length-2).trim();
		}
	var tmpArray=inputString.split(dtInfo.timeSeparator);
	var compCount=tmpArray.length;
	if(compCount>2)
		return false;
	var i;
	for(i=0; i<compCount; i++)
		{
		tmpArray[i]=tmpArray[i].trim();
		if(!tmpArray[i].isNumeric())
			return false;
		}
	//if we got here, all components can be parsed to numbers
	var hour;
	var minutes;
	if(compCount<2)//handle default minutes
		{
		minutes=0;
		}
	else
		{
		minutes=parseInt(tmpArray[1], 10);
		if(!validateMinutes(minutes))
			return false;
		}
	hour=parseInt(tmpArray[0], 10);
	//check for army-style time format, like 1100
	if(hour>=100 && compCount<2)
		{
		var tmpHour=hour;
		hour=Math.floor(tmpHour/100);
		minutes=tmpHour%100;
		if(!validateMinutes(minutes))
			return false;
		}
	if(!validateHour(hour, amPmSpec))
		return false;
	//if we got here, we have valid values in hour and minutes
	//handle AM / PM
	if(amPmSpec)
		{
		if(pm)
			{
			if(hour<12)
				hour+=12;
			}
		else
			{
			if(hour==12)
				hour=0;
			}
		}
	//adjust the field value
	var tmpMinString=minutes.toString();
	if(tmpMinString.length<2)
		tmpMinString="0"+tmpMinString;
	inputField.value=hour+dtInfo.timeSeparator+tmpMinString;
	return true;
	}

//returns true if the value in minutes is valid, false otherwise
//does not check for NaN, the caller is supposed to do that

function validateMinutes(minutes)
	{
	if(minutes<0 || minutes>59)
		return false;
	return true;
	}
	
//returns true if the hour is valid, false otherwise
//takes into account the value of amPmSpec: true if the time contains AM or PM
//it doesn't test for NaN, the caller is supposed to do that

function validateHour(hour, amPmSpec)
	{
	if(amPmSpec)
		{
		if(hour<1 || hour>12)
			return false;
		}
	else
		{
		if(hour<0 || hour >23)
			return false;
		}
	return true;
	}

//added as a method to the String class
//returns the string without any blank at the beginning or end

function trimSpaces()
	{
	var size=this.length;
	if(size==0) return this;
	var i;
	var j;
	for(i=0; i<size; i++)
		if(this.charAt(i)!=" ") break;
	for(j=size-1; j>i; j--)
		if(this.charAt(j)!=" ") break;
	if(i>j) return "";
	return this.substring(i, j+1);
	}

//used by isNumeric()
var firstDigit="0";
var lastDigit="9";

//added as a method to the String class
//returns true if the string is composed of numeric characters only; false otherwise
//also returns false if the string is empty

function isNumericString(){
  var size=this.length;
  if(size==0) return false;
  var i;
  for(i=0; i<size; i++){
    var tmpDigit=this.substring(i, i+1);
    if( tmpDigit < firstDigit || tmpDigit > lastDigit){
      return false;
    }
  }
  return true;
}

function alertIfNotNumber( nb ){

  var inputString = nb.value.trim();

  var size=inputString.length;
  //alert( " inputString  = \""+ inputString + "\"!");
  var tmpTime=new Date();
  if(size==0){
  // alert( " size = "+ size);
    return true;
  }
  else{
    // alert( " size = "+ size);
  }

  var i;
  for(i=0; i<size; i++){
    var tmpDigit=inputString.substring(i, i+1);
    // alert( " inputString  = \""+ inputString + "\"!");
    if( tmpDigit!= "." && (  tmpDigit < firstDigit || tmpDigit > lastDigit) ){
      if(tmpTime-lastErrorTime>999){
	lastErrorTime=tmpTime;
	alert( "\""+ inputString + "\" is an invalid number!");
	lastErrorTime=new Date();
	nb.focus();
      }
    }
  }
}




function checkValidEmail(x){
    //alert (x.value);
    var validEmailMsg="Please enter a valid email adress";
    
    if (typeof validEmailMsgLng!="undefined"){
	validEmailMsg=validEmailMsgLng;
    }		
    
    var emails= new Array();

    emails[0]=x.value;
    
    if( emails[0].indexOf(";")>-1){
      emails = emails[0].split(";");
    }
    
    var ok=1;
    var nokemail="";
 
    for(var i=0; i<emails.length; i++){
      if ( emails[i]!=""){
  	  var filter  = /^([a-zA-Z'0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
          if (filter.test(emails[i])){
             // alert('YES! Correct email address');
			 	if (emails[i].indexOf(".@")>0){
					//alert("THE dot pb");
					 ok=0;
             	 	nokemail = emails[i]
				}
          }
          else{
              ok=0;
              nokemail = emails[i]
          }
       }
    }
    if(!ok){
        alert(validEmailMsg);
        return false ;
    }
    else {
		// return false ;
        return true;
    }
}

function checkFieldSize(thisField,maxLenght){
    
    if (thisField && maxLenght){				
	if (thisField.value!=""){
	    var myLength=thisField.value.length;
	    var myFieldName='for field '+thisField.id;
	    if( myFieldName.indexOf('ACTIVITY_ANSWER')>-1) myFieldName='';
	    if (myLength<=maxLenght){
		return true;
	    }
	    else{
		alert('Inserted value is too large '+myFieldName+'. Max allowed: '+maxLenght+', your lenght: '+myLength+'!');
		return false ;
	    }
	}
	else {
	    return true;
	}
    }
    else {
	return true;
    }
}


//////////// start section for functions to search in menu with the String typed in a menu
//
// Script développé par Tout JavaScript.com et modified by artegis
// usage:
// var optionName='ORGANIZATION';
// var optionId='ORGANIZATION_ID';
// var myForm='totoForm';
// var mySearch='totoSearch';
//
// var Liste=new optionsList(optionName, optionId , 5, 200)
//
//Liste.Add("Afghanistan", "1");
//Liste.Add("Afrique du sud", "2");
//Liste.Add("Albanie", "3");
//Liste.Add("Algérie", "4");
//Liste.Add("Allemagne", "5");
//Liste.Add("Andorre", "6");
//Liste.Add("Angola", "7");
//Liste.Add("bAngola", "8");
//<script type="text/javascript" src="/utils/js/dtVal.js"></script>
//<FORM name="totoForm" action="/jsp/sampleposteddata.jsp">
//<INPUT type="text" name="totoSearch"><BR>
//<SCRIPT language=javascript>
//	Liste.myPrint();
//	ListeCheck(myForm, mySearch);
// or
//	ListeCheckByForm(document.forms[0], mySearch);
//</SCRIPT>
//<input type=submit>
//</FORM>



function optionsList(fieldName, fieldId, height, width) {
	this.fieldName=fieldName; 
	this.height=height; 
	this.width=width;
	this.search="";
	this.nb=0; 
	this.ids=new Array();
	this.fieldId=fieldId;
	this.Add=addItem;
	this.myPrint=printList;
	this.parse=parseList;
}

function addItem(item, id) {
  this[this.nb]=item;
  this.ids[this.nb]=id;
  this.nb++;
}


function printList() {
	if (document.layers) {
		var Z="<SELECT name="+this.fieldId+">";
	} else {
		var Z="<SELECT name="+this.fieldId+" size="+this.height+" style='width:"+this.width+"'>";
	}
	for (var i=0; i<this.nb; i++) {
		Z+="<OPTION value=\""+this.ids[i]+"\">"+this[i]+"</OPTION>"		
	}
	Z+="</SELECT>"
	document.write(Z);
}


function parseList(txt,myForm) {
	if (txt!=this.search) {
		this.search=txt
		myForm.elements[this.fieldId].options.length=0; 
		for (var i=0; i<this.nb; i++) {
			if ( this[i].substring(0,txt.length).toUpperCase()==txt.toUpperCase() ) {
				var o=new Option(this[i], this.ids[i]);
				myForm.elements[this.fieldId].options[myForm.elements[this.fieldId].options.length]=o;
			}
		}
		if (myForm.elements[this.fieldId].options.length==1) {
			myForm.elements[this.fieldId].selectedIndex=0;
		}
	}
}
function ListeCheckByForm(thisSearch){
 
  Liste.parse(document.forms[0].elements[thisSearch].value, document.forms[0]);
  if (document.layers){
    setTimeout("ListeCheckByForm(\""+thisSearch+"\")", 1001);
  } 
  else{
   setTimeout("ListeCheckByForm(\""+thisSearch+"\")", 100);
  }
}
function eventListeCheckByForm0(thisSearch){
  
  eventListe.parse(document.forms[0].elements[thisSearch].value, document.forms[0]);
  if (document.layers){
    setTimeout("eventListeCheckByForm0(\""+thisSearch+"\")", 1001);
  } 
  else{
   setTimeout("eventListeCheckByForm0(\""+thisSearch+"\")", 100);
  }
}
function eventListeCheckByForm1(thisSearch){
  
  eventListe.parse(document.forms[1].elements[thisSearch].value, document.forms[1]);
  if (document.layers){
    setTimeout("eventListeCheckByForm1(\""+thisSearch+"\")", 1001);
  } 
  else{
   setTimeout("eventListeCheckByForm1(\""+thisSearch+"\")", 100);
  }
}
function customerListeCheckByForm(thisSearch){
 
  customerListe.parse(document.forms[0].elements[thisSearch].value, document.forms[0]);
  if (document.layers){
    setTimeout("customerListeCheckByForm(\""+thisSearch+"\")", 1001);
  } 
  else{
   setTimeout("customerListeCheckByForm(\""+thisSearch+"\")", 100);
  }
}


function ListeCheck(thisForm, thisSearch) {
  // this function call itself endlessly!!!!	
  Liste.parse(document.forms[thisForm].elements[thisSearch].value, document.forms[thisForm]);
  if (document.layers){
    setTimeout("ListeCheck(\""+thisForm+"\", \""+thisSearch+"\")", 1001);
  } 
  else{
    setTimeout("ListeCheck(\""+thisForm+"\", \""+thisSearch+"\")", 100);
  }
}

function fillText(myElem,thisSearch){
	//alert(document.forms[0].elements[thisSearch].value);
	//document.forms[0].elements[thisSearch]
	//if (myElem.forms.elements['ORGANIZATION_MENU_NAME']){
	//alert(myElem.options[myElem.selectedIndex].text);
	if (document.forms[0].elements[thisSearch] && myElem.options[myElem.selectedIndex].text !=""){
		document.forms[0].elements[thisSearch].value=myElem.options[myElem.selectedIndex].text;
		
	}
	//}
}


//////////// end section for functions to search in menu with the String typed in a menu
