/******************************************************************/
/*	Vérification du Rib par les données d'entrée :                */
/*  cb = code banque                                              */
/*  cg = code guichet                                             */
/*  nc = n° de compte                                             */
/*  cr = clé RIB                                                  */
/*  ob = RIB non vide obligatoire                                 */
/******************************************************************/
function verifRIB(cb,cg,nc,cr,ob)
{

	if ( (cb=="") && (cg=="") && (nc=="") && (cr=="") && (!ob)) return true;

	var a,b,c,d,e,f,g,h,i,j,k,l;
	var x1 = 0, x2;
	var valrib = "A1B2C3D4E5F6G7H8I9J1K2L3M4N5O6P7Q8R9S2T3U4V5W6X7Y8Z9";
	do
	{

		if ( nc.charCodeAt(x1) > 57 )
		{

		  for ( x2 = 0; x2 < valrib.length; x2 += 2 )
		  {
			  if (  valrib.charCodeAt(x2) == nc.charCodeAt(x1) )
			  {
				 if (x1 != nc.length - 1)
					nc = nc.substr( 0, x1  ) + valrib.charAt( x2 + 1) + nc.substr( x1+1 , nc.length);
				 else
					nc = nc.substr( 0, x1  ) + valrib.charAt( x2 + 1);

				 break;
			  }
		  }
		}
		x1++;
	}while ( x1 < nc.length )

	//alert( nc );
	a = cb;
	b = cg;
	c = nc;

	d = (a*8);
	a = Math.floor(d/97);
	a = d-(a*97);

	e = (b*15);
	b = Math.floor(e/97);
	b = 97-(e-(b*97));

	f = (c*3);
	c = Math.floor(f/97);
	c = 97-(f-(c*97));

	g = a+b+c;
	h = Math.floor(g/97);
	i = g-(h*97);

	if (i==0) i = 97;

	if (i == cr  && cb.length == 5 && cg.length == 5 && nc.length == 11 && cr.length == 2)
		return true;
	else
		return false;
}
//*************************************************************************************************************************
//*************************************************************************************************************************
// retourne true si la chaine passée en paramètres ne contient pas d'autres caractères que ceux saisis en parametre
// valeur --> chaine à tester
// charPoss --> caractères tolérés
function charOk(valeur, charPoss)
{
    var i=0;
    var val;
    for (i=0;(i<valeur.length);i++) {
        val = charPoss.indexOf(valeur.charAt(i));
	if (val == -1) {
	    return false;
	}
    }

return true;

}
//*************************************************************************************************************************
// retourne FALSE si la chaine passée en paramètres  contient un ou plusieurs caractères saisis en parametre
// valeur --> chaine à tester
// charInterd --> caractères interdits
function charKo(valeur, charInterd) {

    i=0;
    ok='ok';
    for (i=0; (ok=='ok' ) && (i<valeur.length);i++) {
	val = charInterd.indexOf(valeur.charAt(i));
            if (val!= -1 ) {
	        return false;
	    }
    }

return true;

}

//*************************************************************************************************************************
function controleCharOk (valeur){

	return charOk(valeur, "ABCDEFGHIJKLMNOPQRSTUVWXYZ -'");
}

//*************************************************************************************************************************
function controleCharKo (valeur){

	return charKo (valeur,"&#~{([|`_]=+}£%µ*§$!012345\6789/;,");
}

function sysdate () {

var d=new Date();

return d.getFullYear() +''+ (d.getMonth()+1) +''+ d.getDate();

}

