// controls the UI behavior and its interaction with FlightSearchController
// displays the search dropdown
// @deprecated
function ShowSearchDropdown(TargetFieldName, PopUpLeftPosition, PopUpTopPosition){
	var SearchDropdown = document.getElementById("SearchDropdown");
	
	if(DropDownAlreadyOpened()){
	    HideSearchDropdown();
	    return false;
	}
	
	/* determine wether to show or hide several stations */
	var PreselectedStation = "";
	if(TargetFieldName == "Destination" || TargetFieldName == "LFCDestination"){
	    // activate the active destinations only
	    // when a specific origin has already been
	    // selected - the others should be grey
	    var OriginForm = document.getElementById("Origin");

	    if(TargetFieldName == "LFCDestination"){
		OriginForm = document.getElementById("LFCOrigin");
	    }

	    if(OriginForm){
	        if(OriginForm.value!=""){
	            PreselectedStation = OriginForm.value;
	        }
	    }
	}

    // Track the element click with OMTR
    setTimeout("trackElementClick('"+TargetFieldName+"Container','CompactSearch: "
                            +TargetFieldName+"-list opened')",10);

	if(SearchDropdown){
		// write all stations to the dropdown
		if(Stations!=null&&SortedStations!=null){
		    /* CODE OPTIMIZATION FIX:
		        theres a fix here that refers to
		        test where joining the strings in
		        an array is a little faster than
		        just concatinating the strings.
		    */
			var DropdownCode = new Array(200);
			var CodeBracketNumber = 0;
			
			// get the stations matching the searchterm
			var StationResults = GetMatchingStations("");
			var IsCologneDestination = false;
			
			// determine the amount of local airports
            var LocalAirportsCount = 0;
            for(var i=0;i<StationResults.length;i++){
                var CurrentStationCode = StationResults[i];
				var CurrentIsLocal = Stations[CurrentStationCode].islocal;
                if(CurrentIsLocal){LocalAirportsCount++;}
            }
            
            // when the local airport number is still 
            // null then hide the local airport
            // head text and show the internationals only
            if(LocalAirportsCount!=0){
                DropdownCode[CodeBracketNumber]
                        = "<div id='LocalStationsHead' class='StationHeadText'>"
						+ "<table style='width:100%;'><tr><td>"
			            + LocalAirportsText
						+ "</td><td style='text-align:right;padding-right:25px;'>"
						+ "<a href='#' onClick='HideSearchDropdown(); return false;'><img src='../../downloads/btn_close.gif' alt='[X]'></a></td></tr></table></div>";
			    CodeBracketNumber++;
            }
            			
			// now step thru all stations
			var RowStationId = 0;
			for(var i=0;i<StationResults.length;i++){
				var CurrentStationCode = StationResults[i];
				var CurrentStationName = Stations[CurrentStationCode].name;
				
				if(PreselectedStation!=""){
				    if(IsValidDestination(PreselectedStation,"CGN"))
				        {IsCologneDestination=true;}
				}
				
				if(i==LocalAirportsCount){
				    DropdownCode[CodeBracketNumber] = "<div class='StationHeadText'>" 
			                         + ForeignAirportsText + "</div>";
			        RowStationId = 0;
			        CodeBracketNumber++;
				}
			                                
			    var StationSelectEvent = "onclick='javascript:if(document.getElementById(\"InfoBoxLowfareCal\")) {ShowInfoBox();} SetStation(\"" 
				                            + TargetFieldName + "\",\"" 
				                            + CurrentStationCode + "\",\"" 
				                            + CurrentStationName + "\");' ";
			
			    var IEMouseOverWorkaround = "onmouseenter='javascript:if(OldColor==\"\"){OldColor=this.style.backgroundColor;"
                    + "this.style.backgroundColor=\"#ffec00\";}'"
                    + " onmouseout='javascript:this.style.backgroundColor=OldColor;'";
								
				if(PreselectedStation!=""){
				    if(IsValidDestination(PreselectedStation,CurrentStationCode)){
						DropdownCode[CodeBracketNumber] = "<div id='StationItem" + i 
						                    + "' class='StationItem sta" + i 
						                    + " rowsta" + RowStationId + "' " 
				                            + StationSelectEvent
                                            + IEMouseOverWorkaround + ">"
											+ CurrentStationName + "</div>";	
						CodeBracketNumber++;		
				    }else{
						DropdownCode[CodeBracketNumber] = "<div id='StationItem" + i 
						                    + "' class='InactiveStationItem sta" + i 
						                    + " rowsta" + RowStationId + "' "
				                            + IEMouseOverWorkaround + ">"
											+ CurrentStationName + "</div>";
						CodeBracketNumber++;
				    }
				}else{
				    // take every fourth element
				    DropdownCode[CodeBracketNumber] = "<div id='StationItem" + i 
				                            + "' class='StationItem sta" + i 
				                            + " rowsta" + RowStationId + "' " 
				                            + StationSelectEvent
				                            + IEMouseOverWorkaround + ">"
											+ CurrentStationName + "</div>";
					CodeBracketNumber++;
				}
				
				// dont add the separator to the most right element
				// which is the fourth element in each row, but all
				// the others do get the separator on the right side
				if((RowStationId+1) % 4 != 0){
				    DropdownCode[CodeBracketNumber] = "<div class='StationSeparator'>&nbsp;</div>";
				    CodeBracketNumber++;
				}
				
				// update the row station id
				RowStationId++;
			}
			
			// verify if we need to add an additional
			// link to the cologne bonn connection
			// website for other destinations
			if(IsCologneDestination
			    &&PreselectedStation!=""
			    && TargetFieldName == "Destination"){
			        // verify this is a valid destination for this route
		            DropdownCode[CodeBracketNumber] = "<div id='StationItemCBC' "
		                                    + "class='StationItem staCBC rowsta" 
		                                    + RowStationId + "' " 
			                                + " onclick='javascript:ShowCologneBonnWebsite();'>"
										    + CologneBonnConnectLabel + "</div>"; 
			        CodeBracketNumber++;  
			}
		}
		
		// now join the array and fill the target element
		SearchDropdown.innerHTML = DropdownCode.join("\n");

		// finally set its css style
		SearchDropdown.style.visibility = "visible";
		SearchDropdown.style.position = "absolute";
		SearchDropdown.style.left = PopUpLeftPosition+"px";
		SearchDropdown.style.top = PopUpTopPosition+"px";
	}
}

