
// init the parameters for the calendar
var monthLength = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var monthLengthBi = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var dayHeaders = new Array('Dim','Lun','Mar','Mer','Jeu','Ven','Sam');
var monthNames = new Array('janvier','fevrier','mars','avril','mai','juin','juillet','aout','septembre','octobre','novembre','decembre');
var cancelTxt = "Fermer";

var currentDate = new Date(); // the current date displayed on the calendar
var firstDate = new Date(); // the first date to display
firstDate.setHours(12);
firstDate.setMinutes(0);
firstDate.setSeconds(0);

var selected = new Date(); // the selected day in the calendar
var theDate = new Date();

var form = "document.forms[0]";
var dateRealField;
var monthYearField;
var dateField;
//var departureDay;

var tempParam;
var existParam = false;
var existRetour = false;
var existAller = false;

var dayValue;
var monthValue;
var yearValue;
var dateValue;

var oneSecond = 1000;
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;

var bgNoInfo = "#FFFFFF";
var bgNotInMonth = "#FFFFFF";
var bgSelectedDay = "#D52530"; //backGround SelectedDate
var fntNoInfo = "#20506A"; // blue-grey
var fntAvail = "#FFFFFF";
var fntNotInMonth = "#CCCCCC"; // grey

var verStr = navigator.appVersion;
var app = navigator.appName;
var nn;
var ie;

var conditionDate;

// check the user browser (netscape or IE)
function checkBrowser() {
	var verStr = navigator.appVersion;
	var app = navigator.appName;
	if (app.indexOf("Netscape") != -1) {
		nn = true;
		ie = false;
		show = "visible";
		hide = "hidden";
	} else if (app.indexOf("Explorer") != -1) {
		nn = false;
		ie = true;
		show = "visible";
		hide = "hidden";
	} else {
		alert("Warning - this browser does not support this page");
	}
}

checkBrowser();

// the main function : build the calendar from the date entered by the user
function showCalendar(departDate,param,paramRetour) {
	
	if (param != null) {
		tempParam = param;
		existParam = true;
		paramR = paramRetour;
		//alert(paramR, (paramR == "aller"));
		if (paramR == "aller") {
		
			firstDate = new Date(opener.firstYearNumberGlobal, opener.firstMonthNumberGlobal - 1, opener.firstDayNumberGlobal); // the first date to display
			firstDate.setHours(12);
			firstDate.setMinutes(0);
			firstDate.setSeconds(0);
		
			existAller = true;
			//alert("mode retour");
		}
		
		if (paramRetour == "retour") {
			firstDate = new Date(opener.firstRelativeYearNumberGlobal, opener.firstRelativeMonthNumberGlobal - 1, opener.firstRelativeDayNumberGlobal); // the first date to display
			firstDate.setHours(12);
			firstDate.setMinutes(0);
			firstDate.setSeconds(0);
			
			existRetour= true;
		}
	} else {
		//firstDate = new Date(opener.firstYearNumberGlobal, opener.firstMonthNumberGlobal - 1, opener.firstDayNumberGlobal); // the first date to display
		//firstDate.setHours(12);
		//firstDate.setMinutes(0);
		//firstDate.setSeconds(0);
	}
	
	//dayValue = opener.document.productSearchForm.departureDay.value;
    //monthYearValue = opener.document.productSearchForm.departureMonthYear.value;
    
    //dateRealField = eval(dayVal);
    //dayValue = dateRealField.value;
    
    //monthYearField = eval(monthYearVal);
    //monthYearValue = monthYearField.value;
    
    dateField = eval(departDate);
    dateValue = dateField.value;
        
    //alert(eval(dayVal) + "\n" + eval(dayVal+'.value'));
    //monthYearValue = monthYearVal;
    //dateValue = dayValue + '/' + monthYearValue;
    //alert(dateValue);
    var tab = dateValue.split("index.html");
    dayValue = parseInt(tab[0], 10);
    monthValue = parseInt(tab[1], 10) - 1;     
    yearValue = parseInt(tab[2], 10);
    //alert(dayValue + "/" + monthValue + "/" + yearValue);
   
    if (!isDate(dayValue, monthValue, yearValue)) {
      //alert("pas une date");
      currentDate = new Date();
    } else {

      currentDate.setDate(dayValue);
      currentDate.setMonth(monthValue);
      currentDate.setYear(yearValue); 
    }
    //alert("current date : " + currentDate);
      
    updateCalendar(currentDate);
    Hide(true);    
}

