/*********************************************************/
/* Netarchitects YSDE					 */
/* form validation framework				 */
/*********************************************************/

// - validation of forms
// - coloring of mandatory fields on most modern browsers
// - coloring of error fields on most modern browsers

// "public" functions

//----------------

// function initForms();
//
// changes background color on fields that are marked as
// mandatory in the configuration section. Works trough all
// the forms in the page
//
// usually added as an onload script
//
// LIMITATIONS: does nothing in Netscape 4
// does not colorize checkboxes in Netscape 6 and Mozilla

//----------------

// function submitForm ( formName )
//
// checks the form's fields a series of tests. If all the
// tests are successful, submits the form.
//
// If an error is encountered while checking the form, it
// is not submitted and an alert() is displayed containing the
// list of the errors as given back by checkForm()

//----------------

// function linkBoxToFields ( state , formName , fieldNameList )
//
// the state is coveniently retrieves as "this.checked" in an onclick
// function
// When the checkbox's onclick function is launched, then
// if checked: the fields in the "," separated list are
//             emptied and disabled
// if unchecked: the fields in the "," separated list are
//               enabled
// the input cursor appears in the last field in the list

//----------------

// function linkSelectToFields ( value, checkvalue, formName, fieldNameList ) {
//
// When the selects's onchange function is launched, then
// if value = checkvalue: the fields in the "," separated list are
//                        emptied and disabled
// else: the fields in the "," separated list are
//       enabled
// the input cursor appears in the last field in the list



/********* predefined regular expressions ****************/

var regNoCheck = /./
var regNum = /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
var regAlpha = /^[a-zA-Z ]*$/
var regOnpFaxData = /^[0-9]{7}$|^\*$/
var regDat = /\d{2}\.\d{2}\.\d{4}/
var regTime = /(0\d|1\d|2[0-3]):[0-5]\d/
var regEmail = /^[\w.-]+\@([\w.-]+\.)+\w{2,}$/
var regImei = /\d{6}-\d{2}-\d{6}-\d/

/********* initForms *************************************/

//wait until page has finished loading until we enable onblur checks
var enableOneFieldChecks = false;
var delayErrorMessage = true;
var errorMessageDelay = 200;
var displayErrorMessages = true;
var is_nav4 = false;

/********* implementation ********************************/

function rTrim(str) {

  // We don't want to trip JUST spaces, but also tabs,
  // line feeds, etc.  Add anything else you want to
  // "trim" here in Whitespace

  var whitespace = new String(" \t\n\r");

  var s = new String(str);

  if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {

    // We have a string with trailing blank(s)...

    var i = s.length - 1;       // Get length of string

    // Iterate from the far right of string until we
    // don't have any more whitespace...

    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) {
      i--;
    }

    // Get the substring from the front of the string to
    // where the last non-whitespace character is...

    s = s.substring(0, i+1);
  }

  return s;
}


function lTrim(str) {
  var whitespace = new String(" \t\n\r");

  var s = new String(str);

  if (whitespace.indexOf(s.charAt(0)) != -1) {

      // We have a string with leading blank(s)...

      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...

      while (j < i && whitespace.indexOf(s.charAt(j)) != -1) {
        j++;
      }

      // Get the substring from the first non-whitespace
      // character to the end of the string...

      s = s.substring(j, i);
  }

  return s;
}

function trim(str) {
  return rTrim(lTrim(str));
}



/*********************************************************/

// checks wether a JavaScript variable exists that has a
// given name.
// If the optional formName is supplied, the search goes
// for variable formName.name
//
// tested against boolean, int and RegExp values.
//
// LIMITATIONS: does not work with string values

function checkExists (spath) {
	var frags = (new String(spath)).split(".");

	var searchspace = window;

	for(i in frags) {
		if(typeof(searchspace[frags[i]]) == "undefined") {
			return false;
		}
		searchspace = searchspace[frags[i]];
	}

	return true;
}

/*********************************************************/

