var actualCalendar;
var actualCalendarTimeOutId;

//this function initializes a double calendar
function initDoubleCalendier(idImage, idDiv, idCalendar, idDay, idMonthYear, nbrMonthsToShow, idWeekDay, calendarXYPosition, executeAfterSelectDate, executeAfterSelectMonth, dayMask, monthYearMask) {
	
  calendar = new YAHOO.widget.CalendarGroup(idCalendar,idDiv,{ pages:2 });
  //calendar = new YAHOO.widget.Calendar(idCalendar,idDiv);  //Just in case you want to test a single calendar ;)

  // Calendier basic properties. Due a bug in this release, the "pages" property MUST be the first property !!!!!!
  // Due a bug, if we specify the number of pages, after we cannot use the "selected" property. So, we don't use the "pages" property :<
  //calendar.cfg.setProperty("pages",2);  //two page calendar.
  //we use the title as the legend:
  calendar.cfg.setProperty("title","<img src='/img_opodo/calendar/vacances.gif' alt='Vacances scolaires' align='bottom' /> Vacances scolaires <span><img src='/img_opodo/calendar/feries.gif' alt='Jours f&eacute;ri&eacute;s' align='bottom' /> Jours f&eacute;ri&eacute;s </span>");
  calendar.cfg.setProperty("close",true); //we can close the calendar
  calendar.cfg.setProperty("LOCALE_WEEKDAYS", "medium");
  calendar.cfg.setProperty("START_WEEKDAY", 1); //the first day is monday
  calendar.cfg.setProperty("iframe", true);

  //French dates:
  calendar.cfg.setProperty("MONTHS_SHORT",   ["Jan", "F\u00e9v", "Mar", "Avr", "Mai", "Jui", "Jul", "Ao\u00fb", "Sep", "Oct", "Nov", "D\u00e9c"]);
  calendar.cfg.setProperty("MONTHS_LONG",    ["Janvier", "F\u00e9vrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Ao\u00fbt", "Septembre", "Octobre", "Novembre", "D\u00e9cembre"]);
  calendar.cfg.setProperty("WEEKDAYS_1CHAR", ["D", "L", "M", "M", "J", "V", "S"]);
  calendar.cfg.setProperty("WEEKDAYS_SHORT", ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"]);
  calendar.cfg.setProperty("WEEKDAYS_MEDIUM",["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]);
  calendar.cfg.setProperty("WEEKDAYS_LONG",  ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"]);

  /* NOTE : USE SOMETHING LIKE THAT PENALIZES A LOT THE PERFORMANCE OF THE CALENDAR.
            INSTED, WE CREATE A CLASS FOR EVERY HOLIDAY !!!!!!
  
  //Vacances d'hiver 2007
  calendar.addRenderer("2/10/2007-3/12/2007", calendar.renderCellStyleHighlight2);

  //Important days:
  calendar.addRenderer("1/1", calendar.renderCellStyleHighlight3);

  //Weekends in different colour. It's a BIT better to use the specific classes: w0 and w6
  calendar.addWeekdayRenderer(7, calendar.renderCellStyleHighlight1);  //saturdays
  calendar.addWeekdayRenderer(1, calendar.renderCellStyleHighlight1);  //sundays
  */

  //First selectable day in Calendar:
  var now = new Date();
  var month = now.getMonth() + 1;
  var day = now.getDate();
  var year = now.getFullYear();
  var stringNow =  month + "/" + day + "/" + year;
  calendar.cfg.setProperty("mindate", stringNow);

  // we cross out all the dates from the current month thar are smaller than "today"
  var stringFirstDay =  month + "/01/" + year;
  calendar.addRenderer(stringFirstDay+"-"+stringNow, calendar.renderBodyCellRestricted);

  //Last selectable day in Calendar:
  var lastDate = new Date();
  lastDate.setMonth(lastDate.getMonth()+nbrMonthsToShow);
  var lastMonth = lastDate.getMonth()+1;
  var lastDay = lastDate.getDate();
  var lastYear = lastDate.getFullYear();
  var stringLastDate = lastMonth + "/" + lastDay + "/" + lastYear;
  calendar.cfg.setProperty("maxdate", stringLastDate);  

  //calendar.render(); //we will render the calendar when it's opened :) Otherwise the performance is really bad!!!

  // tmp variable to pass the 3 id where the result will be "writen" + the extra parameters to place the calendar in the right position
  var selectIds= [idDay, idMonthYear, idWeekDay, idImage, idDiv, calendarXYPosition, executeAfterSelectDate, executeAfterSelectMonth, dayMask, monthYearMask]

  // Listener to show the calendar when idImage is clicked
  YAHOO.util.Event.addListener(idImage, "click",openCalendar, {cal: calendar, selIds: selectIds } );

  // we pass 2 objects to the callback funtion. The first one is the calendar (because we need to close it) and the second
  // object is an array with the select's id names where the calendar will write the selected day.
  calendar.selectEvent.subscribe(handleSelect, {cal: calendar, selIds: selectIds } );
  
  //the calendar will be closed when the cursor is not over the image or thde calendar div.
  YAHOO.util.Event.addListener(idImage, "mouseout", closeCalendarByTimeOut, {cal: calendar });
  YAHOO.util.Event.addListener(idImage, "mouseover", cancelCalendarTimeOut, {cal: calendar });
  YAHOO.util.Event.addListener(idDiv, "mouseout", closeCalendarByTimeOut, {cal: calendar });
  YAHOO.util.Event.addListener(idDiv, "mouseover", cancelCalendarTimeOut, {cal: calendar });

}


function cancelCalendarTimeOut(type, obj){
	
	//just in case htere is more than one calendar in the same page and you go from one calendar image to onother one.
	if (actualCalendar != null && actualCalendar != obj.cal )
		actualCalendar.hide();
		
	clearTimeout(actualCalendarTimeOutId);
}


function closeCalendarByTimeOut(type, obj){
	actualCalendar = obj.cal;
	actualCalendarTimeOutId = setTimeout('actualCalendar.hide();',2000);
}


function openCalendar(type, obj){
  
  // we show in the calendar the selected day from the select list.
  var selectDayId = obj.selIds[0];
  var selectMonthYearId = obj.selIds[1];
  
  var idImage = obj.selIds[3];
  var idDiv = obj.selIds[4]; 
  var calendarXYPosition = obj.selIds[5];

  var day = YAHOO.util.Dom.get(selectDayId).value;
  var monthYear = YAHOO.util.Dom.get(selectMonthYearId).value;
  
  var numericMonth = "";
  var selectedMonth = 0;
  var month;
  var year;
 
  if (monthYear.length==6){ //format YYYYMM Ex: 200711
		numericMonth = monthYear.substring(4,6);
		selectedMonth = numericMonth-1;		
	  year  = monthYear.substring(0,4);
  }
  else {  //format MMM YYYY

	  month = monthYear.substring(0,3);
	  year  = monthYear.substring(4,8);
	
	  switch(month){
	    case "JAN": numericMonth="01"; selectedMonth=0; break;
	    case "FEV": numericMonth="02"; selectedMonth=1; break;
	    case "MAR": numericMonth="03"; selectedMonth=2; break;
	    case "AVR": numericMonth="04"; selectedMonth=3; break;
	    case "MAI": numericMonth="05"; selectedMonth=4; break;
	    case "JUN": numericMonth="06"; selectedMonth=5; break;
	    case "JUL": numericMonth="07"; selectedMonth=6; break;
	    case "AOU": numericMonth="08"; selectedMonth=7; break;
	    case "SEP": numericMonth="09"; selectedMonth=8; break;
	    case "OCT": numericMonth="10"; selectedMonth=9; break;
	    case "NOV": numericMonth="11"; selectedMonth=10; break;
	    case "DEC": numericMonth="12"; selectedMonth=11; break;
	    default: numericMonth=""; selectedMonth=0; break;
	  }
  }
  
  if ( numericMonth=="" || day == "" ){
  	// if the date is not correct, we will open de calendar in tomorrows date
  	var today = new Date();
  	today.setDate(today.getDate()+1);
  	day = today.getDate();
  	selectedMonth = today.getMonth();
  	numericMonth = selectedMonth+1;
  	numericMonth = (numericMonth<10?"0":"")+numericMonth;
  	year = today.getFullYear();
  }
  	

  //We show the rigth page:
  obj.cal.setMonth(selectedMonth);
  obj.cal.setYear(year);
  
  //we mark the rigth day:
  obj.cal.cfg.setProperty("selected", numericMonth+"/"+day+"/"+year);    
  
  //we define where the calendar will be placed:
  changeCalendarPosition(selectDayId, idDiv, calendarXYPosition);

  //Here is where we render the calendar!!!!
  
  obj.cal.render();

  obj.cal.show();
}

// That manage the select:
// VERY IMPORTANT:
// The format of the values from the select must be: "DD" for the day select and "MMM YYYY" for the month select
function handleSelect(type,args,obj){

  var selectDayId = obj.selIds[0];
  var selectMonthYearId = obj.selIds[1];
  var idWeekDay = obj.selIds[2];

  var selDateArray = args[0][0];

  // the date format is 2/14/2007
  var yr = selDateArray[0];

  var numericMonth = selDateArray[1];
  var month=""
  var day = "";
  
  var monthYear = YAHOO.util.Dom.get(selectMonthYearId).value;
  var dt = selDateArray[2];
 
  if(monthYear.length == 6 ){  //Format YYYYNN Ex: 200709
	  month = (numericMonth<10?"0":"")+numericMonth;
    
    var dayMask = ""+obj.selIds[8];
    
    if("DD" == dayMask)
    	 dt = (dt<10?"0":"")+dt;
    
    YAHOO.util.Dom.get(selectMonthYearId).value =yr+month;
    
  	//We execute something after the month has been changed:
  	var executeAfterSelectMonth = ""+obj.selIds[7];
  	eval(executeAfterSelectMonth);
  	
  	YAHOO.util.Dom.get(selectDayId).value =dt;
    
    
  }
  else{  //Format "MM YYYY"
    switch(numericMonth){
      case 1: month="JAN"; break;
      case 2: month="FEV"; break;
      case 3: month="MAR"; break;
      case 4: month="AVR"; break;
      case 5: month="MAI"; break;
      case 6: month="JUN"; break;
      case 7: month="JUL"; break;
      case 8: month="AOU"; break;
      case 9: month="SEP"; break;
      case 10: month="OCT"; break;
      case 11: month="NOV"; break;
      case 12: month="DEC"; break;
      default: month=""; break;
    }
    
    var dayList = YAHOO.util.Dom.get(selectDayId);
    var firstDayinList = dayList[0].value;
    
    //we will know if the format of days is D or DD
    if (firstDayinList.length != 1 )
    	day = (dt<10?"0":"")+dt;
    else
    	day = dt;
  
    YAHOO.util.Dom.get(selectMonthYearId).value =month+" "+yr;
    
  	//We execute something after the month has been changed:
  	var executeAfterSelectMonth = ""+obj.selIds[7];
  	eval(executeAfterSelectMonth);
  	
    // VERY IMPORTANT:
    // The format of the values from the select must be: "DD" for the day select and "MM YYYY" for the month select
    YAHOO.util.Dom.get(selectDayId).value =day;
  }
  
  if (idWeekDay != "" ){
    var myDays = new Array("Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi");
    //new Date("Month dd, yyyy")
    //myDate=new Date(eval('"'+aText.value+'"'))
    var myDate = new Date(Date.UTC(yr,numericMonth-1,dt,0,0,0));
    
    //var myDate=new Date(eval('"'+numericMonth+" "+dt+", "+yr+'"'));
    YAHOO.util.Dom.get(idWeekDay).value = myDays[myDate.getDay()];
  }

  obj.cal.hide();
  
  //We execute the onchange form the select. Usually will refrech the other date pair.
  var executeAfterSelectDate = ""+obj.selIds[6];
  var dummy = setTimeout(executeAfterSelectDate,10); 

}


function changeCalendarPosition(idReference, idDiv, calendarXYPosition){	
  //we will place the calendar close to the image:  
  var imagePosition = getPosition( YAHOO.util.Dom.get(idReference) );
  
  document.getElementById(idDiv).style.position = 'absolute';
  document.getElementById(idDiv).style.top = imagePosition.y+25+"px"; //we have to add "px" for Firefox!!!!!
  document.getElementById(idDiv).style.left = imagePosition.x+5+"px"; 

  if ("LEFT_UP" == calendarXYPosition){
  	document.getElementById(idDiv).style.top = imagePosition.y-240+"px";
		document.getElementById(idDiv).style.left = imagePosition.x-150+"px";
	}
	else if ("LEFT" == calendarXYPosition){
  	document.getElementById(idDiv).style.left = imagePosition.x-150+"px";
  }
  else if (typeof(calendarXYPosition) != String && calendarXYPosition != "" ){
	  if(calendarXYPosition.xPosition != 0 )
	  	document.getElementById(idDiv).style.left = imagePosition.x + calendarXYPosition.xPosition + "px";
	  
	  if(calendarXYPosition.yPosition != 0 )
	  	document.getElementById(idDiv).style.top = imagePosition.y + calendarXYPosition.yPosition + "px";
	}
  
  /* NOTE: this version of you (0.12) is buggy; CalendarGroup since end up
           attaching the iframe shim to the individual Calendars and not to the
           CalendarGroup container.
  */

  
}

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}

function calendarPosition(xPosition, yPosition){
	this.xPosition = xPosition;
	this.yPosition = yPosition;
}