
var jsName = "calendar.js";
if (typeof logError == "undefined") {
        logError = function(){};
}
if (typeof logLoaded == "undefined") {
        logLoaded = function(){};
}
if (typeof logDebug == "undefined") {
        logDebug = function(){};
}
logLoaded(jsName + "@start");

//-----------------------------------------------------------
// These variables can be set in the calling HTML page after
// calling the initCalendar function. See the configCalendar
// function for reference.
//-----------------------------------------------------------
var today;
var lang;

try {

// Date range validation
var checkBegin = true;
var checkEnd = false;

// Maximum number of days from today which are allowed for selection.
var daysLimit;

// Vertical offset for calendar from top of date input field.
var inputOffset = 21;

logLoaded("calendar@init1");

// Arrays of month names by language.
// Ambika - added arrays for DE and IT
var mNames = {};
mNames["en"] = ["January","February","March","April","May","June","July","August","September","October","November","December"];
mNames["fr"] = ["Janvier","F&eacute;vrier","Mars","Avril","Mai","Juin","Juillet","Ao&ucirc;t","Septembre","Octobre","Novembre","D&eacute;cembre"];

var dNames = {};
dNames["en"] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
dNames["fr"] = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"];

var dMsg = {};
dMsg["en"] = {};
dMsg["fr"] = {};
dMsg["en"]["invaliddate"] = "invalid date";
dMsg["fr"]["invaliddate"] = "date invalide";

} catch (err) {
  logError(err, jsName + "@65")
}

logLoaded("calendar@init2");

//-----------------------------------------------------------
// These variables should not be changed.
//-----------------------------------------------------------

var dateFormat = {};
var dateTpl = {};
var shownDate;

var c1cells = new Array(43);
var c2cells = new Array(43);

//Months to num array for use with Flight Search JSP to handle request from Special Offers
var m2n = {};
m2n["Jan"] = "01";
m2n["Feb"] = "02";
m2n["Mar"] = "03";
m2n["Apr"] = "04";
m2n["May"] = "05";
m2n["Jun"] = "06";
m2n["Jul"] = "07";
m2n["Aug"] = "08";
m2n["Sep"] = "09";
m2n["Oct"] = "10";
m2n["Nov"] = "11";
m2n["Dec"] = "12";

// Associative array of drop-downs select by field name.
var selectList = {};
var selectListCount = 0;

var nextFocusList = {};

// Associative array of date values.
var dateValue = {};
var dateDisplayed = {};

var departureField;
var arrivalField;
var currentDateField = null;
var defaultDateField = null;
var dateSources = {};
var dateTargets = {};
var displayFields = {};

var overCalendar = false;
var inDateField = false;

var previousClass;

// Flag set if month change buttons should be hidden.
var isEndReached = false;
var isAtBeginning = true;

// Associative array of disabled days.
var disabledDays = {};

var initCalFlag = false;
var initCalFunction = null;

// Deprecated function.
function registerInitCalendar(initFunction){};

// Deprecated function.
function  checkInit(){};

// Initialize calendar.
// If you need to set variables to specific values,
// do it in the calling code just after calling init().
//
function initCalendar(departureId,arrivalId,optionalLang){
	if(optionalLang != null)
		lang = optionalLang;
	if(!calCreated)
		createCalendar();

	logDebug("initCalendar start " + departureId + " " + arrivalId);
	configCalendar();
	// Cache calendar1 cells for better performance.
	for(var i = 1; i <= 42; i++){
		var elem = document.getElementById("c1c" + i);
		c1cells[i] = elem;
	}
	// Cache calendar2 cells for better performance.
	for(var i = 1; i <= 42; i++){
		var elem = document.getElementById("c2c" + i);
		c2cells[i] = elem;
	}
	setDateAdjustFields(departureId,arrivalId);

	initCalFlag = true;
	logDebug("initCalendar end ");
}

