 /**
 + ===================================================================================
 * luxair JS tools
 + -----------------------------------------------------------------------------------
 * All java script tools needed to handle luxair website
 + -----------------------------------------------------------------------------------
 * @author jimmy vinueza 
 + ================================================================================ */

 /**
 + ===================================================================================
 * debuggin function
 + -----------------------------------------------------------------------------------
 * @param what, string to be debugged
 + ================================================================================ */
function trace(what){
	var debug = $('toDebug');
	debug.innerHTML = what + '<br>' + debug.innerHTML;
}

 /**
 + ===================================================================================
 * global LUXAIR workspace
 + ================================================================================ */
var LUXAIR = new Object();

 /**
 + ===================================================================================
 * static definitions
 + ================================================================================ */
LUXAIR.defaultFormat 			=		"%d.%m.%Y";
LUXAIR.maxTravellers 			=		9;

 /**
 + ===================================================================================
 * change style of one specific element
 + -----------------------------------------------------------------------------------
 * change style to one DOM element
 + -----------------------------------------------------------------------------------
 * @param 	ElementID string, with the element ID we want to modify, 
 * @param	ClaseName string, new class name to be assigned to ElementID
 + ================================================================================ */
LUXAIR.changeStyle = function(ElementID, ClaseName){
    var target = $(ElementID);
    if(target != null){
        target.className = ClaseName;
    }
}    

LUXAIR.switchContent = function(source, target, cleanSource){
	var theTarget = document.getElementById(target);
	var theSource = document.getElementById(source);
	
	if(theTarget!=null && theSource!=null){
		theTarget.innerHTML = theSource.innerHTML;
		if(cleanSource==1){
			theSource.innerHTML = '';
		}
	}
}

LUXAIR.handleContentSearch = function(event, source, target, cleanSource){
	LUXAIR.switchContent(source, target, cleanSource);
}

LUXAIR.callURLinNewWindow = function(url){
	//create the new window
	var helpWindow = window.open(url, 'help', 'resizable=yes,scrollbars=yes,status=yes,width=640,height=480');
	if(helpWindow!=null){
		helpWindow.focus();
	}
}

 /**
 + ===================================================================================
 * no name
 + -----------------------------------------------------------------------------------
 * no desc
 + -----------------------------------------------------------------------------------
 * @param 	noparam,
 + ================================================================================ */
// -----------------------------------------------
// check if the div has links
// -----------------------------------------------
LUXAIR.tagExistsIn = function(container, lookFor){
	var searchHere = $(container);
	
	//check if the elem has a
	if(searchHere!=null){
		check = searchHere.getElementsByTagName(lookFor);
		if(check.length){
			return 1;		
		}
	}

	return 0;
}


 /**
 + ===================================================================================
 * no name
 + -----------------------------------------------------------------------------------
 * no desc
 + -----------------------------------------------------------------------------------
 * @param 	noparam,
 + ================================================================================ */
LUXAIR.displayRelevantLinks = function(className, title){
	var numLinks = 0;
	//get the containers
	var containers = document.getElementsByClassName(className);
	
	if(containers!=null){
		for(var i=0; i<containers.length; i++){
			//get the links form this element
			var links = containers[i].getElementsByTagName('a');
			if(links!=null){
				var linksText = '';
				for(var j=0; j< links.length; j++){
					
					//we have a new element
					numLinks++;
					
					//set the title
					if(numLinks==1){
						linksText += '<p class="relevantlinksTitle">' + title + '</p>';
					}

					var linkClass = '';					
					//define the class of the link
					//Odd
					if((numLinks%2)!=0){
						linkClass = 'relevantlinksOdd';
					//Even
					}else{
						linkClass = 'relevantlinksEven';
					}
					linksText += '<a id="relevantLinks' + numLinks + '" href="' + links[j].href + '" class="' + linkClass + '">' + links[j].innerHTML + '</a>';
				}
			}
		}
	}
	
	//if there are links				
	if(numLinks>0){
		var target = $('relevantlinksEnvelop');
		if(target!=null){
			target.className = 'relevantlinksEnvelop';
			target.innerHTML = linksText;
			
			//change the style of the last element
			//Odd
			if((numLinks%2)!=0){
				linkClass = 'relevantlinksBottomOdd';
			//Even
			}else{
				linkClass = 'relevantlinksBottomEven';
			}
			
			$('relevantLinks' + numLinks).className = linkClass;
		}
	}
}

 /**
 + ===================================================================================
 * no name
 + -----------------------------------------------------------------------------------
 * no desc
 + -----------------------------------------------------------------------------------
 * @param 	noparam,
 + ================================================================================ */
LUXAIR.changeLayoutFrom3to2 = function(){
	LUXAIR.changeStyle('contentWrapper', 'contentWrapper2');
	LUXAIR.changeStyle('topContentShadow', 'topContentShadow2');
	LUXAIR.changeStyle('leftAndCentralColumns', 'leftAndCentralColumns2');
	LUXAIR.changeStyle('centralColumn', 'centralColumn2');
	LUXAIR.changeStyle('rightColumn', 'rightColumn2');
	LUXAIR.changeStyle('footer', 'footer2');
}

 /**
 + ===================================================================================
 * no name
 + -----------------------------------------------------------------------------------
 * no desc
 + -----------------------------------------------------------------------------------
 * @param 	noparam,
 + ================================================================================ */
