// JavaScript Document
var blnDoneXHtmlForm = false;

function initxhtmlform() {
   // quit if this function has already been called
   if (blnDoneXHtmlForm) return;

   // flag this function so we don't do the same thing twice
   blnDone = true;
	
  
   
   var strRequiredFields = "";
   var strRegExFields = "";
   
   var objForms = document.getElementsByTagName("form");
   
   if (objForms) {
	   	for (var i=0;i<objForms.length;i++) {
			if (objForms[i].getAttribute("xhtmlValidate")) {
				if (objForms[i].getAttribute("xhtmlValidate") == "true") {
					objForms[i].onsubmit = function() {
						return validateForm(this);	
					}		
				}
			}
			
				
		}								
   }
   
  
   
   // Add the close function on the specified button
   var objClose = document.getElementById("close");

   if (objClose) {
		objClose.onclick = function() {
			window.close();	
		}
   }
   
};


function showFeedback(objFeedback) {
	window.open(objFeedback.getAttribute("value"), "win1", "height=680,width=500,scrollbars=no,status=no,toolbar=no,location=no");
}

// Function that launch the validation over the form passed as a parameter
function validateForm(objForm) {
	var strRequiredFields = "";
	var strRequiredCheckboxRadio = "";
	var strRequiredSelect = "";
	var strStripHtmlFields = "";
	var strRegExFields = "";
	var strValFuncFields = "";
	var strMaxLengthTextArea = "";
	var blnValidationClear = false;
	
	if (objForm) {		
		// Get the list of input elements
		var objInput = objForm.getElementsByTagName("input");
		var objPwd = objForm.getElementsByTagName("password");
		var objTextArea = objForm.getElementsByTagName("textarea");
		var objSelect = objForm.getElementsByTagName("select");
		var objInputTextArea = new Array(objInput.length + objPwd.length + objTextArea.length);
		
		for(i=0;i<objInput.length;i++)
		{
			objInputTextArea[i] = objInput[i];
		}
		for(i=0;i<objPwd.length;i++)
		{
			objInputTextArea[i+objInput.length] = objPwd[i];
		}
		for(i=0;i<objTextArea.length;i++)
		{
			objInputTextArea[i + objInput.length + objPwd.length] = objTextArea[i];
			attrMaxLength = objTextArea[i].getAttribute("maxlength");
			if (attrMaxLength) {		
				strMaxLengthTextArea += objTextArea[i].id + ";";	
			}
		}
		
		for(i=0;i<objSelect.length;i++)
		{
			objInputTextArea[objInputTextArea.length] = objSelect[i];
		}
		
		if (objInputTextArea) {
			
				
			// Loop on each input
			for (i=0; i < objInputTextArea.length; i++) {
				strFieldType = objInputTextArea[i].type;
				//traiter les champs hidden comme les champs text
				if (strFieldType == "hidden" || strFieldType == "password" || strFieldType == "textarea"){
					strFieldType = "text";
				}
				// Check the type of input and add it to the right list of validation if it fulfill the requirements
				switch (strFieldType) {
				
					case "text":
						// Mandatory field
						attrRequired = objInputTextArea[i].getAttribute("required");
						if (attrRequired && attrRequired == "true") {							
							strRequiredFields += objInputTextArea[i].id + ";";	
						}
						// Field to strip html
						attrRejectHtml = objInputTextArea[i].getAttribute("rejecthtmltag");
						if (attrRejectHtml && attrRejectHtml == "true") {							
							strStripHtmlFields += objInputTextArea[i].id + ";";	
						}
						// Field that must be tested against a regular expression
						attrRegex = objInputTextArea[i].getAttribute("regexp");
						attrRegexValidationFormat = objInputTextArea[i].getAttribute("regexpFormat");
						if (attrRegex && attrRegex != "") {
							strRegExFields += objInputTextArea[i].id + "$REGX$" + attrRegex + "$REGX$" + attrRegexValidationFormat + ";";		
						}
						
						// Field that have a specific validation function
						attrValidationFunction = objInputTextArea[i].getAttribute("validationjsfunction");
						if (attrValidationFunction && attrValidationFunction != "") {
							strValFuncFields += objInputTextArea[i].id + "$VALFUNC$" + attrValidationFunction + ";";
						}
						break;
					case "checkbox":
						// Mandatory field
						attrRequired = objInputTextArea[i].getAttribute("required");
						if (attrRequired && attrRequired == "true" && strRequiredCheckboxRadio.indexOf(objInputTextArea[i].id + ";")==-1) {							
							strRequiredCheckboxRadio += objInputTextArea[i].name + ";";	
						}
						break;
					case "radio":
						// Mandatory field
						attrRequired = objInputTextArea[i].getAttribute("required");
						if (attrRequired && attrRequired == "true" && strRequiredCheckboxRadio.indexOf(objInputTextArea[i].id + ";")==-1) {							
							strRequiredCheckboxRadio += objInputTextArea[i].name + ";";	
						}
						break;
					case "select-one":
						// Mandatory field
						attrRequired = objInputTextArea[i].getAttribute("required");
						if (attrRequired && attrRequired == "true") {							
							strRequiredSelect += objInputTextArea[i].id + ";";	
						}
						break;
				}
																	
			}
		}
	}
	// Validation of the mandatory fields
	if (valideRequireFields(objForm, strRequiredFields)) {
		if (valideRequireRadioAndCheckbox(objForm, strRequiredCheckboxRadio)) {
			if (valideRequireSelect(objForm,strRequiredSelect)) {
				if (valideCustom(objForm)){
					// Regular Expressions validationss
					if (valideRegEx(objForm, strRegExFields)) {
						if (valideHTMLStripFields(objForm, strStripHtmlFields)){
							if (valideSpecificFunction(objForm, strValFuncFields)) {
								blnValidationClear = true;
							}
						}
					}
				}
			}
		}				
	}

	
	if (!valideMaxLengthTextarea(objForm, strMaxLengthTextArea)) {
		blnValidationClear = false;
	}
	return blnValidationClear;
}