// checks wether a name is acceptable as a javascript variable
//
// Customized to reject ATG Dynamo hidden fields which have
// unexploitable names.

function checkName ( name ) {

	var nameOk = true;

	// set hurdles defining wrong names

	// exception for Dynamo forms: exclude results named "*_D:*"

	nameOk = nameOk && (name.indexOf( "_D:" ) == -1);

	// exception for Dynamo forms: exclude results named "*/*"

	nameOk = nameOk && (name.indexOf( "/" ) == -1);

	//alert( "checkName:" + name + ":test1:" + ( name.indexOf( "_D:" ) == -1 ) + ":test2:" + ( name.indexOf( "/" ) == -1 ) );

	//exception for empty names (for examples read only fields used for the layout)

	nameOk = nameOk && (name!="");

	return nameOk;

}

/*********************************************************/

// changes background color on fields that are marked as
// mandatory in the configuration section. Works trough all
// the forms in the page
//
// usually added as an onload script
//
// LIMITATIONS: does nothing in Netscape 4
// does not colorize checkboxes in Netscape 6 and Mozilla

function initForms() {
	if(document.forms.length == 0) {
		return;
	}

	for ( var t = 0 ; t < document.forms.length ; t++ ) {
		//check if a test object exists for the form
		if (window[document.forms[t].name]) {
			initFields ( document.forms[t] );
			mandatorizeLinkedFields(document.forms[t]);
		}
	}

	//initialize cursor to the right field of the first form on the page
	//check if a test object exists for the form
	var config = window[document.forms[0].name];
	if (config) {
		var onLoadField = config["onLoadField"];
		if (onLoadField) {
			setFocus(document.forms[0][onLoadField]);
		}
	}
	setTimeout('enableOneFieldChecks = true;',100);
}


/*********************************************************/

// Called by the iterator function initForms()
// changes background color on fields that are marked as
// mandatory in the configuration section
//
// usually added as an onload script
//
// LIMITATIONS: does nothing in Netscape 4
// does not colorize checkboxes in Netscape 6 and Mozilla

function initFields ( form ) {

	//limit colorization possibility to modern browsers

	if (!is_nav4) {

		var out = "";

		// part 1: adress the right form

		for (var u = 0 ; u < form.length ; u++ ) {

			// part 3: for each element in the form, check wether a check object exists


			if ( checkName ( form[u].name )) {

				var element = form[u].name;

				if ( checkExists ( form.name + "." + element ) ) {

					// colorize mandatory fields

					var testElement = form.name + "." + element;

					if ( checkExists ( form.name + "." + element + ".mandatory"  ) ) {

						//check for the value of the mandatory attribute in case it is set to false

						if ( eval ( testElement + ".mandatory" ) ) {
							form[element].className += ' mandatory';
						}
					}

				} // if checkexists test element
			} // if checkname makes sense
		} //for each form
	}
}

/*********************************************************/

// Called by runTestSuite()
// changes background color on fields that are marked as
// errors
//
// LIMITATIONS: does nothing in Netscape 4
// does not colorize checkboxes in Netscape 6 and Mozilla

function markError ( field ) {

	//limit colorization possibility to modern browsers

	if (!is_nav4) {

		var theClassName = new String ( field.className ) ;

		//mark only if not yet marked

		if ( theClassName.indexOf( 'error' ) == -1 ) {
			//field.className += ' error';
			theClassName += ' error';
			setTimeout("timedClassName('"+field.form.name+"', '"+field.name+"', '"+theClassName+"')", errorMessageDelay);
		}
	}
}

/*********************************************************/

// Called by runTestSuite()
// changes background color back to normal on fields that
// do not (or no longer) contain errors
//
// LIMITATIONS: does nothing in Netscape 4
// does not colorize checkboxes in Netscape 6 and Mozilla