LUXAIR.handleNews = function(){
	var source = $('newsPlaceHolder');
	var target = $('rightColumn');
	
	if(source!=null && target!=null){
		target.innerHTML = target.innerHTML + source.innerHTML;
	}
}

// ===============================================
// API for flash animation
// ===============================================
LUXAIR.mapSetOrigin = function(val){
	if($('origin')){
		$('origin').value=val;
		//refresh destination
		LUXAIR.fillDestination(airportList, routeList, bookingSelectCity);	
	}	
}

LUXAIR.mapSetDestination = function(val){
	if($('destination')){
		$('destination').value=val;
	}
}

LUXAIR.mapResetForm = function(formId){
	if($('formId')){
		$(formId).reset();
	}
}


// -----------------------------------------------
// handling submit
// -----------------------------------------------
LUXAIR.handleClickSearch = function(amadeusMI){
	LUXAIR.formSubmit('flightSearchForm', amadeusMI);
}

// -----------------------------------------------
// form handler
// -----------------------------------------------
LUXAIR.formSubmit = function(formID, amadeusMI){
	var errorMessage = LUXAIR.formCheck(formID);
	//"origin",
	var origin = $('origin').value;
	//"destination",
	var destination = $('destination').value;
	//"frmDeparture"
	var departure = $('frmDeparture').value;

	//an error was found
	if(errorMessage){
		alert(errorMessage);
	//send request to application server	
	}else{
		//check for tour operator flights
		if(routeList.isTourOperator(origin, destination)){
			if($('departureFromCalendar')!=null && $F('departureFromCalendar') &&  $('arrivalFromCalendar')!=null && $F('arrivalFromCalendar')){
				LUXAIR.formCallAmadeusHandler(amadeusMI, bookingService, bookingServiceParams);
			}else{
				LUXAIR.handleTOFlights();
			}
		}else{
			//20090302 disable DCC
			//check if the flight could be one way combinable
			//if(!isEtlInMaintenance() && LUXAIR.isOneWayCobinable(origin, destination) && !LUXAIR.checkCodeShareAndException(origin, destination)){
			//	LUXAIR.formCallOWCHandler(bookingOWCHandler, bookingService, bookingServiceParams);
			//if the flight is not one way combinable, call the normal amadeus interface
			//}else{
				//define the URL for calling the application server
				LUXAIR.formCallAmadeusHandler(amadeusMI, bookingService, bookingServiceParams);
			//}
		}
	}
}

LUXAIR.formatURLParams = function(amadeusURL, bookingService, bookingServiceParams, format){
	var params = "";
	//define the parameters
	//"mode",
	var mode = $F('mode');
	
	//"lang",
	var lang = $F('lang');

	//"tripType",
	var tripType = ($F('frmTripTypeRoundTrip')?2:1);
	
	//"cabin",
	var cabin = $F('frmCabin');

	//"origin",
	var origin = $('origin').value;

	//"destination",
	var destination = $('destination').value;


	//"departureDay",
	//"departureMonth",
	var departure = $F('frmDeparture');
	tmp = LUXAIR.dateHandler.parseDate(departure);
	var departureDay = tmp[0];
	var departureMonth = tmp[2] + tmp[1];

	//"returnDay",
	//"returnMonth",
	var returnDay = '';
	var returnMonth = '';

	//only for round trip
	if(tripType==2){
		var arrival = $F('frmArrival');
		tmp = LUXAIR.dateHandler.parseDate(arrival);
		var returnDay = tmp[0];
		var returnMonth = tmp[2] + tmp[1];
	}

	//"flexible",
	var flexible =  $F('frmFlexibleTrue')||$F('frmFlexibleFalse');
	
	//"adultPax",
	//"yougthPax"
	//"childPax",
	//"infantPax",
	var adultPax = 0;
	var yougthPax = 0;
	var childPax = 0;
	var infantPax = 0; 
	
	//adult
	if($F('frmAgeTypeAdult')){
		adultPax = $F('frmTravellers');
		childPax = $F('frmChildPAX');
		infantPax = $F('frmInfantPAX'); 
			
	//yougth
	}else{
		yougthPax = $F('frmTravellers');
	}

	var pricing = '';

	if(format!=null && format=='OWC'){
		params = 	origin + ',' + 
					destination + ',' + 
					departureMonth+departureDay + ',' + 
					returnMonth + returnDay + ',' + 
					tripType + ',' + 
					cabin + ',' + 
					flexible + ',' + 
					adultPax + ',' + 
					childPax + ',' + 
					infantPax + ',' + 
					yougthPax + ',' + 
					'';
	}else{
		params = 	mode + ',' + 
					lang + ',' + 
					tripType + ',' + 
					cabin + ',' + 
					origin + ',' + 
					destination + ',' + 
					departureMonth+departureDay + ',' + 
					returnMonth + returnDay + ',' + 
					flexible + ',' + 
					adultPax + ',' + 
					childPax + ',' + 
					infantPax + ',' + 
					yougthPax + ',' + 
					pricing + ',' + 
					'';
	}				

	//alert(amadeusURL + '&lap=' + params);
	document.location = amadeusURL + '&lap=' + params;
}

