var monthLengths=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var monthNameForCalc = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var dayNameShort= new Array('Dim','Lun','Mar','Mer','Jeu','Ven','Sam');

rightnow = new Date();

function month(i,name) {
	var thisyear = rightnow.getFullYear();
	var nextyear = thisyear + 1;
	var a = "<option value=\"";
	(i<rightnow.getMonth()) ? a +=nextyear : a +=thisyear;
	(i<9) ? a += "0"+(i+1) : a +=(i+1);
	a += "\">"+name+" 0";
	(i<rightnow.getMonth()) ? a +=(nextyear-2000) : a +=(thisyear-2000);
	a += "</option>\n";
	this.option = a;
}
var months = new Array(new month(0,"janv"), new month(1,"f&eacute;v"),new month(2,"mar"),new month(3,"avr"),new month(4,"mai"), new month(5,"juin"), new month(6,"juil"), new month(7,"aoû"), new month(8,"sept"), new month(9,"oct"), new month(10,"nov"), new month(11,"d&eacute;c"));

var Maximum = 10;
function setOptions(chosen) {
	frm = document.flightSearch;
	var selbox = frm.BE_AIR_NUM_OF_CHILDREN;
	selbox.options.length = 0;
	var selbox2 = frm.BE_AIR_NUM_OF_INFANTS;
	selbox2.options.length = 0;
	var box1 = frm.BE_AIR_NUM_OF_ADULTS.options[frm.BE_AIR_NUM_OF_ADULTS.selectedIndex].value;
	for(q=0;q<=box1;q++){
		selbox2.options[selbox2.options.length] = new Option(q,q);
	}
	for(i=0 ; i < Maximum ; i++){
		if (chosen == i) {
			selbox.options[selbox.options.length] = new Option(0,0);
			for(z=1;z <(Maximum-i) ; z++){
				selbox.options[selbox.options.length] = new Option(z,z);
			}
		}
	}
}

function createDate(day, monthYear) {
	dayVal = day;
	monthYearVal = monthYear;
	x = dayVal.substr(0,1);
	(x == "0") ? day = parseInt(dayVal.substr(1,1)) : day = parseInt(dayVal.substr(0,2));
	
	y = monthYearVal.substr(4,1);
	(y == "0") ? month = parseInt(monthYearVal.substr(5,1)) : month = parseInt(monthYearVal.substr(4,2));
	
	year = parseInt(monthYearVal.substr(0,4));
	if (year < 1900) year = year + 1900;
	newDate = new Date(year, month-1, day);
	return newDate;
}

function validReturnDate(formName, elementArray) {
	firstDay = eval('document.' + formName + '.' + elementArray[0] + ".options[" + 'document.' + formName + '.' + elementArray[0] + '.selectedIndex].value');
	firstMonth = eval('document.' + formName + '.' + elementArray[1] + ".options[" + 'document.'	+ formName + '.' + elementArray[1] + '.selectedIndex].value');
	firstYear = firstMonth.substr(0,4);
	secondDay = eval('document.' + formName + '.' + elementArray[2] + ".options[" + 'document.'	+ formName + '.' + elementArray[2] + '.selectedIndex].value');
	secondMonth = eval('document.' + formName + '.' + elementArray[3] + ".options[" + 'document.'	+ formName + '.' + elementArray[3] + '.selectedIndex].value');
	secondYear = secondMonth.substr(0,4);
	if ((validMonthDay(firstDay, firstMonth, firstYear))&& (validMonthDay(secondDay, secondMonth, secondYear))){
		outboundDate = createDate(firstDay, firstMonth);
		returnDate = createDate(secondDay, secondMonth);
		return ((outboundDate.valueOf() <= returnDate.valueOf()) && (outboundDate.valueOf() > rightnow.valueOf())) ? true : false;
	} else {
		return false;
	}
}

function isLeapYear(year) {
	return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}

