// Diverses fonctions Javascript (contrôles, tests, etc...) utilisees sur tout le site

window.onerror=null;
function OW (lien) {
	window.open (lien,'PopUpWd1','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=730,height=580,screenX=250,screenY=300');
}

function valide_id(){
	if(_CF_checkform_id(document.form_id)){
		document.form_id.submit();
	}
}
function gotoPopUrl(mode,file_name,root_url,title,param){
//
// fonction (tres basique...) specifique a l'outil de diagnostic
// facilitant l'appel des conseils, actions et outils
//
// mode = goto : equivaut a un cflocation
//         popup : nouvelle fenetre
//
// file_name = nom du fichier a charger a partir du repertoire de la homepage
//                  ex : outidiag/actions/logeabilite/cfm/logeabilite.cfm
//
// root_url = #Request.AppGlobal_root_url#
//
// title = titre de la page
//
	var host_module = root_url+"host_module.cfm";
	if (param != null) param = "&" + param
	else param = ''	;
	var parameters = "?"+"title="+title+"&mode=popup"+param+"&file_name="+file_name;
	var target_url = host_module+parameters;
	if (mode == "popup")
	{
		var myParameters = 'resizable,scrollbars=yes,status=no,width=513,height=500,top=10,left=200';
		var newWin = open(target_url, 'popup', myParameters);
	}
	else
	if (mode == "popup_offre")
	{
		var myParameters = 'resizable,scrollbars=yes,status=no,width=650,height=500,top=10,left=200';
		var newWin = open(target_url, 'popup', myParameters);
	}
}

// A supprimer si pas de pb rencontrer

//function openWin(url_name){
//	var url_name_local = url_name;
//	var myParameters = 'resizable,scrollbars=yes';
//	var newWin = open(url_name_local, '', myParameters);
//}

/*************************************************
* controles.js
* ensembles des fonctions de controles des champ
*************************************************/

function onErrorPerformed(form, input, value, message) {
	alert(message);
	
	//input.select();
	input.focus();
}



//validation d'un float
function checkFloat(form, input, value) {

	ind = value.indexOf(',');
	
	if(ind >=0) {
		
		v1 = value.substring(0, ind);
		v2 = value.substring(ind+1);
		v1 = v1.concat('.');
		v1 = v1.concat(v2);
		
		value = v1;
		
		input.value = value;
	}
	
	if(!isFloat(value)) {
		return false;
	} 
	else {
		return true;
	}
}

function checkCroissance(form, input, value) {
	if(checkFloat(form, input, value)) {
		if(value <= -100) {
			return false;
		}
		else {
			return true;
		}
	}
	else {
		return false;
	}
}


//validation d'un entier
function checkInteger(form, input, value) {
	
	if(!isInteger(value)) {
		return false;
	} 
	else {
		return true;
	}
}


//validation d'une heure
function checkHour(form, input, object_value) {
	
    if (object_value.length == 0)
        return true;

    //Returns true if value is a hour in the HH/MM format
        isplit = object_value.indexOf('/');

        if (isplit == -1)
        {
                isplit = object_value.indexOf('.');
        }

        if (isplit == -1 || isplit == object_value.length)
                return false;

    sHour = object_value.substring(0, isplit);
    sMinute = object_value.substring((sHour.length + 1));
	
			
        if (!_CF_checkinteger(sHour)) 
                return false;
        else
        if (!_CF_checkrange(sHour, 0, 24)) 
                return false;
        else
        if (!_CF_checkinteger(sMinute)) 
                return false;
        else
        if (!_CF_checkrange(sMinute, 0, 59)) 
                return false;
        else
                return true;
}
function checkEmail(form, input, value) {
	
	// le champ est vide..
	if(value == "") return true;
	
	// verifier si @ est present
	if (value.indexOf ('@', 0) == -1 || value.indexOf ('.', 0) == -1) {
		return (false);
	} else
    // sinon ok 
	return (true);
}

//validation d'un numero de siren
function checkSirenNumber(form, input, value)
{
var ok  = true;
value=value.replace( /[ ]*/g,""); //vire les espaces de l objet

//si le premier caracteres est un P alors le reste doit etre un entier alors OK

if (((input.value.substring(0,1) == "P") || (input.value.substring(0,1) == "p")))
  {
   if (input.value.length==9)
    {
       ok = controlersirenprovisoire(input.value.substring(1,8));
   if (!ok)
    {
      input.select();
      input.focus();
	}
    }
   else
    {
   input.select();
   input.focus();
   ok = false;
}
  }
else
{
ok =  NbrPositif(input);
if (ok && (input.value!="") )
{
  res = SommePonderationsSiren(input.value);
  if  ((res %10) != 0 )
     {
   input.select();
   input.focus();
   ok = false;
     }
}
}
   if (!ok)
   {
   	  alert('Veuillez entrer un numéro de SIREN correct.');
   }

return ok;
}

