jQuery.fn.center = function () {
	this.css("position","absolute");
	var top = parseInt(parseInt(parseInt($(window).height() - this.height()) / 2) + parseInt($(window).scrollTop()));
	var left = parseInt(parseInt(parseInt($(window).width() - this.width()) / 2) + parseInt($(window).scrollLeft()));
	this.css("top", top + "px");
	this.css("left", left + "px");
	return this;
}

jQuery.fn.escape = function() {
    return escape(this.val());
};

$(function(){
	$(".popIn .close").click(function(event) {
		hidePopIn($(this).parent().parent());
	});
	// la touche échap ferme la popup
	$(".popIn").live("keydown",function(event) {
		var KEY_ECHAP = "27";
		var key = event.keyCode ? event.keyCode : event.which;
		if (key == KEY_ECHAP) {
			hidePopIn($(this));
		}
	});
});

function hidePopIn(sourceName) {
	$(sourceName).css("display", "none");
	closeGlass();
}

function removePopIn(source) {
	source.remove();
	closeGlass();
}

function showPopIn(source) {
	// permet de positionner la popup depuis le body et ne pas avoir de probleme de position relative
	$('body').prepend($(source));
	$(source).css("display", "block");
	$(source).center();
	$(source).attr('tabindex','0'); // pour qu'il soit focusable (pour prendre en compte la touche echap)
	$(source).focus();
	showGlass();
}

function createPopIn(id,title,txt,color){
	var d = document;
	// Creation de la fenetre g�n�rale
	var popIn = d.createElement("div");
	$(popIn).attr('id', id);
	$(popIn).addClass('popIn');
	$(popIn).addClass('popIn'+color);
	
	// Creation du header
	var header = d.createElement("div");
	$(header).addClass('header');
	
	var close = d.createElement("div");
	$(close).addClass('close');
	$(close).click(function(){
		removePopIn($(popIn));
	});
	
	$(header).append(close);
	$(popIn).append(header);
	
	// Creation du contenu
	var content = d.createElement("div");
	$(content).addClass('content');
	$(content).html("<h1>"+title+"</h1><p>"+txt+"</p>");
	$(popIn).append(content);
	
	// Creation du header
	var footer = d.createElement("div");
	$(footer).addClass('footer');
	$(popIn).append(footer);
	
	$('body').prepend(popIn);
	$(popIn).css("display", "block");
	$(popIn).center();
	showGlass();
}

function createPopInWithOkButton(contextPath,id,title,txt,color){
	var d = document;
	// Creation de la fenetre g�n�rale
	var popIn = d.createElement("div");
	$(popIn).attr('id', id);
	$(popIn).addClass('popIn');
	$(popIn).addClass('popIn'+color);
	
	// Creation du header
	var header = d.createElement("div");
	$(header).addClass('header');
	
	var close = d.createElement("div");
	$(close).addClass('close');
	$(close).click(function(){
		removePopIn($(popIn));
	});
	
	$(header).append(close);
	$(popIn).append(header);
	
	// Creation du contenu
	var content = d.createElement("div");
	$(content).addClass('content');
	$(content).html("<h1>"+title+"</h1><p>"+txt+"</p><p>&nbsp;</p>");
	$(popIn).append(content);
	
	// Creation du button ok
	var okBtnDiv = d.createElement("div");
	$(okBtnDiv).addClass('okBtn');
	$(okBtnDiv).html("<input type='image' id='btnOkDemandeContactTelPopup' value='Envoyer' src='" + contextPath + "/commun/images/agence-mutuelle/searchBt.jpg'/>");
	$(okBtnDiv).click(function(){
		removePopIn($(popIn));
	});
	$(content).append(okBtnDiv);
	
	// Creation du header
	var footer = d.createElement("div");
	$(footer).addClass('footer');
	$(popIn).append(footer);
	
	$('body').prepend(popIn);
	$(popIn).css("display", "block");
	$(popIn).center();
	showGlass();
}