function validMonthDay(dayVal, monthVal, yearVal){
	var error = 0;
	if ((monthVal.substr(4,2) == 4)||(monthVal.substr(4,2) == 6)||(monthVal.substr(4,2) == 9)||(monthVal.substr(4,2) == 11)){
		if (dayVal>30) error = 1;
	} else if (monthVal.substr(4,2) == 2) {
		if (isLeapYear(yearVal)){ 
			if (dayVal>29) error = 1;
		} else {
			if (dayVal>28) error = 1;
		}
	} else {
		if (dayVal>31) error = 1;
	}
	return (error == 1) ? false : true;	
}
	
function flightSearchSubmit(buttonValue){
	document.flightSearch.whereTo.value = buttonValue;
	document.flightSearch.BE_QUICK_SEARCH_FLAG.value = true;
	var datesArray= new Array('D_Day', 'D_Month', 'R_Day', 'R_Month');
	var formName = 'flightSearch';
	firstDay = eval('document.' + formName + '.' + datesArray[0] + ".options[" + 'document.' + formName + '.' + datesArray[0] + '.selectedIndex].value');
	firstMonth = eval('document.' + formName + '.' + datesArray[1] + ".options[" + 'document.' + formName + '.' + datesArray[1] + '.selectedIndex].value');
	firstYear=firstMonth.substr(0,4);
	secondDay = eval('document.' + formName + '.' + datesArray[2] + ".options[" + 'document.' + formName + '.' + datesArray[2] + '.selectedIndex].value');
	secondMonth = eval('document.' + formName + '.' + datesArray[3] + ".options[" + 'document.'	+ formName + '.' + datesArray[3] + '.selectedIndex].value');
	secondYear=secondMonth.substr(0,4);
	
	if ((document.flightSearch.D_City.value.length > 0) && (document.flightSearch.A_City.value.length > 0)) {
		if(!validMonthDay(firstDay, firstMonth, firstYear)) {
			alert("Veuillez saisir une date valable");
			return false;
		} else {
			if(document.forms.flightSearch.TripType[0].checked == true){
				if(!validMonthDay(secondDay, secondMonth, secondYear)){
					alert("Veuillez saisir une date valable");
					return false;
				} else {
					if (validReturnDate(formName, datesArray)){
						return true;
					} else {
						alert("Veuillez saisir une date valable");
						return false;
					}
				}
			} else {
				return true;
			}
		}
	} else {
		alert("Veuillez saisir votre ville de départ et d'arrivée");
		//document.getElementById("searchFrom").style.color="#FF3300";
		//document.getElementById("searchTo").style.color="#FF3300";
		return false;
	}
}
	
function emptyDropDown(whichDD) {
	var thisDD = eval('document.forms.flightSearch.' + whichDD);
	var oOptions = thisDD.options;
	for (var i=oOptions.length; i>=0; i--) {
		oOptions[i]	= null;
	}
	thisDD.selectedIndex=0;
	thisDD.length=0;
}

function addOptionToDD(whichDD, optionText, optionValue) {
	var thisDD = eval('document.forms.flightSearch.' + whichDD);
	thisDD[thisDD.length] = new Option(optionText, optionValue);
}

function populateDDforThisMonth(sWhich, iYear, iMonth, iDay) {
	var thisDate;
	emptyDropDown(sWhich);
	for (counter=1; counter<=monthLengths[parseInt(iMonth - 1)]; counter++) {
		thisDate = new Date(monthNameForCalc[parseInt(iMonth - 1)] + ' ' + counter + ', ' + iYear);
		addOptionToDD(sWhich, dayNameShort[thisDate.getDay()] + ' ' + counter, (counter<10)?"0"+counter:counter);
	}

	addOptionToDD(sWhich, ' ', 100);
	var newIndex = monthLengths[parseInt(iMonth - 1)] - 1;
	if((iDay<=monthLengths[parseInt(iMonth - 1)])&&(iDay>0)){
		newIndex = iDay - 1;
	}
	var thisDD = eval('document.flightSearch.' + sWhich);
	thisDD.selectedIndex=newIndex;
}