function NbrPositif(val)
{
if (val >= "0")
    { 
    return (true);
	}
else return (false);
}
//------------------------------
function controlersirenprovisoire(val)
{
var ok =true;
for(i=0;(i<val.length) && ok;i++)
if( val.charAt(i)<"0" || val.charAt(i)>"9") ok =false;
return ok;
}
//----------------------------
function SommePonderationsSiren(val)
{
somme = 0;
j     = 0;
for (i=0;i<9;i++)
{
   j = 9 - i;
   if (( j%2)==0) { p = 2;}
   else           { p = 1;}
   sp = (p * parseInt(val.charAt(i),10) );
   sps = sp.toString();
   if  ( sp >= 10 )
        {s = parseInt(sps.charAt(0),10) + parseInt(sps.charAt(1),10); }
   else
       { s = sp;}
   somme = somme + s;
}
return somme;
}

// verifie si value est un float
// utilisee par checkFloat.
function isFloat(value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false   

    if (value.length == 0)
        return true;

    //Returns true if value is a number defined as
    //   having an optional leading + or -.
    //   having at most 1 decimal point.
    //   otherwise containing only the characters 0-9.
        var start_format = " .+-0123456789";
        var number_format = " .0123456789";
        var check_char;
        var decimal = false;
        var trailing_blank = false;
        var digits = false;

    //The first character can be + - .  blank or a digit.
        check_char = start_format.indexOf(value.charAt(0))
    //Was it a decimal?
        if (check_char == 1)
            decimal = true;
        else if (check_char < 1)
                return false;
        
        //Remaining characters can be only . or a digit, but only one decimal.
        for (var i = 1; i < value.length; i++)
        {
                check_char = number_format.indexOf(value.charAt(i))
                if (check_char < 0)
                        return false;
                else if (check_char == 1)
                {
                        if (decimal)            // Second decimal.
                                return false;
                        else
                                decimal = true;
                }
                else if (check_char == 0)
                {
                        if (decimal || digits)  
                                trailing_blank = true;
        // ignore leading blanks

                }
                else if (trailing_blank)
                        return false;
                else
                        digits = true;
        }       
    //All tests passed, so...
    return true
    }
	
	
//validation d'une date
function checkDate(form, input, value) {
	
	return _CF_checkeurodate(value);
}
	
	function _CF_checkeurodate(object_value)
    {
    //Returns true if value is a eurodate format or is NULL
    //otherwise returns false   

    if (object_value.length == 0)
        return true;

    //Returns true if value is a date in the dd/mm/yyyy format
        isplit = object_value.indexOf('/');

        if (isplit == -1)
        {
                isplit = object_value.indexOf('.');
        }

        if (isplit == -1 || isplit == object_value.length)
                return false;

    sDay = object_value.substring(0, isplit);

        monthSplit = isplit + 1;

        isplit = object_value.indexOf('/', monthSplit);

        if (isplit == -1)
        {
                isplit = object_value.indexOf('.', monthSplit);
        }

        if (isplit == -1 ||  (isplit + 1 )  == object_value.length)
                return false;

    sMonth = object_value.substring((sDay.length + 1), isplit);

        sYear = object_value.substring(isplit + 1);

        if (!_CF_checkinteger(sMonth)) //check month
                return false;
        else
        if (!_CF_checkrange(sMonth, 1, 12)) // check month
                return false;
        else
        if (!_CF_checkinteger(sYear))  //check year
                return false;
		else
        if (!_CF_checkrange(sYear, 1800, 3000))  //check year
                return false;
        else
        if (!_CF_checkinteger(sDay)) //check day
                return false;
        else
        if (!_CF_checkday(sYear, sMonth, sDay)) //check day
                return false;
		else
		if (sYear.length != 4)   //check year size
		        return false;
		else
		if (sMonth.length != 2)   //check month size
		        return false;
		else
		if (sDay.length != 2)   //check day size
		        return false;						
        else
                return true;
    }