/*********** OMTR link tracking ******** 
 * this function is not described here */
function trackCBCRedirect(obj){
    var s=s_gi('germanwingscomprod');
    s.linkTrackVars='None';
    s.linkTrackEvents='None';
    s.tl(obj,'e','CompactSearch Link: Cologne-Bonn-Connect');    
}

/*********** OMTR link tracking ******** 
 * this function is not described here */
function trackElementClick(ElementId, ElementTrackName){
    var s=s_gi('germanwingscomprod');
    s.linkTrackVars='None';
    s.linkTrackEvents='None';
    s.tl(document.getElementById(ElementId),'o',ElementTrackName);     
}

// refers to the cologne bonn connect
// website which is linked when cologne
// is a destination of the current origin
// @deprecated
function ShowCologneBonnWebsite(){
    var DoRedirect = false;
    var LanguageId = 2;
    DoRedirect = confirm(CologneBonnConnectPrompt.replace(/<BR>/g,"\n")); 
    
    if(CurrentCompactCulture.toLowerCase()=="de-de"){LanguageId=1;} 
    
    if(DoRedirect){
        window.open(CologneBonnConnectURL+"?pid=1&from="
                    +document.getElementById("Origin").value
                    +"&lang="+LanguageId, "CBCWindow");
        // tell OMTR we're passing to CBC website
        trackCBCRedirect(document.getElementById("StationItemCBC"));
        ResetDestinationStationSelection();
    }      
}

// displays a popup window
// with the passenger information
// especially for children and
// infants
function ShowUnderagePaxInfo(){
    // open the pax info window
    window.open('/skysales/html/' 
                + CurrentCompactCulture.substring(0,2) 
                + '/child.html',
                'Germanwings',
                'left=20,top=20,width=500,'
                + 'height=358,scrollbars=0,'
                +'status=0,toolbar=0,resizable=0');
}

// OldColor variable required by the station list
// for a javascript IE6 hightlighting workaround
// that is normally done by css in modern browsers.
var OldColor = "";

/* Calendar functions for the YUI stuff */
var CurrentActiveDateField = "";

var TodaysDateObj = new Date();
var CalendarStartDate = (TodaysDateObj.getMonth()+1) 
                      + "/" + TodaysDateObj.getFullYear();
var SelectedOutwardDate = null;
                      
var gwDynCalendar;