function unmarkError ( field ) {

	//limit colorization possibility to modern browsers

	if (!is_nav4) {

		var theClassName = new String ( field.className ) ;

		//alert (theClassName);

		theClassName = theClassName.replace ( ' error', '' );

		//field.className = theClassName;
		setTimeout("timedClassName('"+field.form.name+"', '"+field.name+"', '"+theClassName+"')", errorMessageDelay);

	}
}
function timedClassName ( form, field, theClassName) {
	//alert(form+field+theClassName)
	if (displayErrorMessages) document.forms[form][field].className = theClassName;
}

function writeError(field,text){
	//field.name is much to detailed: the last part is the name of the field as defined in the name attribute

	var theFieldName = new String(field.name)
	theFieldName = theFieldName.substr(theFieldName.lastIndexOf('.')+1);

	var theDiv = document.getElementById("errorDiv_"+theFieldName);

	//for debugging only!
	if (theDiv == null) {
		//alert('DEBUGGING: errorDiv missing:'+field.name);
	}

	theDiv.innerHTML = text;

	//additional tweak when IE not in standarts compliant mode: set errorDiv display to none when empty

	if (text.length==0) {
		theDiv.style.display='none';
	} else {
		theDiv.style.display='block';
	}

}

function checkOneField ( field ) {

	/*has the page finished loading ? (i.e was the initial field highlighted ?) */

	if (!enableOneFieldChecks) {
		//if not, abort checks for now.
		return true;
	}

	/* check wether test object exists */

	if (! checkExists(field.form.name+"."+field.name)) {
		// if not, abort the tests
		//alert('aborting');
		return true;
	}

	var errorTxt = runTestSuite(field);
	if (displayErrorMessages) {
		//prevent the page from eliminating or inserting error lines immediately upon submission,
		//probably eliminating doubleclicj impression on page shifts when erros are corrected
		
		//additional tweak when IE not in standarts compliant mode: set errorDiv display to none when empty
		
		setTimeout("if (displayErrorMessages) document.getElementById('errorDiv_"+field.name+"').innerHTML='"+errorTxt+"';document.getElementById('errorDiv_"+field.name+"').style.display=("+(errorTxt.length==0)+")?'none':'block';",errorMessageDelay);
	}

	//return true if no error on the field

	return (errorTxt=='');
}


/*********************************************************/

// Called by the iterator checkForm()
// checks the given element of a form against a series of
// tests
//
// OUT: string. Is the length is 0, no errors where reported
//	else contains the list of the errors fro the field,
//	possibly preceded by a custom error message defined
//	in the configuration section for the field