function calcDayOfWeek(sWhich) {
	if (sWhich == 'D_Day') {
		var iYear = parseInt(document.forms.flightSearch.D_Month.options[document.forms.flightSearch.D_Month.selectedIndex].value.substring(0,4));
		var iMonth = document.forms.flightSearch.D_Month.options[document.forms.flightSearch.D_Month.selectedIndex].value.substring(4,6);
		var iDay = document.forms.flightSearch.D_Day.options[document.forms.flightSearch.D_Day.selectedIndex].value;
		
		monthLengths[1] = ((iYear%4==0 && iYear%100!=0)||(iYear%400==0)) ? 29 : 28;
	} else {
		var iYear = parseInt(document.forms.flightSearch.R_Month.options[document.forms.flightSearch.R_Month.selectedIndex].value.substring(0,4));
		var iMonth = document.forms.flightSearch.R_Month.options[document.forms.flightSearch.R_Month.selectedIndex].value.substring(4,6);
		if (document.forms.flightSearch.R_Day.selectedIndex < 0){
			document.forms.flightSearch.R_Day.selectedIndex=0;
		}
		var iDay = document.forms.flightSearch.R_Day.options[document.forms.flightSearch.R_Day.selectedIndex].value;
		
		monthLengths[1] = ((iYear%4==0 && iYear%100!=0)||(iYear%400==0)) ? 29 : 28;
	}
	populateDDforThisMonth(sWhich, iYear, iMonth, iDay);
}

function init_opodo() {
	tomorrow = new Date(rightnow.getTime()+(86400000));
	document.flightSearch.D_Day.selectedIndex = tomorrow.getDate()-1;
	then = new Date(tomorrow.getTime()+(604800000))
	document.flightSearch.R_Day.selectedIndex = then.getDate()-1;
	document.flightSearch.R_Month.selectedIndex = (then.getMonth() - tomorrow.getMonth()) % 12;

	var oldDepartIndex = document.flightSearch.D_Day.selectedIndex;
	calcDayOfWeek('D_Day');
	document.flightSearch.D_Day.selectedIndex = oldDepartIndex;
	var oldReturnIndex = document.flightSearch.R_Day.selectedIndex;
	calcDayOfWeek('R_Day');
	document.flightSearch.R_Day.selectedIndex = oldReturnIndex;
	if(tomorrow.getDate()-1 == 0){
	document.flightSearch.D_Month.selectedIndex = (then.getMonth()+1 - tomorrow.getMonth())
	document.flightSearch.R_Month.selectedIndex = (then.getMonth()+1 - tomorrow.getMonth())
	}	
}

function verif_vol(){
	var name = ["destinationName","checkInDay","checkOutMonthYear","checkOutDay","checkInMonthYear","roomOccupancies[0].numberOfAdults","roomOccupancies[0].numberOfChildren","numberOfRooms"];
	var count  = name.length;
	
	//	document.getElementById(name[i]).value= ""; 
		var destino = $("#destination").val();
		if(destino == ""){
			alert("Veuillez choisir une destination.");
			return false;
		}
		var d_day = $("#D_Day").val();
		d_day = (d_day < 10) ? "0"+d_day : d_day;
		var d_month = $("#D_MONTH").val();
		var r_day = $("#R_Day").val();
		r_day = (r_day < 10) ? "0"+r_day : r_day;
		var r_month = $("#R_MONTH").val();
		var adulte = $("#adultes").val();
		var chambre = $("#chambres").val();
		if(chambre > adulte){
			alert("Le nombre de chambre est supérieur au nombre d'adulte.");
			return false;
		}
		if(r_month < d_month || (r_month == d_month && d_day > r_day)){
			alert("Veuillez choisir des dates de voyage correctes.");
			return false;
		}
		document.getElementById("destinationName").value= destino; 
		document.getElementById("checkInDay").value= d_day; 
		document.getElementById("checkInMonthYear").value= d_month; 
		document.getElementById("checkOutDay").value= r_day; 
		document.getElementById("checkOutMonthYear").value= r_month; 
		document.getElementById("roomOccupancies[0].numberOfAdults").value= adulte; 
		document.getElementById("roomOccupancies[0].numberOfChildren").value= 0; 
		document.getElementById("numberOfRooms").value= chambre; 
		return true;
}
function create_month(mod,voyage){
	tab_mois = ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"];
	tab_mois1 = ["Janv.","Fév.","Mars","Avril","Mai","Juin","Juillet","Août","Sept.","Oct.","Nov.","Déc."];
	var ajd = new Date();
	var mois = ajd.getMonth();
	var annee = ajd.getFullYear();
	texte_mois ="";
	for(var i = mois;i < 12;i++){
		var j = (i >= 9) ? i+1 : "0"+(i+1);
		if(mod == "mod1")
			texte_mois += "<option value=\""+annee+"-"+j+"-01\">"+tab_mois[i]+" "+annee+"</option>";
		if(mod == "mod2")
			texte_mois += "<option value=\""+annee+j+"\">"+tab_mois1[i]+" "+annee+"</option>";
	}
	if(mois != 0){
		for(var i = 0;i < mois;i++){
			var j = (i >= 9) ? i+1 : "0"+(i+1);
			if(mod == "mod1")
				texte_mois += "<option value=\""+(annee+1)+"-"+j+"-01\">"+tab_mois[i]+" "+(annee+1)+"</option>";
			if(mod == "mod2")
				texte_mois += "<option value=\""+(annee+1)+j+"\">"+tab_mois1[i]+" "+(annee+1)+"</option>";
		}								
	}
	if(voyage=="retour")
	{
		$('#R_MONTH').html(texte_mois);
	}
	if(voyage=="aller")
	{
		$('#D_MONTH').html(texte_mois);
	}
	create_day_vol(voyage);
}