function createLoadingPopIn(id,title,txt,color){
	var d = document;
	// Creation de la fenetre générale
	var popIn = d.createElement("div");
	$(popIn).attr('id', id);
	$(popIn).addClass('popIn');
	$(popIn).addClass('popIn'+color);
	
	// Creation du header
	var header = d.createElement("div");
	$(header).addClass('header');
	$(popIn).append(header);
	
	// Creation du contenu
	var content = d.createElement("div");
	$(content).addClass('content');
	$(content).html("<h1>"+title+"</h1><p>"+txt+"</p>");
	var loading = d.createElement("div");
	$(loading).addClass('loading');
	$(content).append(loading);
	$(popIn).append(content);
	
	// Creation du header
	var footer = d.createElement("div");
	$(footer).addClass('footer');
	$(popIn).append(footer);
	
	$('body').prepend(popIn);
	$(popIn).css("display", "block");
	$(popIn).center();
	showGlass();
}

function createConfirmPopIn(id,title,txt,color){
	var d = document;
	// Creation de la fenetre générale
	var popIn = d.createElement("div");
	$(popIn).attr('id', id);
	$(popIn).addClass('popIn');
	$(popIn).addClass('popIn'+color);
	
	// Creation du header
	var header = d.createElement("div");
	$(header).addClass('header');
	$(popIn).append(header);
	
	// Creation du contenu
	var content = d.createElement("div");
	$(content).addClass('content');
	$(content).html("<h1>"+title+"</h1><p>"+txt+"</p>");
	$(popIn).append(content);
	
	// Creation du header
	var footer = d.createElement("div");
	$(footer).addClass('footer');
	$(popIn).append(footer);
	
	$('body').prepend(popIn);
	$(popIn).css("display", "block");
	$(popIn).center();
	showGlass();

	var timeOut = setTimeout(function(){
		$(popIn).css("display", "none");
		closeGlass();
		clearTimeout(timeOut);
	},3000);
}

function showGlass() {
	var d = document;
	// Creation du mask
	var mask = d.createElement("div");
	$(mask).addClass('glass');
	$('body').prepend(mask);
	$(mask).height($(document).height());
	$(mask).width($(document).width());
}

function closeGlass(){
	$(".glass").remove();
}

function arreterInfoBulle(source) {
	if(typeof(infoBulle) != "undefined"){
		clearTimeout(infoBulle);
	}
	cacherInfoBulle(source);
}

function afficherInfoBulle(index) {
	cacherInfoBulleErreur(index);
	cacherBlocValidation(index);
	$("#label" + index).addClass("valid");
	$("#input" + index).addClass("valid");
	$("#blocInfoBulle" + index).css("display", "block");
}

function afficherInfoBulleErreur(index, message) {
	cacherInfoBulle(index);
	cacherBlocValidation(index);
	$("#label" + index).addClass("error");
	$("#input" + index).addClass("error");
	$("#error" + index).text(message);
	$("#blocError" + index).css("display", "block");
}

function afficherBlocValidation(index, message) {
	cacherInfoBulleErreur(index);
	cacherInfoBulle(index);
	$("#blocValidation" + index).css("display", "block");
}

function cacherInfoBulle(index) {
	$("#label" + index).removeClass("valid");
	$("#input" + index).removeClass("valid");
	$("#blocInfoBulle" + index).css("display", "none");
}

function cacherInfoBulleErreur(index) {
	$("#label" + index).removeClass("error");
	$("#input" + index).removeClass("error");
	$("#blocError" + index).css("display", "none");
}

function cacherBlocValidation(index) {
	$("#blocValidation" + index).css("display", "none");
}

function isEmail(email) {
	var expression = new RegExp("[A-Za-z0-9\\._\\-~#]+@[A-Za-z0-9][A-Za-z0-9\\._\\-~#]*\\.[A-Za-z]{2,4}");
	return expression.test(email);
}