// draw the calendar with the parameter as the selected date
function updateCalendar(oneDate) {
	var tmpDate = new Date(oneDate);
	document.getElementById("CalendarLYR").innerHTML = drawCalendar();
	document.getElementById("monthHeading").innerHTML = addHeading(tmpDate);
	document.getElementById("holder").innerHTML = addDays(tmpDate);
}

// update the calendar when user changes the selected date
function updateCalendarToNavigate(oneDate) {
	var tmpDate = new Date(oneDate);
	document.getElementById("monthHeading").innerHTML = addHeading(tmpDate);
	document.getElementById("holder").innerHTML = addDays(tmpDate);
	//alert("updateCalendatToNavigate : " + tmpDate.getDate());
	 
	updateFormFields(tmpDate);
	
}

// show or hide the calendar layer
function Hide(Show) {
  document.getElementById('CalendarLYR').style.visibility = Show ? "visible" : "hidden";
  document.getElementById('monthHeading').style.visibility = Show ? "visible" : "hidden";
  document.getElementById('holder').style.visibility = Show ? "visible" : "hidden";
}

// draw the calendar head
function addHeading(aDate) {
        var tmpDate = new Date(aDate);
//        var currDate = new Date();
//        var currMonth = currDate.getMonth();
//        if (tmpDate.getYear() > currDate.getYear()) {
//        	currMonth
//        }
        //alert("currMont = " + currMonth + " alors que tmpMonth = " + tmpDate.getMonth());
	hstr =  "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"160\" height=\"15\">\n\n";
	hstr += "<tr class=\"mainStyle\">\n";
	hstr += "<td width=\"30\" height=\"15\" align=\"left\" valign\"middle\">&nbsp;<a class=\"calendar\" href=\"javascript:prevMonth()\";><<</a></td>";
	hstr += "<td width=\"100\" align=\"center\" valign=\"middle\" class=\"mainStyle\">\n" + tmpDate.getDate() + "&nbsp;"  + monthNames[tmpDate.getMonth()] + "&nbsp;" + tmpDate.getFullYear() + "\n</td>\n";
	hstr += "<td width=\"30\" height=\"15\" align=\"right\" valign\"middle\"><a class=\"calendar\" href=\"javascript:nextMonth()\";>>></a>&nbsp;</td>\n";
	hstr += "</tr>\n\n";
	hstr += "</table>\n";

	return hstr;
}

// draw the calendar body
function drawCalendar() {
	str = new String();
	str +=  "<table width=\"160\" border=\"0\" cellspacing=\"0\" cellpadding=\"1\" bgcolor=\"#000000\" class=\"mainStyle\">\n\n";
	str +=  "<tr>";
	str +=  "<td>\n";
	str +=  "   <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"160\">\n\n";
	str +=  "   <tr>\n";
	str +=  "   <td>\n";

	if (ie) {
		str +=  "<div id=\"monthHeading\" style=\"position: relative; align: center width: 160px; height: 15px; visibility: hidden\">\n" + addHeading(theDate) + "</div>\n";
	}

	if (nn) {
                str +=  "<ilayer id=\"main\">\n";
                str +=  "   <layer id=\"monthHeading\" left=\"0\" top=\"0\" width=\"160\" height=\"15\"></layer>\n";
                str +=  "</ilayer>\n";
	}

	str +=  "   </td>\n";
	str +=  "   </tr>\n\n";
	str +=  "   <tr>";
	str +=  "   <td>\n";
	str +=  "   <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"160\">\n\n";
	str +=  "   <tr>\n";

        for(i =0; i <= 6 ; i++) {
                str +=  "   <td width=\"30\" height=\"15\" align=\"center\" valign=\"middle\" class=\"dayStyle\">" + dayHeaders[i] + "</td>\n";
        }

	str +=  "       </tr>\n\n";
	str +=  "       </table>\n";
	str +=  "   </td>\n";
	str +=  "   </tr>\n\n";
	str +=  "   <tr>\n";
	str +=  "   <td>\n";

	if (ie) {
		str += "<div id=\"holder\" style=\"position: relative; visibility: hidden\">\n" + addDays(theDate) + "</div>\n";
	}

	if (nn) {
                str += "<div id=\"holder\" style=\"position: relative; visibility: hidden\">\n" + addDays(theDate) + "</div>\n";
	}

	str += "    </td>\n";
	str += "    </tr>\n\n";
	str += "    </table>\n";
	str += "</td>\n";
	str += "</tr>\n\n";
	str += "<tr class=\"mainStyle\">\n";
	str += "<td width=\"160\" height=\"15\" align=\"center\" valign=\"middle\"><a class=\"calendar\" href=\"javascript:cancel();\">"+cancelTxt+"</a></td>\n";
	str += "</tr>\n\n";
	str += "</table>\n";

	return str;
}

