var xmlHttp;
var WindowPopUp;

function loadFrame() {

}

function initAjax() {
try
		{
		xmlHttp=new XMLHttpRequest();
		}
catch (e)
	{
	try
	{
		xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
	}
	catch (e)
		{
			try
				{
					xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
				}
			catch (e)
				{
					return false;
				}
		}
	}
return true;
}

function showPopup(file, h, w) {
	if((typeof WindowPopUp != "undefined") && (WindowPopUp != null))
		WindowPopUp.close();

	 WindowPopUp = window.open(file,"popup","left="+parseInt((screen.width-w)/2)+", top="+parseInt((screen.height-h)/2)+", width="+w+", height="+h);

	if(WindowPopUp != null)
		WindowPopUp.focus();
}

function showImage(strFile, nWidth, nHeight)
{

	if((typeof WindowPopUp != "undefined") && (WindowPopUp != null))
		WindowPopUp.close();

    WindowPopUp = window.open("admin/popup.php?file="+strFile, "image", "left="+parseInt((screen.width-nWidth)/2)+", top="+parseInt((screen.height-nHeight)/2)+", width="+nWidth+", height="+nHeight);
    if(WindowPopUp != null)
		WindowPopUp.focus();
}

function checkEmail(txtEmail)
{
	strMail = txtEmail.replace(/ /g,"");
		regex = 
/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	if (regex.test(strMail)) {
			return true;
	}	else {
			return false;
	}
}

function isFloat(objText) {
	var floatPoint = false;
		if (objText.charAt(0) == "." || objText.charAt(0) == ",")
		return false;
		for (i=0; i < objText.length; i++) {
			if (!isDigit(objText.charAt(i))) {
			if (!floatPoint && (objText.charAt(i) == "." || objText.charAt(i) == ","))
			floatPoint = true;
			else
			return false;
			}
		}
		return true;
}

function checkFirstLetter(strString) {
		letter = strString.charAt(0);
		switch (letter) {
				case "e":
				case "a":
				case "i":
				case "o":
				case "u":
				case "é":
					return true;
				break;
				default:
					return false;
				break;
		}
}


function isDigit (c) {
	return ((c >= "0") && (c <= "9"));
}


function isNumber(param) {
	strLocalString = param.replace(/ /g, "");
	for (t = 0; t < strLocalString.length; t++) {
		if (!isDigit(strLocalString.charAt(t))) {
			return false;
		}
	}
	return true;
}


function doFormSubmit(objForm, strFormTarget, strFormAction, strAddErr, objCausedErr) {
/*
Attributes needed on input/select fields:
mandatory=yes to have the object included in validation process
tip= ...  to force a certain validation process. (this defaults to text if attribute is missing or empty)
 -- valid tip attributes include: email, checkbox, text, number, select
errormsg= ... an error message to be displayed if the validation process for that field has failed

copy/paste this code into a "button" tag to use for submitting a form:
 -=  onClick="doFormSubmit(this.form)"  =-
*/

    if (typeof(strAddErr) == "undefined")
        strAddErr = "";
    if (typeof(objCausedErr) == "undefined")
        objCausedErr = null;
	arrValidation = Array();
	arrRejected = Array();
	txtErr = "";
	strTmp = "";
	arrElements = objForm.elements;
	for(i=0;i<arrElements.length;i++) {
			obj = arrElements[i];
			if((obj.getAttribute("mandatory") && obj.getAttribute("mandatory") == "yes") || (obj.getAttribute("tip") && obj.getAttribute("tip").replace(/ /g,"")!= "")) {
					arrValidation[arrValidation.length] = obj;
			}
	}

	for(i=0;i<arrValidation.length;i++) {
			obj = arrValidation[i];
			if(obj.getAttribute("tip") && obj.getAttribute("tip").replace(/ /g,"") != "") {
				objValidationType = obj.getAttribute("tip");
			} else if(obj.getAttribute("type") && obj.getAttribute("type").replace(/ /g,"") != "") {
				objValidationType = obj.getAttribute("type");
			} else {
				objValidationType = "text";
			}
			
			if(!(obj.getAttribute("mandatory") && obj.getAttribute("mandatory") == "yes") && (obj.getAttribute("tip") && obj.getAttribute("tip").replace(/ /g,"") != "")) {
				strTmp = validateObjectByType(obj, objValidationType, true);
			} else {
				strTmp = validateObjectByType(obj, objValidationType, false);
			}
			if(strTmp != "") {
				txtErr += strTmp;
				arrRejected[arrRejected.length] = obj;
			}
	}

    txtErr = strAddErr + txtErr;
    if (objCausedErr !== null)
        arrRejected[0] = objCausedErr;
	if(txtErr != "") {
		alert(txtErr);
		arrRejected[0].focus();
	} else {
		if(strFormTarget.replace(/ /g,"") != "")
				objForm.setAttribute("target",strFormTarget.replace(/ /g,""));
		if(strFormAction.replace(/ /g,"") != "")
				objForm.setAttribute("action",strFormAction.replace(/ /g,""));
		objForm.submit();
	}

}