//
// Set the arrival and depature fields. Useful if calendar is used
// for more than one calendar field on the page and each calendar
// needs the arrival and departure dates adjusted so the arrival is
// always after depature. Set on date field focus. Set both parameters
// to null to turn off the date adjustment feature.
//
// Integrated PANKAJ's (IBM) fix for reading initial field values.
//
function setDateAdjustFields(sourceFieldId,targetFieldId){
	if(sourceFieldId != null){
		departureField = document.getElementById(sourceFieldId);
		currentDateField = departureField;
		dateChange(departureField);

		// Register parent and child links between fields.
		if(targetFieldId != null){
			dateSources[targetFieldId] = sourceFieldId;
			dateTargets[sourceFieldId] = targetFieldId;
		}
	}
	else
		departureField = null;

	if(targetFieldId != null){
		arrivalField = document.getElementById(targetFieldId);
		currentDateField = arrivalField;
		dateChange(arrivalField);
	}
	else
		arrivalField = null;

	currentDateField = null;
}

function setDisplayFields(sourceFieldId,targetFieldId){
	displayFields[sourceFieldId] = targetFieldId;
}

//
// Configure calendar with default values. These values can be overriden
// by the calling HTML page after it has called initCalendar().
//
// This function is called by init(). If you need to set variables to specific
// values, such as lang, do it in the calling code after calling init().
//
function configCalendar(){
	logDebug("configCalendar start ");
	// This next line should be in the initialization code, not in the calendar. This function
	// does not even exist in the calendar... Not changing yet to simplify deployment.
	today = new Date(); //getGMTServerDate();

	// Maximum number of days from today which are allowed for selection.
	daysLimit = 353;

	// Date formats.
	dateFormat = new Object();
	dateFormat["en"] = "DD/MM/YYYY";
	dateFormat["en"] = "YYYY-MM-DD";
	dateFormat["fr"] = "DD/MM/YYYY";
	dateFormat["fr"] = "YYYY-MM-DD";

	// Template for empty dates.
	dateTpl = new Object();
	dateTpl["en"] = "DD/MM/YYYY";
	dateTpl["fr"] = "JJ/MM/AAAA";

	shownDate = new Date(today.getFullYear(),today.getMonth(),1);

	logDebug("configCalendar end ");
}

//
// Must be called when the user clicks or tabs into a date input field (onfocus event).
//
function dateFocus(o,defaultDateFieldId){
	try {
		if (! initCalFlag) {
			logError("Calendar not initialized", "dateFocus/calNotInit");
			return;
		}
		logDebug("dateFocus");
		inDateField = true;
		currentDateField = o;

		// Store default date field if set.
		if(defaultDateFieldId != undefined && defaultDateFieldId != null)
			defaultDateField = document.getElementById(defaultDateFieldId);
		else
			defaultDateField = null;

		logDebug("dateFocus/bsc");
		if(! overCalendar)
			showCalendar(o);
		logDebug("dateFocus/asc");

		o.select();
	} catch (err) {
		logError(err, "calendar.dateFocus@260");
	}
}

//
// Must be called when the user clicks or tabs out of a date input field (onblur event).
//
function dateBlur(o){
	try {
		if (! initCalFlag) {
			logDebug("dateBlur/calNotInit");
			return;
		}
		inDateField = false;
		if(! overCalendar)
			hideCalendar();
	} catch (err) {
		logError(err, "calendar.dateBlur@273");
	}
}

//
// Must be called when the content of a date input field changes (onchange event).
//
function dateChange(o){
try {
	if (! initCalFlag) {
		logDebug("dateChange/calNotInit");
		return;
	}
	dateValue[o.id] = null;
	dateDisplayed[o.id] = null;
	displayAsText(o.id,"");
	//o.className = "";

	if(o.value.length == 0)
		o.value = dateTpl[lang];
	if(o.value == dateTpl[lang])
		return;

	var theDate = parseDate(o.value);
	if(theDate == null || isDateBeforeToday(theDate) || isDateTooFar(theDate,1)){
		o.className = "invalid";
	displayAsText(o.id,dMsg[lang]["invaliddate"]);
		return;
	}

	setDate(o,theDate);
	dateDisplayed[o.id] = theDate;

	adjustDates(o);
} catch (err) {
	logError(err, "calendar.dateChange@304");
}
}

function displayAsText(dateFieldId,text){
	if (displayFields[dateFieldId] != null){
		var e = document.getElementById(displayFields[dateFieldId]);
	  if (e != null){
		  e.innerHTML = "";
		  e.innerHTML = text;
		}
	}
}

//
// Must be called when the mouse goes over the calendar (onmouseover event). Will be called
// whenever the mouse changes date cell too.
//
function calendarOver(o){
	overCalendar = true;
}