function create_day_vol(voyage){
	var ajd = new Date();
	var jour = ajd.getDate();
	var mois = ajd.getMonth();
	var annee = ajd.getFullYear();
	if(jour < 31-14){
		var jourdpt = parseInt(jour)+7;
		var jourret = parseInt(jour)+14;
		var moisdpt = annee+mois;;
	}
	else{
		if(jour < 31-7){
			var jourdpt = parseInt(jour)+7;
			var jourret = 7-(31-jourdpt);
			mois = (ajd.getMonth()+1 < 10) ? "0"+(ajd.getMonth()+1) : ajd.getMonth()+1;
			var moisdpt = annee+mois;
		}
		else{
			var jourdpt = 31;
			var jourret = 6;
			mois = (ajd.getMonth()+1 < 10) ? "0"+(ajd.getMonth()+2) : ajd.getMonth()+2;
			var moisdpt = annee+mois;
		}
	}
	var listmois  = "";
	for(i=1;i<=31;i++){
		if(i == jourdpt && voyage == "aller")
			var select = "selected=\"selected\"";
			else if(i == jourret && voyage == "retour")
			var select = "selected=\"selected\"";
		
		else
			var select = "";
			listmois  += "<option value=\""+i+"\" "+select+">"+i+"</option>";
		}
	var kelselect = (voyage == "aller") ? "D_Day" : "R_Day";
	$("select#"+kelselect+"").prepend(listmois);
	if(voyage == "retour")
		document.getElementById("R_MONTH").value = moisdpt;
}

rightnow = new Date();

function month_car(i,name) {
	var thisyear = rightnow.getFullYear();
	var nextyear = thisyear + 1;
	var a =	"";
    (i<rightnow.getMonth()) ? a+=nextyear : a+=thisyear;
	(i<9) ? a += "0"+(i+1) : a +=(i+1);
	var b = name+ " ";
	(i<rightnow.getMonth()) ? b +=nextyear : b +=thisyear;
	this.name = b;
	this.value = a;
}