function runTestSuite ( field ) {

	//field.name is much to detailed: the last part is the name of the field as defined in the name attribute

	var testElement = field.form.name + "." + field.name;

	var errorStream = "";
	var error = false;
	var debug = false;

	//check contents per regExp

	if ( checkExists ( testElement + ".testRegExp") ) {
		if ((! eval( testElement + ".testRegExp").test( field.value ) ) && ( trim ( field.value ).length != 0  )) {

			switch (eval( testElement + ".testRegExp" )) {
				case regDat:
					errorStream += error_regexp_regDat;
				break;
				case regTime:
					errorStream += error_regexp_regTime;
				break;
				case regNum:
					errorStream += error_regexp_regNum;
				break;
				case regImei:
					errorStream += error_regexp_regImei;
				break;
				case regEmail:
					errorStream += error_regexp_regEmail;
				break;
				case regOnpFaxData:
					errorStream += error_regexp_regOnpFaxData;
				break;
				default:
					errorStream += error_regexp;
				break;
			}
			error = true;
		}
	}

	//check contents per minLength

	if ((!error) &&  checkExists(testElement + ".minLength") ) {
		if (( trim(field.value).length < eval(testElement + ".minLength" ) ) && ( trim ( field.value ).length != 0)) {
			if (debug) {
				errorStream += error_length + ':min:'+trim(field.value).length+'<br/>\n';
			} else {
				errorStream += error_length_min;
			}
			error = true;
		}
	}

	//check contents per maxLength

	if ((!error) && checkExists (testElement + ".maxLength")) {
		if (( trim ( field.value ).length > eval(testElement + ".maxLength" )) && ( trim ( field.value ).length != 0)) {
			if (debug) {
				errorStream += error_length + ':max:'+trim(field.value).length+'<br/>\n';
			} else {
				errorStream += error_length_max;
			}
			error = true;
		}
	}

	//check contents per mandatory

	if ((!error) && checkExists( testElement + ".mandatory")) {

		//check for the value of the mandatory attribute in case it is set to false

		if ( eval ( testElement + ".mandatory" ) ) {

			//mandatory and type:checkbox

			if ( field.type == 'checkbox' ) {
				if ( ! field.checked ) {
					errorStream += error_mandatory;
					error = true;
				}
			}
			else { // mandatory and text based input
				if ( trim ( field.value ).length == 0 ) {
					errorStream += error_mandatory;
					error = true;
				}
			}

			//additional testing for selects: emptyValue
			//type returns 'select-one' for single-select-selectfields
			if ( field.type == 'select-one') {
				if ( eval(testElement)['emptyValue'] != 'undefined') {
					if ( field.value ==  eval(testElement)['emptyValue']) {
						errorStream += error_mandatory;
						error = true;
					}
				}
			}
		} // else mandatory = false
	}

	if ( error && displayErrorMessages ) {
		markError ( field );

		/* prefix custom error message if there is one
			if ( checkExists (testElement + ".hasErrorMessage") ) {
				//check for the value of the hasErrorMessage attribute in case it is set to false
				if ( eval ( testElement + ".hasErrorMessage" ) ) {
					errorStream = eval ( testElement + ".errorMessage" ) + "<br />\n" + errorStream;
				}
			}
		*/
	}
	else {
		unmarkError ( field );
	}


	//this makes a blank line to separate section for displaying in the alert box
	//if (errorStream.length > 0) {
	//	errorStream += "\n";
	//}

	return errorStream;
	
}


/*********************************************************/

// Called by submitForm()
// checks the form's fields a series of tests
// 
// OUT: boolean. True if the tests where successful

function checkForm ( form ) {

	var error = false;
	var resultOk = false;
	var v = 0;

	// part 1: adress the right form
	
	for ( v = 0 ; v < form.length ; v++ ) {

		resultOk = checkOneField(form[v]);
		error = error || !resultOk;
	
	}
	//return true if checks OK
	return (!error);
}

/*********************************************************/

// Called by checkedLink()
// checks whether a checkbox is checked or a text value is non empty
//
// OUT: boolean.
//	Careful: Returns true (field filled) if the field does not exist!!!
//	Nessessary evil when writing for fields that are not always visible.
//	Take extra care care when writing the config, then !!!

function checkNotEmpty (formName, element) {

	//check element content

	if ( document.forms[formName][element] ) {
		var el = document.forms[formName][element];

		if ( el.type  == 'checkbox' ) {

			// checkbox input

			if ( !el.checked ) {
				return false;
			}
		}
		else { // value (select, text, textfield) based input
			if ( trim ( el.value ) .length == 0 ) {
				return false;
			}
		}

		//additional testing for selects: emptyValue
		//type returns 'select-one' for single-select-selectfields
		if ( el.type == 'select-one') {
			if ( eval(el.form.name+'.'+el.name)['emptyValue'] != 'undefined') {
				if ( el.value ==  eval(el.form.name+'.'+el.name)['emptyValue']) {
					return false;
				}
			}
		}
	}
	else {

		//element does not exist: do not hinder the acceptance

		return true;
	}

	//field exists and is not empty:

	return true;
}

/*********************************************************/


/*********************************************************/

// Called by submitTheForm()
// checks the form's linked fields
//
// OUT: string. Is the length is 0, no errors where reported
//	else contains the list of the errors from the linked fields,