//
// Must be called when the mouse leaves the calendar (onmouseout event). Will be called
// whenever the mouse changes date cell too.
//
function calendarOut(o){
	overCalendar = false;
}

//
// Changes display class when mouse is over element.
//
function mover(target){
	previousClass = target.className;
	target.className = "over";
}

//
// Restores previous display class when mouse goes off element.
//
function mout(target){
	target.className = previousClass;
}

//
// Changes display class when mouse is over element.
//
function cover(target){
	if(Number(target.innerHTML) > 0 && target.className != "past"
					&& target.className != "weekendpast" && target.className != "disabled"){
		previousClass = target.className;
		target.className = "over";
	}
}

//
// Restores previous display class when mouse goes off element.
//
function cout(target){
	if(Number(target.innerHTML) > 0 && target.className != "past"
					&& target.className != "weekendpast" && target.className != "disabled"){
		target.className = previousClass;
	}
}

//
// Registers a select drop-down field so it is hidden when the calendar for
// the specified date field is displayed. Required only because of a bug with
// Internet Explorer.
//
function registerSelect(dateId,selectId){
	if(selectList[dateId] == null)
		selectList[dateId] = new Array();
	selectList[dateId][selectList[dateId].length] = selectId;
}

function setNextFocusField(fieldId,nextFieldId){
	nextFocusList[fieldId] = nextFieldId;
}

//
// Display the calendar beneath the current field.
//
function showCalendar(dateField){
	if (! initCalFlag) {
		logDebug("howCalendar/calNotInit");
		return;
	}
   	var c = document.getElementById("cal");
	if (c == null) {
		logDebug("showCalendar/noCalDiv");
		return;
	}
	// 1.3.x If departure is in month preceeding than arrival, show arrival month on right
	// to avoid users accidentally chosing return date one month after desired date.

	// If this date was previously selected, display the same 2 months.
	var d = dateDisplayed[dateField.id];

	// If only departure field was selected, display those 2 months instead.
	if (d == null && dateField != null && arrivalField != null && dateField.id == arrivalField.id)
		d = dateDisplayed[departureField.id];

	// If still null, try previously entered date.
	if (d == null)
		d = dateValue[dateField.id];

	// Determine default month and year to open calendar.
	if(d == null){
		// See if default fields set
		if(defaultDateField != null)
			d = parseDate(defaultDateField.value);
	}
	if(d == null){
		// Still null, set today's date as default.
		d = today;
	}

	shownDate = new Date(d.getFullYear(),d.getMonth(),1);

	logDebug("showCalendar/bcal");

	// Position (hidden) calendar underneath field.
	//c.style.position = "absolute";
	//c.style.left = findPosX(dateField) + "px";
	//c.style.top = (findPosY(dateField) + inputOffset) + "px";

	// Loop through array of select elements to hide.
	var fields = selectList[dateField.id];
	if(fields) for(var i = 0; i < fields.length; i++){
		if(document.getElementById(fields[i]) != null)
			document.getElementById(fields[i]).style.visibility = "hidden";
	}

	logDebug("showCalendar/bshow");

	// Show calendar.
	document.getElementById("photo").style.display = "none";
	c.style.display = "block";

	// Display dates in calendar.
	displayDates();
}

function hideCalendar(){
	// Hide calendar.
	document.getElementById("cal").style.display = "none";
	document.getElementById("photo").style.display = "";

	// Loop through array of previously hidden select elements.
	if(currentDateField){
		var fields = selectList[currentDateField.id];
		if(fields) for(var i = 0; i < fields.length; i++){
			if(document.getElementById(fields[i]) != null)
				document.getElementById(fields[i]).style.visibility = "visible";
		}
	}

	// Make sure "over" variable is reset.
	overCalendar = false;
}


function changeMonth(i){
	shownDate.setMonth(shownDate.getMonth() + i);
	displayDates();

	try { currentDateField.focus(); } catch (err) {
    // Ignore, field could be hidden, no harm.
  };
}