function isDateValide(chaineDate) {
	// Je regarde tout d'abord si la chaine n'est pas vide, sinon pas la peine d'aller plus loin
	if (chaineDate == "") return false;

	// J'utilise split pour creer un tableau dans lequel je recupere les jour mois annee
	// J'attends bien sur une date formatee en JJ/MM/AAAA
	var ladate = (chaineDate).split("/");

	// Si je n'ai pas recupere trois elements ou bien s'il ne s'agit pas d'entiers, pas la peine non plus d'aller plus loin
	if ((ladate.length != 3) || isNaN(parseInt(ladate[0])) || isNaN(parseInt(ladate[1])) || isNaN(parseInt(ladate[2]))) return false;

	// Sinon, c'est maintenant que je cree la date correspondante. Attention, les mois sont etalonnes de 0 � 11
	var unedate = new Date(eval(ladate[2]),eval(ladate[1])-1,eval(ladate[0]));

	// Bug de l'an 2000 oblige, lorsque je recupere l'annee, je n'ai pas toujours 4 chiffres selon les navigateurs, je rectifie donc ici le tir.
	var annee = unedate.getYear()
	if ((Math.abs(annee)+"").length < 4) annee = annee + 1900;

	// Il ne reste plus qu'� verifier si le jour, le mois et l'annee obtenus sont les m�mes que ceux saisis par l'utilisateur.
	return ((unedate.getDate() == eval(ladate[0])) && (unedate.getMonth() == eval(ladate[1])-1) && (annee == eval(ladate[2])));
}

/**
 * V�rifie que la cha�ne de caract�res pass�e en param�tre respecte le format d'un nom / pr�nom
 * @param valeur le nom / pr�nom � v�rifier
 * @return true si le nom / pr�nom est valide, false sinon
 */
function isNomOuPrenomValide(valeur) {
	var expression = new RegExp("^[a-zA-Z'������������������\\s-]+$");
	return expression.test(valeur);
}

/**
 * Contruit une date � partir des 3 champs day / month / year
 * @param source 
 * @param champ le champ dans lequel il faut stocker la date construire
 * @param index
 * @return la date construite au format 'dd/MM/yyyy'
 */
function construireDate(source, champ, index) {
	var valDay = $("#day" + index).attr("value");
	var valMonth = $("#month" + index).attr("value");
	var valYear = $("#year" + index).attr("value");
	if (valDay == '' && valMonth == '' && valYear == '') {
		champ.attr("value", '');
	} else {
		var date = valDay + '/' + valMonth + '/' + valYear;
		champ.attr("value",  date);
		return date;
	}
}

function createInfoBulleAidePopIn(id, title,txt,color,y,x){
	var d = document;
	// Creation de la fenetre g�n�rale
	var popIn = d.createElement("div");
	$(popIn).attr('id', id);
	$(popIn).addClass('popInInfoBulleAide');

	// Creation du contenu
	var content = d.createElement("div");
	$(content).addClass('content');
	$(content).html("<h1>"+title+"</h1><p>"+txt+"</p>");
	$(popIn).append(content);
	
	var popInFooter = d.createElement("div");
	$(popInFooter).addClass('popInInfoBulleAideFooter');
	$(popIn).append(popInFooter);

	$('body').prepend(popIn);
	$(popIn).css("display", "block");
	$(popIn).css("left", parseInt(x) - $(popIn).width() + 40);
	$(popIn).css("top", parseInt(y) - $(popIn).height());
	$(popIn).css("height", $(popIn).height() - $(popInFooter).height());
}

function removeInfoBulleAidePopIn(id) {
	$("#"+id).remove();
}

function recupererAideInternet(idPopup, urlServlet, top, left) {
	$.ajax({
	    url: urlServlet,
	    type: 'GET',
	    dataType: 'xml',
	    timeout: 3000,
	    error: function(){
			top.location.href = '<%=request.getContextPath()%>/error.jsp';
	    },
	    success: function(xml){
	        // r�cup�re les suggestions
	        aideInternet = $('aideInternet', xml);
	        var titre = $('titre', aideInternet);
	        var html = $('html', aideInternet);

	        if (titre.text() != '' && html.text() != '') {
	        	createInfoBulleAidePopIn(idPopup, titre.text(), html.text(), "Green", top, left);
	        }
	    }
	});
}