function checkLinks ( form ) {
	var error = false;
	var returnValue = "";
	var formName = form.name;
	var config = eval(formName)["linkChecks"];

	var allsuccessful = true;

	if (config) {
		for( var testIndex in config.testList) {
			var testName = config.testList[testIndex];
			var testGroups = config[testName];
			var testMessage = config[testName+"Str"];

			var successful = false;
			var testInputs = new Array();
			for(var testGroupTextIndex in testGroups) {
				var testGroupText = testGroups[testGroupTextIndex];

				var groupComplete = true;

				var testGroupTextSplit = testGroupText.split(",");
				for(var inputNameIndex in testGroupTextSplit) {
					var inputName = testGroupTextSplit[inputNameIndex];
//					testInputs.concat(new Array(trim(inputName)));
					testInputs[testInputs.length]=trim(inputName);
					if( !checkNotEmpty(formName, trim(inputName))) {
						groupComplete = false;
					}
				}

				if(groupComplete) {
					successful = true;
				}
			}


			if(successful) {
				for(var t in testInputs) {
					if (form[testInputs[t]]) {
						unmarkError(form[testInputs[t]]);
						document.getElementById('errorDiv_linked_'+testName).innerHTML = "";
						//additional tweak when IE not in standarts compliant mode: set errorDiv display to none when empty
						document.getElementById('errorDiv_linked_'+testName).style.display='none';
					}
				}
			} else {
				allsuccessful = false;

				for(var t in testInputs) {
					if (form[testInputs[t]]) {
						markError(form[testInputs[t]]);
						document.getElementById('errorDiv_linked_'+testName).innerHTML = testMessage;
						//additional tweak when IE not in standarts compliant mode: set errorDiv display back to block
						document.getElementById('errorDiv_linked_'+testName).style.display='block';
					}
				}
			}

		}
	}

	return allsuccessful;
}

/*********************************************************/

// checks the form's fields a series of tests. If all the
// tests are successful, submits the form.
//
// If an error is encountered while checking the form, it
// is not submitted and an alert() is displayed containing the
// list of the errors as given back by checkForm() and checklinks()

function submitForm ( formName ) {

//	alert('submitForm is DEPRECATED: use submitTheForm instead');
	return false;

	var returnValue = checkForm ( formName );
	returnValue += checkLinks ( formName );
	
	if ( returnValue.length > 0 ) {
//		alert ( returnValue );
		return ( false );
	} 
	else {
		//leave form submission to the submit button
		//document.forms[formName].submit();
		return ( true );
	}
}

/*********************************************************/

// When the checkbox's onclick function is launched, then
// if checked: the fields in the "," separated list are
// emptied and disabled
// if unchecked: the fields in the "," separated list are
// enabled
// the input cursor appears in the last field in the list

function linkBoxToFields ( state, formName, fieldNameList ) {
	//part 1: create the list of fields
	
	fieldNames = new String ( fieldNameList );
	fieldNames = fieldNames.split(",");
//	alert (state);

	if (state) {
		for ( h=0 ; h < fieldNames.length ; h++ ) {
			disableField(document.forms[formName][fieldNames[h]]);
		}
	}
	else {
		for ( h=0 ; h < fieldNames.length ; h++ ) {
			undisableField(document.forms[formName][fieldNames[h]]);
		}
	}

}

/*********************************************************/

// When the selects' onchange function is launched, then
// if value = checkvalue: the fields in the "," separated list are
//						 emptied and disabled
// else: the fields in the "," separated list are
//							 enabled
// the input cursor appears in the last field in the list

function linkSelectToFields ( value, checkvalue, formName, fieldNameList ) {
	//part 1: create the list of fields

	var fieldNames = new String ( fieldNameList );
	fieldNames = fieldNames.split(",");
//	alert (state);

	if (value==checkvalue) {
		for ( h=0 ; h < fieldNames.length ; h++ ) {
			disableField(document.forms[formName][fieldNames[h]]);
		}
	}
	else {
		for ( h=0 ; h < fieldNames.length ; h++ ) {
			undisableField(document.forms[formName][fieldNames[h]]);
		}
	}
}


/*********************************************************/

// Colorize linked fields as if they where mandatory