LUXAIR.formCallAmadeusHandler = function(amadeusURL, serviceURL, paramsDefinition){
	LUXAIR.formatURLParams(amadeusURL, serviceURL, paramsDefinition, 'AMADEUS');
}

LUXAIR.formCallOWCHandler = function(amadeusURL, serviceURL, paramsDefinition){
	LUXAIR.formatURLParams(amadeusURL, serviceURL, paramsDefinition, 'OWC');
}

LUXAIR.formCheck = function(formID){
	//get the variables
	var origin = $('origin');
	var originValue = '';

	if(origin.selectedIndex>=0){
		originValue = origin.options[origin.selectedIndex].value;
	}
	
	var destination = $('destination');
	var destinationValue = '';

	if(destination.selectedIndex>=0){
		destinationValue = destination.options[destination.selectedIndex].value;
	}
	
	var departure = $('frmDeparture');
	departure = departure.value		;
	
	var arrival = $('frmArrival');
	arrival = arrival.value
	
	//control error cases.
	var errors = [];

	//invalid origin
	if(originValue==''){
		errors[errors.length] = missingOriginErrMsg;
	}
	
	//invalid destination
	if(destinationValue==''){
		errors[errors.length] = missingDestErrMsg;
	}
	
	//origin and arrival are the same
	if((originValue!='' && originValue==destinationValue)){
		errors[errors.length] = destConstraintViolationErrMsg;
	}
	
	//check the dates
	var today = LUXAIR.dateHandler.formatInputDate(bookingMinPossibleBooking);
	var maxBookingday = LUXAIR.dateHandler.formatInputDate(bookingMaxPossibleBooking);
	
	if(!isDate($('frmDeparture').value)){
		errors[errors.length] = nonValidDepartureDateErrMsg;
	}else{
		var date1 = LUXAIR.dateHandler.formatInputDate($('frmDeparture').value);
		if(date1 < today || date1 > maxBookingday){
			errors[errors.length] = nonValidDepartureDateErrMsg;
		}
	}

	if($('frmTripTypeRoundTrip').checked){
		if(!isDate($('frmArrival').value)){
			errors[errors.length] = nonValidReturnDateErrMsg;
		}else{
			var date2 = LUXAIR.dateHandler.formatInputDate($('frmArrival').value);
			if(date2 < today || date2 > maxBookingday){
				errors[errors.length] = nonValidReturnDateErrMsg;
			}
		}
	}
	
	//check departure is bigger as arrival
	if(isDate($('frmDeparture').value) && isDate($('frmArrival').value)){		
		//for first minute, check that the frmArrival is minimum frmDeparture + 2
		if((date2 < date1)){
			errors[errors.length] = returnDateConstraintViolationErrMsg;
		}
	}
		
	//format the message
	var message = '';
	if(errors.length>0){
		for(var i=0; i<errors.length; i++){
			message = message + errors[i] + "\n";	
		}
	}

	return message;
}

// -----------------------------------------------
// helpers
// -----------------------------------------------

/**
  * Function used to check the minimum stay rules
  * param departure : departure date
  * param arrival : return date
  * param msg : message to display if the rule is violated
  * param nightCount : night count of the minimum stay
 * return the message to display (may be empty)  
  */
LUXAIR.checkSimpleMinimumStayRules = function(departure, arrival, msg, nightCount) {
	var msgs = msgs!=null ? msgs : new Array();  

	var emptyMessage = "";	

   	var departureTS = LUXAIR.dateHandler.formatInputDate(departure);
   	var arrivalTS = LUXAIR.dateHandler.formatInputDate(arrival);
   	var departureDate = LUXAIR.dateHandler.formatToJSDate(departureTS);
   	var arrivalDate = LUXAIR.dateHandler.formatToJSDate(arrivalTS);
   	var tmpDate = LUXAIR.dateHandler.formatToJSDate(departureTS);
   	
	tmpDate.setDate(tmpDate.getDate() + nightCount);		
	var tmpDateTS = LUXAIR.dateHandler.formatJSDate(tmpDate);    

    if(LUXAIR.dateHandler.formatInputDate(tmpDateTS) > arrivalTS && !LUXAIR.sundayRule(departureTS, arrivalTS)){
        return msg;
    }
	
	return emptyMessage;
}