var months = new Array(new month_car(0,"janvier"), new month_car(1,"février"),new month_car(2,"mars"),new month_car(3,"avril"),new month_car(4,"mai"), new month_car(5,"juin"), new month_car(6,"juillet"), new month_car(7,"août"), new month_car(8,"septembre"), new month_car(9,"octobre"), new month_car(10,"novembre"), new month_car(11,"décembre"));
function init_car(){
	for(i=0;i<12;i++) {
		wrappedIndex = (rightnow.getMonth() + i) % 12;
		document.carSearchFormBean.pickMonth[i] = new Option (months[wrappedIndex].name,months[wrappedIndex].value);
		document.carSearchFormBean.dropMonth[i] = new Option (months[wrappedIndex].name,months[wrappedIndex].value);
	}

    for(d=0;d<31;d++) {
    	document.carSearchFormBean.dropDate[d] = new Option(d+1,((d<10)?"0"+(d+1):d+1));
    	document.carSearchFormBean.pickDate[d] = new Option(d+1,((d<10)?"0"+(d+1):d+1));
    }

    for(i=0;i<24;i++) {
    	document.carSearchFormBean.pickHour[i] = (i==12)? new Option(((i<10)?"0"+i:i)+":00",i,true,true): new Option(((i<10)?"0"+i:i)+":00",i);
    	document.carSearchFormBean.dropHour[i] = (i==12)? new Option(((i<10)?"0"+i:i)+":00",i,true,true): new Option(((i<10)?"0"+i:i)+":00",i);
    }

    if(document.carSearchFormBean.pickUpDateForm.value==""){
		sevendays = new Date(rightnow.getTime()+(604800000));
		document.carSearchFormBean.pickDate.selectedIndex = sevendays.getDate()-1;
		then = new Date(sevendays.getTime()+(604800000))
		document.carSearchFormBean.dropDate.selectedIndex = then.getDate()-1;
		var datum = monthLengths[sevendays.getMonth()] -7
		if(rightnow.getDate() > datum ){document.carSearchFormBean.pickMonth.selectedIndex = document.carSearchFormBean.pickMonth.selectedIndex+1;}
		if(sevendays.getDate() > datum || rightnow.getMonth() < sevendays.getMonth() ){document.carSearchFormBean.dropMonth.selectedIndex = document.carSearchFormBean.dropMonth.selectedIndex+1;}
	}else{
		var pickup=document.carSearchFormBean.pickUpDateForm.value;
		var drop=document.carSearchFormBean.dropOffDateForm.value;
		var pmonth=parseInt(pickup.slice(4,6),10);
		var pday=parseInt(pickup.slice(6,8),10);
		var ptime=parseInt(pickup.slice(8,10),10);
		document.carSearchFormBean.pickMonth.selectedIndex=pmonth-1;
		document.carSearchFormBean.pickDate.selectedIndex=pday-1;
		document.carSearchFormBean.pickHour.selectedIndex=ptime;
		var dmonth=parseInt(drop.slice(4,6),10);
		var dday=parseInt(drop.slice(6,8),10);
		var dtime=parseInt(drop.slice(8,10),10);
		document.carSearchFormBean.dropMonth.selectedIndex=dmonth-1;
		document.carSearchFormBean.dropDate.selectedIndex=dday-1;
		document.carSearchFormBean.dropHour.selectedIndex=dtime;
	}

}
function setPickLoc_car() {
	document.carSearchFormBean.destination1.value = document.carSearchFormBean.searchString.value;
}
function setDropLoc_car() {
	document.carSearchFormBean.destination2.value = document.carSearchFormBean.searchStringDrop.value;
}
function submitCheck_car() {
    if (document.carSearchFormBean.age.selectedIndex!=0){
    	var day = parseInt(document.carSearchFormBean.pickDate.options[document.carSearchFormBean.pickDate.selectedIndex].value,10);
    	var monthVal = new String(document.carSearchFormBean.pickMonth.options[document.carSearchFormBean.pickMonth.selectedIndex].value);
    	var month = parseInt(monthVal.slice(4),10);
    	var year = parseInt(monthVal.slice(0,4),10);
    	var pickupDate = new Date(year,month-1,day,12,0,0,0);
    	day = parseInt(document.carSearchFormBean.dropDate.options[document.carSearchFormBean.dropDate.selectedIndex].value,10);
    	monthVal = new String(document.carSearchFormBean.dropMonth.options[document.carSearchFormBean.dropMonth.selectedIndex].value);
    	month = parseInt(monthVal.slice(4),10);
    	year = parseInt(monthVal.slice(0,4),10);

		var dropoffDate = new Date(year,month-1,day,12,0,0,0);
    	if (pickupDate>dropoffDate || pickupDate<rightnow) {
			if (pickupDate>dropoffDate) {
    			alert("La date sélectionnée est incorrecte");
				document.getElementById("returnDate").style.color="#FF3300";
			}
	    	if (pickupDate<rightnow) {
	    		alert("Veuillez vérifier la date de restitution");
	    		document.getElementById("outboundDate").style.color="#FF3300";
	    	}
    		return false;
    	} else {
			document.carSearchFormBean.pickUpDateForm.value=""+pickupDate.getFullYear()+
			(((pickupDate.getMonth()+1)<10)?"0"+(pickupDate.getMonth()+1):(pickupDate.getMonth()+1))+
				((pickupDate.getDate()<10)?"0"+pickupDate.getDate():pickupDate.getDate())+
				((pickupDate.getHours()<10)?"0"+pickupDate.getHours():pickupDate.getHours())
				+((pickupDate.getMinutes()<10)?"0"+pickupDate.getMinutes():pickupDate.getMinutes());
			document.carSearchFormBean.dropOffDateForm.value=""+dropoffDate.getFullYear()+
			(((dropoffDate.getMonth()+1)<10)?"0"+(dropoffDate.getMonth()+1):(dropoffDate.getMonth()+1))+
				((dropoffDate.getDate()<10)?"0"+dropoffDate.getDate():dropoffDate.getDate())+
				((dropoffDate.getHours()<10)?"0"+dropoffDate.getHours():dropoffDate.getHours())+
				((dropoffDate.getMinutes()<10)?"0"+dropoffDate.getMinutes():dropoffDate.getMinutes());

			if (document.carSearchFormBean.destination2.value=="") {
				document.carSearchFormBean.destination2.value = document.carSearchFormBean.destination1.value;
			}
			document.carSearchFormBean.destination1.value=escape(document.carSearchFormBean.destination1.value);
			document.carSearchFormBean.destination2.value=escape(document.carSearchFormBean.destination2.value);
			return true;
        }
    }
}