function validerCodePostal(idSource) {
	var codePostal = $("#" + idSource).val();
	var booleanLength = $(codePostal.length == 5);
	if (booleanLength) {
		var expression = new RegExp("[0-9]{5}");
		if (expression.test(codePostal) && codePostal != '00000') {
			$("#inputCodePostal").removeClass("error");
			$("#blocErrorCodePostal").css("visibility", "hidden");
		} else {
			$("#inputCodePostal").addClass("error");
			$("#errorCodePostal").text('Le format du code postal est incorrect');
			$("#blocErrorCodePostal").css("visibility", "visible");
			booleanLength =  false;
		}
	} else {
		$("#inputCodePostal").addClass("error");
		$("#errorCodePostal").text('Le format du code postal est incorrect');
		$("#blocErrorCodePostal").css("visibility", "visible");
	}
	return booleanLength;
}


var timerCodePostalMini;
function validerCodePostalMini(idSource) {
	var codePostal = $("#" + idSource).val();
	var booleanLength = $(codePostal.length == 5);
	if (booleanLength) {
		var expression = new RegExp("[0-9]{5}");
		if (expression.test(codePostal) && codePostal != '00000') {
			$("#inputCodePostalMini").removeClass("error");
			$("#blocErrorCodePostalMini").css("visibility", "hidden");
		} else {
			$("#inputCodePostalMini").addClass("error");
			$("#errorCodePostalMini").text('Le format du code postal est incorrect');
			$("#blocErrorCodePostalMini").css("visibility", "visible");
			booleanLength =  false;
		}
	} else {
		$("#inputCodePostalMini").addClass("error");
		$("#errorCodePostalMini").text('Le format du code postal est incorrect');
		$("#blocErrorCodePostalMini").css("visibility", "visible");
	}
    clearTimeout(timerCodePostalMini);
    timerCodePostalMini = setTimeout(function() {
		$("#inputCodePostalMini").removeClass("error");
		$("#blocErrorCodePostalMini").css("visibility", "hidden");
    }, 2000);
	return booleanLength;
}

var timerCodePostalMiniPage;
function validerCodePostalMiniPage(idSource) {
	var codePostal = $("#" + idSource).val();
	var booleanLength = $(codePostal.length == 5);
	if (booleanLength) {
		var expression = new RegExp("[0-9]{5}");
		if (expression.test(codePostal) && codePostal != '00000') {
			$("#inputCodePostalMiniPage").removeClass("error");
			$("#blocErrorCodePostalMiniPage").css("visibility", "hidden");
		} else {
			$("#inputCodePostalMiniPage").addClass("error");
			$("#errorCodePostalMiniPage").text('Le format du code postal est incorrect');
			$("#blocErrorCodePostalMiniPage").css("visibility", "visible");
			booleanLength = false;
		}
	} else {
		$("#inputCodePostalMiniPage").addClass("error");
		$("#errorCodePostalMiniPage").text('Le format du code postal est incorrect');
		$("#blocErrorCodePostalMiniPage").css("visibility", "visible");
	}
    clearTimeout(timerCodePostalMiniPage);
    timerCodePostalMiniPage = setTimeout(function() {
		$("#inputCodePostalMiniPage").removeClass("error");
		$("#blocErrorCodePostalMiniPage").css("visibility", "hidden");
    }, 2000);
	return booleanLength;
}

/*************** Partie réservées aux dates ***********/


/**
 * Initialise une date
 * @param string idJour l'id de l'élément jour
 * @param string idMois l'id de l'élément mois
 * @param string idAnnee l'id de l'élément année
 * @param boolean afficherInfoBulle affiche les infos bulles ou non
 * @return
 */