function selectDate(o,monthOffset){
	if(o.className == "past" || o.className == "weekendpast" ||
		 o.className == "disabled" || ! Number(o.innerHTML) > 0){
		try { currentDateField.focus(); } catch (err) {
      // Ignore, field could be hidden, no harm.
    };
		return;
	}

	var newDate = new Date(shownDate.getFullYear(),shownDate.getMonth() + monthOffset,o.innerHTML);
	setDate(currentDateField,newDate);
	//currentDateField.className = "";

	// Setting the field does not trigger "onchange", so change it manually.
	dateDisplayed[currentDateField.id] = shownDate;
	adjustDates(currentDateField);

	hideCalendar();

	// Set focus to next field if set.
	if(nextFocusList[currentDateField.id] != null)
	{
		var elemName = nextFocusList[currentDateField.id];
		var elem = document.getElementById(elemName);
		if(elem != null)
			setTimeout("tabDateField('" + elemName + "')", 100);
	}
}

function tabDateField(elemName) {
	var elem = document.getElementById(elemName);
	try { elem.focus(); } catch (err) {
		// Ignore, field could be hidden, no harm.
	};
}

var dateAdjustPlugin;
function adjustDates(sourceField){
	var getSource = function(f){
		return dateSources[f] == null ? null : document.getElementById(dateSources[f]);
	};
	var getTarget = function(f){
		return dateTargets[f] == null ? null : document.getElementById(dateTargets[f]);
	};
	adjustField(getSource(sourceField.id),"target",getSource);
	adjustField(sourceField,"source",getTarget);
}

function adjustField(sourceField,type,getNext){
	if(sourceField == null)
		return null;
	var targetName = dateTargets[sourceField.id];
	if(targetName == null)
		return;
	var targetField = document.getElementById(targetName);
	if(targetField == null)
		return;

	dateAdjustPlugin(sourceField,targetField,type);
	adjustField(getNext(sourceField.id),type,getNext);
}

function setDate(f, newDate){
	if(f.id == null || dateValue[f.id] == newDate)
	  return;
	dateValue[f.id] = newDate;
	f.value = formatDate(newDate,dateFormat[lang]);
	displayAsText(f.id,formatTextDate(newDate));
	fix_nb_nights();
}

function defaultDateAdjustPlugin(sourceField,targetField,type){
	var sourceDate = dateValue[sourceField.id];
	var targetDate = dateValue[targetField.id];
	if(sourceDate != null && targetDate != null && sourceDate.getTime() > targetDate.getTime()){
		if(type == "source"){
			setDate(targetField, sourceDate);
			dateDisplayed[targetField.id] = dateDisplayed[sourceField.id]
		} else if(type = "target") {
			setDate(sourceField, targetDate);
			dateDisplayed[sourceField.id] = dateDisplayed[targetField.id]
		}
	}
}
// Set this plugin as the default behavior.
dateAdjustPlugin = defaultDateAdjustPlugin;

function displayDates(){
	var nextMonthDate = new Date(shownDate.getFullYear(),shownDate.getMonth() + 1,1);

	// Display calendar titles.
	var cal1Title = document.getElementById("cal1Title");
	var cal2Title = document.getElementById("cal2Title");
	if (cal1Title == null) {
		logDebug("displayDates/cal1TitleNull");
		return;
	}
	if (cal2Title == null) {
		logDebug("displayDates/cal2TitleNull");
		return;
	}
	cal1Title.innerHTML = "";
	cal1Title.innerHTML = mNames[lang][shownDate.getMonth()] + " " + shownDate.getFullYear();
	cal2Title.innerHTML = "";
	cal2Title.innerHTML = mNames[lang][nextMonthDate.getMonth()] + " " + nextMonthDate.getFullYear();

	isEndReached = false;
	isAtBeginning = false;

	displayMonth(c1cells,shownDate);
	displayMonth(c2cells,nextMonthDate);

	// Hide month navigation as appropriate.
	document.getElementById("calarrowback").style.display = (isAtBeginning) ? "none" : "block";
	document.getElementById("calarrowfwd").style.display = (isEndReached) ? "none" : "block";
}

// Constant containing the number of milliseconds in one day, used for date arithmetics.
var msInDay = 24 * 60 * 60 * 1000;