function mandatorizeLinkedFields ( form ) {

	var config = eval(form.name)["linkChecks"];

	if (config) {
		for( var testIndex in config.testList) {
			var testName = config.testList[testIndex];
			var testGroups = config[testName];
			var testMessage = config[testName+"Str"];

			var testInputs = new Array();

			for(var testGroupTextIndex in testGroups) {
				var testGroupText = testGroups[testGroupTextIndex];

				var testGroupTextSplit = testGroupText.split(",");

				for(var inputNameIndex in testGroupTextSplit) {
					var inputName = testGroupTextSplit[inputNameIndex];
//					testInputs.concat(new Array(trim(inputName)));
					testInputs[testInputs.length]=trim(inputName);
				}


			}


			for(var t in testInputs) {
				if (form[testInputs[t]]) {
					mandatorizeField(form[testInputs[t]]);
				}
			}

		}
	}
}

/*********************************************************/
// submits the form, includes testing and workarounds for old browsers

function submitTheForm(submitButton, bypassTheTests) {

	/* run checks on the form */

	var error=false;
	
	/* antispamm */
	if(submitButton.form.remarque.value != "")
		return false;

	/* check wether the test object exists */

	if (!checkExists(submitButton.form.name)) {
		// if not, abort the tests
		//alert('aborting');
		bypassTheTests = true;
	}

	if (!bypassTheTests) {
		displayErrorMessages = true;
		//run the tests
		//the tests are assigned to theError in order to make sure they get called.
		//Otherwise, the optimization routines cut the test once the result is clear (true || xxx = true)
		if( !checkForm(submitButton.form)) {
			return false;
		}
		if( !checkLinks(submitButton.form)) {
			return false;
		}
		if (window.checkSpecial) {
			if(!checkSpecial(submitButton)) {
				return false;
			}
		}		
//		if (submitButton.form.user_validator.value == "false"){
//			alert("Please select a user to send the form");
//			return false;
//		}
	} else {
		//prevent the page from altering error lines on submission
		displayErrorMessages = false;
	}

	/* give OK to the submission of the form */

	//prepare terrain for netscape 6.0-6.2
	if (is_nav6) {
		document.getElementById(submitButton.form.name+'_submissionTempInput').name = submitButton.name;
		document.getElementById(submitButton.form.name+'_submissionTempInput').value = submitButton.value;
		document.getElementById(submitButton.form.name+'_submissionTempInput2').name = "_D:"+submitButton.name;
		document.getElementById(submitButton.form.name+'_submissionTempInput2').value = " ";
		submitButton.form.submit();
	}
	return (true);

}

/*********************************************************/
// Colorize field as if they where mandatory

function mandatorizeField ( field ) {
	//limit colorization possibility to modern browsers

	if (!is_nav4) {

		var theClassName = new String ( field.className ) ;

		//mark only if not yet marked

		if ( theClassName.indexOf( 'mandatory' ) == -1 ) {
			field.className += ' mandatory';
		}
	}
}

function unmandatorizeField ( field ) {

	//limit colorization possibility to modern browsers

	if (!is_nav4) {

		var theClassName = new String ( field.className ) ;

		//alert (theClassName);

		theClassName = theClassName.replace ( ' mandatory', '' );

		field.className = theClassName;

	}
}

/*********************************************************/
// Colorize disabled fields

function disableField ( field ) {

	//set value to empty for newly disabled text fields
	if (field.type=="text") {
		field.value="";
	}

	field.readOnly=true;

	//limit colorization possibility to modern browsers

	if (!is_nav4) {

		var theClassName = new String ( field.className ) ;

		//mark only if not yet marked

		if ( theClassName.indexOf( 'disabled' ) == -1 ) {
			field.className += ' disabled';
		}
	}
}

function undisableField ( field ) {

	field.readOnly=false;

	//limit colorization possibility to modern browsers

	if (!is_nav4) {

		var theClassName = new String ( field.className ) ;

		//alert (theClassName);

		theClassName = theClassName.replace ( ' disabled', '' );

		field.className = theClassName;

	}
}