// naiss : date de naissance
// min : age mini
// max : age max
function verifAge(n, min, max, j) {
	if (j=='') {
		var d = new Date();
	} else {
		var d = new Date(parseInt(j.substr(6,4)), parseInt(j.substr(3,2)-1), parseInt(j.substr(0,2)));
	}
	var nmax = new Date(0);
	nmax.setFullYear(parseInt(n.substr(6,4))+max, parseInt(n.substr(3,2)-1) , n.substr(0,2) );
	var nmin = new Date(0);
	nmin.setFullYear(parseInt(n.substr(6,4))+min, parseInt(n.substr(3,2)-1) , n.substr(0,2) );

	return ( nmin < d && d < nmax );
}
// function pour effacer tous les champs d'un formulaire
function effacerForm(f) {
	for (var i=0 ; i<document.forms[f].elements.length; i++) {
		try {
				if (document.forms[f].elements[i].type.substr(0, 6)=='select') {
						document.forms[f].elements[i].selectedIndex=0;
				}
				else if (document.forms[f].elements[i].type!='radio' && document.forms[f].elements[i].type!='submit') {
					document.forms[f].elements[i].value='';
				}
				else {
					document.forms[f].elements[i].checked=false;
				}
		}
		catch (e) {}
		try {
				if (document.forms[f].elements[i].name.substr(document.forms[f].elements[i].name.length-4)=='_LST' ) {
					document.forms[f].elements[i].options.length=0;
					findDOM(document.forms[f].elements[i].name.substr(0, document.forms[f].elements[i].name.length-4)+'_DIV').style.display='none';
				}
		}
		catch (e) {}
		try {
				document.forms[f].elements[i].checked=false;
		}
		catch (e) {}
		try {
				runEvent('coche' + i + '_BOX', 'onclick');
		}
		catch (e) {}
		try {
				runEvent('coche' + i + '_BOX', 'onchange');
		}
		catch (e) {}
	}
	try {
		document.forms[f].elements['recherche'].value=1;
	}
	catch (e) {}
	try {
		document.forms[f].elements['recherche_etat'].value=document.forms[f].elements['recherche_etat'].options[0].value;
	}
	catch (e) {}
	try {
		document.forms[f].elements['recherche_demande_date_de_creation_operateur_RADIO_2'].checked=true;
	}
	catch (e) {}
	try {
		document.forms[f].elements['recherche_etat_RADIO_0'].checked=true;
	}
	catch (e) {}
}

// function pour effacer tous les champs d'un formulaire
function formVide(f) {
	var saisie=false;
	for (var i=0 ; i<document.forms[f].elements.length && !saisie; i++) {
		try {
			if ((document.forms[f].elements[i].type.substr(0, 6)=='select' || document.forms[f].elements[i].type=='text')
				&& document.forms[f].elements[i].name!='recherche_etat'
				&& document.forms[f].elements[i].name!='recherche') {
				saisie=document.forms[f].elements[i].value!='';
			}
//			alert(document.forms[f].elements[i].type + ' ' + document.forms[f].elements[i].name + ' ' + document.forms[f].elements[i].value);
		}
		catch (e) {}
	}
	return !saisie;
}
function submitForm(f) {
	if (findDOM('recherche_etat').value=='a_reconduire') {
		if (formVide(f))
			alert('Merci de saisir au moins un critère de recherche.');
		else
			document.forms[f].submit();
	}
	else document.forms[f].submit();
}

function openwin(url, name, opt, hist) {
	var w=window.open(url, name, opt, hist);
	w.window.focus();
}

function trim(s) {
    return s.replace(/^\s+/, '').replace(/\s+$/, '');
}
//*************************************************************************************************************************
// o	l'objet en question
// c1	le nom de la première classe
// c2	le nom de la deuxième classe
// a	définit l'action que vous souhaitez effectuer
//		actions :
//		- swap :	remplace la classe c1 avec la classe c2 dans l'objet o
//		- add :		ajoute la classe c1 à l'objet o
//		- remove :	supprime la classe c1 de l'objet o
//		- check	 :	test si la classe c1 est déjà appliquée à l'objet o et retourne true ou false
function jsclass(a,o,c1,c2) {
  switch (a){
    case 'swap':
      o.className=!jsclass('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jsclass('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}

function str_pad( input, pad_length, pad_string, pad_type ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://crestidg.com)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'

    var half = '', pad_to_go;

    var str_pad_repeater = function(s, len){
            var collect = '', i;

            while(collect.length < len) collect += s;
            collect = collect.substr(0,len);

            return collect;
        };

    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }
        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    }

    return input;
}
var euro = String.fromCharCode(8364);

function windowPaiement() {
	var win = window.open('', 'payer', 'status=yes,height=575,width=760');
	win.focus();
}