// draw the available days for the date aDate
function addDays(aDate) {
	var tmpDate = new Date(aDate);
	var currentMonth = tmpDate.getMonth();
	//alert(currentMonth);	
	var currDay = tmpDate.getDate();
	maxWeek = getMaxWeek(tmpDate);
	date = new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 1, 12, 0, 0);	
//	currDate = new Date();
//	diff = new Date();
//	diff.setTime(Math.abs(date.getTime() - currDate.getTime()));
//	var diffYear = Math.abs(currDate.getYear() - date.getYear());
//	var diffCurrYear = 0;
//	if ( date.getYear() > firstDate.getYear() ) {
//		diffCurrYear = 12;
//	}
	//alert("getDay : " + date.getDay() );
	while (date.getDay() > 0) {
		date = new Date(date.getTime() - oneDay);
	}

	height = maxWeek * 15;
	var str = new String();

	str += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" height=\"" + height + "\" width=\"160\">\n\n";

	for (w = 0; w < maxWeek; w++) {
		str += "<tr>\n"

		for (d = 0; d < 7; d++) {
			 borderColor;	
			
			var bgColor = bgNotInMonth;
			var fontColor = fntNotInMonth;
			var borderColor = bgColor;
			var link = "";
			var endLink = "";
			

			/*if (((date.getMonth() == currentMonth) && (date >= firstDate) && (diff.getMonth() < 5) && (diffYear < 2)  ) || 
			((date.getMonth() == firstDate.getMonth() && date.getYear() == firstDate.getYear() && date.getDate() == firstDate.getDate())) || 
			((diff.getMonth() == 5) && (date.getDate() < firstDate.getDate()) && (((date.getMonth() +  1 + diffCurrYear ) - (firstDate.getMonth()+1) ) <= 6 )  ) || 
			((diff.getMonth() == 5) && (date.getDate() > firstDate.getDate()) && (((date.getMonth() +  1 + diffCurrYear ) - (firstDate.getMonth()+1) ) == 5 ) )) {*/
			if (lessSixMonth(date,currentMonth) ) {
			    bgColor = bgNoInfo;
			    fontColor = fntNoInfo;
			    borderColor = bgColor;
			    link = "<a href=\"javascript:selectDate(" + date.getTime() + ","+ currentMonth +")\"; style=\"text-decoration: none;\">";
			    endLink = "</a>";
			    
				//cursor on date
			    /*if (selectSpecial(date, tmpDate)) {
			    
			      bgColor = bgSelectedDay;
			      fontColor = fntAvail;
			      
			    }*/
			  
			}

			str += "<td bgcolor=\"" + bgColor + "\" align=\"center\" bordercolor=\"" + borderColor + "\">" + link + "<b><font face=\"Arial\" size=\"2\" color=\"" + fontColor + "\">" + date.getDate() + "</font>" + endLink + "</b></td>\n";
			date = new Date(date.getTime() + oneDay);
		}

		str += "</tr>\n\n";
	}

	str += "</table>\n";
	return str;
}

// put the cursor on the selected day
function selectSpecial(date, currentDate) {
	strcolor = false;
	if ((currentDate.getDate() == date.getDate()) && (currentDate.getMonth() == date.getMonth()) && (currentDate.getYear() == date.getYear())) {
	  strcolor = true;		
	}
	return strcolor;
}