// this method pre-renders the calendar
function PreRenderCalendar(){
    gwDynCalendar = new YAHOO.widget.CalendarGroup
                ("yCalendar","CalendarContainer", 
                { pages:3, title:"", close:false } );

    localizeCalendar(gwDynCalendar);
	
    // registers the hover handlers when its rendered
    gwDynCalendar.changePageEvent.subscribe(RegisterDaySelectorsEventsAsync);
    gwDynCalendar.render();
	
    /// initially call the renderer
    RegisterDaySelectorsEventsAsync();	
    
    // subscribe the calendars event to my handler-function
    gwDynCalendar.selectEvent.subscribe(SelectDate, gwDynCalendar, true); 
    
    // finally render the month quick access
    RenderQuickMonthAccess();
}

// this function renders the quick month
// access below the actual calendar object
function RenderQuickMonthAccess(){
    // it starts from the current month
    // and shows 14 months.
    var QuickMonthContainer = document.getElementById
                                ("CalendarQuickMonth");
    var CurrentMonth = TodaysDateObj.getMonth();   
    var CurrentYear = TodaysDateObj.getFullYear();                       
    var MonthCodeBrackets = new Array();
    var MonthCodeBracketNum = 0;
    
    MonthCodeBrackets[MonthCodeBracketNum] 
            = "<table cellspacing='1' cellpadding='2'><tr>";
    MonthCodeBracketNum++;
    
    for(var m=0; m<14; m++){
        // start from the beginning if one year is full
        if(CurrentMonth==12){CurrentMonth=0;CurrentYear++;}
        if(m==7){
            MonthCodeBrackets[MonthCodeBracketNum] = "</tr><tr>";
            MonthCodeBracketNum++;
        }
        MonthCodeBrackets[MonthCodeBracketNum] 
                             = "<td id='QuickMonth" + CurrentMonth 
                             + "_" + CurrentYear + "' class='QuickMonthEntry'>"
                             + "<a href='#' onclick='javascript:SetCalendarMonth("
                             + CurrentMonth + "," + CurrentYear + ");'>"
                             + LocalizedShortMonths[CurrentMonth]
                             + "&nbsp;" + CurrentYear
                             + "</a></td>";
        MonthCodeBracketNum++;
        CurrentMonth++;
    }
    
    MonthCodeBrackets[MonthCodeBracketNum] 
            = "</tr></table>";
    MonthCodeBracketNum++;
    
    // finally join the array and flush it to the document
    QuickMonthContainer.innerHTML = MonthCodeBrackets.join("\n");
    setTimeout("MarkCurrentMonthsInQuickMonth()",100);
}


// not currently in use
function MarkCurrentMonthsInQuickMonth(){
    var Months = new Array();
    Months[0] = gwDynCalendar.pages[0].getDateByCellId("yCalendar_0_cell20");
    Months[1] = gwDynCalendar.pages[1].getDateByCellId("yCalendar_1_cell20");
    Months[2] = gwDynCalendar.pages[2].getDateByCellId("yCalendar_2_cell20");
    
    for(var i=0; i<Months.length; i++){
        var CurrentQuickMonth = document.getElementById
            ("QuickMonth"+Months[i].getMonth()+"_"+Months[i].getFullYear());
            
        if(CurrentQuickMonth){
            CurrentQuickMonth.style.backgroundColor = "#e8e8e8";
        }
    }
}

// sets the new month for the calendar
// which has been selected in the quick
// month selection menu below the calendar
function SetCalendarMonth(newMonth,newYear){
    gwDynCalendar.setMonth(newMonth);
    gwDynCalendar.setYear(newYear);
    
	// call the calendar refresh now 
	// (PERFORMANCE-OPTIMIZED METHOD)
	// ASYNC CALL FOR IMPROVING UI SPEED
	setTimeout("RefreshCalendarObject()",0);
	setTimeout("RenderQuickMonthAccess()",100);
}
	                    