function valideCustom(objForm)
{
	var blnValidationClear = true;
	if(typeof valideCustomImpl=='function' && !valideCustomImpl(objForm))
	{
			blnValidationClear = false;
	}
	return blnValidationClear;
}

// Function that validate the maxlength of the textarea
function valideMaxLengthTextarea(objForm, strListFields) {
	
	var blnValide = true;
	var blnLabelFound = false;
	var strLabel = "";
	if (strListFields != "") {
		// Build an array with the list of fields to validate
		var arrField = strListFields.split(";");
		for (var i=0; blnValide && i < arrField.length; i++) {
			if (arrField[i] != "") {
				var value = document.getElementById(arrField[i]).value;
				var maxlength =  document.getElementById(arrField[i]).getAttribute("maxlength");
				if (value.length > maxlength)
				{
					strLabel = getLabel(objForm, arrField[i]);
					
					if (document.getElementById("userLanguage").value == "fr") {
						alert("La longueur du champ " + strLabel + " dépasse la limite autorisée. ("+maxlength+" caractères)");
					}
					else {
						alert("The length of the field " + strLabel + " exceed the limit. ("+maxlength+" characters)");
					}
					
					//set the focus()
					document.getElementById(arrField[i]).focus();
					
					// Flag the process that an error has been found
					blnValide = false;
				}
				
			}
		}
	}
	
	return blnValide;
}