function _CF_checkday(checkYear, checkMonth, checkDay)
    {

        maxDay = 31;

        if (checkMonth == 4 || checkMonth == 6 ||
                        checkMonth == 9 || checkMonth == 11)
                maxDay = 30;
        else
        if (checkMonth == 2)
        {
                if (checkYear % 4 > 0)
                        maxDay =28;
                else
                if (checkYear % 100 == 0 && checkYear % 400 > 0)
                        maxDay = 28;
                else
                        maxDay = 29;
        }

        return _CF_checkrange(checkDay, 1, maxDay); //check day
    }
function _CF_checkinteger(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false   

    if (object_value.length == 0)
        return true;

    //Returns true if value is an integer defined as
    //   having an optional leading + or -.
    //   otherwise containing only the characters 0-9.
        var decimal_format = ".";
        var check_char;

    //The first character can be + -  blank or a digit.
        check_char = object_value.indexOf(decimal_format)
    //Was it a decimal?
    if (check_char < 1)
        return _CF_checknumber(object_value);
    else
        return false;
    }
function _CF_numberrange(object_value, min_value, max_value)
    {
    // check minimum
    if (min_value != null)
        {
        if (object_value < min_value)
                return false;
        }

    // check maximum
    if (max_value != null)
        {
        if (object_value > max_value)
                return false;
        }
        
    //All tests passed, so...
    return true;
    }
function _CF_checknumber(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false   

    if (object_value.length == 0)
        return true;

    //Returns true if value is a number defined as
    //   having an optional leading + or -.
    //   having at most 1 decimal point.
    //   otherwise containing only the characters 0-9.
        var start_format = " .+-0123456789";
        var number_format = " .0123456789";
        var check_char;
        var decimal = false;
        var trailing_blank = false;
        var digits = false;

    //The first character can be + - .  blank or a digit.
        check_char = start_format.indexOf(object_value.charAt(0))
    //Was it a decimal?
        if (check_char == 1)
            decimal = true;
        else if (check_char < 1)
                return false;
        
        //Remaining characters can be only . or a digit, but only one decimal.
        for (var i = 1; i < object_value.length; i++)
        {
                check_char = number_format.indexOf(object_value.charAt(i))
                if (check_char < 0)
                        return false;
                else if (check_char == 1)
                {
                        if (decimal)            // Second decimal.
                                return false;
                        else
                                decimal = true;
                }
                else if (check_char == 0)
                {
                        if (decimal || digits)  
                                trailing_blank = true;
        // ignore leading blanks

                }
                else if (trailing_blank)
                        return false;
                else
                        digits = true;
        }       
    //All tests passed, so...
    return true
    }
function _CF_checkrange(object_value, min_value, max_value)
    {
    //if value is in range then return true else return false

    if (object_value.length == 0)
        return true;


    if (!_CF_checknumber(object_value))
        {
        return false;
        }
    else
        {
        return (_CF_numberrange((eval(object_value)), min_value, max_value));
        }
        
    //All tests passed, so...
    return true;
    }
function OuvreInsMemb_Action() {
	if(_CF_checkInsMemb(document.InsMemb) && checkPresisez())
		{
		document.InsMemb.action = "InsMemb_Action.cfm";
		document.InsMemb.submit();
	    }

}	
function checkPresisez() {
	if(document.InsMemb.Comment_avez_vous_connu_le_site[4].checked == true && document.InsMemb.Preciser.value =="")
	{
	alert('Veuillez préciser comment avez-vous connu le site ?');
	document.InsMemb.Preciser.select();
	return false;
	}
	else return true;	

}	
var reInteger = /^\d+$/;

function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}

// isInteger (STRING s)
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s) {
	var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return 0;
       else return (isInteger.arguments[1] == true);

    return reInteger.test(s)
}

// isIntegerInRange (STRING s, INTEGER a, INTEGER b)
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isIntegerInRange (s, a, b) {
	if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.

    if (!isInteger(s, false)) return 0;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    return ((parseInt (s,10) >= a) && (parseInt (s,10) <= b));
}


// isNonnegativeInteger (STRING s)
// 
// Returns true if string s is an integer >= 0.
//

function isNonnegativeInteger (s)
{   var secondArg = 0;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0
    return (isInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s,10) >= 0) ) );
}

// isYear (STRING s)
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.

function isYear (s) {

	if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return 0;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return 0;
    return (s.length == 4);

}

function isMonth (s) {
	if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return 0;
       else return (isMonth.arguments[1] == true);
       return isIntegerInRange (s, 1, 12);
}

