
function showCalendrier(idInputMois, idInputJour, openerButton, top, left, onShow, onClose, idInputLabel) {
	// alert("enter");
	if (openBy) { 
		/* le calendrier est deja ouvert :
		     soit on a clique sur le meme bouton calendrier : on ferme le calendrier
		     soit on a clique sur un autre bouton calendrier : on le reinitialise (ie on le ferme, puis on reouvre).
		 */
		var sameButton = (openBy == openerButton);
		/* ferme le calendrier */
		closeCalendrier();
		/*  si on ne reouvre pas le calendrier, on quitte */
                if (sameButton) {
			return;
		}
	}
	openBy = openerButton;


	/* Handlers pour fermer le calendrier si on clique en dehors du calendrier.
	   L'algorithme de "bubbling" est majoritairement utilise par les navigateurs pour gerer les evenements.
	   Ainsi, lorsqu'on clique sur le calendrier, le handler attache au calendrier est declenche *avant* celui
	   sur le document. On utilise cette propriete pour mettre un flag indiquant qui ne faut pas fermer le 
	   calendrier lorsqu'on a clique sur le calendrier.
	*/
	isClickInsideCal = true; 
	
	var captureClickDoc = function() {if (!isClickInsideCal){closeCalendrier();};isClickInsideCal=false;}
	var captureClickCal = function() {isClickInsideCal=true;}
	var captureEscape = function(e) {var keyID=(window.event)?event.keyCode:e.keyCode; if (keyID==27){closeCalendrier();}}
	var captureTab = function(e) {var keyID=(window.event)?event.keyCode:e.keyCode; if (keyID==9){closeCalendrier();}}
	
	
	
	document.onclick = captureClickDoc;
	$('idCalendrier').onclick = captureClickCal;
	document.onkeyup = captureEscape;
	document.onkeydown = captureTab;
	
 
	handlerOnClose = onClose;  /* sauvegarde l'action a effectuer a la fermeture du calendrier */

	/* Definit la plage de selection du calendrier */
	var jourAllerOrigine = $('jourAllerOrigine').value;
	var moisAllerOrigine = $('moisAllerOrigine').value;
	var jourAllerFin = $('jourAllerFin').value;
	var moisAllerFin = $('moisAllerFin').value;

	CAL_MIN_DATE = jourAllerOrigine;
	CAL_MIN_MONTH = parseInt(moisAllerOrigine.substring(4,6), 10) - 1;
	CAL_MIN_YEAR = moisAllerOrigine.substring(0,4);
	CAL_MAX_DATE = jourAllerFin;
	CAL_MAX_MONTH = parseInt(moisAllerFin.substring(4,6), 10) - 1;
	CAL_MAX_YEAR = moisAllerFin.substring(0,4);

	//alert("min = " + CAL_MIN_DATE + "/" + CAL_MIN_MONTH + "/" + CAL_MIN_YEAR);
	//alert("max = " + CAL_MAX_DATE + "/" + CAL_MAX_MONTH + "/" + CAL_MAX_YEAR);

	if (!top) {
		top = 0;
	}
	if (!left) {
		left = 0;
	} 

	/* les inputs associes au calendrier */
	inputYearMonth = $(idInputMois);
	inputDate = $(idInputJour);
	inputLabel = $(idInputLabel);

	//alert("inputYearMonth = " + inputYearMonth);
	//alert("inputDate = " + inputDate);
	//alert("selectedIndex = " +inputYearMonth.selectedIndex);
   
	/* la date selectionnee */
	var yearMonth;
	if (inputYearMonth.options) {
		yearMonth = inputYearMonth.options[inputYearMonth.selectedIndex].value;
	} else {
		yearMonth = inputYearMonth.value;
	}

	selectedYear = yearMonth.substr(0, 4);
	selectedMonth = yearMonth.substr(4, 2) - 1;
	selectedDate;
	if (inputDate.options) {
		selectedDate = inputDate.options[inputDate.selectedIndex].value;
	} else {
		selectedDate = inputDate.value;
	}

	//alert("selected = " + selectedDate + "/" + selectedMonth + "/" + selectedYear);

	/* le mois affiche */
	calendarMonth = selectedMonth;
	calendarYear = selectedYear;
        buildCalendar();
	/* positionne le calendrier */
	var divCalendrier = $("idCalendrier");
	divCalendrier.style.top = (getPosY(openerButton) + top) + 'px';
	divCalendrier.style.left = (getPosX(openerButton) + left) + 'px';
	/* affiche le calendrier */
	divCalendrier.style.display="block";

	/* Handler a executer l'ouverture du calendrier */
	if (onShow) {
		onShow();
	}
}