function invalidChars_car(sTestString){
	var regExp = new RegExp(/^[A-Za-z]{2,4}\d{2,4}/);
	return regExp.test(sTestString);
}

function setAdvancedSearch_car(yes){
	document.carSearchFormBean.isAdvancedSearch.value = (yes == "1");
}

var monthLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function isLeapYear_car(year) {
	return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

function changeDate_car(objMonth, objDate) {
	maxDays = monthLengths[(rightnow.getMonth() + objMonth.selectedIndex) % 12];
	if ( (objMonth.selectedIndex == 1) && (isLeapYear(objMonth.value.substring(0, 4))) ) maxDays="29";

	var oldSelect = objDate.selectedIndex;
	if (oldSelect > maxDays-1) oldSelect = maxDays-1;

	objDate.length = 0;
	for (d=0;d<maxDays;d++) objDate[d] = new Option(d+1,((d<10)?"0"+(d+1):d+1));

	objDate.selectedIndex = oldSelect;
}

function validateAge_car() {
	var valid = (document.carSearchFormBean.age.selectedIndex != 0);
	if (valid == false) {
		alert("Veuillez sélectionner l'âge du conducteur");
		document.getElementById("driverAge").style.color="#FF3300";
	}
	return valid;
}

function validatePickup_car() {
	var valid = (document.carSearchFormBean.destination1.value != "");
	if (valid == false) {
		alert("Veuillez saisir un lieu de prise en charge");
		document.getElementById("pickupDest").style.color="#FF3300";
	}
	return valid;
}

function validateForm_car() {
	document.getElementById("driverAge").style.color="#000000";
	document.getElementById("pickupDest").style.color="#000000";
	document.getElementById("returnDate").style.color="#000000";
    document.getElementById("outboundDate").style.color="#000000";
	return ( validateAge() ) && ( validatePickup() ) && ( submitCheck() );
}