function isDay (s) {
	if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return 0;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}

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 makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}


function ctr_txt (txt_nam,size,type,option,field) {

/*
	Fonction permettant de faire des controles sur
	les champ de saisies de type <input type="text">

	txt_nam = myform.textname
	size :	string  -\> string lenght max
		num	-\> max value (+ et -)
		=-1, peut importe la taille
	type : s,S or n,N  or m,M or d,D or u,U or cb, h or H  (string or numeric or mail or date or url or combo box or hour )
	option : o,O or f,F (obligatory or optional)
	field : field label

*/

	var str_TextName = "document." + txt_nam + ".value";
	var var_ValTest = eval(str_TextName);
	if ((option == "O" || option == "o") && var_ValTest.replace(/ /gi,"") == "") {
		alert("Le champ '" + field + "' est obligatoire.");
		eval("document." + txt_nam).focus();
		return 0
	}
	if ((type == "n" || type == "N") && var_ValTest != "" ){
		if (! isNonnegativeInteger(var_ValTest)) {
			alert("La valeur de '" + field
			+ "' doit être un nombre positif.");
			eval("document." + txt_nam).focus();
			return 0;
		}
		if (Math.abs(var_ValTest) >= size  && size != -1) {
			alert("La valeur de  '" + field
			+ "' ne doit pas excéder " + size + ".");
			eval("document." + txt_nam).focus();
			return 0;
		}
	}else if ((type == "m" || type == "M") && var_ValTest != ""){
			var reEmail = /^.+\@.+\..+$/;
			var Valide = reEmail.test(var_ValTest);
			if (Valide == false){ 
				alert("Le format du mail n'est pas valide.");
				eval("document." + txt_nam).focus();
				return 0;
			}
		}
	else if ((type == "u" || type == "U")  && var_ValTest != ""){
			var reEmail = /^.+\..+\..+$/;
			var Valide = reEmail.test(var_ValTest);
			if (Valide == false){ 
				alert("L'url n'est pas valide.");
				eval("document." + txt_nam).focus();
				return 0;
			}
		}
	else if ((type == "h" || type == "H") && (var_ValTest != "")){
			var reEmail = /^.+\:.+$/;
			var Valide = reEmail.test(var_ValTest);
			var hour  = var_ValTest.substr(0,2);
			var minutes = var_ValTest.substr(3,2);
			if (! isNonnegativeInteger(hour)) Valide = false;
			if (! isNonnegativeInteger(minutes)) Valide = false;
			if (Valide == true){
				var intHour = parseInt(hour,10);
				var intMinutes = parseInt(minutes,10);
				if ((intHour > 24) || (intMinutes > 60)) Valide = false;
			};
			if (Valide == false){ 
				alert("Le format de l'heure n'est pas valide.");
				eval("document." + txt_nam).focus();
				return 0;
			}
		}
	else if (type == "cb" || type == "CB"){
			if (eval("document."+ txt_nam).options[eval("document."+ txt_nam).selectedIndex].value == "0"){
				alert("Vous devez sélectionner une valeur dans '"+ field +"'.");
				eval("document." + txt_nam).focus();
				return 0;
			}
		}
	else if (((type == "d" || type == "D") || (type == "dfuture" || type == "DFUTURE")) && (var_ValTest != "")){
			var daysInMonth = makeArray(12);
			daysInMonth[1] = 31;
			daysInMonth[2] = 29;   // must programmatically check this
			daysInMonth[3] = 31;
			daysInMonth[4] = 30;
			daysInMonth[5] = 31;
			daysInMonth[6] = 30;
			daysInMonth[7] = 31;
			daysInMonth[8] = 31;
			daysInMonth[9] = 30;
			daysInMonth[10] = 31;
			daysInMonth[11] = 30;
			daysInMonth[12] = 31;
			var day  = var_ValTest.substr(0,2);
			var month = var_ValTest.substr(3,2);
			var year = var_ValTest.substr(6,4);
 			if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false)) || var_ValTest.length > 10){
				alert("La valeur de '" + field + "' ne possède pas un format de date valide.");
				eval("document." + txt_nam).focus();
 			 	return 0;
 			}
		    var intYear = parseInt(year,10);
			var intMonth = parseInt(month,10);
			var intDay = parseInt(day,10);
			// catch invalid days, except for February
			if (intDay > daysInMonth[intMonth]){
				alert("La valeur de '" + field + "', n'est pas un jour valide pour ce mois.");
				eval("document." + txt_nam).focus();
				return 0; 
			} 
			if ((intMonth == 2) && (intDay > daysInFebruary(intYear))){
				alert("La valeur '" + field + "' n'est pas un jour valide pour le mois de février.");
				eval("document." + txt_nam).focus();
				return 0; 
			}
		}	
	 else {
		if (var_ValTest.length > size  && size != -1) {
			alert("La valeur du champ '" +
			field + "' est trop longue.");
			eval("document." + txt_nam).focus();
			return 0;
		}
	}
	return 1;
}
// function : tested if one check-box is checked
function fct_checkbox(FormName,CheckName,Message) {
	var strCheckName
	strCheckName = eval('document.'+FormName+'.'+CheckName);
	strCheckName.value='';
	for ( var i=0; i < strCheckName.length ; i++) {
		if (strCheckName[i].checked) { return true}
	}
	alert (Message)
	return 0;
}
// vérifie si la date entrée est inf à year, month, day
function date_future(txt_nam,year,month,day,Message) {
	var str_TextName = "document." + txt_nam + ".value";
	var var_ValTest = eval(str_TextName);
	var dayF   = var_ValTest.substr(0,2);
	var monthF = var_ValTest.substr(3,2);
	var yearF  = var_ValTest.substr(6,4);
	var sDateField = yearF + monthF + dayF;
	if (month.length < 2) month = '0'+ month;
	if (day.length < 2) day = '0'+ day;
	var sDateNow   = year + month + day;
	if (parseInt(sDateField) < parseInt(sDateNow)){
		alert (Message)
		eval("document." + txt_nam).focus();
		return 0;
	}
	return true;
}