function buildCalendar() {
	/* le calendrier du 1er mois */
	buildCalendrier(calendarMonth, calendarYear, "labelCalendar", "tableCalendar");
        /* le calendrier du 2eme mois */
        var nextCalendarMonth = calendarMonth + 1;
        var nextCalendarYear = calendarYear;
        if (nextCalendarMonth > 11) {
          nextCalendarMonth = 0;
          nextCalendarYear++;
        }
        buildCalendrier(nextCalendarMonth, nextCalendarYear, "labelCalendar2", "tableCalendar2");
}

function buildCalendrier(calendarMonthP, calendarYearP, labelCalendar, tableCalendar) {
	var premierJourMois = (new Date(calendarYearP, calendarMonthP, 1).getDay()-deltaFirstDayOfWeek+7)%7;  /* colonne (0-based) du premier jour du mois, a partir de lundi */
	var nbJoursDansLeMois= nbJourDansMois(calendarYearP, calendarMonthP);
	/* Met a jour le titre du calendrier */
	$(labelCalendar).innerHTML = monthLabel[calendarMonthP] + " " + calendarYearP;
	var nbCols = 7; /* 7 jours par semaine */
	/* Construit le calendrier */
	var r = 1; 
	for (var row = $(tableCalendar).rows[1]; row != null; row = row.nextSibling) {
        if (row.nodeType == 1) { /* not text */
			c = 0;
			for (var td = row.firstChild, i = 0; td != null; td = td.nextSibling) {
				if (td.nodeType == 1) { /* not text */
					var indexCell = (r-1)*nbCols + c;
					var date = indexCell - premierJourMois + 1;
					if (date >= 1 && date <= nbJoursDansLeMois) {
						if (   compareDate(calendarYearP, calendarMonthP, date, CAL_MIN_YEAR, CAL_MIN_MONTH, CAL_MIN_DATE) == -1
							|| compareDate(calendarYearP, calendarMonthP, date, CAL_MAX_YEAR, CAL_MAX_MONTH, CAL_MAX_DATE) == 1) {
								/* non selectionnable */
								td.className= 'disabled';
								td.innerHTML = date;
						} else {
								/* selectionnable */
								td.innerHTML='<a href="javascript:void(0);"  onclick="javascript:selectDate('+calendarYearP+','+calendarMonthP+','+date+');">'+date+'</a>';
								
								if (selectedYear == calendarYearP && selectedMonth == calendarMonthP && selectedDate == date) {
									td.className="selected";
								} else {
									td.className="";
								}
						}
					} else {
						td.className='empty';
						td.innerHTML='&nbsp;';
					}
					c++;
				}
			} /* fin foreach cell */
			r++;
		}		
	} /* fin foreach row; */

	/* Masque ou affiche les fleches de next/previous month */
	showOrHideShiftMonth();
}
function showOrHideShiftMonth() {
     if (compareDate(CAL_MIN_YEAR, CAL_MIN_MONTH, CAL_MIN_DATE, calendarYear, calendarMonth, 1) >= 0) {
        /* masque previous month si la date min  >= 1er du mois affiche */
        $('idCalPreviousMonth').style.visibility = "hidden";
     } else {
        /* affiche previous month */
        $('idCalPreviousMonth').style.visibility = "visible";
     }
     if (compareDate(CAL_MAX_YEAR, CAL_MAX_MONTH, CAL_MAX_DATE, calendarYear, calendarMonth, 31) <= 0) {
        /* masque next month si la date max  >= 31 du mois affiche (meme si ce mois ne comporte que 28 ou 30j)*/
        $('idCalNextMonth').style.visibility = "hidden";
     } else {
        /* affiche next month */
        $('idCalNextMonth').style.visibility = "visible";
     }
}
function previousMonth() {
	/* backup */
	var saveYear = calendarYear, saveMonth = calendarMonth;  
	/* on recule d'un mois */
	calendarMonth--;
	if (calendarMonth < 0) {
		calendarMonth = 11;
		calendarYear--;
	}
	/* on reconstruit le calendrier */
	if (compareDate(calendarYear, calendarMonth, 31, CAL_MIN_YEAR, CAL_MIN_MONTH, CAL_MIN_DATE) >= 0) {
		buildCalendar();
	} else {
		calendarYear = saveYear;
		calendarMonth = saveMonth; 
	}
}
function nextMonth() {
	/* backup */
	var saveYear = calendarYear, saveMonth = calendarMonth;  
	/* on avance d'un mois */
	calendarMonth++;
	if (calendarMonth > 11) {
		calendarMonth = 0;
		calendarYear++;
	}
	/* on reconstruit le calendrier */
	if (compareDate(calendarYear, calendarMonth, 1, CAL_MAX_YEAR, CAL_MAX_MONTH, CAL_MAX_DATE) <= 0) {
		buildCalendar();
	} else {
		calendarYear = saveYear;
		calendarMonth = saveMonth; 
	}
}
function nbJourDansMois(annee, mois) {
	if (mois == 1) {
		return verifAnneeBissextile(annee);
	} else if (mois == 3 || mois == 5 || mois == 8 || mois == 10) {
		return 30;	
	} else {
		return 31;
	}
}
function selectDate(year, month, theDate) {
	if (inputDate.options) {
		selectOption(inputYearMonth, concatYearMonth(year,month));
		selectOption(inputDate, theDate);
	
		if (inputYearMonth.onchange) {
        	    inputYearMonth.onchange();
	        }
	} else {
		inputYearMonth.value = concatYearMonth(year,month);
		inputDate.value = format2(theDate);
		if (inputLabel) {
			printFormatedDate(inputLabel, year, parseInt(month, 10)+1, theDate);
		}
	}
	
	/* masque le calendrier */
	closeCalendrier()
}
function updateInbound(label, yearMonthOutbound, dayOutbound, yearMonthInbound, dayInbound) {
	if (yearMonthOutbound.value > yearMonthInbound.value || yearMonthOutbound.value == yearMonthInbound.value && dayOutbound.value > dayInbound.value) {
		yearMonthInbound.value = yearMonthOutbound.value;
		dayInbound.value = dayOutbound.value;
	}
	printFormatedDate(label, yearMonthInbound.value.substring(0,4), yearMonthInbound.value.substring(4), dayInbound.value);
}
function updateOutbound(label, yearMonthOutbound, dayOutbound, yearMonthInbound, dayInbound) {
	if (yearMonthOutbound.value > yearMonthInbound.value || yearMonthOutbound.value == yearMonthInbound.value && dayOutbound.value > dayInbound.value) {
		yearMonthOutbound.value = yearMonthInbound.value;
		dayOutbound.value = dayInbound.value;
	}
	printFormatedDate(label, yearMonthOutbound.value.substring(0,4), yearMonthOutbound.value.substring(4), dayOutbound.value);
}
function printFormatedDate(label, year, month, theDate) {
	var jDate = new Date(year, parseInt(month, 10)-1, theDate);
	var libelle = formatDates;
	libelle = libelle.replace('#S', daylabels[jDate.getDay()]);
	libelle = libelle.replace('#D', format2(theDate));
	libelle = libelle.replace('#M', format2(month));
	libelle = libelle.replace('#Y', year);
        if (label.value != null) {
	  label.value = libelle;
        } else {
	  label.innerHTML = libelle;
        }
}
function format2(value) {
	value=parseInt(value,10);
	return (value<10)?'0'+value:value;
}
function closeCalendrier(closeForthisId) {
	/* 
           si closeForthisId est renseigne, on ferme le calendrier seulement si openBy.id == closeForthisId 
           sinon, on ferme le calendrier dans tous les cas
         */ 
	if (closeForthisId && openBy != null && closeForthisId != openBy.id) {
             return;  /* on ne ferme pas le calendrier */
        }

	/* supprime les handlers */
	document.onclick = null;
	$('idCalendrier').onclick = null;
	document.onkeyup = null;

	/* handler sur la fermeture du calendrier */
	if (handlerOnClose) {
		handlerOnClose();
	}

	$("idCalendrier").style.display="none";

	openBy = null; 
}
function isOpenCalendrier(openWithThis) {
	return openBy && openBy == openWithThis;
}
function concatYearMonth(year, month) {
	month = month + 1;  /* les mois commencent a 1; */
	if (month <= 9) {
		month = '0' + month;
	}
	return '' + year + month;
}
/**
 *  Compare 2 dates. retourne -1,0,1 si la date1 est respectivement inferieure/egale/superieure a date2
 */