/*********************************************************/
// Sets the focus, disabling onblur statements for a short while in order not to trigger errors

function setFocus(field) {

	if (!field) {
		return true;
	}

	enableOneFieldChecks = false;
	field.focus();

	//wait a bit for the focus() to work, then enable the field oblur() checks

	setTimeout('enableOneFieldChecks = true;',100);
}

/*********************************************************/
// Retrieves the value of the selected item in a radio button
// group.
// The group is accessed by document.forms[formname][groupname]

function getRadioValue ( fieldGroup ) {
	for (var i=0; i < fieldGroup.length; i++) {
		if (fieldGroup[i].checked) {

			//there can be only one: if more than one element of a radio button group is
			//selected, which is not supposed to be possible, return the first.

			return fieldGroup[i].value;
		}
	}
}

function checkBirthDate (datefield) {

	//field is empty
	if (trim(datefield.value).length == 0) {
		return true;
	}

	//as single field check is passed and field is not empty, we now can extract the values directly from the string

	var dayValue = parseInt(datefield.value.substr(0,2),10);
	//months in Javascript are numbered 0 through 11;
	var monthValue = parseInt(datefield.value.substr(3,2),10)-1;
	var yearValue = parseInt(datefield.value.substr(6,4),10);
	var error = false;

	//create a date value from the collected information

	var testDate = new Date (yearValue, monthValue, dayValue);

	//test 1: if year changed, month was wrong

	if ((!error) && (yearValue != testDate.getFullYear())) {
		//alert ('what a month!');
		error = true;
	}

	//test 2: if year is the same, but the month changed, the day was wrong

	if ((!error) && (monthValue != testDate.getMonth())) {
		//alert ('what a day!');
		error = true;
	}

	var errorTxt = error_checkSpecial_date;

	//test 3: the person is 18 years old

	var toDay = new Date();
	var lastBirthDate = new Date (toDay.getFullYear()-18,toDay.getMonth(),toDay.getDay());

	if ((!error) && ((lastBirthDate-testDate)<0)) {
		//alert('Must be 18');
		errorTxt = error_checkSpecial_date_too_young;
		error = true;
	}

	//test 4: the person is born after the 01.01.1904

	firstBirthDate = new Date(1904,0,1);

	if ((!error) && ((testDate-firstBirthDate)<0)) {
		//alert('Must be born after 01.01.1904');
		errorTxt = error_checkSpecial_date_too_old;
		error = true;
	}

	if (!error) {
		document.getElementById('checkSpecial_'+datefield.name).innerHTML = "";
		unmarkError( datefield );
	} else {
		document.getElementById('checkSpecial_'+datefield.name).innerHTML = errorTxt;
		markError( datefield );
	}
	return (!error);
}

function checkDate (datefield) {

	//field is empty
	if (trim(datefield.value).length == 0) {
		return true;
	}

	//as single field check is passed and field is not empty, we now can extract the values directly from the string
	
	var dayValue = parseInt(datefield.value.substr(0,2),10);
	//months in Javascript are numbered 0 through 11;
	var monthValue = parseInt(datefield.value.substr(3,2),10)-1;
	var yearValue = parseInt(datefield.value.substr(6,4),10);
	var error = false;

	//create a date value from the collected information
	
	var testDate = new Date (yearValue, monthValue, dayValue);
	
	//test 1: if year changed, month was wrong
	
	if ((!error) && (yearValue != testDate.getFullYear())) {
		//alert ('what a month!');
		error = true;
	}

	//test 2: if year is the same, but the month changed, the day was wrong

	if ((!error) && (monthValue != testDate.getMonth())) {
		//alert ('what a day!');
		error = true;
	}

	//test 3: the date is in the past

	var toDay = new Date();

	if ((!error) && ((toDay-testDate)<0)) {
		//alert('Must be in the past');
		error = true;
	}

	if (!error) {
		document.getElementById('checkDate_'+datefield.name).innerHTML = "";
		unmarkError( datefield );
	} else {
		document.getElementById('checkDate_'+datefield.name).innerHTML = error_checkSpecial_date;
		markError( datefield );
	}
	return (!error);
}