function ShowCalendar(TargetElement, PositionLeft, PositionTop){
    // check if the calendar is already there and if so
    // hide it to keep a real dropdown functionality
    var PopUpControl = document.getElementById("CalendarPopUp");
    if(PopUpControl.style.visibility == "visible"){
        PopUpControl.style.visibility = "hidden";
        return false;
    }
    
    // dont show the calendar for the return flight dropdown
    // list if it has been disabled by the oneway selection
    if(TargetElement == "Return"
        && document.getElementById
            ("TripTypeOneWayRadio").checked == true){
        return false;
    }
    
    // if the outward date is selected
    // set the minimum date to today
    if(TargetElement=="Outward"){
        var currTodayDate = new Date();
	    MinimumDate = (currTodayDate.getMonth()+1) 
	                    + "/" + currTodayDate.getDate()
	                    + "/" + currTodayDate.getFullYear();
	}
	
	// define the current active field
	CurrentActiveDateField = TargetElement;
    
    // check for the active instance
    // and instanciate if the pre-render
    // function was unable to create it
    if(!gwDynCalendar){
	    PreRenderCalendar();
	}else{
	    gwDynCalendar.setMonth(CalendarStartDate.substring(0,CalendarStartDate.indexOf("/"))-1);
	    gwDynCalendar.setYear(CalendarStartDate.substring(CalendarStartDate.indexOf("/")+1));
	}
	
	var CalendarHeadText = document.getElementById("CalendarHeadText");
	if(TargetElement=="Outward"){CalendarHeadText.innerHTML = CalendarHeadOutbound;}
	if(TargetElement=="Return"){CalendarHeadText.innerHTML = CalendarHeadReturn;}
	
	// show the calendar container
	var PopUpControl = document.getElementById("CalendarPopUp");
	PopUpControl.style.visibility = "visible";
	PopUpControl.style.left = PositionLeft+"px";
	PopUpControl.style.top = PositionTop+"px";

	// call the calendar refresh now 
	// (PERFORMANCE-OPTIMIZED METHOD)
	// ASYNC CALL FOR IMPROVING UI SPEED
	setTimeout("RefreshCalendarObject()",0);
	
	// Track the element click with OMTR
    setTimeout("trackElementClick('CalendarPopUp','CompactSearch: "
                            +TargetElement+"-calendar opened')",10);
}

// this method handles a date-select on the calendar
function SelectDate(type,args,obj) {
	var dates = args[0];
	var date = dates[0];
	var year = date[0], month = date[1], day = date[2];

    var FormField = document.getElementById(CurrentActiveDateField+"Date");
    var TextField = document.getElementById(CurrentActiveDateField+"DateField");

	TextField.innerHTML = day + ". " + LocalizedMonths[(month-1)] + " " + year;
	FormField.value = day + "." + month + "." + year;
	
    var dateField = $( CurrentActiveDateField + 'DateField' );
    dateField.style.backgroundImage = "url('/images/maincontent/compactsearch/searchfield.jpg')";
    
	// set the minimum date to the selected
	// outward date as return flights have
	// to be after the outward flight.
	if(CurrentActiveDateField=="Outward"){
	    MinimumDate = month + "/" + day + "/" + year;
	    CalendarStartDate = month + "/" + year;
	    SelectedOutwardDate = month + "/" + day + "/" + year;
	}
	
	// finally hide the calendars
	var PopUpControl = document.getElementById("CalendarPopUp");
	PopUpControl.style.visibility = "hidden";
	
	// call the calendar refresh now 
	// (PERFORMANCE-OPTIMIZED METHOD)
	// ASYNC CALL FOR IMPROVING UI SPEED
	setTimeout("RefreshCalendarObject()",0);
}

function RefreshCalendarObject(){
    gwDynCalendar.cfg.setProperty("mindate",new Date(MinimumDate));
    gwDynCalendar.cfg.setProperty("maxdate",new Date(MaximumDate));
    if(SelectedOutwardDate!=null){
        gwDynCalendar.cfg.setProperty("selected",
	        SelectedOutwardDate+"-"+SelectedOutwardDate);
	        
	    // refresh the calendar if its 
	    // for the outward flight
	    // (PERFORMANCE-OPTIMIZED METHOD)
	    // ASYNC CALL FOR IMPROVING UI SPEED
	    RegisterDaySelectorsEventsAsync();
	}
    gwDynCalendar.render();
}

// calls the function below async
var CurrentSrcElement;
var RangeRendererActive = false;
function MarkTripDateRangeInCalendarAsync(evt){
    // set the event object when its 
    // not set in any circiumstances.
    if (!evt){evt = window.event;}

    var eSrcElement;
    if(evt.target){
        eSrcElement = evt.target;
    }if(evt.srcElement){
        eSrcElement = evt.srcElement;
    }
    
    // call the core function now
    CurrentSrcElement = eSrcElement;
    if(!RangeRendererActive){
        setTimeout("MarkTripDateRangeInCalendar()",10);
        RangeRendererActive=true;
    }
}