function displayMonth(cells,monthDate){
	var lastDate = getMonthDays(monthDate);
	var offset = getCalendarOffset(monthDate);
	var cell = null;

	// Wipe first and last rows.
	for(var i = 1; i <= offset; i++){
		cell = cells[i];
		cell.innerHTML = "";
		cell.innerHTML = "&nbsp;";
		if(i % 7 <= 1)
			cell.className = "weekend";
		else
			cell.className = "";
	}
	for(var i = offset + lastDate; i <= 42; i++){
		cell = cells[i];
		cell.innerHTML = "";
		cell.innerHTML = "&nbsp;";
		if(i % 7 <= 1)
			cell.className = "weekend";
		else
			cell.className = "";
	}

	// Display dates.
	var isTodayMonth = isSameMonth(monthDate,today);
	var isSelectedMonth = isSameMonth(monthDate,dateValue[currentDateField.id]);
	var isDate1Month = departureField != null && isSameMonth(monthDate,dateValue[departureField.id]);
	var isDate2Month = arrivalField != null && isSameMonth(monthDate,dateValue[arrivalField.id]);

	for(var i = 1; i <= lastDate; i++){
		// Display day of month.
		cell = cells[i + offset];
		cell.innerHTML = "";
		// First set to empty string, required for IE 5 Mac
		cell.innerHTML = i;

		if(checkBegin && monthDate.getTime() <= today.getTime()){
			isAtBeginning = true;
		}

		var normalClass = "";
		var pastClass = "past";
		var isWeekEnd = ((i + offset) % 7) <= 1;
		if(isWeekEnd){
			normalClass = "weekend";
			pastClass = "weekendpast";
		}

		// Select display class.
		if(checkBegin && isTodayMonth && today.getDate() > i){
			cell.className = pastClass;
			isAtBeginning = true;
		}
		else if(isSelectedMonth && dateValue[currentDateField.id].getDate() == i){
			// This is the currently selected date.
			cell.className = "current";
		}
		else if(isDate1Month && dateValue[departureField.id].getDate() == i){
			cell.className = "selected";
		}
		else if(isDate2Month && dateValue[arrivalField.id].getDate() == i){
			cell.className = "selected";
		}
		else if(checkEnd && isDateTooFar(monthDate,i)){
			// This date is too far in the future.
			cell.className = pastClass;
			isEndReached = true;
		}
		else if(disabledDays[(i + offset - 1) % 7] == true){
			cell.className = "disabled";
		}
		else{
			cell.className = normalClass;
		}
	}
}

function isDateBeforeToday(theDate){
//Quick Fix for third party ads
  today = getGMTServerDate();
	if(theDate.getFullYear() != today.getFullYear())
		return theDate.getFullYear() < today.getFullYear();
	if(theDate.getMonth() != today.getMonth())
		return theDate.getMonth() < today.getMonth();
	return theDate.getDate() < today.getDate();
}

function isDateTooFar(theDate,offset){
//Quick Fix for third party ads
  today = getGMTServerDate();
	// Calculate the maximum number of days from today.
	var days = Math.ceil((theDate.getTime() - today.getTime()) / msInDay) + offset - 1;
	return days > daysLimit;
}

//
// Returns the number of days in the month.
//
function getMonthDays(theDate){
	// Return the last day of the current month. Using 0 as a date substract
	// 1 days from the next month, which is what we need.
	var lastDate = new Date(theDate.getFullYear(),theDate.getMonth() + 1,0);
	return lastDate.getDate();
}

//
// Returns the weekday offset of the first day of the month.
//
function getCalendarOffset(theDate){
	var firstDay = new Date(theDate.getFullYear(),theDate.getMonth(),1);
	return firstDay.getDay();
}

//
// Returns true is the two dates have the same year and month//
function isSameMonth(firstDate,secondDate){
	if(firstDate == null || secondDate == null)
		return false;
	return firstDate.getFullYear() == secondDate.getFullYear() &&
				 firstDate.getMonth() == secondDate.getMonth();
}


function formatDate(theDate,format){
	if(theDate == null) return null;
	var result = format.toLowerCase();
	result = result.replace(/yyyy/,theDate.getFullYear());
	result = result.replace(/mm/,formatToTwoDigits(theDate.getMonth() + 1));
	result = result.replace(/dd/,formatToTwoDigits(theDate.getDate()));
	return result;
}

//
// Return date in text format: 	Lun 13-Fev, 2007
//
function formatTextDate(theDate,format){
	var textLang = lang;
	var textMonth = theDate.getMonth();
	// Fix "Jui n" and "Jui llet" in French to be "jun" and "jul" instead.
	if (lang == "fr" && (textMonth == 5 || textMonth == 6))
	    textLang = "en";
	if(theDate == null) return null;
		return "- " + dNames[textLang][theDate.getDay()].substring(0, 3) + " " +
			theDate.getDate() + "-" +
			mNames[textLang][textMonth].substring(0, 3) + ", " +
			theDate.getFullYear();
}

