var xmlHttp;
var WindowPopUp;

function loadFrame() {

}
function html_entity_decode(str) {	  
	  var ta=document.createElement("textarea");
	  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	 //alert(str+" "+ta.value);
	  return ta.value;
}

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) {
/*
attributes will be read fron id value
your id should be of the form id="x/y/z", if not then the corresponding element won't be checked

where:
  x = "mandatory"(if the lement is mandatory ) or any other string if you do not want that element to be mandatory(try to use "notmandatory"..estetics)
  y = the element type  = email, checkbox, text, number, select, password
  z = 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)"  =-
*/

	arrValidation = Array();
  	arrRejected = Array();
    var arrVisited = new Array();
	txtErr = "";
	strTmp = "";
	arrElements = objForm.elements;
	for(var i=0;i<arrElements.length;i++) {
	  obj = arrElements[i];
	  if(jQuery.inArray(obj.name, arrVisited) != -1) continue;

	  arrVisited.push(obj.name);

      arrObjOptions = obj.id.split("---");
      if ((arrObjOptions.length == 3)) {

        if (arrObjOptions[0] == "mandatory")
          strTmp = validateObjectByType(obj, arrObjOptions[1], arrObjOptions[2].replace(/_/g," "), false);
        else
          strTmp = validateObjectByType(obj, arrObjOptions[1], arrObjOptions[2].replace(/_/g," "), true);

    	if(strTmp != "") {
    	    txtErr += strTmp;
    	    arrRejected[arrRejected.length] = obj;
        }
      }
  }

   if((objForm.elements["capa"] != null && (document.getElementById("capa").value.replace(/ /g,"") == ""))){
				txtErr += "Vous devez remplir le code de sécurité!\r\n";

             arrRejected[arrRejected.length] = objForm.elements["capa"];
	}
	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, strIdent, bTypeOnly) {
		bErr = false;
		errType = -1;
		strErrorMsg = "";

    		if(!bTypeOnly) {
    			objVal = obj.value;
    			if(objVal.replace(/ /g,"") == "") {
    					bErr = true;
    					errType = 0;
    			}
		    }

			if(strType == "email") {
					objVal = obj.value.replace(/ /g,"");
					if( !bTypeOnly || objVal != "") {
             if(objVal == "") {
              errType = 0;
             } else if(!checkEmail(objVal)) {
									errType = 1;
							}
					}
			} else if(strType == "text")  {
					objVal = obj.value;

					if(objVal.replace(/ /g,"") == "") {
					  if (!bTypeOnly)
							errType = 0;
					}
			} else if(strType == "checkbox" || strType == "radio") {
				   //	if(!obj.checked) {

                   if(!bTypeOnly) {
				   	if(typeof($("input[name='"+obj.name+"']:"+strType+":checked").val()) == 'undefined') {
							errType = 0;
					}
                   }
			} else if(strType == "select")  {
					objVal = obj.value;
					if(objVal.replace(/ /g,"") == "" || parseInt(objVal.replace(/ /g,"")) == 0) {
							errType = 1;
					}
			} else if(strType == "number") {
					objVal = obj.value;
          if(!bTypeOnly) {
             if(objVal == "") {
              errType = 0;
             } else 	if(!isNumber(objVal)) {
   						errType = 1;
   					}
					}

          if(bTypeOnly) {
   					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;
					}
			}



		if(errType != -1) {
			switch(errType) {
					case 0:
							strErrorMsg = "Vous devez saisir votre " + strIdent + " dans le formulaire!\r\n";
					break;
					case 1:
							if(checkFirstLetter(strIdent)) {
								strErrorMsg = "L'"+strIdent;
							} else {
								strErrorMsg = "Le " + strIdent;
							}
								strErrorMsg += " que vous avez introduit n'est pas valide!\r\n";
					break;
					case 2:
								strErrorMsg = "Les mots de passe introduits ne correspondent pas\r\n";
					break;
					case 3:
								strErrorMsg = "Le formulaire est invalide\r\n";
					break;

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

function makeHttpRequest(scriptpath,urlmethod) {
		if(!initAjax()) {
				alert('Votre navigateur ne supporte pas 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);
}


   function echeck(str) {
    var message = "l\'addresse d\'email n\'est pas valide";
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   csscody.alert(message)
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   csscody.alert(message)
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    csscody.alert(message)
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    csscody.alert(message)
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    csscody.alert(message)
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    csscody.alert(message)
		    return false
		 }

		 if (str.indexOf(" ")!=-1){
		    csscody.alert(message)
		    return false
		 }

 		 return true
	}


    function isURL(id) {
            if (document.getElementById(id) == null) return true;
            urlStr = document.getElementById(id).value;
            if (urlStr.indexOf(" ") != -1) {
              csscody.alert("Spaces are not allowed in an URL");
              return false;
            }

           if (urlStr == "" || urlStr == null) {
            return true;
           }

           urlStr=urlStr.toLowerCase();

           var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
           var validChars="\[^\\s" + specialChars + "\]";
           var atom=validChars + '+';
           //var urlPat=/^http:\/\/([\-\_\+a-z0-9]*)\.(\w*)/;
           var urlPat=/^http:\/\/(\w*)\.([\-\_\+a-z0-9]*)\.(\w*)/;
           var matchArray=urlStr.match(urlPat);

           if (matchArray==null) {
             //alert("The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s");
             return false;
           }

           var user=matchArray[2];
           var domain=matchArray[3];

           for (i=0; i<user.length; i++) {
             if (user.charCodeAt(i)>127) {
               //alert("This domain contains invalid characters.");
               return false;
             }
           }

           for (i=0; i<domain.length; i++) {
             if (domain.charCodeAt(i) > 127) {
               //alert("This domain name contains invalid characters.");
               return false;
             }
           }

           var atomPat=new RegExp("^" + atom + "$");
           var domArr=domain.split(".");
           var len=domArr.length;

           for (i=0;i<len;i++) {
             if (domArr[i].search(atomPat) == -1) {
               //alert("The domain name does not seem to be valid.");
               return false;
             }
           }

           return true;
}


function saveAlert() {

    csscody.success("Vos donn&eacute;es ont &eacute;t&eacute; enregistr&eacute;es !");

}

function AddCodeToFunction(strFunc, strCode)
{
	var strParams = "";
	if (strCode.length > 0)
	{
		if (window[strFunc] != null)
		{
			strFnCode = window[strFunc].toString();
			if (strFnCode.length > 0)
			{
				var nPos = strFnCode.indexOf("{");
				var nParamPos = strFnCode.indexOf("(");
				var nLastPos;
				if ((nParamPos >= 0) && (nParamPos < nPos))
				{
					nLastPos = nParamPos + 1;
					while ((strFnCode.charAt(nLastPos) != ")") && (nLastPos < strFnCode.length))
						nLastPos++;
					strParams = strFnCode.substr(nParamPos + 1, nLastPos - nParamPos - 1);
				}

				nLastPos = strFnCode.lastIndexOf("}");
				strFnCode = strFnCode.substr(nPos + 1, nLastPos - nPos - 1);
			}
			strFnCode =  strFnCode + ";" + strCode + ";";
		}
		else
			strFnCode = strCode;
		window[strFunc] = new Function(strParams, strFnCode);
	}
}

function isNumber(str)
{
	bStatus = true;
	for(var i=0; i<str.length; i++)
	{
		var ch = str.charAt(i);
		if ((ch < '0' || ch > '9') && (ch != "."))
		{
			bStatus = false;
			break;
		}
	}
	return bStatus;
}
function isInteger(str)
{
	bStatus = true;
	for(var i=0; i<str.length; i++)
	{
		var ch = str.charAt(i);
		if ((ch < '0' || ch > '9'))
		{
			bStatus = false;
			break
		}
	}
	return bStatus;
}

function ControlExists(strObject)
{
	return ((document.getElementById(strObject) != null) && (document.getElementById(strObject) != "undefined"));
}

function ValidateMamdatory()
{
	strMsg = "";
	for (i = 0; i < arrMandatory.length; i++)
	{
		arrControl = arrMandatory[i].split(" ");
		if (ControlExists(arrControl[0]) &&  document.getElementById(arrControl[0]).value.length == 0)
		{
			strMsg += (arrControl[1]+' ');
			document.getElementById(arrControl[0]).focus();
		}
	}
	if (strMsg != "")
	{
		csscody.alert('Vous devez remplir tous les champs obligatoires : ' + strMsg + ' !');
		return false;
	}
	else
		return true;
}