LUXAIR.checkMinimumStayRules = function(origin, destination, departure, arrival, msgs){
		var msgs = msgs!=null ? msgs : new Array();  

		var msg = "";	
		//these are the 3D routes
    var destinations3D = new Array('FRA','GVA','HAM', 'MUC', 'VIE', 'MIL', 'MXP', 'TRN', 'NCE');
		//these are the 1D routes
    var destinations1D = new Array('CDG','LCY','PAR','LON');
   	var departureTS = LUXAIR.dateHandler.formatInputDate(departure);
   	var arrivalTS = LUXAIR.dateHandler.formatInputDate(arrival);
   	var departureDate = LUXAIR.dateHandler.formatToJSDate(departureTS);
   	var arrivalDate = LUXAIR.dateHandler.formatToJSDate(arrivalTS);
   	var tmpDate = LUXAIR.dateHandler.formatToJSDate(departureTS);
   	
		//no minimun stay rule required
    if((origin=='SCN' && destination=='MUC') || (origin=='MUC' && destination=='SCN')){
    	//no minimun destination required
    	return;

		//3D rule
    }else if(
    	((destinations3D.indexOf(origin)>=0) &&  destination=='LUX')
    	|| ((destinations3D.indexOf(destination)>=0) && origin=='LUX')
    ){
			tmpDate.setDate(tmpDate.getDate()+3);		
			var tmpDateTS = LUXAIR.dateHandler.formatJSDate(tmpDate);    

      if(LUXAIR.dateHandler.formatInputDate(tmpDateTS) > arrivalTS && !LUXAIR.sundayRule(departureTS, arrivalTS)){
      	return msgs[0]!=null?msgs[0]:'???no message???';
     	}
     
		//1D rule
		} else if(
    	((destinations1D.indexOf(origin)>=0) &&  destination=='LUX')
    	|| ((destinations1D.indexOf(destination)>=0) && origin=='LUX')
    ){
			tmpDate.setDate(tmpDate.getDate()+1);		
			var tmpDateTS = LUXAIR.dateHandler.formatJSDate(tmpDate);    

      if(LUXAIR.dateHandler.formatInputDate(tmpDateTS) > arrivalTS && !LUXAIR.sundayRule(departureTS, arrivalTS)){
      	/* Get here the right message */
				return msgs[3]!=null?msgs[3]:'???no message???';
      }
      
		//2D rule
    }else{
			tmpDate.setDate(tmpDate.getDate()+2);		
			var tmpDateTS = LUXAIR.dateHandler.formatJSDate(tmpDate);    

      if(LUXAIR.dateHandler.formatInputDate(tmpDateTS) > arrivalTS && !LUXAIR.sundayRule(departureTS, arrivalTS)){
      	return msgs[2]!=null?msgs[2]:'???no message???';
      }
    }
	
		return msg;
}

LUXAIR.checkMaximumStayRules = function(departure, arrival, msg, nightCount){
	var emptyMsg = "";	

   	var departureTS = LUXAIR.dateHandler.formatInputDate(departure);
   	var arrivalTS = LUXAIR.dateHandler.formatInputDate(arrival);
   	var departureDate = LUXAIR.dateHandler.formatToJSDate(departureTS);
   	var arrivalDate = LUXAIR.dateHandler.formatToJSDate(arrivalTS);
   	var tmpDate = LUXAIR.dateHandler.formatToJSDate(departureTS);
   	
	tmpDate.setDate(tmpDate.getDate() + nightCount);		
	var tmpDateTS = LUXAIR.dateHandler.formatJSDate(tmpDate);    

	if(LUXAIR.dateHandler.formatInputDate(tmpDateTS) < arrivalTS){
		return msg;
	}
	
	return emptyMsg;
}

LUXAIR.sundayRule = function(departureTS, arrivalTS){
    if(departureTS==arrivalTS){
        return false;
    }
    while(departureTS<arrivalTS){
    	var tmpDate = LUXAIR.dateHandler.formatToJSDate(departureTS);
    	tmpDate.setDate(tmpDate.getDate()+1);
		//set the next value    	
        departureTS = LUXAIR.dateHandler.formatInputDate(LUXAIR.dateHandler.formatJSDate(tmpDate));
    	
    	//check the day
        if(tmpDate.getDay() == 0){
            return true;
        }
    }
    return false;
}

LUXAIR.fillIntegerSelectBox = function(elem, begin, end, selected, clean){
	if(elem!=null){
		if(clean) elem.options.length = 0;
	
		//set the initial data
		var option;

		for(var i=begin; i<=end; i++){
			//create the new option
			option = new Option(i, i, ((i==selected)?true:false), ((i==selected)?true:false));
			//add to the select box
			elem.options[elem.options.length] = option;
		}
	}
}
	
LUXAIR.selectContent = function(element){
	if(element.select!=null){
		element.select();
	}else{
		//trace('no se puede seleccionar nada');
	}
}

function disableFunc(date){
    if(!showformat){
        alert(date);
        showformat = 1;
    }
    return true;
}

// -----------------------------------------------
// init the origin and destinations in booking mask
// -----------------------------------------------

// ================================================
// AIRPORT CLASS
// ================================================
LUXAIR.airport = function(){
	this.airportList = {};
}

LUXAIR.airport.prototype = {
	add:		function(code, name){
		if(this.airportList[code]!=null) return;
		this.airportList[code] = name;
	},
	
	get:		function(code){
		if(code!=null){
			return this.airportList[code];
		}else{
			return this.airportList;
		}
	}
}

// ================================================
// ROUTE CLASS
// ================================================
LUXAIR.route = function(){
	this.routeList = {};
	this.TOFlights = {};
}