function compareDate(year1, month1, date1, year2, month2, date2) {
	if (year1 == year2 && month1 == month2 && date1 == date2) {
		return 0;
	} else if (	 year1 < year2 || 
				(year1 == year2 && month1 < month2) ||
				(year1 == year2 && month1 == month2 && date1 < date2)  ) {
		return -1			
	} else {
		return 1;
	}
}
function getPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}
function getPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}

function verifAnneeBissextile(a) {

  var num = a - 1900;

  if( (num == 100) || (num % 4 == 0 && num % 100 != 0) || (num % 400 == 0) ) {

	return(29);

  } else {

	return(28);

  }

}


/*-----------  Gestion des elements select -----------------*/


/**
 * visible: true ou false, pour afficher ou masquer les select
 * elemMenu: l'element du menu qui définit la zone à masquer/afficher
 */
function setSelectVisibility(visible,elemMenu){ 
	
	if (!isWinIE6ouMoins()) {
		return;
	}

	var x = getPosX(elemMenu);
	var y = getPosY(elemMenu);
	var w = getWidth(elemMenu);
	var h = getHeight(elemMenu)

	var selx,sely,selw,selh,i 
	var sel=document.getElementsByTagName("SELECT") 
	for(i=0;i<sel.length;i++){ 
		selx=0; sely=0; var selp; 
		if(sel[i].offsetParent){ 
			selp=sel[i]; 
			while(selp.offsetParent){ 
				selp=selp.offsetParent; 
				selx+=selp.offsetLeft; 
				sely+=selp.offsetTop; 
			} 
		} 
		selx+=sel[i].offsetLeft; 
		sely+=sel[i].offsetTop; 
		selw=sel[i].offsetWidth; 
		selh=sel[i].offsetHeight;
		/*ajout seb pour ne pas masquer tous les select par verif si menu = false*/ 
		if(selx+selw>x && selx<x+w && sely+selh>y && sely<y+h && !sel[i].menu ){
			if(visible){
				if (updateCountHidden(sel[i],-1)==0){
					sel[i].style.visibility="visible"; 				
				}
			}else{
				updateCountHidden(sel[i],+1);
				sel[i].style.visibility="hidden";
			}
		}
	} 
} 
function updateCountHidden(sel, delta) {
	if (!sel.countHidden) {  /* initialize to 0 if sel is displayed, or to 1 if sel is hidden */
		if (sel.style.visibility == 'hidden' || sel.style.display == 'none') {
			sel.countHidden = 1;
		} else {
			sel.countHidden = 0;
		}
	}
	sel.countHidden += delta; 
	return sel.countHidden;
}