function initDate(idJour, idMois, idAnnee, afficherInfoBulle, fonctionCacherMessageErreur){
	//gestion des evenements sur le jour
		var jour = $('input[type=text]#' + idJour);
		
		if(afficherInfoBulle){
			jour.focus(function(){
				$(this).addClass('hasFocus');//pour gérer les infos bulles
				
				if(typeof lancerInfoBulle == "function")
					lancerInfoBulle(document.getElementById(idJour))
			});
		}
		
		jour.keypress(function(event){
			if(afficherInfoBulle && typeof lancerInfoBulle == "function")
				arreterInfoBulle(document.getElementById(idJour)); 
			
			return FiltreDate(event, null, idMois, document.getElementById(idJour), fonctionCacherMessageErreur);
		});

	//gestion des evenements sur le mois
		var mois = $('input[type=text]#' + idMois);
	
		if(afficherInfoBulle){
			mois.focus(function(){
				$(this).addClass('hasFocus');//pour gérer les infos bulles
				
				if(typeof lancerInfoBulle == "function")
					lancerInfoBulle(document.getElementById(idMois))
			});
		}
		
		mois.keypress(function(event){
			if(afficherInfoBulle && typeof lancerInfoBulle == "function")
				arreterInfoBulle(document.getElementById(idMois)); 
			
			return FiltreDate(event, idJour, idAnnee, document.getElementById(idMois), fonctionCacherMessageErreur);
		});

	//gestion des evenements sur l'année
		var annee = $('input[type=text]#' + idAnnee);
	
		if(afficherInfoBulle){
			annee.focus(function(){
				$(this).addClass('hasFocus');//pour gérer les infos bulles
				
				if(typeof lancerInfoBulle == "function")
					lancerInfoBulle(document.getElementById(idAnnee))
			});
		}
		
		annee.keypress(function(event){
			if(afficherInfoBulle && typeof lancerInfoBulle == "function")
				arreterInfoBulle(document.getElementById(idAnnee)); 
			
			return FiltreDate(event, idMois, null, document.getElementById(idAnnee), fonctionCacherMessageErreur);
		});
		
	
	if(afficherInfoBulle){//si les infos bulles doivent être gérées
		jour.blur(function(){
			$(this).removeClass('hasFocus');
	
			setTimeout(function(){
				validerDonnees(document.getElementById(idJour))
			}, 100);
		});
	}
	
	if(afficherInfoBulle){
		mois.blur(function(){
			$(this).removeClass('hasFocus');
			
			setTimeout(function(){
				validerDonnees(document.getElementById(idMois))
			}, 100);
		});
	}
	
	if(afficherInfoBulle){
		annee.blur(function(){
			$(this).removeClass('hasFocus');
			
			setTimeout(function(){
				validerDonnees(document.getElementById(idAnnee))
			}, 100);
		});
	}
	
}

/**
 * Retourne le texte selectionn� dans l'�l�ment donn� en param�tre
 * @param obj objet javascript
 * @return le texte selectionn�
 */
function getSelection(obj) { 
	var selection;
    if(document.selection)//IE
    	selection = document.selection.createRange().text;
    else //Autres
    	selection = obj.value.substr(obj.selectionStart, obj.selectionEnd); 
    
    return selection;
} 

/**
 * retourn un objet javascript contenant la position de d�but et la position de fin de la selection de texte
 * @param obj
 * @return un objet: position.selectionStart et position.selectionEnd
 */
function getSelectionPosition(obj){
	var position = new Object();
	if(document.selection){//IE
    	selection = getSelection(obj);
    	var contenuObj = obj.value;
    	
    	if(selection.length > 0){
    		position.selectionStart = contenuObj.indexOf(selection, 0);//recherche de la position de la selection dans le champs texte
    		position.selectionEnd = position.selectionStart + selection.length;
    	}else{
    		position.selectionStart = contenuObj.length;
    		position.selectionEnd = contenuObj.length; 
    	}    		
	}else{ //Autres
		position.selectionStart = obj.selectionStart;
		position.selectionEnd = obj.selectionEnd; 
	}
	return position;
}

/**
 * filtre les touches autorisées et switch sur les éléments précédents ou suivants en fonction des données dans les champs
 * 
 * @param event: l'objet javascript event de l'evenement
 * @param idPrevious: l'id de l'élément précédent ou null si il n'y en a pas
 * @param idNext: l'id de l'élément suivant ou null si il n'y en a pas
 * @param object: l'élément sur lequel porte la fonction
 * @param function fonctionCacherMessageErreur: (optionel) fonction a appeler pour cacher la bull en cas de modification
 */