LUXAIR.route.prototype = {
	add:		function(originCode, destinationCode, isTO){
		//add the list
		if(this.routeList[originCode]==null){
			this.routeList[originCode] = new Array();
		}
		
		this.routeList[originCode][this.routeList[originCode].length] = destinationCode;
		
		//add to the tour operators flights
		if(this.TOFlights[originCode]==null){
			this.TOFlights[originCode] = {};
		}
		
		var flag = (isTO=='true'?1:0);
		this.TOFlights[originCode][destinationCode] = flag;
	},
	
	get:		function(code){
		if(code!=null){
			//sort the list before returining ...
			if(routeList!=null){
                //trace('the code is: ' + code);			     
				var unsorted = this.routeList[code];
				
				var unsortedFormated = {};
				for(var i=0; i<unsorted.length; i++){
					unsortedFormated[unsorted[i]] = true;
					//trace('unsorted: ' + i + ' ... ' + unsorted[i] + ' ... ' + unsortedFormated[unsorted[i]]);
				}

				var toReturn = [];
				var tmp = airportList.get();
				//LUX => 'Luxenburg'
				var sortedAirports = new Array();
                if(tmp!=null){
                    for(var i in tmp){                        
                        sortedAirports[sortedAirports.length] = tmp[i] + '|' + i;
                        //trace('tmp: ' + tmp[i] + '|' + i);       
                    }
                    sortedAirports.sort();
                }
				
				for(var i=0; i<sortedAirports.length; i++){
					//trace('sorted ... ' + sortedAirports[i]);
					var splited = sortedAirports[i].split('|');
					
					if(unsortedFormated[splited[1]]){
						//trace('<b>found1</b> ... ' + splited[0]);
						toReturn[toReturn.length] = splited[1];
					}
				}

				return toReturn;
			}else{
				return this.routeList[code];
			}
		}else{
			return this.routeList;
		}
	},
	
	isTourOperator: function(originCode, destinationCode){
		if(
			originCode 
			&& destinationCode 
			&& this.TOFlights[originCode]!=null
			&& this.TOFlights[originCode][destinationCode]!=null
			&& this.TOFlights[originCode][destinationCode]==1
		){
			return true;		
		}
		
		return false;
	}
}

/**
 + ===================================================================================
 * DATEHANDLER CLASS
 + -----------------------------------------------------------------------------------
 * helper methods for days handling
 + ================================================================================ */
LUXAIR.fMAvailableDatesOrigin 	= {};

LUXAIR.fMAvailableDatesDestination 	= {};

LUXAIR.date = function(dateFrom, dateTo){
	var tmp;
	//parse the date that is comming in format
	tmp = this.parseDate(dateFrom);
	this.dateFromDay	= tmp[0];
	this.dateFromMonth	= tmp[1];
	this.dateFromYear	= tmp[2];
	this.dateFrom		=  new Date(tmp[2], tmp[1]-1, tmp[0]);

	tmp = this.parseDate(dateTo);
	this.dateToDay		= tmp[0];
	this.dateToMonth	= tmp[1];
	this.dateToYear		= tmp[2];
	this.dateTo			=  new Date(tmp[2], tmp[1]-1, tmp[0]);
}

LUXAIR.date.prototype = {
	getFormat:		function(){
		return LUXAIR.defaultFormat;
	},

	// ----------------------------------
	// the default date for the application is today + 1
	// ----------------------------------
	getDefault:		function(){
		return this.dateFromDay + '.' + this.dateFromMonth + '.' + this.dateFromYear;
	},
	
	getDateFrom:	function(){
		return this.dateFrom;
	},
	
	getDateTo:	function(){
		return this.dateTo;
	},
	
	getMinDate:	function(){
		if(this.minDate!=null)return this.minDate;
		return this.dateFrom
	},

	setMinDate:	function(minDate){
		//trace('settin min value with ' + minDate);
	
		var tmp = this.parseDate(minDate);
		this.minDateDay		= tmp[0];
		this.minDateMonth	= tmp[1];
		this.minDateYear	= tmp[2];
		this.minDate		=  new Date(tmp[2], tmp[1]-1, tmp[0]);
	},

	isOutOfRange: function(from, to, current){
		if(
			current.getTime() < from.getTime() 
			|| current.getTime() > to.getTime()
		){
			return true;
		}		
		return false;
	},
	
	// -------------------------------------------------
	// it is specting a date with the format dd.mm.yyyy
	// returns an array with the day, month and year
	// -------------------------------------------------
	parseDate:	function(date){
		var tmp		= date.split('.');
		tmp[0]		= this.normalize(tmp[0]);
		tmp[1]		= this.normalize(tmp[1]);
		tmp[2]		= tmp[2];

		return tmp; 
	},

	// -------------------------------------------------
	// format a date with format 25.05.2007
	// return a date with format 20070525
	// -------------------------------------------------
	formatInputDate:	function(date){
		var tmp = this.parseDate(date);
		return (tmp[2].length==2?'20'+tmp[2]:tmp[2]) + tmp[1] + tmp[0];
	},

	// -------------------------------------------------
	// format a date with format 20070525
	// return a date with format 25.05.2007
	// -------------------------------------------------
	formatDateStamp:	function(date){
		var day 	= date.substr(6,2);
		var month 	= date.substr(4,2);
		var year 	= date.substr(0,4);

		return day + '.' + month + '.' + year;
	},

	// -------------------------------------------------
	// format a JS date
	// return a date with format 25.05.2007
	// -------------------------------------------------
	formatJSDate:	function(date){
		var year = date.getFullYear();
		var month = this.normalize(date.getMonth() + 1);     // integer, 0..11
		var day = this.normalize(date.getDate());      // integer, 1..31

		return day + '.' + month + '.' + year;
	},	

	// -------------------------------------------------
	// format a date with format 20070525
	// return a JS date
	// -------------------------------------------------
	formatToJSDate: function(date){
		tmp = this.parseDate(this.formatDateStamp(date));
		return new Date(tmp[2], tmp[1]-1, tmp[0]);
	},

	normalize: 		function(num){
		var tmp = '0' + num;
		return tmp.substr(tmp.length-2);
	},
	
	checkDate:		function(toCheck){
		//trace('checking date ... ' + toCheck);
		var tmp = this.parseDate(toCheck);
		return false;
	},
	
	/**
	 + ===================================================================================
	 * get available booking dates for TO requests
	 + -----------------------------------------------------------------------------------
	 * @param 	originCode, string(3)
	 * @param 	destinationCode, string(3)
	 * @param 	departure, string(8)
	 * @param 	arrival, string(8)
	 + ================================================================================ */
	getVariableDatesTOAvailableDates: function(originCode, destinationCode, departure, arrival){
		if(LUXAIR.wasSubmitted && routeList.isTourOperator(originCode, destinationCode)){
			//start waiting
			LUXAIR.startWaiting('labmSection1DepartingWait', 'labmShowWaitingIcon');
			LUXAIR.startWaiting('labmSection1ReturningWait', 'labmShowWaitingIcon');

			var origin = originCode;
			var destination = destinationCode;
			
			//perform the request to the server
    		var parameters = {};
			    query_string = "&ajaxRequest=1" +
	                       "&functionID=getTOAvailableDates" +
			                   "&departureDate=" + departure + 
			                   "&returnDate=" + arrival + 
			                   "&originCode=" + originCode + 
			                   "&destinationCode=" + destinationCode + 
			                   "";

        completeUrl = document.location + query_string;

    		new Ajax.Request(
    			completeUrl, 
    			{
    				//asynchronous: false,
    		  		method: 	"post",
    		  		parameters:	parameters,
    				onComplete: LUXAIR.handleTOAvailableDates
    				//onException:function(transport, error){alert(error);}
    			}
    		);	

			//cache the origin and destination
			this.cachedOrigin 	= origin;
			this.cachedDestination 	= destination;
		}
	}
}