/*********************************************************/

// this is a keypress handler that only reacts to return-keypresses
// if "return" is pressed it *tries* to submit the currently focused form
// or the last form on the page
//
// it checks for the configuration for the variable 'formname'.returnKeySubmitButton
// it submit the form by doing a eval('formname"+"."+returnKeySubmission).click()
// if there is no such configuration, it blocks the form submission by Enter

function enterKeyHandler(eventOrSource) {
	eventSource = (window.event) ?	window.event.srcElement : eventOrSource.target;

	if(eventSource.type == "textarea")
	return;

	key = (window.event) ?	window.event.keyCode : eventOrSource.keyCode;

	if(key == 13) {
		var form;
		if(eventSource["form"]) {
			form = eventSource["form"];
		} else if ( document.forms.length > 0 ) {
			form = document.forms[document.forms.length-1];
		} else {
			return;
		}

		if((window[form.name]) && (form.name.indexOf("form")==0)) {
			var buttonname = eval(form.name+'["returnKeySubmitButton"]');
			if(buttonname) {
				if(form[buttonname]) {
					form[buttonname].click();
				}
				return false;
			}
			return false;
		}
	}
}


function sendFormEdit (form,url,urlparams) {

	var strForm = "&formlist=";
	var strURL = url+'?'+urlparams;
	var v = 0;
	
	for ( v = 0 ; v < form.length ; v++ ) {
		if(form[v].name.indexOf('dt_') != -1){
			switch (form[v].type) {
				case "radio":
					if(form[v].checked)
						strForm += escape('&') + form[v].name + '=' + form[v].value;
					break;
				
				default:
					strForm += escape('&') + form[v].name + '=' + form[v].value;
					break;
			}
		}
	}
	strURL += strForm;
	window.open(strURL);
}

document.onkeypress = enterKeyHandler;

var error_length = "La taille du champ n est pas correct";
var error_length_min = "La taille du champ est trop court";
var error_length_max = "La taille du champ est trop long";
var error_regexp = "Le format du champ n'est pas correct";
var error_regexp_regDat = "Controllez le format du champs date";
var error_regexp_regTime = "Controllez le format des heures (e.g. 09:47)";
var error_regexp_regImei = "Controllez le format IMEI format";
var error_regexp_regEmail = "Controllez le format de l e-mail";
var error_regexp_regNum = "Le champ doit etre num&#233;rique";
var error_mandatory = "Le champ est obligatoire";
var error_linked = "Veuillez controler que le champs est complet";
var error_checkSpecial_cmpl_searchParam = "Veuillez entrer un param&#232;tre de recherche";
var error_checkSpecial_untildate = "La date A Partir doit etre post&#233;rieur &#224; la date de d&#233;but";
var error_checkSpecial_descriptive_inquiry = "Un champ doit etre rempli";
var error_checkSpecial_passwordequality = "Le mot de passe n est pas &#233;gal";
var error_checkSpecial_asdealeridcheck = "ID is mandatory to log on as a dealer";
var error_checkSpecial_date = "La date n est pas valide ou dans le futur";
var error_checkSpecial_date_too_young = "La personne est trop jeune";
var error_checkSpecial_date_too_old = "La personne est trop ag&#233;e";
var error_linkChecks_houseNum = "Veuillez indiquer votre num&#233;ro";
var error_linkChecks_phoneNum = "Veuillez entrer votre num&#233;ro de t&#233;l&#233;phone";
var error_linkChecks_ownerInfos = "You must enter the information of the real owner if the checkbox is unchecked";
var error_linkChecks_switchboard = "You must enter the switchboard details if you click the checkbox";
var error_linkChecks_additionalinfos = "You must click the checkbox, if you do not want to enter this information";

if (typeof(jQuery) != 'undefined') {
	jQuery(document).ready(initForms);
} else {
	//clear out any other onload code!
	window.onload=initForms;
}