function formatToTwoDigits(n){
	if(n > 0 && n < 10)
		return "0" + n;
	else
		return n;
}

//
// Parse a text date in dd/mm/yyyy or dd/mm/yy format and a return a date object.
// The separator can be a dash '-' instead and the year can be left out.
//
function parseDate(text){
	if (text == null) return null;
	var parts = text.split(/[-\/]/);
	var origPartsLength = parts.length;

	// Validate.
	if(parts.length < 2 || parts.length > 3)
		return null;

	if(parts.length == 2)
		parts[2] = String(today.getFullYear());
	else if(parts[0].length <= 2)
		parts[0] = String(2000 + Number(parts[0]));

	if(parts[2].length < 1 || parts[2].length > 2 || ! parts[2].match(/[0-9]+/))
		return null;
	if(parts[1].length < 1 || parts[1].length > 2 || ! parts[1].match(/[0-9]+/))
		return null;
	if(parts[0].length == 0 || parts[0].length == 3 ||
		 parts[0].length > 4 || ! parts[0].match(/[0-9]+/))
		return null;

	var newDate = new Date(parts[0],Number(parts[1]) - 1,parts[2]);

	// Adjust year if date is past and same date next year is not too far.
	if(origPartsLength == 2 && newDate.getTime() < today.getTime()){
		var dateYearAdjusted = new Date(newDate.getTime());
		dateYearAdjusted.setFullYear(dateYearAdjusted.getFullYear() + 1);
		if(! isDateTooFar(dateYearAdjusted,1))
			newDate = dateYearAdjusted;
	}

	return newDate;
}

//===
//=== End of calendar.Code following this line is for calendar implementations.
//===

function isDateDefined(f){
	if(f.value == "")
		return false;
	if(! lang)
		return true;

	// Date formats. Quick Fix for third party ads
	dateFormat = new Object();
	dateFormat["en"] = "DD/MM/YYYY";
	dateFormat["fr"] = "DD/MM/YYYY";
	dateFormat["de"] = "DD/MM/YYYY";
	dateFormat["it"] = "DD/MM/YYYY";

	if(f.value == dateFormat[lang])
		return false;

	var theDate = parseDate(f.value);
	if(theDate == null || isDateBeforeToday(theDate) || isDateTooFar(theDate,1))
		return false;

	return true;
}


// Automatic language configuration. This code is run before the calendar is initialized, so the language
// can still easily be overridden in the calendar initalization code.
try {

var weekdays = {};
weekdays["en"] = ["S", "M", "T", "W", "T", "F", "S"];
weekdays["us"] = ["S", "M", "T", "W", "T", "F", "S"];
weekdays["fr"] = ["D", "L", "M", "M", "J", "V", "S"];
weekdays["it"] = ["D", "L", "M", "M", "G", "V", "S"];
weekdays["de"] = ["S", "M", "D", "M", "D", "F", "S"];

} catch (err) {
  logError(err, jsName + "@816");
}

var calCreated = false;
// 
// Generate the calendar