// ================================================
// FIRST MINUTE HELPERS
// ================================================
LUXAIR.getContentLanguage = function(){
	var curURL = document.location.href;
	//search the language
	//case IdLanguage 
	var lookFor1 = /IdLanguage=(.{2})/i;
	var lookFor2 = /p=(.{2})/i;
	var ret = curURL.match(lookFor1)
	if(ret){
	
	}else{
		ret = curURL.match(lookFor2)	;
	}
	
	if(ret){
		return ret[1];
	}else{
		return 'EN';
	}
}

/**
 + ===================================================================================
 * set the wait icon in one specific element ID
 + -----------------------------------------------------------------------------------
 * 
 + -----------------------------------------------------------------------------------
 * @param waitID, id of the wait element
 + ================================================================================ */
LUXAIR.startWaiting = function(waitID, className){
	if($(waitID)!=null){
		$(waitID).className = className!=null?className:'show';
	}
}

/**
 + ===================================================================================
 * clean and stop waiting
 + -----------------------------------------------------------------------------------
 * 
 + -----------------------------------------------------------------------------------
 * @param target, id of the target element
 * @param waitID, id of the wait element
 + ================================================================================ */
LUXAIR.stopWaiting = function(waitID){
	if($(waitID)!=null){
		$(waitID).className = 'hidden';
	}
}

/**
 + ===================================================================================
 * this function will be called the moment the TO available dates finish loading
 + -----------------------------------------------------------------------------------
 * @param 	departures, departures | returs
 * @param 	originCode, string(3)
 * @param 	destinationCode, string(3)
 + ================================================================================ */

LUXAIR.handleTOAvailableDates = function(transport){
	var departure = $("frmDeparture");
	var arrival = $("frmArrival");
	var departureHidden = $("frmDepartureHidden");
	var arrivalHidden = $("frmArrivalHidden");
	var origin = $("origin");
	var destination = $("destination");

	var departureOK = false;
	var arrivalOK = false;

	eval("var tmp=" + transport.responseText);

	if(tmp!=null){
		//set the new list of orignes and destinations
		LUXAIR.fMAvailableDatesOrigin=tmp['origin'];
		LUXAIR.fMAvailableDatesDestination=tmp['destination'];
		
		//set the initial values of the frmDeparture and frmArrival
		//we get everytime the closest avilable for: 
	
		//frmDeparture, get the next available fly in the future
		var curDeparture = LUXAIR.dateHandler.formatInputDate(departure.value);
		var firstDeparture = '';
		var goDirectDeparture = 0;
		for(var checkDate in LUXAIR.fMAvailableDatesOrigin){
			if(checkDate>=curDeparture){
				if(checkDate==curDeparture)goDirectDeparture = 1;
				firstDeparture = checkDate;
				break;
			}
		}
	
		//set the default value of frmDeparture
		if(firstDeparture!=null && firstDeparture!=''){
			if(departure!=null){
				departure.value = LUXAIR.dateHandler.formatDateStamp(firstDeparture);
				departureHidden.innerHTML = departure.value;
				departureOK = true;
			}			
		}
		
		//frmArrival
		var goDirectArrival = 0;
		var curArrival = LUXAIR.dateHandler.formatInputDate(arrival.value);
		var firstArrival = '';
		for(var checkDate in LUXAIR.fMAvailableDatesDestination){
			if(checkDate>=curArrival){
				if(checkDate==curArrival)goDirectArrival = 1;
				firstArrival = checkDate;
				break;
			}
		}
	
		//set the default value of frmArrival
		if(firstArrival!=null && firstArrival!=''){
			if(arrival!=null){
				arrival.value = LUXAIR.dateHandler.formatDateStamp(firstArrival);
				arrivalHidden.innerHTML = arrival.value;
				arrivalOK = true;
			}			
		}
	}

	//clean the waittin status always
	LUXAIR.stopWaiting('labmSection1DepartingWait');
	LUXAIR.stopWaiting('labmSection1ReturningWait');


	//if no data were found, 
	//treat the fly like a normal amadeus fly
	if((!departureOK || !arrivalOK) || (goDirectDeparture && goDirectArrival)){
		//submit the request ... 
		LUXAIR.formCallAmadeusHandler(cmsAmadeusLink, bookingService, bookingServiceParams);

	}else{
	
		//configure the calendar 
		LUXAIR.setupDepartureCalendar('landspace', 'labmSection1DepartingCalendar', firstDeparture);
		LUXAIR.setupArrivalCalendar('landspace', 'labmSection1ReturningCalendar', firstArrival);
	}
}