function list_postal_code(txt_nam,field,delimiter) {
	var str_TextName = "document." + txt_nam + ".value";
	var var_ValTest = eval(str_TextName);
	var index;
	var temp;
	if (var_ValTest != ''){
		while (var_ValTest.length != 0){
			index = var_ValTest.indexOf(delimiter);
			if (index < 0) index = var_ValTest.length; 
			temp = var_ValTest.substr(0,index);
			if (! (temp.length == 2 || temp.length == 5) || (! isNonnegativeInteger (temp))){
				alert ('Vous devez renseigner une liste de codes postaux pour le champ \'' + field + '\'.');
				eval("document." + txt_nam).focus();
				return 0;
			}
			var_ValTest = var_ValTest.substr(index+1,var_ValTest.length-1);
		}
	}
	return true;
}

function checkPostalCode(form_obj, input_obj, input_val) {

	return(input_val.length == 5 && isIntegerInRange(input_val, 1000, 99999));
}

function checkPhoneNumber(form_obj, input_obj, input_val) {

	return(isNonnegativeInteger(input_val) && input_val.length > 9 && input_val.length < 15);
}

function checkPositiveInteger(form_obj, input_obj, input_val) {

	return(isNonnegativeInteger(input_val));
}

function fourchette_numerique(txt_nam,field,delimiter) {
	var str_TextName = "document." + txt_nam + ".value";
	var var_ValTest = eval(str_TextName);
	if (var_ValTest != ''){
		var valide = true;
		var index;
		var fourcheInf;
		var fourcheSup;
		index = var_ValTest.indexOf(delimiter);
		if (index == 0) valide = false;
		if (valide){
			fourcheInf = var_ValTest.substr(0,index-1);
			fourcheSup = var_ValTest.substr(index+1,var_ValTest.length-1);
		}
		if ((! isNonnegativeInteger (fourcheInf) || (! isNonnegativeInteger (fourcheSup)))  || (! (parseInt(fourcheInf) <= parseInt(fourcheSup)))) valide = false;
		if (! valide){
				alert ('Vous devez renseigner une fourchette du type 1500-3000 pour  \'' + field + '\'.');
				eval("document." + txt_nam).focus();
				return 0;
		}
	}
	return true;
}

function modifierdl(datedl)
{
	dated = datedl.toString();
	dd = dated.substr(0,2);
	mm = dated.substr(3,2);
	yy = dated.substr(6,4);
	dateech = new Date(yy, mm-1, dd, 23, 59, 59);
	date_today = new Date();
	nb_today = Date.parse(date_today);
	nb_dateech = Date.parse(dateech);
	
	if(nb_dateech >= nb_today)
	{
		return true;
	}
	else
	{
		alert('Veuillez choisir une date d\'échéance ultérieure !');
		return false;
	}
}