// Function that validate if a field contain HTML tag
function valideHTMLStripFields(objForm, strListFields) {
	var blnValide = true;
	var blnLabelFound = false;
	var strLabel = "";
	
	if (strListFields != "") {
		// Build an array with the list of fields to validate
		var arrFields = strListFields.split(";");
		for (var i=0; blnValide && i < arrFields.length; i++) {
			if (arrFields[i] != "") {
				var fieldValue = document.getElementById(arrFields[i]).value;
				
				if (!valideHTMLStripField(fieldValue)) {	
								
					strLabel = getLabel(objForm, arrFields[i]);					
					
					// Inform the user that an error has occured
					if (document.getElementById("userLanguage").value == "fr") {
						alert("N'utiliser que du texte dans le champ " + strLabel + ", surtout ne pas utiliser de balises HTML.");
					}
					else {
						alert("Use only plain text in the field " + strLabel + ", do not use HTML tag.");
					}
					
					//set the focus()
					document.getElementById(arrFields[i]).focus();
					
					// Flag the process that an error has been found
					blnValide = false;
				}
			}
		}
	}
	
	return blnValide;
}
function valideHTMLStripField(fieldValue)
{
	var reg = new RegExp("<(.)*>");
	if(reg.test(fieldValue))
	{
		return false;
	}
	return true;
}
// Function that gives the opportunity to validate if the specified mandatory fields have been filled in
function valideRequireFields(objForm, strListFields) {
	
	var blnValide = true;
	var blnLabelFound = false;
	var strLabel = "";
	if (strListFields != "") {
		// Build an array with the list of fields to validate
		var arrRequired = strListFields.split(";");
		for (var i=0; blnValide && i < arrRequired.length; i++) {
			if (arrRequired[i] != "") {
				var initValue = document.getElementById(arrRequired[i]).getAttribute("emptyvaluemessage=");
				if (document.getElementById(arrRequired[i]).value == "" || document.getElementById(arrRequired[i]).value == initValue) {					
					strLabel = getLabel(objForm, arrRequired[i]);					
					
					// Inform the user that an error has occured
					if (document.getElementById("userLanguage").value == "fr") {
						alert("Le champ " + strLabel + " est obligatoire.");
					}
					else {
						alert("The field " + strLabel + " is mandatory");
					}
					
					//set the focus()
					document.getElementById(arrRequired[i]).focus();
					
					// Flag the process that an error has been found
					blnValide = false;
				}
				else
				{
					if (document.getElementById(arrRequired[i]).value == initValue)
					{
						document.getElementById(arrRequired[i]).value = "";
					}
				}
			}
		}
	}
	
	return blnValide;
}

// Function that gives the opportunity to validate if the specified mandatory fields have been filled in
function valideRequireRadioAndCheckbox(objForm, strListFields) {
	
	var blnValide = true;
	var blnLabelFound = false;
	var strLabel = "";
	if (strListFields != "") {
		// Build an array with the list of fields to validate
		var arrRequired = strListFields.split(";");
		for (var i=0; blnValide && i < arrRequired.length; i++) {
			if (arrRequired[i] != "") {
				strLabel = getLabel(objForm, arrRequired[i]);		
				var l_elements = document.getElementsByName(arrRequired[i]);
				var selected = false;
				for (var j=0; !selected && j < l_elements.length; j++)
				{
					if (l_elements[j].checked)
						selected = true;	
				}
				
				if (!selected)
				{
					if (document.getElementById("userLanguage").value == "fr") {
						alert("Vous devez faire un choix pour le champs " + strLabel);
					}
					else {
						alert("You must select a choice for " + strLabel + " field");
					}
					blnValide = false
				}
				
			}
		}
	}
	
	return blnValide;
}

function valideRequireSelect(objForm, strListFields) {
	
	var blnValide = true;
	var blnLabelFound = false;
	var strLabel = "";
	if (strListFields != "") {
		// Build an array with the list of fields to validate
		var arrRequired = strListFields.split(";");
		for (var i=0; blnValide && i < arrRequired.length; i++) {
			if (arrRequired[i] != "") {
				strLabel = getLabel(objForm, arrRequired[i]);		
				var l_elements = document.getElementById(arrRequired[i]);
				if (l_elements[l_elements.selectedIndex].value == "")
				{
					if (document.getElementById("userLanguage").value == "fr") {
						alert("Vous devez faire un choix pour le champs " + strLabel);
					}
					else {
						alert("You must select a choice for " + strLabel + " field");
					}
					blnValide = false
				}
				
			}
		}
	}
	
	return blnValide;
}

// Function that gives the opportunity to validate the content of fields against regular expressions
function valideRegEx(objForm, strListFields) {
	
	var blnValide = true;
	var blnLabelFound = false;
	var strLabel = "";
	var arrRegExDetail;
	
	var blnRegExValid = true;
	var strFormat = "";
	
	if (strListFields != "") {
		var arrRegEx = strListFields.split(";");
		 
		for (var i=0; blnValide && i < arrRegEx.length; i++) {
			if (arrRegEx[i] != "") {
				// Get all the details of the field to be tested
				arrRegExDetail = arrRegEx[i].split("$REGX$");			
				
				// Call the regular expression validation
				blnRegExValid = validateRegEx(arrRegExDetail[0], arrRegExDetail[1]);								

				// If the validation returned an error, we must inform the user
				if (!blnRegExValid) {					
					strLabel = getLabel(objForm, arrRegExDetail[0]);					
					strFormat = arrRegExDetail[2];
					
					// Inform the user that an error has occured
					if (document.getElementById("userLanguage").value == "fr") {
						alert("Le format du champ " + strLabel + " est incorrect. Le format est : " + strFormat);
					}
					else {
						alert("The format of the field " + strLabel + " is incorrect. You must respect this format : " + strFormat);
					}
					
					//set the focus()
					document.getElementById(arrRegExDetail[0]).focus();
					
					// Flag the process that an error has been found
					blnValide = false;
				}
			}
		}
	}
	
	return blnValide;
}