/**
 + ===================================================================================
 * overview links wrapper
 + -----------------------------------------------------------------------------------
 * this function checks if there is a link inside possibleLink DIV element.  
 * if a valid link is present there, it will use it if not, it wil use default URL
 + -----------------------------------------------------------------------------------
 * @param 	defaultURL, string
 * @param 	possibleLink, ID of a hidden div containing the other link
 + ================================================================================ */
LUXAIR.handleOverviewLink = function(defaultURL, possibleLink, bypassLangCheck){
	var url = defaultURL;
	var link = $(possibleLink);
	if(link!=null){
		//check for a tags in the element
		var as = link.getElementsByTagName('a');
		if(as!=null && as.length>0){
			//get the first link in the list
			for(var i=0; i<1; i++){
				url = as[i].href;
			}
		}
	}

	var language = LUXAIR.getContentLanguage();
	var lookFor  = /p=(.{2})/i;

	//redirect the document
	if(url!=''){
		//correct the URL we need
		var newurl = url.replace(lookFor, 'p=' + language);
		if(bypassLangCheck==null || bypassLangCheck==false){
			window.document.location.href  = newurl;
		}else{
			window.document.location.href  = url;
		}
	}
	return true;
}

/**
 + ===================================================================================
 * check for valid dates
 + -----------------------------------------------------------------------------------
 * check if the passed date is a valid one
 + -----------------------------------------------------------------------------------
 * @param 	
 * @param 	
 + ================================================================================ */
var dtCh= ".";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear

	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)

	if (strYr.length == 2) {
		strYr = "20" + strYr;
	}
		
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)

	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length < 2 || strYear.length == 3 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
	return true
}

/**
 + ===================================================================================
 * configure image gallery
 + -----------------------------------------------------------------------------------
 * check if the passed date is a valid one
 + -----------------------------------------------------------------------------------
 * @param 	
 * @param 	
 + ================================================================================ */
LUXAIR.resortMediaLibraryImages = function(){
	var imageContainers = document.getElementsByClassName('imageContainer');
	if(imageContainers!=null && imageContainers.length>0){
		for(var i=0; i<imageContainers.length; i++){
			//get the images from this element	
			var images = imageContainers[i].getElementsByTagName('img');
			if(images!=null && images.length>0){
				for(var j=0; j<images.length; j++){
					//check the size of the image
					var height = images[j].getHeight() || images[j].height;
					var width = images[j].getWidth() || images[j].width;
					
					//portrait, 
					//rewrite the image class
					if(height>width){
						images[j].className = "landspace";
					}
				}
			}
		}
	}
}

LUXAIR.documentsToHandle = [3068, 3098, 3107, 6006, 7654];
LUXAIR.cachedImagesOn = {'EN': new Array(5), 'DE': new Array(5), 'FR': new Array(5)};
LUXAIR.cachedImagesOff = {'EN': new Array(5), 'DE': new Array(5), 'FR': new Array(5)};

/**
 + ===================================================================================
 * configure image gallery by adding the right rows div
 + -----------------------------------------------------------------------------------
 * check if the passed date is a valid one
 + -----------------------------------------------------------------------------------
 * @param 	
 * @param 	
 + ================================================================================ */
LUXAIR.correctImageLibraryDisplay = function() {
	var imageBoxes = document.getElementsByClassName('box1');
	var leftContent = document.getElementById('col-left');
	if(imageBoxes != null && imageBoxes.length > 0) {
		var template03Div = document.createElement("div"); 
		template03Div.setAttribute('class', 'template03'); 
		template03Div.setAttribute('className', 'template03'); 
		for(var i = 0; i < imageBoxes.length; i ++) {
			template03Div.appendChild(imageBoxes[i]);
			/* If we have a full line (4 images) or if we have the last image */
			if ((i + 1) % 4 == 0 || (i + 1) == imageBoxes.length) {
				leftContent.appendChild(template03Div);
				template03Div = document.createElement("div"); 
				template03Div.setAttribute('class', 'template03'); 
				template03Div.setAttribute('className', 'template03'); 
			}
		}
	}
}