function createCalendar(){
	logDebug("createCalendar start");
        var div = document.getElementById("cal");

        // Internet Explorer 5, 6 and 7 will unload the page if we try to add an element to an unclosed tag.
        // Use static "div" inside the pages as much as possible. 

	if (div == null) {
        	div = document.createElement("div");
	        div.setAttribute("id","cal");
        	div.style.display = "none";
		document.getElementById("photo").style.display = "";
	        //div.style.position = "absolute";
        	document.body.appendChild(div);
	}

       if(document.all){
               div.attachEvent("onmouseover",calendarOver);
               div.attachEvent("onmouseout",calendarOut);
       }
        else{
               div.addEventListener("mouseover",calendarOver,true);
               div.addEventListener("mouseout",calendarOut,true);
        }
        var cn = new Array(7);
        for(var cpt=0;cpt<7;cpt++)
        	cn[cpt]='';
        cn[0] = ' class="weekend"';
        cn[6] = ' class="weekend"';
        var wd = weekdays[lang];
        var c = "";
        // Write calendar table header.
        c += '<table cellpadding="0" cellspacing="0" class="calendar">';
        c += '<tr class="mtitle">';
        c += '<td><div id="calarrowback" onmouseout="mout(this)" onmouseover="mover(this)" class="next" onclick="changeMonth(-1)"><img src="/images/cal_prev.gif" alt="" width="4" height="7" border="0"/></div></td>';
        c += '<td id="cal1Title" colspan="5" class="title" nowrap="nowrap"></td>';
        c += '<td>&nbsp;</td><td rowspan="9" class="spacerA">&nbsp;</td><td rowspan="9" class="spacerB">&nbsp;</td><td>&nbsp;</td>';
        c += '<td id="cal2Title" colspan="5" class="title" nowrap="nowrap"></td>';
        c += '<td><div id="calarrowfwd" onmouseout="mout(this)" onmouseover="mover(this)"  class="next" onclick="changeMonth(1)"><img src="/images/cal_next.gif" alt="" width="4" height="7" border="0"/></div></td>';
        c += '</tr><tr><td colspan="7" style="font-size: 0px" height="2">&nbsp;</td><td colspan="7" style="font-size: 0px" height="2">&nbsp;</td>';
        c += '</tr><tr class="wtitle">';
        for(var i = 0; i < 2; i++)
               for(var j = 0; j < 7; j++)
                       c += '<td' + cn[j] + '>' + wd[j] + '</td>';
        c += '</tr>';
        var k = 1;
        while(k <= 42){
               c += '<tr class="cells">';
               for(var i = 1; i <= 2; i++){
                   for(var j = 1; j <= 7; j++){
                   	c += '<td id="c' + i + 'c' + (k++) + '"  onmouseout="cout(this)" onmouseover="cover(this)" onclick="selectDate(this, ' + (i - 1) + ')"' + cn[j] + '>&nbsp;</td>';
                   }
                   if(i == 1)
                   	k = k-7;
              }
              c += '</tr>';
        }
        c += '<tr><td colspan="16" class="link"><a href="javascript:hideCalendar()"><font color="#ffffff" face="Verdana, Arial, Helvetica, sans-serif">X</font></a></td></tr>';
        c += '</table>';
      div.innerHTML = c;
calCreated = true; 
	logDebug("createCalendar end");
}

function check_date_displayed() {
	if (dateDisplayed['from_date'] == null) {
		d = document.getElementById('from_date').value;
		if (d != null) {
			dateDisplayed['from_date'] = parseDate(d);;
			o = document.getElementById('from_date');
			setDate(o, dateDisplayed['from_date']);
		}
	}
	if (dateDisplayed['to_date'] == null) {
		d = document.getElementById('to_date').value;
		if (d != null) {
			dateDisplayed['to_date'] = parseDate(d);;
			o = document.getElementById('to_date');
			setDate(o, dateDisplayed['to_date']);
		}
	}
}

function numberOfNightsChanged() {
	check_date_displayed();
	var nights = document.getElementById("search_model_nights").value;
	if (nights == ""){
		return;
	}

	d = document.getElementById('from_date').value;
	if (d != null) {
		o = parseDate(d);
		setDate(o, dateDisplayed['from_date']);
		var newDate = new Date();
		newDate.setFullYear(o.getFullYear(), o.getMonth(), o.getDate() + parseInt(nights));
		newDate.setHours(0);
		newDate.setMinutes(0);
		newDate.setSeconds(0);
	}

	o = document.getElementById('to_date');
	setDate(o,newDate);
	dateDisplayed[o.id] = newDate;
}

function showCalendarDiv() {
	var hideLink = document.getElementById("hideLink");
	var a_hideLink = document.getElementById("a_hideLink");
	if(hideLink != null){
		var calendar = new YAHOO.widget.Module("calFormContainer");
		calendar.render();
		a_hideLink.onclick = hideCalendar;
		hideLink.src = hideImg;
	}
}


function fix_nb_nights() {
	from = document.getElementById('from_date').value;
	to = document.getElementById('to_date').value;
	if(from != null && to != null && from != "" && to != ""){
		var nights = numberOfDayBetween(parseDate(from), parseDate(to));
		document.getElementById("search_model_nights").value = nights;
	}
}

function numberOfDayBetween(fromDate, toDate){
	deltaTime = toDate.getTime() - fromDate.getTime();
	deltaJours = deltaTime / (86400000);//1000*3600*24
	var nights = Math.round(deltaJours);

	if(nights > 0 && nights <= 60){
		return nights;
	}
	return "";
}

logLoaded(jsName);