// this function marks the date range
// in the calendar when the customer
// picks his return flight in the search
function MarkTripDateRangeInCalendar(){   
    // only do this funny stuff when 
    // we're in the return flight selection
    if(CurrentActiveDateField=="Outward"){return false;}

    // is passed by the async handler
    var Source = CurrentSrcElement;
    
    // check if its the link and if so
    // use the parent element which is
    // the current day container
    if(Source.className == "selector"){
        Source = Source.parentNode;
    }
    
    var StartingCell = "yCalendar_0_cell0";
    var SelectedCell = GetSelectedDateObject().id;
    if(SelectedCell){StartingCell=SelectedCell;}
    
    // determine starting calendar and cell
    var StartCalendarNumber = StartingCell.substring
        ((StartingCell.indexOf("_")+1),
        (StartingCell.lastIndexOf("_")));
    var StartCellNumber = StartingCell.substring
        ((StartingCell.indexOf("cell")+4));
        
    var TargetCell = Source.id;
    
    // determine target calendar and cell
    var TargetCalendarNumber = TargetCell.substring
        ((TargetCell.indexOf("_")+1),
        (TargetCell.lastIndexOf("_")));
    var TargetCellNumber = TargetCell.substring
        ((TargetCell.indexOf("cell")+4));
            
    // step thru all elements between the starting
    // element and the target element and mark them
    for(var c=0; c<34; c++){
        for(var d=0; d<43; d++){
            var ElementIdSum = c + "0" + d;
            if(d<10){ElementIdSum = c + "00" + d; }  
            var StartIdSum = StartCalendarNumber + "0" + StartCellNumber;
            if(StartCellNumber<10){StartIdSum = StartCalendarNumber + "00" + StartCellNumber;} 
            var TargetIdSum = TargetCalendarNumber + "0" + TargetCellNumber;
            if(TargetCellNumber<10){TargetIdSum = TargetCalendarNumber + "00" + TargetCellNumber;}
            
            // get the instance of the current cell
            var CurrentCellName = "yCalendar_" + c + "_cell" + d;
            var CurrentCell = document.getElementById(CurrentCellName);
                
            // dont catch disabled fields
            if(CurrentCell){
                if(CurrentCell.className.indexOf("oom")<0
                    && CurrentCell.className.indexOf("previous")<0){
                    if(ElementIdSum>StartIdSum&&ElementIdSum<TargetIdSum){                
                        // field is in the timeframe
                        CurrentCell.style.backgroundColor = "#EDE9BA";
                    }else{
                        // reset the cell when its not marked
                        CurrentCell.style.backgroundColor = "#E8E8E8";
                    }
                    
                    // mark the current target
                    if(ElementIdSum==TargetIdSum){ 
                        // this field is allowed, just reset it
                        CurrentCell.style.backgroundColor = "#FFEC00";
                    }
                }
            }
        }
    }
 
    // reset the async thread activity indicator
    RangeRendererActive=false;
}

// returns the cell of the selected
// date in if there's none it simply
// returns false.
function GetSelectedDateObject(){
    // step thru each day element
    // and look for the selected
    // classname in it
    for(var c=0; c<3; c++){
        for(var d=0; d<43; d++){
            var CurrentCellName = "yCalendar_" + c + "_cell" + d;
            if(document.getElementById(CurrentCellName)){
                if(document.getElementById(CurrentCellName)
                    .className.indexOf("selected")>0){
                    return document.getElementById(CurrentCellName);    
                }
            }
        }
    }
    
    // return false, when not found
    return false;
}

// same as the function below but called
// in an asynchronous context
function RegisterDaySelectorsEventsAsync(){
    setTimeout("RenderQuickMonthAccess()",0);
    // setTimeout("RegisterDaySelectorsEvents()",0);
}

// registers the two handlers above for
// the day selectors in the calendar
function RegisterDaySelectorsEvents(){
    // step thru each day element and
    // register it for the handlers
    for(var c=0; c<3; c++){
        for(var d=0; d<43; d++){
            var CurrentCellName = "yCalendar_" + c + "_cell" + d;
            if(document.getElementById(CurrentCellName)){
                document.getElementById(CurrentCellName)
                    .onmouseover = MarkTripDateRangeInCalendarAsync;
                
                // also mark the link subelement
                var SelectorElements = document.getElementsByTagName('a');
                for(var t=0; t<SelectorElements.length; t++){
                    if(SelectorElements[t].className == "selector"){
                        SelectorElements[t].onmouseover = MarkTripDateRangeInCalendarAsync;
                    }
                }
            }
        }
    }
}

