
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;
var Language;
var retStartDate;

try {

// Date range validation
var checkBegin = true;
var checkEnd = true;

// 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évrier","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"];
mNames["de"] = ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"];
mNames["it"] = ["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"];

var dNames = {};
dNames["en"] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
dNames["fr"] = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"];
dNames["de"] = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];
dNames["it"] = ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"];

var dMsg = {};
dMsg["en"] = {};
dMsg["fr"] = {};
dMsg["de"] = {};
dMsg["it"] = {};
dMsg["en"]["invaliddate"] = "invalid date";
dMsg["fr"]["invaliddate"] = "date invalide";
dMsg["de"]["invaliddate"] = "unzulässiges Datum";
dMsg["it"]["invaliddate"] = "data non valida";

} 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(!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);

	if(optionalLang != null)
		lang = optionalLang;
	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 = getGMTServerDate();
	
	// Maximum number of days from today which are allowed for selection.
	daysLimit = 353;

	// Date formats.
	dateFormat = new Object();
	dateFormat["en"] = "DD-MM-YYYY";

	// Template for empty dates.
	dateTpl = new Object();
	dateTpl["en"] = "";

	//shownDate = new Date(today.getFullYear(),today.getMonth()+1,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.style.color = "red";
	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 = getGMTServerDate();

	// 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";
	c.style.left = "20px";
	c.style.top = "70px";
	
	// select elements to hide (ie problem.)
	document.getElementById('fmCode').style.visibility = "hidden";
	document.getElementById('toCode').style.visibility = "hidden";
	document.getElementById('Adults').style.visibility = "hidden";
	document.getElementById('Children').style.visibility = "hidden";
	document.getElementById('Infant').style.visibility = "hidden";

	logDebug("showCalendar/bshow");

	// Show calendar.
	c.style.display = "block";

	// Display dates in calendar.
	displayDates();
}


function hideCalendar(){
	// Hide calendar.
	document.getElementById("cal").style.display = "none";

	// display select elements hidden previously( ie problem).
	document.getElementById('fmCode').style.visibility = "visible";
	document.getElementById('toCode').style.visibility = "visible";
	document.getElementById('Adults').style.visibility = "visible";
	document.getElementById('Children').style.visibility = "visible";
	document.getElementById('Infant').style.visibility = "visible";

	// Make sure "over" variable is reset.
	overCalendar = false;
	
	var retDate= document.FRM.toDate.value;
	if (retDate ==null || retDate == '') 
		document.FRM.toDate.value = document.FRM.fromDate.value;
}


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));
}

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[2].length <= 2)
		parts[2] = String(2000 + Number(parts[2]));

	if(parts[0].length < 1 || parts[0].length > 2 || ! parts[0].match(/[0-9]+/))
		return null;
	if(parts[1].length < 1 || parts[1].length > 2 || ! parts[1].match(/[0-9]+/))
		return null;
	if(parts[2].length == 0 || parts[2].length == 3 ||
		 parts[2].length > 4 || ! parts[2].match(/[0-9]+/))
		return null;

	var newDate = new Date(parts[2],Number(parts[1]) - 1,parts[0]);

	// 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;
}

//
// Two positionning functions from site http://www.quirksmode.org/js/findpos.html.
//
function findPosX(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 findPosY(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;
}

//===
//=== 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";

	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 {

if(!lang && Language){
	switch(Language.toLowerCase()){
		case "french":	lang = "fr"; break;
		case "english": lang = "en"; break;
		case "de": case "it": case "fr": case "en": lang = Language; break;
		default: lang = "en";
	}
}


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";
	        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="http://www.omanair.aero/flight_schedule/js/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="http://www.omanair.aero/flight_schedule/js/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">Close</font></a></td></tr>';
        c += '</table>';
      div.innerHTML = c;
calCreated = true; 
	logDebug("createCalendar end");
}

// Script loader indicator.
logLoaded(jsName);

/* Calendar support script */
// JavaScript Document
function initHomeCalendar(startDate){
	retStartDate = startDate;
	logDebug("initHomeCalendar start ");
  try {
	
	lang = "en";
	initCalendar();
	//setDisplayFields("departure1", "dl1");
	//setDisplayFields("departure2", "dl2");
	//setDateAdjustFields("departure1","departure2");

	//registerSelect("departure1", "departTime2");
	//setNextFocusField("departure1", "departure2");
  } catch (err) {
    logError(err, "initHomeCalendar @2191");
  }
	logDebug("initHomeCalendar end ");
}

//======================================
// returns a Date object as a representation of
// the current time obtained via a SSI
// timefmt="%d-%m-%Y %H:%M:%S"
// eg : 16-11-2004 00:04:45
//======================================
// SR97501934 CALENDAR - USE SERVER DATE INSTEAD OF PC DATE
var SERVER_DATE;
//
function getServerTime(ssiDate) {

	var dateTime = ssiDate.split(" ");
	var date = dateTime[0].split("-");
	var time = dateTime[1].split(":");

	//alert("getSErverTime for "+ssiDate);
	//alert("date = "+dateTime[0]);
	//alert("time  = "+dateTime[1]);

	var serverTime = new Date();
	//alert("server time 1 = "+serverTime);
	serverTime.setDate(date[0]);
	serverTime.setMonth(parseInt(date[1],10)-1);
	serverTime.setYear(date[2]);
	serverTime.setHours(time[0]);
	serverTime.setMinutes(time[1]);
	serverTime.setSeconds(time[2]);

	//alert("serverTime = "+ serverTime.toLocaleString());

	// SR97501934 *********** code start
	SERVER_DATE = new Date();
	SERVER_DATE.setDate(serverTime.getDate());
	SERVER_DATE.setMonth(serverTime.getMonth());
	SERVER_DATE.setYear(serverTime.getFullYear());
	SERVER_DATE.setHours(serverTime.getHours());
	SERVER_DATE.setMinutes(serverTime.getMinutes());
	SERVER_DATE.setSeconds(serverTime.getSeconds());

	LocalDate = new Date();

	currentTimeZoneOffsetInMinutes = LocalDate.getTimezoneOffset();
	currentTimeZoneOffsetInHours = parseInt(currentTimeZoneOffsetInMinutes/60, 10);
	currentTimeZoneOffsetInMinutes = currentTimeZoneOffsetInMinutes - currentTimeZoneOffsetInHours*60;

	newHours = parseInt(time[0],10)-currentTimeZoneOffsetInHours;

	SERVER_DATE.setHours(newHours);
	SERVER_DATE.setMinutes(parseInt(time[1],10)+currentTimeZoneOffsetInMinutes);
	// SR97501934 ***** code end
	return serverTime;
}

function getGMTServerDate(){

	if(retStartDate==null || retStartDate=='' ){
		newDate = new Date();
		if(SERVER_DATE){
			newDate.setDate(SERVER_DATE.getDate());
			newDate.setMonth(SERVER_DATE.getMonth());
			newDate.setYear(SERVER_DATE.getFullYear());
			newDate.setHours(SERVER_DATE.getHours());
			newDate.setMinutes(SERVER_DATE.getMinutes());
			newDate.setSeconds(SERVER_DATE.getSeconds());
		}
	}else{
		var tempdateArr=retStartDate.split("-");
		var tday = tempdateArr[0];
		var tmonth = tempdateArr[1];
		var tyear = tempdateArr[2];
		newDate = new Date(tyear, tmonth-1, tday);
	}
	return newDate;
}