// update the calendar with the next month days
function nextMonth() {

	// theDate represents the date to be reached by the next button
	theDate = new Date(currentDate.getTime());
	theDate.setDate(1);
	theDate.setMonth(theDate.getMonth()+1);
    
       // alert("last date : " + lastDate.toString() + " the date : " + theDate.toString());

	next = theDate.getMonth();
	year = theDate.getFullYear();
	//alert("the date : " + currentDate.getDate());
	//alert("the date : " + theDate.getDate());
	
	day = theDate.getDate();
	var tempYear = 0;
	if (next >= 12) {
	    next -= 12;
	    year += 1;
	}
	if (currentDate.getYear() > firstDate.getYear() ) {
		tempYear = 12;
	}	
	//alert(((currentDate.getMonth() + tempYear) - firstDate.getMonth() ) < 6);
	if (( (currentDate.getMonth() + tempYear) - firstDate.getMonth() ) < 6) {
		
		currentDate = new Date(year, next, 1, 12, 0, 0);
      	//updateCalendarToNavigate(currentDate);
    	updateCalendar(currentDate)
		Hide(true);		
	}
}

// update the calendar with the previous month days
function prevMonth() {
	
   var day = 30;
   if (currentDate.getMonth()-1 == 1) {
     var day = 28;
   }
   theDate = new Date(eval(currentDate.getFullYear()), currentDate.getMonth()-1, day, 0, 0, 0);
   //theDate.setUTCDate(monthLength[theDate.getMonth()-1]);

    //alert("the date : " + theDate.toString() + " firstDate : " + firstDate.toString());

    if (theDate >= firstDate) {

	  lastMonth = theDate.getMonth();
	  year = theDate.getFullYear();

	  if (lastMonth < 0) {
	   	lastMonth += 12;
		year -= 1 ;
	  }
	 
	  
	  currentDate = new Date(year, lastMonth, 1, 12, 0, 0);	  

	  //updateCalendarToNavigate(currentDate);
	  updateCalendar(currentDate);
	  Hide(true);
	  
    }
}

// update the date form field when a date is selected
function selectDate(theDate, currentMonth) {	
	selected = new Date(theDate);
			
	if (lessSixMonth(selected,currentMonth)) {
	  // updateCalendarToNavigate(selected);
	  updateSearchFormFields(selected);	  
	}

	window.close();
}

// put the choosen calendar date in the form field 
function updateSearchFormFields(selected){
	dateField.value = formatDate(selected);
	//alert(selectDate);
	//opener.depDateChange();
}

// put the choosen calendar date in the form field 
function updateFormFields(selected) {	
       //alert("format selected : " + formatDate(selected));
	  	
       selectMonthYear(selected);
	   
	   if (!existRetour) {
           opener.depMthYearChange();
       } else {
           opener.retMthYearChange();
       }
	   
	  	
       selectDay(selected, dateRealField);
       
       if (!existRetour) {
           opener.depDayChange();
       } else {
           opener.retDayChange();
       }
	  	
}

function selectMonthYear(selectedDate) {

	var selectedYear = selectedDate.getYear();
    if(selectedYear < 999) {
        selectedYear+=1900;
    }
    var selectedMonth = selectedDate.getMonth() + 1;
    var zeroStr = "";
    if (selectedMonth < 10) {
	    zeroStr = "0";
    }
    var selectedMthYear = zeroStr + selectedMonth + "/" + selectedYear;
    var selectedIndex = 0;
    var found = false;
	for (var i = 0; i < monthYearField.options.length && !found; i ++) {
		if (monthYearField.options[i].value == selectedMthYear) {
            selectedIndex = i;
            found = true;
		}
	}
    monthYearField.selectedIndex = selectedIndex;
}
// selectDay in Navigator
function selectDay(selectedDate, dayField) {
//    var selectedDay = selectedDate.getDate();
//	  	
//    //alert("selectDay : " + dayField);
//	var selectedIndex = 0;
//	  	alert("here12");
//    var found = false;
//	  	alert("here13");
//    var monthNumber = selectedDate.getMonth() + 1 ;
//	  	alert("here14");
//    firstDayNumber = selectedDate.getDate();
//	  	alert("here15");
//    firstMonthNumber = monthNumber;
//	  	alert("here16");
//    yearNumber = selectedDate.getYear();
//	  	alert("here17");
//    firstYearNumber = yearNumber;
//	  	alert("here18");
//    preselectedDayParam = null;
//	  	alert("here19");
//    buildDaysListFromValues(dayField, monthNumber, yearNumber, firstDayNumber, firstMonthNumber, firstYearNumber, preselectedDayParam);
//	  	alert("here20");
//	for (var i = 0; i < dayField.options.length && !found; i ++) {
//	  	alert("here21");
//		if (dayField.options[i].value == selectedDay) {
//	  	alert("here22");
//            selectedIndex = i;
//            found = true;
//		}
//	}
//	  	alert("here23");
//    dayField.selectedIndex = selectedIndex;

     var selectedDay = selectedDate.getDate();
     var selectedIndex = 0;
     var found = false;
     for (var i = 0; i < dayField.options.length && !found; i ++) {
		if (parseInt(dayField.options[i].value, 10) == selectedDay) {
            selectedIndex = i;
            found = true;
		}
     }
     dayField.selectedIndex = selectedIndex;
}