function windowPaypal() {
	var win = window.open('', 'payer', 'status=yes,height=575,width=1000,scrollbars=yes');
	win.focus();
}
/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function strtr (str, from, to) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: uestla
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Alan C
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Taras Bogach
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: jpfle
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -   depends on: krsort
    // -   depends on: ini_set
    // *     example 1: $trans = {'hello' : 'hi', 'hi' : 'hello'};
    // *     example 1: strtr('hi all, I said hello', $trans)
    // *     returns 1: 'hello all, I said hi'
    // *     example 2: strtr('äaabaåccasdeöoo', 'äåö','aao');
    // *     returns 2: 'aaabaaccasdeooo'
    // *     example 3: strtr('ääääääää', 'ä', 'a');
    // *     returns 3: 'aaaaaaaa'
    // *     example 4: strtr('http', 'pthxyz','xyzpth');
    // *     returns 4: 'zyyx'
    // *     example 5: strtr('zyyx', 'pthxyz','xyzpth');
    // *     returns 5: 'http'
    // *     example 6: strtr('aa', {'a':1,'aa':2});
    // *     returns 6: '2'

    var fr = '', i = 0, j = 0, lenStr = 0, lenFrom = 0, tmpStrictForIn = false, fromTypeStr = '', toTypeStr = '', istr = '';
    var tmpFrom = [];
    var tmpTo = [];
    var ret = '';
    var match = false;

    // Received replace_pairs?
    // Convert to normal from->to chars
    if (typeof from === 'object') {
        tmpStrictForIn = this.ini_set('phpjs.strictForIn', false); // Not thread-safe; temporarily set to true
        from = this.krsort(from);
        this.ini_set('phpjs.strictForIn', tmpStrictForIn);

        for (fr in from) {
            if (from.hasOwnProperty(fr)) {
                tmpFrom.push(fr);
                tmpTo.push(from[fr]);
            }
        }

        from = tmpFrom;
        to = tmpTo;
    }
    
    // Walk through subject and replace chars when needed
    lenStr  = str.length;
    lenFrom = from.length;
    fromTypeStr = typeof from === 'string';
    toTypeStr = typeof to === 'string';

    for (i = 0; i < lenStr; i++) {
        match = false;
        if (fromTypeStr) {
            istr = str.charAt(i);
            for (j = 0; j < lenFrom; j++) {
                if (istr == from.charAt(j)) {
                    match = true;
                    break;
                }
            }
        }
        else {
            for (j = 0; j < lenFrom; j++) {
                if (str.substr(i, from[j].length) == from[j]) {
                    match = true;
                    // Fast forward
                    i = (i + from[j].length)-1;
                    break;
                }
            }
        }
        if (match) {
            ret += toTypeStr ? to.charAt(j) : to[j];
        } else {
            ret += str.charAt(i);
        }
    }

    return ret;
}

function sansAccent() {
	var conv = "ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËéèêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ";
	var conp = "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn";

	return strtr(this, conv, conp);
}
String.prototype.sansAccent = sansAccent;


function calcRoute(field, location_type, arg1, arg2, arg3, arg4) {


	if (location_type=='ROOFTOP')
		type = 'street_address';

	if (arg3==undefined || arg3=='') {
		start = arg1.replace(/[']/g, " ");
		end = arg2.replace(/[']/g, " ");
	} else {
		if (arg4==undefined || arg4=='') {
			if (typeof(arg1)=='string') {
				start = arg1.replace(/[']/g, " ");
				end = new google.maps.LatLng(arg2, arg3);
			} else {
				start = new google.maps.LatLng(arg1, arg2);
				end = arg3.replace(/[']/g, " ");
			}
		} else {
			start = new google.maps.LatLng(arg1, arg2);
			end = new google.maps.LatLng(arg3, arg4);
		}
	}

	// Retrieve the start and end locations and create
	// a DirectionsRequest using DRIVING directions.
	var request = {
		origin: start,
		destination: end,
		travelMode: google.maps.DirectionsTravelMode.DRIVING,
		provideRouteAlternatives: true
	};

	// Route the directions and pass the response to a
	// function to create markers for each step.
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			distance = 1000000000;
			for (var i=0; i<response.routes.length; i++) {
			}
			for (var i=0; i<response.routes.length; i++) {
				if (response.routes[i].legs[0].distance.value < distance) {
					distance = response.routes[i].legs[0].distance.value;
					route = response.routes[i].legs[0];
				}
			}
			if (
				location_type==''
				||
				(
					(
						route.start_geocode.geometry.location_type==location_type
						||
						in_array(type, route.start_geocode.types)
					)
					&&
					(typeof(route.start_geocode.partial_match)=='undefined' || !route.start_geocode.partial_match)
					&&
					(
						route.end_geocode.geometry.location_type==location_type
						||
						in_array(type, route.end_geocode.types)
					)
					&&
					(typeof(route.end_geocode.partial_match)=='undefined' || !route.end_geocode.partial_match)
				)
			) {
				findDOM(field).value = distance/1000;
				try {
					eval(field+'TexteRenseigne();');
				} catch (e) {}
			}
		}
	});
}

function codeAddress(field, address) {
	address = address.replace(/[']/g, " ");
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if ((in_array('street_address', results[0].types) || results[0].geometry.location_type=='ROOFTOP') && (typeof(route.end_geocode.partial_match)=='undefined' || !route.end_geocode.partial_match)) {
				findDOM(field).value = results[0].geometry.location.lat() + ';' + results[0].geometry.location.lng();
				eval(field+'TexteRenseigne();');
			} else {
				eval('try {'+field+'TexteNonRenseigne(); } catch(e) {}');
			}
		}
	});
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}