function validateObjectByType(obj, strType, bTypeOnly) {
var lang1 = "fr";
		bErr = false;
		errType = -1;
		strErrorMsg = "";
		
		if(!bTypeOnly) {
			objVal = obj.value;
			if(objVal.replace(/ /g,"") == "") {
					bErr = true;
					errType = 0;
			}
		}

		if(!bErr) {
			if(strType == "email") {
					objVal = obj.value.replace(/ /g,"");
					if(!bTypeOnly || objVal != "") {
							if(!checkEmail(objVal)) {
									errType = 1;
							}
					}
			} else if(strType == "text")  {
					objVal = obj.value;
					if(objVal.replace(/ /g,"") == "") {
							errType = 1;
					}
			} else if(strType == "checkbox" || strType == "radio") {
					if(!obj.checked) {
							errType = 1;
					}
			}  else if(strType == "select")  {
					objVal = obj.value;
					if(objVal.replace(/ /g,"") == "" || parseInt(objVal.replace(/ /g,"")) == -1) {
							errType = 1;
					}
			} else if(strType == "number") {
					objVal = obj.value;
					if(!isNumber(objVal)) {
						errType = 1;
					}
			} else if(strType == "password")  {
					objVal = obj.value;
					objID = obj.getAttribute("id") + "2";
					if(!document.getElementById(objID)) {
							errType = 3;
					} else if((objVal.replace(/ /g,"") == "") || (document.getElementById(objID).value.replace(/ /g,"") == "") ){
							errType = 0;
					} else if (document.getElementById(objID).value.replace(/ /g,"") != objVal.replace(/ /g,"")) {
							errType = 2;
					}
			} else if(strType == "date") {
					objVal = obj.value.replace(/ /g,"");
					if(!bTypeOnly || objVal != "") {
							errType = -2;
							strErrorMsg = isDate(objVal);
					}
			}
		}


		if(errType != -1) {
			if(obj.getAttribute("errormsg") && obj.getAttribute("errormsg").replace(/ /g,"") != "") {
				strIdent = obj.getAttribute("errormsg");
			} else {
				strIdent = obj.getAttribute("name");
			}
			switch(errType) {
					case 0:
                            if (lang1 == 'en') {
							strErrorMsg = "Write your " + strIdent + " in the form!\r\n";
                            } else {
                              strErrorMsg = "Vous devez saisir votre " + strIdent + " dans le formulaire!\r\n";
                            }
					break;
					case 1:
							if(checkFirstLetter(strIdent)) {
								strErrorMsg = "L'"+strIdent;
							} else {
								strErrorMsg = "Le " + strIdent;
							}
                            if (lang1 == 'fr') {
								strErrorMsg +=" que vous avez introduit n'est pas valide!\r\n";
                             } else {
                              strErrorMsg = "Invalid data!\r\n";
                            }
					break;
					case 2:
                    if (lang1 == 'fr') {
								strErrorMsg = "Les mots de passe introduits ne correspondent pas\r\n";
                                 } else {
                              strErrorMsg = "invalid password!\r\n";
                            }
					break;
					case 3:
                     if (lang1 == 'fr') {
								strErrorMsg = "Le formulaire est invalide\r\n";
                                 } else {
                              strErrorMsg = "invalid form!\r\n";
                            }
					break;

			}
			return strErrorMsg;
		}  else {
			return "";
		}
}

