// JavaScript Document
var blnDone = false;

function init() {
   // quit if this function has already been called
   if (blnDone) return;

   // flag this function so we don't do the same thing twice
   blnDone = true;
   
   var objPrint = document.getElementById("print-friendly");
   
   if (objPrint) {
		objPrint.onclick = function() {
			printPage();
			return false;
		}
   }
   
   var objMailThis = document.getElementById("mail");
   
   if (objMailThis) {
		objMailThis.onclick = function() {
			sendLink();
			return false;
		}
   }
   
   var objDivs = document.getElementsByTagName("div");
   var blnTagFound = false;
   var objForms;
   
   for (var i=0; !blnTagFound && i < objDivs.length;i++) {
		if (objDivs[i].className == "content-description") {
			if (objDivs[i].innerHTML.length >= 2750) {
				objForms = objDivs[i].getElementsByTagName("form");
				if (objForms.length <= 0) {
					var objImage = document.getElementById("img-footer");			
					if (objImage) {
						objImage.style.display = "block";
						var strOldImage = objImage.src;
						var intPos = strOldImage.lastIndexOf("/");
						var strImagePath = strOldImage.substring(0, intPos+1);
						var strImage = strImagePath + "img-footer" + getRandom(1, 6) +".gif";
						objImage.src= strImage;
						blnTagFound = true;		
					}
				}
			}
		}
   }
   
};

function printPage() {
	window.print();
}

function getRandom(intMin, intMax) {
	
	var intRandom;
	
	if (intMin == 0) {
		intRandom = (Math.round(Math.random() * intMax));
	}
	else {
		intRandom = (Math.round(Math.random() * intMax - 1) + 1);
	}
	
	return intRandom;
}

function sendLink() {
	var link = "/webconcepteur/web/Drakkar/" + document.getElementById("user-language").value + "/sendlink.prt?link="+escape(document.getElementById("full-path").value);
	
	link_popup(link,'false',375,420, 'location=0,statusbar=0,menubar=0,scrollbars=0,resizable=0');
	
}

/* Ce bout de code est ajout? afin d'appeler init seulement lorsque le DOM est charg? compl?tement */
/* for Mozilla */
if (document.addEventListener) {
   document.addEventListener("DOMContentLoaded", init, null);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
   document.write("<script defer src="+strPath+"/fichiersGlobal/js/ie_onload.js><"+"/script>");
/*@end @*/

/* for other browsers */
window.onload = init;

// Function that launch the validation over the form passed as a parameter
function validateForm(objForm) {
	
	var strRequiredFields = "";
	var strRegExFields = "";
	var strValFuncFields = "";
	var blnValidationClear = false;
	
	if (objForm) {		
		
		// Get the list of input elements
		var objInput = objForm.getElementsByTagName("input");
		
		if (objInput) {
			// Loop on each input
			for (i=0; i < objInput.length; i++) {
				strFieldType = objInput[i].type;
				
				//traiter les champs hidden comme les champs text
				if (strFieldType = "hidden"){
					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 = objInput[i].getAttribute("required");
						if (attrRequired && attrRequired == "true") {							
							strRequiredFields += objInput[i].id + ";";	
						}
						// Field that must be tested against a regular expression
						attrRegex = objInput[i].getAttribute("regexp");
						attrRegexValidationFormat = objInput[i].getAttribute("regexpFormat");
						if (attrRegex && attrRegex != "") {
							strRegExFields += objInput[i].id + "$REGX$" + attrRegex + "$REGX$" + attrRegexValidationFormat + ";";		
						}
						
						// Field that have a specific validation function
						attrValidationFunction = objInput[i].getAttribute("validationjsfunction");
						if (attrValidationFunction && attrValidationFunction != "") {
							strValFuncFields += objInput[i].id + "$VALFUNC$" + attrValidationFunction + ";";
						}
						break;
					case "checkbox":
						break;
				}
																	
			}
		}
	}
	
	// Validation of the mandatory fields
	if (valideRequireFields(objForm, strRequiredFields)) {
		// Regular Expressions validationss
		if (valideRegEx(objForm, strRegExFields)) {
			if (valideSpecificFunction(objForm, strValFuncFields)) {
				blnValidationClear = true;
			}
		}
		
						
	}
	
	return blnValidationClear;
}

// 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] != "") {
				if (document.getElementById(arrRequired[i]).value == "") {					
					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;
				}
			}
		}
	}
	
	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;
			}
		}
																				
	}
	
	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
}