function FiltreDate(event, idPrevious, idNext, object, fonctionCacherMessageErreur){
	var KEY_LEFT = 37;
	var KEY_RIGHT = 39;
	var KEY_DELETE = 46;
	var KEY_BACKSPACE = 8;
	var KEY_TAB = 9;		
	var key = event.keyCode ? event.keyCode : event.which;		
	var c = String.fromCharCode(key);
	var jobject = $('#' + object.id);//cr�ation d'un objet jquery
	var length = jobject.val().length;
	var position = getSelectionPosition(object);//contient la position du curseur (selectionstart et selectionEnd)
	
    //si la fonction cacherMessageErreur est d�finie on l'appel
    if(key != KEY_TAB && key != KEY_LEFT && key != KEY_RIGHT && typeof(fonctionCacherMessageErreur) != "undefined")
    	fonctionCacherMessageErreur();

	switch(key){
		case KEY_TAB: 		return true; break;//touche tabulation: fonctionnement normal
		case KEY_DELETE:	return true; break;//touche delete: fonctionnement normal
		case KEY_BACKSPACE: 
			if(idPrevious != null && position.selectionStart == 0){//si l'id precedent est renseign� et le curseur � zero
				$('#' + idPrevious).focus();
			}else
				return true; 
		break;//touche backspace
		
		case KEY_LEFT: 		
			if(idPrevious != null && position.selectionStart == 0){//si l'id precedent est renseign� et le curseur � zero
				$('#' + idPrevious).focus();
			}else
				return true; 
		break;//touche fleche gauche
		
		case KEY_RIGHT: 
			if(idNext != null && position.selectionEnd == length){//si l'id precedent est renseign� et le curseur � zero
				$('#' + idNext).focus();
			}else
				return true; 
		break;//touche fleche droite
		
		default:
			if (((c >= "0") && (c <= "9"))){//si touche de chiffre
		    	if((idNext == null && (length < 4 || position.selectionStart != position.selectionEnd))//si c'est l'ann�e
		    		|| (idNext != null && (length < 2 || position.selectionStart != position.selectionEnd))){//le mois ou le jour
		    		var contenu = jobject.val();
		    		if(position.selectionStart != position.selectionEnd){//des choses sont selectionn�es dans le champ
		    			var strAvant = contenu.substr(0, position.selectionStart);
		    			var strApres = contenu.substr(position.selectionEnd, contenu.length - position.selectionEnd);
		    			jobject.val(strAvant + c + strApres);
		    		}else
		    			jobject.val(jobject.val() + c);
		    	}
		    }else
		    	return false;
		
			if (idNext != null) {//si l'id suivant est d�fini
				if(length == 1){//1 + le caract�re qui vient d'etre ajout�
					document.getElementById(idNext).select();//selectionne tout le texte de l'objet suivant
					$('#' + idNext).focus();
				}
			}
		break;
	}
    
	/*if (idPrevious != null) {//si l'id pr�c�dent est d�fini	
		// touche BACKSPACE
		if (key == KEY_BACKSPACE && object.selectionStart == 0) {
			var length = document.getElementById(idPrevious).value.length;
			document.getElementById(idPrevious).setSelectionRange(length, length);
			document.getElementById(idPrevious).focus();
		}
		// fleche gauche
		else if (key == KEY_LEFT && object.selectionStart == 0) {
			document.getElementById(idPrevious).focus();
			return false;
		}	*			
	}
	if (idNext != null) {//si l'id suivant est d�fini
		// les chiffres
		if (object.value.length == 1 && object.selectionEnd == object.selectionStart && key != KEY_TAB && key != KEY_BACKSPACE && key != KEY_DELETE 
				&& key != KEY_LEFT && key != KEY_RIGHT) {
			
			var length = document.getElementById(idNext).value.length;
			document.getElementById(idNext).setSelectionRange(0, length);		
			document.getElementById(idNext).focus();	
		}
		// fleche droite
        else if (key == KEY_RIGHT && object.selectionStart == object.value.length) {
			document.getElementById(idNext).focus();
			return false;
		}	
	}*/
    return false;
}

/**
 * Retourne true ou false suivant que la date à la focus ou non
 * @param idJour l'id de l'élément jour
 * @param idMois l'id de l'élément mois
 * @param idAnnee l'id de l'élément année
 * @return boolean 
 */
function dateHasFocus(idJour, idMois, idAnnee){
	if($('#' + idJour).hasClass('hasFocus') || $('#' + idMois).hasClass('hasFocus') || $('#' + idAnnee).hasClass('hasFocus'))
		return true;
	else
		return false;
}