function makeHttpRequest(scriptpath,urlmethod) {
		if(!initAjax()) {
				alert('Your browser does not support AJAX!');
				return false;
		}
		strString = "";
		xmlHttp.open(urlmethod,scriptpath,true);
		xmlHttp.onreadystatechange = function() {
				if(xmlHttp.readyState == 4) {
						if(xmlHttp.status == 200) {
							strString = xmlHttp.responseText.toString();
						} else {
							strString = "Page: " + scriptpath + " - " + xmlHttp.status + ": " + xmlHttp.statusText.toString();
						}
							
				} else {
							//parent.document.getElementById("divContact").innerHTML = "<strong>Envoi du message</strong>";
				}
				processResult(strString, xmlHttp.readyState);
		}
    xmlHttp.send(null);
}

// *************************** Date validation *********************************

/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var currDate = new Date();
var minYear=1900;
//var maxYear=currDate.getFullYear();
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(dtStr){            
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=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){
		return "Date '"+dtStr+"' est incorrecte."+"Le format de la date devrait être : jj/mm/aaaa.\r\n"
	}
	if (strMonth.length<1 || month<1 || month>12){
		return "Date '"+dtStr+"' est incorrecte."+"Veuillez saisir un mois correct.\r\n"
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return "Date '"+dtStr+"' est incorrecte."+"Veuillez saisir un jour correct.\r\n"
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return "Date '"+dtStr+"' est incorrecte."+"Veuillez saisir une annee de 4 chiffres entre "+minYear+" et "+maxYear+".\r\n"
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return "Date '"+dtStr+"' est incorrecte."+"Veuillez saisir une date correcte.\r\n"
	}
	return ""
}

// formatting currency

function parseFloatLocale(strVar)
{
	if ((strVar == "undefined") || (strVar == null))
		return 0;
	else
	{
		strVar = strVar.toString();
		if (strVar.length == 0)
			return 0;

		strVar = strVar.replace(/,/g, ".");
		strVar = strVar.replace(/ /g, "");
		if ((g_strFloatSeparator != ".") && (g_strFloatSeparator != ","))
			eval("strVar = strVar.replace(/" + g_strFloatSeparator + "/g, \".\");");
		if (strVar.charAt(0) == '.')
			strVar = '0' + strVar;

		return parseFloat(strVar);
	}
}

function getPrecision(nVar, nDec)
{
   var i, strVar, nSepPos, nDecNum;
   var strZero = "0000000000000000";

   if ((nVar == "undefined") || (nVar == null) || (nVar.length == 0))
       nVar = "0";

   //fTmp = parseFloat(1) / 10;
   //g_strFloatSeparator = fTmp.toLocaleString().substr(1, 1);
   g_strFloatSeparator = ".";
   strVar = ((Math.round(parseFloatLocale(nVar) * Math.pow(10, nDec))) / Math.pow(10, nDec)).toString();
   nSepPos = strVar.indexOf(".");
      //nDecNum = strVar.substr(nSepPos + 1).length;
   nDecNum = strVar.length - nSepPos;

   if (nSepPos == -1)
   {
       var arrT = new Array(strVar, g_strFloatSeparator, strZero.substr(0, nDec));
       strVar = arrT.join("");
       /*
       strVar += g_strFloatSeparator;
       for (i = 0; i < nDec; i++)
       {
           strVar += "0";
       }
       */
   }
   else
   {
       var arrT = new Array(strVar.substr(0, nSepPos), g_strFloatSeparator, strVar.substr(nSepPos + 1), strZero.substr(0, nDec - nDecNum + 1));
       strVar = arrT.join("");
       /*
       strVar = strVar.substr(0, nSepPos) + g_strFloatSeparator + strVar.substr(nSepPos + 1);
       if (nDecNum < nDec)
       {
           for (i = nDecNum; i < nDec; i++)
           {
               strVar += "0";
           }
       }
       */
   }

   fTmp = 1000;
   strTmp = fTmp.toLocaleString();
   fTmp = 1;

   if (strTmp.length - 4 > fTmp.toLocaleString().length - 1)
   {
       g_strGroupSeparator = strTmp.substr(1, 1);

       i = strVar.indexOf(g_strGroupSeparator);
       nLast = -1;
       if (g_strGroupSeparator == g_strFloatSeparator)
           nLast = strVar.lastIndexOf(g_strGroupSeparator);

       while ((i >= 0) && (i != nLast))
       {
           strVar = strVar.substr(0, i) + strVar.substr(i + 1);
           i = strVar.indexOf(g_strGroupSeparator);
           nLast--;
       }
   }

   return strVar;
}

// end formatting currency