// temporary method that translates
// the calendar to german language
function TranslateCalendarToGerman(CalendarObject){
	CalendarObject.cfg.setProperty("DATE_FIELD_DELIMITER", ".");

    CalendarObject.cfg.setProperty("START_WEEKDAY", 1);
	CalendarObject.cfg.setProperty("MDY_DAY_POSITION", 1);
	CalendarObject.cfg.setProperty("MDY_MONTH_POSITION", 2);
	CalendarObject.cfg.setProperty("MDY_YEAR_POSITION", 3);

	CalendarObject.cfg.setProperty("MD_DAY_POSITION", 1);
	CalendarObject.cfg.setProperty("MD_MONTH_POSITION", 2);
	CalendarObject.cfg.setProperty("HIDE_BLANK_WEEKS",true);

	// Date labels for German locale

	CalendarObject.cfg.setProperty("MONTHS_SHORT",   ["Jan", "Feb", "M&auml;r", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"]);
	CalendarObject.cfg.setProperty("MONTHS_LONG",    ["Januar", "Februar", "M&auml;rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]);
	CalendarObject.cfg.setProperty("WEEKDAYS_1CHAR", ["S", "M", "D", "M", "D", "F", "S"]);
	CalendarObject.cfg.setProperty("WEEKDAYS_SHORT", ["<div class='WeekendDayHead'>So</div>", "Mo", "Di", "Mi", "Do", "Fr", "<div class='WeekendDayHead'>Sa</div>"]);
	CalendarObject.cfg.setProperty("WEEKDAYS_MEDIUM",["<div class='WeekendDayHead'>Son</div>", "Mon", "Die", "Mit", "Don", "Fre", "<div class='WeekendDayHead'>Sam</div>"]);
	CalendarObject.cfg.setProperty("WEEKDAYS_LONG",  ["<div class='WeekendDayHead'>Sonntag</div>", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "<div class='WeekendDayHead'>Samstag</div>"]);
}

// this function simply hides that thing
function HideSearchDropdown(){
    var SearchDropdown = document.getElementById("SearchDropdown");
    if(SearchDropdown){
        SearchDropdown.style.visibility = "hidden";
    }
}

// checks wether the dropdown list is open or not
function DropDownAlreadyOpened(){
    var SearchDropdown = document.getElementById("SearchDropdown");
    if(SearchDropdown){
        if(SearchDropdown.style.visibility == "hidden"){
            return false;
        }else{
            return true;
        }
    }else{
        return false;
    }
}

// for a specific station this method tells
// you wether it's a valid destination or not
function IsValidDestination(OriginStation, DestinationStation){
    var IsValid = false;
    if(Stations!=null){
        for(i=0;i<Stations[OriginStation].mkts.length;i++){
            if(Stations[OriginStation].mkts[i]==DestinationStation){
                IsValid = true;
            }
        }
    }
    
    return IsValid;
}

/* set the station selected in the dropdown popup */
// @deprecated
function SetStation(SelectedField, StationCode, StationName){
    // instantiate the fields for to fill the values
    var FormField = document.getElementById(SelectedField);
    var TextField = document.getElementById(SelectedField + "Text");
    
    // set the field values for the selected option
    FormField.value = StationCode;
    TextField.innerHTML = StationName;
    
    var stationField = $( SelectedField + 'Container' );
    stationField.style.backgroundImage = "url('/images/maincontent/compactsearch/searchfield.jpg')";
    
    if(SelectedField == "Origin")
        {ResetDestinationStationSelection();}
    
    // finally hide the dropdown when user selected his option
    HideSearchDropdown();
}

// this function starts the flight search
// by using the flight search controller
// that is also linked to the search ui
function PerformFlightSearch(Culture){
    var cult = Culture || "de-DE";

    // Track the element click with OMTR
    trackElementClick("FlightSearchButton","CompactSearch: Flightsearch clicked");

    // pick the flight info values
    var OriginValue = document.getElementById("Origin").value;
    var DestinationValue = document.getElementById("Destination").value;
    var OutwardDateValue = document.getElementById("OutwardDate").value;
    var ReturnDateValue = document.getElementById("ReturnDate").value;
    var DateFlexibilityValue = "2|4";
    
    // define the passengers
    var AdultCountValue = document.getElementById("AdultPaxCount").innerHTML;
    var ChildCountValue = document.getElementById("ChildPaxCount").innerHTML;
    var InfantCountValue = document.getElementById("InfantPaxCount").innerHTML;
    
    // regular and flexible fares
    var FareTypesValue = "R,F";
    
    var TravelTypeValue = "OneWay";
    if(document.getElementById("TripTypeRoundTripRadio").checked){
        TravelTypeValue = "RoundTrip";
    }
    
    var originField      = $( 'OriginText' );
    var destinationField = $( 'DestinationText' );
    var outwardDateField = $( 'OutwardDateField' );
    var returnDateField  = $( 'ReturnDateField' );
    
    outwardDateField.style.backgroundImage = "url('/images/maincontent/compactsearch/searchfield.jpg')";
    
    if ( TravelTypeValue == "OneWay" ) {
        returnDateField.style.backgroundImage  = "url('/images/maincontent/compactsearch/searchfield_disabled.jpg')";
    } else {
        returnDateField.style.backgroundImage  = "url('/images/maincontent/compactsearch/searchfield.jpg')";
    }
    Element.removeClassName( $( 'OriginAutocompleteContainer' ), 'inputError' );
    Element.removeClassName( $( 'DestinationAutocompleteContainer' ), 'inputError' );
    
    var hasError = false;
   
    // if the form field is empty but the input field seems to contain a three letter code, use it!
    if ( ( OriginValue == null || OriginValue == '' ) && originField.value != null && originField.value.length == 3 ) {
        OriginValue = originField.value.toUpperCase();
    }

    // if the form field is empty but the input field seems to contain a three letter code, use it!
    if ( ( DestinationValue == null || DestinationValue == '' ) && destinationField.value != null && destinationField.value.length == 3 ) {
        DestinationValue = destinationField.value.toUpperCase();
    }

    if ( OriginValue == null || OriginValue == '' ) {
        hasError = true;
        Element.addClassName( $( 'OriginAutocompleteContainer' ), 'inputError' );
    }
    
    if ( DestinationValue == null || DestinationValue == '' ) {
        hasError = true;
        Element.addClassName( $( 'DestinationAutocompleteContainer' ), 'inputError' );
    }
    
    if ( OutwardDateValue == null || OutwardDateValue == '' ) {
        outwardDateField.style.backgroundImage = "url('/images/maincontent/compactsearch/searchfield_error.jpg')";
        hasError = true;
    }
        
    if ( TravelTypeValue == "RoundTrip" && ( ReturnDateValue == null || ReturnDateValue == '' ) ) {
        returnDateField.style.backgroundImage = "url('/images/maincontent/compactsearch/searchfield_error.jpg')";
        hasError = true;
    }
    
    if ( hasError ) {
        return;
    }
	   
    var ok     = "OK";
    var cancel = "Abbrechen";
    
    // localize the text
    if ( typeof OkButtonLabel != "undefined" && OkButtonLabel != null ) {
      ok = OkButtonLabel;
    }

    if ( typeof CancelButtonLabel != "undefined" && CancelButtonLabel != null ) {
      cancel = CancelButtonLabel;
    }

    var callbacks = {
      "2A": function() {
        this.hide();
        var ViaStation = GetViaStationByRoute( OriginValue, DestinationValue );
        SearchFlights( ViaStation, DestinationValue, OutwardDateValue, ReturnDateValue, 
                 DateFlexibilityValue, AdultCountValue, ChildCountValue, InfantCountValue,
                 FareTypesValue, TravelTypeValue, cult );
      },
      "2AA": function() {
        this.hide();
        var ViaStation = GetViaStationByRoute( OriginValue, DestinationValue );
        SearchFlights( OriginValue, ViaStation, OutwardDateValue, ReturnDateValue, 
                 DateFlexibilityValue, AdultCountValue, ChildCountValue, InfantCountValue,
                 FareTypesValue, TravelTypeValue, cult );
      },
      "WW": function() {
        this.hide();        
        SearchWWFlights( OriginValue, DestinationValue, OutwardDateValue, ReturnDateValue, 
					               DateFlexibilityValue, AdultCountValue, ChildCountValue, InfantCountValue,
					               FareTypesValue, TravelTypeValue, cult );
      },
      "VY": function() {
        this.hide();
        SearchVYFlights( OriginValue, DestinationValue, OutwardDateValue, ReturnDateValue, 
					               DateFlexibilityValue, AdultCountValue, ChildCountValue, InfantCountValue,
					               FareTypesValue, TravelTypeValue, cult );
      },
      "DE": function() {
        this.hide();
        SearchDEFlights( OriginValue, DestinationValue, OutwardDateValue, ReturnDateValue, 
					               DateFlexibilityValue, AdultCountValue, ChildCountValue, InfantCountValue,
					               FareTypesValue, TravelTypeValue, cult );
      },
      "CBC": function() {
        this.hide();
        
        var LanguageId = 2;
        
        if ( CurrentCompactCulture.toLowerCase() == "de-de" ) { 
          LanguageId = 1; 
        }
    
        window.open(CologneBonnConnectURL+"?pid=1&from="
                    +document.getElementById("Origin").value
                    +"&lang="+LanguageId, "CBCWindow");
        // tell OMTR we're passing to CBC website
        trackCBCRedirect(document.getElementById("StationItemCBC"));
      }
    }
    
    if( !FlightSearchMessages.OtherAirline( OriginValue, DestinationValue, ok,
      cancel, callbacks, '/images/rail_and_fly.gif' ) ) {
        if(OutwardDateValue != '' && typeof(todaysDateMessage) != 'undefined' && todaysDateMessage != '')
        {
            var outwardSplit = OutwardDateValue.split(".");
		    var outwardDateObj = Date.UTC(outwardSplit[2], outwardSplit[1], outwardSplit[0]);
		    var today = new Date();
            var todayDateObj = Date.UTC(today.getFullYear(), (today.getMonth()+1), today.getDate());
		    if (outwardDateObj==todayDateObj)
		    {
			    alert(todaysDateMessage);
		    }
		}
	    // start the search now
	    SearchFlights(OriginValue,DestinationValue,
                OutwardDateValue,ReturnDateValue,
                DateFlexibilityValue,AdultCountValue,
                ChildCountValue,InfantCountValue,
                FareTypesValue,TravelTypeValue,cult);
    }/*else{
        // search the other airline for that flight
        var OperatingAirline = GetAirlineCodeByRoute(OriginValue,DestinationValue);
                
        SearchOtherAirlineFlights(OperatingAirline,
                OriginValue,DestinationValue,
                OutwardDateValue,ReturnDateValue,
                DateFlexibilityValue,AdultCountValue,
                ChildCountValue,InfantCountValue,
                FareTypesValue,TravelTypeValue,cult);
    }*/
}

/* switch oneway and return flights with this function */
// newType can be "OneWay" or "RoundTrip"
function SwitchFlightType(newType){
    if(newType=="OneWay"){
        document.getElementById("ReturnDateField")
            .innerHTML = OneWayOnlyText;
        document.getElementById("ReturnDateField")
            .style.backgroundImage = "url('/images/maincontent/compactsearch/searchfield_disabled.jpg')";
        document.getElementById("ReturnDateField")
            .style.color = "#e0e0e0";
        $( 'ReturnDate' ).value = '';
    }else{
        document.getElementById("ReturnDateField")
            .innerHTML = ReturnFlightText;
        document.getElementById("ReturnDateField")
            .style.backgroundImage = "url('/images/maincontent/compactsearch/searchfield.jpg')";
        document.getElementById("ReturnDateField")
            .style.color = "#666666";
    }
}

// define the current active pax-field
var ActivePaxField = "";

// this function shows the pax dropdown
// list where the user picks the number
// of passengers to book tickets for.
function ShowPaxDropdown(TargetElement,PositionLeft,PositionTop){
    var PaxDropdown = document.getElementById("PaxCountDropdown");
    
    PaxDropdown.style.left = PositionLeft + "px";
    PaxDropdown.style.top = PositionTop + "px";
    
    // check which style is active
    if(PaxDropdown.style.visibility == "visible"){
       PaxDropdown.style.visibility = "hidden";
    }else{
        PaxDropdown.style.visibility = "visible";
    }
    
    // update the active pax-field
    ActivePaxField = TargetElement + "PaxCount";
}

function SetPaxCount(NumberOfPax){
    var PaxDropdown = document.getElementById
                        ("PaxCountDropdown");
    PaxDropdown.style.visibility = "hidden";
    
    document.getElementById(ActivePaxField)
                    .innerHTML = NumberOfPax;
}

/* AddOn functions that determine the absolute position */
function GetAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

function GetAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}