// format a date to jj/mm/aaaa 
function formatDate(theDate) {
	var monthValue = eval(theDate.getMonth()+1);
	var dayValue = theDate.getDate();
	var yearValue;
	if (ie) {
	  yearValue = theDate.getYear().toString();          
          //yearValue = yearValue.substring(2,4);          	  
	} else if (nn) {
	  //yearValue = formatYear(eval(theDate.getYear()-100));
	  yearValue = formatYear(eval(theDate.getYear())+1900);
	}	
	if (monthValue < 10) {
	  monthValue = "0"+monthValue;
	}
	if (dayValue < 10) {
          dayValue = "0"+dayValue;
	}	
	return dayValue + "/" + monthValue + "/" + yearValue;	
}

// reset the calendar and close the pop up
function cancel(){
    //reset the current date of the calendar with the date displayed in the fields
    currentDate = new Date();
    currentDate.setDate(dayValue);
    currentDate.setMonth(monthValue);
    currentDate.setYear(yearValue);
    window.close();
}

// check that a date is valid
function isDate(day, month, year) {   
   
   if((!day) ||(!(month+1)) ||(!year)) {
     return false;
   }
   year = 2000 + eval(year);
   var today = new Date();
   var test = new Date(year, month, day);   
   if ((test.getFullYear() == year) &&(month == test.getMonth()) &&(day == test.getDate()) && (test >= today)) {
     return true;
   } else {
     return false;
   }
}

// format a year value on 2 digits
function formatYear(yearValue) {
  if (yearValue < 10) {
    yearValue = "0"+yearValue;	
  }
  return yearValue
}

// retrieve the max number of weeks for the month related to the date parameter
function getMaxWeek(theDate) {
	var yyyy = theDate.getFullYear()
	var mm = theDate.getMonth();
	var first = new Date(yyyy, mm, 1, 12, 0, 0);
	var firstDayOfWeek = first.getDay();
	var max = getMaxDays(yyyy, mm);

	if (nn) {
		return 6;
	}

	return Math.ceil((firstDayOfWeek + max) / 7)
}

// retrieve the max number of days for the month related to the date parameter
function getMaxDays(year, month) {
	if ((year % 4 == 0) && ((year % 100 != 0) || (year% 200 == 0))) {
		var max = monthLengthBi;
	} else {
		var max = monthLength;
	}

	return max[month];
}

function lessSixMonth(selectedDateCheck,currentMonth) {
	//var currentMonth = selectedDateCheck.getMonth();	
	date = new Date(selectedDateCheck.getFullYear(), selectedDateCheck.getMonth(), selectedDateCheck.getDate(), 12, 0, 0);	
	diff = new Date();
	diff.setTime(Math.abs(date.getTime() - firstDate.getTime()));
	var diffYear = Math.abs(firstDate.getYear() - date.getYear());
	var diffCurrYear = 0;
	if ( date.getYear() > firstDate.getYear() ) {
		diffCurrYear = 12;
	}
	//alert(currentMonth +" " + selectedDateCheck.getMonth());
	
	if (((date.getMonth() == currentMonth) && (date >= firstDate) && (diff.getMonth() < 6) && (diffYear < 2)  ) || 
			((date.getMonth() == firstDate.getMonth() && date.getYear() == firstDate.getYear() && date.getDate() == firstDate.getDate())) || 
			((diff.getMonth() == 6) && (date.getDate() <= firstDate.getDate()) && (((date.getMonth() +  1 + diffCurrYear ) - (firstDate.getMonth()+1) ) < 6 )  ) ){ 
			//((diff.getMonth() == 5) && (date.getDate() > firstDate.getDate()) && (((date.getMonth() +  1 + diffCurrYear ) - (firstDate.getMonth()+1) ) == 5 ) )) {
			return true;
			}
    else return false;
			
}