function isWinIE6ouMoins() {
	return isWinIE() && !window.XMLHttpRequest;
}

function getPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent && (obj.style.position == '' || obj.style.position == 'static')) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}
function getPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent && (obj.style.position == '' || obj.style.position == 'static')) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
function getMarginLeft(obj) {
	return obj.style.marginLeft;
}
function getWidth(obj) {
	return obj.offsetWidth;
}
function getHeight(obj) {
	return obj.offsetHeight;
}

function parseDate(input, format) {
	var regDate = /(\d+)\/(\d+)\/(\d+)/;
	var day, month, year;

	if (regDate.test(input.value)) {
		if (formatDates.indexOf("#D/#M/#Y") != -1) {
			day = RegExp.$1;
			month = RegExp.$2;
			year = RegExp.$3;
		} else if (formatDates.indexOf("#M/#D/#Y") != -1) {
			month = RegExp.$1;
			day = RegExp.$2;
			year = RegExp.$3;				
		} else if (formatDates.indexOf("#Y/#M/#D") != -1) {
			year = RegExp.$1;
			month = RegExp.$2;
			day = RegExp.$3;				
		}

		if (year.length == 2) {
			year = "20" + year;
		}
		selectDate(year, parseInt(month, 10)-1, day);

	} else {
		/* reset the field with current selection */
		selectDate(selectedYear, selectedMonth, selectedDate);
	}
}