function valideSpecificFunction(objForm, strListFields) {
	var blnValide = true;
	var blnLabelFound = false;
	var strLabel = "";
	var arrValFuncDetail;
	
	var blnValFuncValid = true;
	var strFormat = "";
	
	if (strListFields != "") {
		var arrValFunc = strListFields.split(";");
		 
		for (var i=0; blnValide && i < arrValFunc.length; i++) {
			
			if (arrValFunc[i] != "") {
				// Get all the details of the field to be tested
				arrValFuncDetail = arrValFunc[i].split("$VALFUNC$");

				
				// Call the regular expression validation
				var strFunction = arrValFuncDetail[1] + "(objForm ,\'" + arrValFuncDetail[0] + "\',\'" + document.getElementById("userLanguage").value + "\')";
				
				blnValFuncValid = eval(strFunction);								
				

				// If the validation returned an error, we must inform the user
				if (!blnValFuncValid) {																														
					
					// Flag the process that an error has been found
					blnValide = false;
				}
			}
		}
	}
	
	return blnValide;		
}

function getInnerText (element) {
	if (typeof element.innerText != 'undefined') {
		return element.innerText;
	}
	else if (document.createRange) {
		var range = document.createRange();
		range.selectNodeContents(element);
		return range.toString();
	}
}


function getLabel(objFormElement, idToFound) {
	var strLabel = "";
	var blnLabelFound = false;
	
	if (objFormElement) {
		// Get the label of the field in error
		var objLabels = objFormElement.getElementsByTagName("label");
		
		for (var y=0; !blnLabelFound && y < objLabels.length; y++) {
			if (objLabels[y].htmlFor == idToFound) {								
				strLabel = 	getInnerText(objLabels[y]);
				blnLabelFound = true;
			}
		}
																				
	}
	if (strLabel.indexOf(" :")!= -1){
		strLabel = strLabel.substring(0,strLabel.indexOf(" :"));
	}
	if (strLabel.indexOf(":")!= -1){
		strLabel = strLabel.substring(0,strLabel.indexOf(":"));
	}
	return strLabel;
}

function validateDate(objFormVal, idField, language) {
	blnRetour = false;
	strLabel = getLabel(objFormVal, idField);
	
	//get field value
	objDate = document.getElementById(idField);
		
	if(isDate(objDate)) {
		blnRetour = true;
	}
	else {
		// Inform the user that an error has occured
		if (language == "fr") {
			alert(strLabel + " : Cette date n'est pas valide");
		}
		else {
			alert(strLabel + " : This date is not valid.");
		}	
	}
	
	return blnRetour;	
}

/* Function that validate the email address against a specific email regular expression */
function validateRegEx(idField, regex) {		
	var reg = new RegExp(regex);
	return reg.test(document.getElementById(idField).value);
}



////////////////////custom function ///////////////////////////////////////////
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(a_dateField){
	
	dtStr = a_dateField.value;
	
	
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		a_errField = document.getElementById(a_dateField.name + ".MONTH");
		a_errField.focus();
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		a_errField = document.getElementById(a_dateField.name + ".MONTH");
		a_errField.focus();
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		a_errField = document.getElementById(a_dateField.name + ".DAY");
		a_errField.focus();
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		a_errField = document.getElementById(a_dateField.name + ".YEAR");
		a_errField.focus();
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		a_errField = document.getElementById(a_dateField.name + ".YEAR");
		a_errField.focus();
		return false
	}
return true
}

function validate2Dates(objFormVal, idFieldDate1, idFieldDate2, language) {
	
	if (validateDate(objFormVal, idFieldDate1, language)){
		if (validateDate(objFormVal, idFieldDate2, language)){
			return true;
		}
	}
	
	return false;	
}