/**
 + ===================================================================================
 * configure partners page
 + -----------------------------------------------------------------------------------
 * check if the passed date is a valid one
 + -----------------------------------------------------------------------------------
 * @param 	
 * @param 	
 + ================================================================================ */
LUXAIR.correctPartnersDisplay = function() {
	var partnerBoxes = document.getElementsByClassName('box2');
	var leftContent = document.getElementById('col-left');
	if(partnerBoxes != null && partnerBoxes.length > 0) {
		var template02Div = document.createElement("div"); 
		template02Div.setAttribute('class', 'template02'); 
		template03Div.setAttribute('className', 'template03'); 
		for(var i = 0; i < partnerBoxes.length; i ++) {
			template02Div.appendChild(partnerBoxes[i]);
			/* If we have a full line (2 partners) or if we have the last partner */
			if ((i + 1) % 2 == 0 || (i + 1) == partnerBoxes.length) {
				leftContent.appendChild(template02Div);
				template02Div = document.createElement("div"); 
				template02Div.setAttribute('class', 'template02'); 
				template03Div.setAttribute('className', 'template03'); 
			}
		}
	}
}


/**
 + ===================================================================================
 * configure the events for the home right boxes
 + ================================================================================ */
LUXAIR.handleRightBanners = function(event){
	var elem = $('rightColumn');
	if(elem!=null){
		var links = elem.getElementsByClassName('flexelemHOME_RIGHTIMGLink');
		if(links!=null){
			for(var i=0;i<links.length;i++){
				//alert('setting event in ' + links[i].className);
			    //Event.observe(links[i], "mouseover", LUXAIR.eventLinksMouseOver);
			    Event.observe(
			    	links[i], 
			    	"mouseover", 
			    	LUXAIR.eventLinksMouseOver.bindAsEventListener(
			    		LUXAIR.eventLinksMouseOver, 
			    		links[i]	
			    	)
			    )
			}
		}

		//init the images
		var languages = ['EN', 'DE', 'FR'];
		for(var i=0; i<LUXAIR.documentsToHandle.length; i++){
			for(var j=0; j<languages.length; j++){
				var imageNameOn = "./luxair/css_images/luxair_banner_" + languages[j] + '_' + i + '_on.jpg';
				var imageNameOff = "./luxair/css_images/luxair_banner_" + languages[j] + '_' + i + '_off.jpg';
				LUXAIR.cachedImagesOn[languages[j]][i] = new Image();
				LUXAIR.cachedImagesOn[languages[j]][i].src = imageNameOn;
				LUXAIR.cachedImagesOff[languages[j]][i] = new Image();
				LUXAIR.cachedImagesOff[languages[j]][i].src = imageNameOff;
			}
		}
	}	
}

/**
 + ===================================================================================
 * event function to handle links on mouse overs
 + -----------------------------------------------------------------------------------
 * @param event, this is the triggerd event 	
 + ================================================================================ */
LUXAIR.eventLinksMouseOver = function(event, link){
	var language = LUXAIR.getContentLanguage();
	//imgbackGroundImage5917
	for(var i=0; i<LUXAIR.documentsToHandle.length; i++){
		//get the images from this link
		var images =  link.getElementsByTagName('img');
		if(images!=null){
			var image = images[0];
			 
			if(image.id==("imgbackGroundImage" + LUXAIR.documentsToHandle[i])){
				image.src = LUXAIR.cachedImagesOn[language][i].src;
				LUXAIR.cleanSelection(LUXAIR.documentsToHandle[i]);
				break;
			}
		}
	}
}

LUXAIR.cleanSelection = function(selected){
	var language = LUXAIR.getContentLanguage();

	//imgbackGroundImage5917
	for(var i=0; i<LUXAIR.documentsToHandle.length; i++){
		if(selected != LUXAIR.documentsToHandle[i]){
			$("imgbackGroundImage" + LUXAIR.documentsToHandle[i]).src = LUXAIR.cachedImagesOff[language][i].src; 
		}
	}
}

LUXAIR.correctHomePageOffersDisplay = function() {
	var imageBoxes = document.getElementsByClassName('offerBox');
	if(imageBoxes != null && imageBoxes.length > 0) {
		var template03Div = document.createElement("div"); 
		template03Div.setAttribute('class', 'offerLine'); 
		template03Div.setAttribute('className', 'offerLine'); 
		var leftContent;
		for(var i = 0; i < imageBoxes.length; i ++) {					
			leftContent = imageBoxes[i].parentNode;			
			template03Div.appendChild(imageBoxes[i]);
			/* If we have a full line (4 images) or if we have the last image */
			if ((i + 1) % 2 == 0 || (i + 1) == imageBoxes.length) {	

				leftContent.appendChild(template03Div);
				template03Div = document.createElement("div"); 
				template03Div.setAttribute('class', 'offerLine'); 
				template03Div.setAttribute('className', 'offerLine');				
				template03Div.setAttribute('id', 'offerLine'+i); 			}
		}
	}
}
