﻿﻿YAHOO.namespace("aerlingus.options.priorityAirports");
YAHOO.namespace("aerlingus.ie6Utils");
YAHOO.namespace("aerlingus.options");
YAHOO.namespace("aerlingus.searchType");
YAHOO.namespace("aerlingus.fareCategory");
YAHOO.namespace("aerlingus.options.autoComplete");
YAHOO.namespace("aerlingus.options.sort");
YAHOO.namespace("aerlingus.promotionalFlights");
YAHOO.namespace("aerlingus.calendar");

//This Value is set on jsp pages as it is req'd to be localised
//var ALL_COUNTRIES_TITLE = 'All Countries';
var ALL_COUNTRIES_VALUE = 'All',
 DESTINATION_OPTIONS = [],
 ALL_OPTIONS = [],
 OUTER_ORIGIN_PANEL = 'pnlOrigin',
 OUTER_DESTINATION_PANEL = 'pnlDestination',
 ORIGIN_COUNTRY_SELECT_ELEMENT = 'sltOriginCountries',
 DESTINATION_COUNTRY_SELECT_ELEMENT = 'sltDestinationCountries',
 OUTER_ORIGIN_RESULTS_PANEL = 'pnlOriginResults',
 OUTER_DESTINATION_RESULTS_PANEL = 'pnlDestinationResults',
 ORIGIN_AIRPORT_RESULTS_PANEL = 'pnlOriginAirports',
 DESTINATION_AIRPORT_RESULTS_PANEL = 'pnlDestinationAirports',
 ORIGIN_SEARCH_ELEMENT = 'txtOriginSearch',
 DESTINATION_SEARCH_ELEMENT = 'txtDestinationSearch',
 ORIGIN_DROP_BUTTON = 'btnOriginDrop',
 DESTINATION_DROP_BUTTON = 'btnDestinationDrop',
 ORIGIN_LOADING_PANEL = 'pnlLoadingOrigin',
 DESTINATION_LOADING_PANEL = 'pnlLoadingDestination',
 ORIGIN_NO_DATA = false,
 DESTINATION_NO_DATA = false,
 ORIGIN = 'Origin',
 DESTINATION = 'Destination',
 AUTO_COMPLETE_ORIGIN_DATA = [],
 AUTO_COMPLETE_DESTINATION_DATA = [],
 AUTOCOMPORIGININSTANCE,
 AUTOCOMPDESTINATIONINSTANCE,
 HIDDEN_ORIGIN_AIRPORT = 'selectedSourceAirport_1',
 HIDDEN_DESTINATION_AIRPORT = 'selectedDestinationAirport_1',
 AIRPORT_OPTIONS_FILE = CURRENT_LOCALE + '_airportOptions.jsp',
 CONTROLS_WRAPPER = 'pnlControlsWrapper',
 INVALID_ORIGIN_SEARCH_PANEL= 'pnlInvalidOriginSearch'
 INVALID_DESTINATION_SEARCH_PANEL= 'pnlInvalidDestinationSearch'
 TAB_KEYCODE = '9',
 SHIFT_KEYCODE = '16',
 COUNTRY_SELECT_ELEMENT = 'selectedWebdealsMarket',
 SEARCH_TYPE_BUTTON_PANEL = 'pnlSearchTypeButtons',
 PROMOTIONAL_FLIGHTS_BUTTON_PANEL = 'pnlPromotionalFlights',
 FARE_CATEGORY_SELECT_ELEMENT= 'selectedFareCategory',
 PRIORITY_PREFIX = 'PTY_',
 SCROLL_FOR_MORE_ID = 'SCR',
 CORPORATE_RATE_RADIO_ONE = '',
 CORPORATE_RATE_RADIO_TWO = '',
 SEARCH_TYPE_RADIO_ONE = '',
 SEARCH_TYPE_RADIO_TWO = '',
 RESET_DESTINATION_ELEMENT = 'resetDestinationAirports',
 RESET_ORIGIN_ELEMENT = 'resetOriginAirports',
 SELECTED_DEPARTURE_DAY = "selectedDay_1",
 SELECTED_DEPARTURE_MONTH = "selectedMonth_1",
 SELECTED_RETURN_DAY = "selectedDay_2",
 SELECTED_RETURN_MONTH = "selectedMonth_2",
 RETURN_TYPE = "selectedFlightTypeReturn",
 ONEWAY_TYPE = "selectedFlightTypeOneway",
 Dom = YAHOO.util.Dom,
 SHOW_DEPARTURE = "showDeparture",
 SHOW_RETURN = "showReturn",
 DEPARTURE_LABEL = "lblSelectedDay_1",
 RETURN_LABEL = "lblSelectedDay_2",
 NUM_CALENDAR_PAGES = 1,
 CHK_PROMO_CODE='chkPromoCode',
 TXT_PROMO_CODE='txtPromoCode',
 NONE = 'none',
 BLOCK = 'block',
 CALENDAR_DEPENDENCIES_LOADED = false;
 var businessRoutes = new Array("ABZJFK","AGPJFK","AMSBOS","AMSJFK","AMSMCO","AMSORD","ATLDUB","AUSDUB","AUSSNN","BCNBOS","BCNJFK","BHXBOS","BHXJFK","BHXMCO","BHXORD","BLKJFK","BNADUB","BOJJFK","BOSAMS","BOSBCN","BOSBHX","BOSBRS","BOSBRU","BOSCDG","BOSCWL","BOSDSA","BOSDUB","BOSDUS","BOSEDI","BOSFAO","BOSFRA","BOSGLA","BOSGVA","BOSLGW","BOSLHR","BOSLIN","BOSLIS","BOSMAD","BOSMAN","BOSMUC","BOSSNN","BQNDUB","BQNSNN","BRSBOS","BRSJFK","BRSMCO","BRSORD","BRUBOS","BRUJFK","BRUMCO","BRUORD","BTVDUB","BTVSNN","BUFDUB","BUFSNN","BURDUB","BURSNN","BWIDUB","BWISNN","CDGBOS","CDGJFK","CDGMCO","CDGORD","CLEDUB","CLTDUB","CLTSNN","CMHDUB","CVGDUB","CWLBOS","CWLJFK","CWLMCO","CWLORD","DCADUB","DCASNN","DENDUB","DFWDUB","DSABOS","DSAJFK","DTWDUB","DUBATL","DUBAUS","DUBBNA","DUBBOS","DUBBQN","DUBBTV","DUBBUF","DUBBUR","DUBBWI","DUBCLE","DUBCLT","DUBCMH","DUBCVG","DUBDEN","DUBDCA","DUBDFW","DUBDTW","DUBFLL","DUBHOU","DUBIAD","DUBIAH","DUBIND","DUBJAX","DUBJFK","DUBLAS","DUBLAX","DUBLEX","DUBLGB","DUBMCI","DUBMCO","DUBMIA","DUBMSP","DUBMSY","DUBOAK","DUBOMA","DUBORD","DUBPBI","DUBPDX","DUBPHX","DUBPIT","DUBPSE","DUBPWM","DUBRDU","DUBRIC","DUBROC","DUBRSW","DUBSAN","DUBSDF","DUBSEA","DUBSFO","DUBSJC","DUBSJU","DUBSLC","DUBSMF","DUBSTL","DUBSYR","DUBTPA","DUBYEG","DUBYVR","DUBYWG","DUBYYC","DUBYYZ","DUSBOS","DUSJFK","DUSORD","EDIBOS","EDIJFK","EDIMCO","EDIORD","FAOBOS","FAOJFK","FCOJFK","FLLDUB","FLLSNN","FRABOS","FRAJFK","FRAORD","GLABOS","GLAJFK","GLAMCO","GLAORD","GVABOS","GVAJFK","GVAORD","HOUDUB","HOUSNN","IADDUB","IADMAD","IADSNN","IAHDUB","INDDUB","JAXDUB","JAXSNN","JERJFK","JFKJER","JFKABZ","JFKAGP","JFKAMS","JFKBCN","JFKBHX","JFKBLK","JFKBOJ","JFKBRS","JFKBRU","JFKCDG","JFKCWL","JFKDSA","JFKDUB","JFKDUS","JFKEDI","JFKFAO","JFKFCO","JFKFRA","JFKGLA","JFKGVA","JFKKRK","JFKLGW","JFKLHR","JFKLIN","JFKLIS","JFKMAD","JFKMAN","JFKMUC","JFKNAP","JFKSNN","JFKSXF","JFKVCE","JFKVIE","JFKWAW","KRKJFK","LASDUB","LASSNN","LAXDUB","LAXSNN","LEXDUB","LGBDUB","LGBSNN","LGWBOS","LGWJFK","LGWMCO","LGWORD","LHRBOS","LHRJFK","LHRMCO","LHRORD","LINBOS","LINJFK","LISBOS","LISJFK","MADBOS","MADIAD","MADJFK","MANBOS","MANJFK","MANMCO","MANORD","MCIDUB","MCOAMS","MCOBHX","MCOBRS","MCOBRU","MCOCDG","MCOCWL","MCODUB","MCOEDI","MCOGLA","MCOLGW","MCOLHR","MCOMAN","MCOSNN","MIADUB","MSPDUB","MSYDUB","MSYSNN","MUCBOS","MUCJFK","MUCORD","NAPJFK","OAKDUB","OMADUB","ORDAMS","ORDBHX","ORDBRS","ORDBRU","ORDCDG","ORDCWL","ORDDUB","ORDDUS","ORDEDI","ORDFRA","ORDGLA","ORDGVA","ORDLGW","ORDLHR","ORDMAN","ORDMUC","ORDSNN","PBIDUB","PBISNN","PDXDUB","PDXSNN","PHXDUB","PHXSNN","PITDUB","PITSNN","PSEDUB","PSESNN","PWMDUB","PWMSNN","RDUDUB","RDUSNN","RICDUB","RICSNN","ROCDUB","ROCSNN","RSWDUB","RSWSNN","SANDUB","SDFDUB","SEADUB","SEASNN","SFODUB","SFOSNN","SJCDUB","SJCSNN","SJUDUB","SJUSNN","SLCDUB","SMFDUB","SMFSNN","SNNAUS","SNNBOS","SNNBQN","SNNBTV","SNNBUF","SNNBUR","SNNBWI","SNNCLT","SNNDCA","SNNFLL","SNNHOU","SNNIAD","SNNJAX","SNNJFK","SNNLAS","SNNLAX","SNNLGB","SNNMCO","SNNMSY","SNNORD","SNNPBI","SNNPDX","SNNPHX","SNNPIT","SNNPSE","SNNPWM","SNNRDU","SNNRIC","SNNROC","SNNRSW","SNNSEA","SNNSFO","SNNSJC","SNNSJU","SNNSMF","SNNSYR","SNNTPA","STLDUB","SXFJFK","SYRDUB","SYRSNN","TPADUB","TPASNN","VCEJFK","VIEJFK","WAWJFK","YEGDUB","YVRDUB","YWGDUB","YYCDUB","YYZDUB"); 


//This Value is set on jsp pages as it is req'd to be localised
// SCROLL_FOR_MORE_VALUE = '------------- scroll for more -------------',

/********************************************************
* closes the options container on x clicked or option selected
* @method YAHOO.aerlingus.options.closeResults_Click()
* @param event
*********************************************************/
YAHOO.aerlingus.options.closeResults_Click = function(e){
    var elTarget = YAHOO.util.Event.getTarget(e);
    while (elTarget.id != CONTROLS_WRAPPER) {
        if(elTarget.nodeName.toUpperCase() == 'DIV') {
            elTarget.innerHTML = '';
        }
        if(elTarget.nodeName.toUpperCase() == 'SPAN') { 
            elTarget.style.visibility = 'hidden';
         break;
        }else{
            //move up until we get to the element we want to close
            elTarget = elTarget.parentNode;
        }
    }
}
 
/********************************************************
* closes both options containers
* @method YAHOO.aerlingus.options.closeAllResults()
*********************************************************/
YAHOO.aerlingus.options.closeAllResults = function(){
    var pnlWrapper, spnElements,i,spnElement,divElements,divElement,j;
    pnlWrapper = Dom.get(CONTROLS_WRAPPER);
    spnElements = Dom.getChildrenBy(pnlWrapper, getSpanElements);
    for(i = 0; i< spnElements.length; i++){
        spnElement = spnElements[i];
        divElements = Dom.getChildrenBy(spnElement, getDivElements);
        for(j = 0; j< divElements.length; j++){
            divElement = divElements[j];
            divElement.innerHTML = ''; 
        }
        spnElement.style.visibility = 'hidden';
    }
}
 
/****************************************************
* open the options panel when the down arrow button 
* is clicked
* @method YAHOO.aerlingus.options.openResults_Click()
* @param event
*****************************************************/
YAHOO.aerlingus.options.openResults_Click = function(e){
    var options,btnElement,pnlLoading,txtElement,pnlLocation,pnlResults,el,dialogEl;
    options = ALL_OPTIONS;
    btnElement = YAHOO.util.Event.getTarget(e);
    pnlLoading = Dom.getNextSibling(btnElement);
    // If the JSON data is not available yet we display the loading icon and set no data variables true
    // The no data values are used by the YAHOO.aerlingus.options.getJSONData function and requests are continually made until
    // data is retrieved
    if(options.length <= 0){
        if(btnElement.id == ORIGIN_DROP_BUTTON){
            ORIGIN_NO_DATA = true;
            pnlLoading.style.display='block';
        }else if(btnElement.id == DESTINATION_DROP_BUTTON){
            DESTINATION_NO_DATA = true;
            pnlLoading.style.display='block';
        }
    }else{
        txtElement = Dom.getPreviousSibling(btnElement);
        pnlLocation = Dom.getAncestorByTagName(txtElement, 'DIV');
        pnlResults = Dom.getNextSibling(pnlLocation);
        YAHOO.aerlingus.options.openResults(pnlResults,pnlLoading);
    }
    //click event handling to close the dialog if anywhere else clicked besides inside the dialog or open dialog button
    YAHOO.util.Event.on(document, "click", function(e) {
        el =  YAHOO.util.Event.getTarget(e);
        if(pnlResults != undefined){
	        dialogEl = pnlResults;
	        if (el != dialogEl && !Dom.isAncestor(dialogEl, el) && el != btnElement && !Dom.isAncestor(btnElement, el)) {
	        	dialogEl.style.visibility = 'hidden';
	        }
        }
    });

}

/****************************************************
* The user selects "View all our Airports"
* @method YAHOO.aerlingus.options.resetOptions_Click ()
* @param event
*****************************************************/
YAHOO.aerlingus.options.resetOptions_Click = function(e){
	var linkElement,pnlResults,pnlLocation,inputElements,divElements,i;
	linkElement = YAHOO.util.Event.getTarget(e);
	pnlResults = Dom.getAncestorByTagName(linkElement, 'SPAN');
	pnlLocation = Dom.getPreviousSibling(pnlResults);
	inputElements = Dom.getChildrenBy(pnlLocation, getInputElements);
	divElements = Dom.getChildrenBy(pnlLocation, getDivElements);
	for(i=0;i<inputElements.length;i++){
		inputElements[i].value = '';
	}
	YAHOO.aerlingus.options.openResults(pnlResults,divElements[1]);
}


/**********************************************
* open the options panel if options available 
* and if no options available at this point 
* continued requests are made to get the data 
* and then this method is called when data 
* becomes available 
* @method YAHOO.aerlingus.options.openResults()
* @param div element, div element
***********************************************/
YAHOO.aerlingus.options.openResults = function (pnlResults,pnlLoading){
    var i, sltCountries, len;
    YAHOO.aerlingus.options.closeAllResults();
    for (i = 0, len = pnlResults.childNodes.length; i < len; ++i){
        //if we have reached the select element
        if(pnlResults.childNodes[i].nodeName.toUpperCase() == "SELECT"){
            sltCountries = pnlResults.childNodes[i];
            YAHOO.aerlingus.options.populateCountryOptions(sltCountries);
            YAHOO.aerlingus.options.populateAirportOptions(sltCountries);
            //now open the results panel
            pnlResults.style.visibility = "visible";
            //and close the loading panel
            pnlLoading.style.display='none';
            break;
        }
    }
}
 
/****************************************************
* populates origin and destination country controls 
* with origin country values
* @method YAHOO.aerlingus.options.populateCountryOptions()
* @param select element
*****************************************************/
YAHOO.aerlingus.options.populateCountryOptions = function(sltCountries){
    var len,pnlResults,pnlLocation,txtElements,selectedAirportCode,selectedCountryCode,selectedOriginAirportCode,options,sOption,i,countryOpt,countryCode,countryMeaning;
    //get the origin or destination results panel
    pnlResults = Dom.getAncestorByTagName(sltCountries.id, "SPAN");
    pnlLocation = Dom.getPreviousSibling(pnlResults);
    //get an array of text elements in the origin or destination panel
    txtElements = Dom.getChildrenBy(pnlLocation, getInputElements);
    //the selected airport code will be the hidden text element value
    selectedAirportCode = txtElements[1].value;
    //the selected country code will be the id of the option selected in the select element
    selectedCountryCode = YAHOO.aerlingus.options.getCountryCodeOfSelectedAirport(selectedAirportCode);
    //we want to select the default country of the origin country by default
    //if(trim(selectedCountryCode,' ') == '' && sltCountries.id == ORIGIN_COUNTRY_SELECT_ELEMENT)
     //selectedCountryCode = Dom.get(COUNTRY_SELECT_ELEMENT).value;
    //the selected origin airport code will be the value in the hidden origin input element
    selectedOriginAirportCode = YAHOO.aerlingus.options.getHiddenElement(OUTER_ORIGIN_PANEL).value;
    //if origin airport code == '' then we just show all origin countries in origin and destination options
    //or if we have opened the origin options drop down then we always show all origin countries in origin options
    options = ALL_OPTIONS;
    sltCountries.innerHTML = '';
    //if an origin is selected then we will develop the destination country options for this option
    if(selectedOriginAirportCode != '' && sltCountries.id != ORIGIN_COUNTRY_SELECT_ELEMENT)
        options = DESTINATION_OPTIONS;
    //Append "ALL" option
    sOption = document.createElement('option');
    sOption.innerHTML = ALL_COUNTRIES_TITLE;
    sOption.value = ALL_COUNTRIES_VALUE;
    sOption.title = ALL_COUNTRIES_TITLE;
    sltCountries.appendChild(sOption);
    //iterate through countries and add each option to the origin select element 
    for (i = 0, len = options.length; i < len; ++i) {
        countryOpt = options[i];
        countryCode = countryOpt.country.code;
        countryMeaning = countryOpt.country.meaning;
        sOption = document.createElement('option');
        //EXAMPLE OPTION: <option title="Dublin (DUB) " value="DUB">Dublin (DUB)</option>
        sOption.innerHTML = countryMeaning;
        sOption.value = countryCode;
        sOption.title = countryMeaning;
        sltCountries.appendChild(sOption);
        if(sOption.value == selectedCountryCode){
            sOption.selected = 'true';    
        }
    }
}
 
/***************************************************************
* Returns the hidden origin/destination element
* @method YAHOO.aerlingus.options.getHiddenElement()
* @param div element
* @return input hidden field
****************************************************************/
YAHOO.aerlingus.options.getHiddenElement = function(outerDirectionPanel){
 //we cant assign an id to the hidden element coz its a html:hidden element so we use this roundabout way of getting the value from it
 var outerPanel, inputElements;
 outerPanel = Dom.get(outerDirectionPanel);
 inputElements = Dom.getChildrenBy(outerPanel, getInputElements);
    return inputElements[1];
}

/***************************************************************
* A user has just entered a string that is  not linked with any 
* airport so we just show an error message and blank the field
* @method YAHOO.aerlingus.options.replaceStringWithNothing()
* @param string
* @return boolean
****************************************************************/
YAHOO.aerlingus.options.replaceStringWithNothing = function(txtElement){
    //if there is no value then we need to set it as no value selected
    YAHOO.aerlingus.options.populateField('', '', txtElement);
}
 
/***************************************************************
* Catch the blur event on the origin search element and replace
* any airport code with full airport details in text element and
* generate destination options from this origin
* @method YAHOO.aerlingus.options.searchOriginElement_Blur()
* @param event
****************************************************************/
YAHOO.aerlingus.options.searchOriginElement_Blur = function(e){
    var txtElement,pnlEntryError;
    txtElement = YAHOO.util.Event.getTarget(e);
    YAHOO.aerlingus.options.replaceEnteredValue(txtElement, ALL_OPTIONS);
    YAHOO.aerlingus.options.generateDestinationOptions_Blur(e);
    pnlEntryError = YAHOO.aerlingus.options.getErrorElement(txtElement);
    Dom.setStyle(pnlEntryError, 'visibility', 'hidden');
}

/***************************************************************
* replaces entered value with airport or nothing 
* @method YAHOO.aerlingus.options.replaceEnteredValue()
* @param txtElement, options
****************************************************************/
YAHOO.aerlingus.options.replaceEnteredValue = function(txtElement, options){
	if(!YAHOO.aerlingus.options.replaceCodeWithAirport(txtElement, options))
	    if(!YAHOO.aerlingus.options.replaceStringWithAirport(txtElement))
	        YAHOO.aerlingus.options.replaceStringWithNothing(txtElement)	
}

/***************************************************************
* returns the error element from a given search element 
* @method YAHOO.aerlingus.options.getErrorElement()
* @param txtElement
* @return error div
****************************************************************/
YAHOO.aerlingus.options.getErrorElement = function(txtElement){
    var pnlOND,pnlResults,pnlAutoComplete,pnlEntryError;
    pnlOND = Dom.getAncestorByTagName(txtElement.id, "DIV");
    pnlResults = Dom.getNextSibling(pnlOND);
    pnlAutoComplete = Dom.getNextSibling(pnlResults);
    pnlEntryError = Dom.getNextSibling(pnlAutoComplete);
	return pnlEntryError;
}

/***************************************************************
* Catch the focus event on the origin or destination search 
* @method YAHOO.aerlingus.options.searchOriginElement_KeyDown()
* @param event
****************************************************************/
YAHOO.aerlingus.options.searchElement_Focus = function(e){
    var txtElement = YAHOO.util.Event.getTarget(e);
    YAHOO.aerlingus.options.closeAllResults();
    txtElement.select();
}
 
/***************************************************************
* Catch the blur event on the origin search element and replace
* any airport code with full airport details in text element
* @method YAHOO.aerlingus.options.searchDestinationElement_Blur()
* @param event
****************************************************************/
YAHOO.aerlingus.options.searchDestinationElement_Blur = function(e){
    var txtElement,options,pnlEntryError;
    txtElement = YAHOO.util.Event.getTarget(e);
    options = DESTINATION_OPTIONS;
    if(options.length == 0)
        options = ALL_OPTIONS;
    YAHOO.aerlingus.options.replaceEnteredValue(txtElement, options);
    pnlEntryError = YAHOO.aerlingus.options.getErrorElement(txtElement);
    Dom.setStyle(pnlEntryError, 'visibility', 'hidden');
	if(YAHOO.aerlingus.fareCategory.isBusinessRoute()){
		YAHOO.aerlingus.fareCategory.disableFareCategory(false);
	}
}
 
/***************************************************************
* This function will generate the destination options based on the
* origin airport selected by the auto complete functionality 
* @method YAHOO.aerlingus.options.generateDestinationOptions_Blur()
* @param input element
****************************************************************/
YAHOO.aerlingus.options.generateDestinationOptions_Blur = function(e){
    //get the resolved target
    var element,pnlOrigin,originTxtElements;
    element = YAHOO.util.Event.getTarget(e);
    //get the parent element
    pnlOrigin = Dom.getAncestorByTagName(element.id, "DIV");
    //get an array of input elements in the origin panel
    originTxtElements = Dom.getChildrenBy(pnlOrigin, getInputElements);
    YAHOO.aerlingus.options.generateDestinationOptions(originTxtElements);
}
 
/***************************************************************
* This function will generate the destination options based on the
* origin airport selected by the auto complete functionality and 
* origin airport selected by the clicking of an airport option
* @method YAHOO.aerlingus.options.generateDestinationOptions()
* @param array of input elements
****************************************************************/
YAHOO.aerlingus.options.generateDestinationOptions = function(originTxtElements){
    var txtOriginMeaning,txtOriginCode,countryOptions,i,countryOpt,j,airport,clear,len;
    txtOriginMeaning = originTxtElements[0];
    txtOriginCode = originTxtElements[1];
    countryOptions = ALL_OPTIONS;
    if(trim(txtOriginCode.value,' ') == ''){
        //set destination options to [] as the origin field must be blank
        DESTINATION_OPTIONS = [];
        //we need to initialise the auto complete destination options based on the new destination options
        YAHOO.aerlingus.options.autoComplete.initAutoComplete(DESTINATION_SEARCH_ELEMENT, 'pnlDestinationAutoComplete', DESTINATION, ALL_OPTIONS);
    }else{
        //iterate through all countries
        outer_loop:
        for (i = 0, len = countryOptions.length; i < len; ++i) {
            countryOpt = countryOptions[i];
            //iterate through origin country airports
            for (j = 0, sublen = countryOpt.country.airports.length; j < sublen; ++j) {
                airport = countryOpt.country.airports[j].airport; 
                //if airport code is same as selected origin airport code
                if(trim(airport.code,' ') == trim(txtOriginCode.value,' ')){
                    DESTINATION_OPTIONS = airport.destinations;
                    //we need to initialise the auto complete destination options based on the new destination options
                    YAHOO.aerlingus.options.autoComplete.initAutoComplete(DESTINATION_SEARCH_ELEMENT, 'pnlDestinationAutoComplete', DESTINATION, DESTINATION_OPTIONS);
                    break outer_loop;
                }
            }
        }
    }
    //check if we should clear the destination text field
    clear = YAHOO.aerlingus.options.clearDestinationField(txtOriginCode);
    if(clear){
        YAHOO.aerlingus.options.populateField('','',Dom.get(DESTINATION_SEARCH_ELEMENT));
    }
}
 

/************************************************************
* populates origin and destination airport li options by 
* country selected
* @method YAHOO.aerlingus.options.populateAirportOptions()
* @param select element
*************************************************************/
YAHOO.aerlingus.options.populateAirportOptions = function(sltCountries){
    var pnlResults,pnlLocation,txtElements,selectedAirportCode,selectedCountryCode,selectedOriginAirportCode,pnlAirports,countryOptions,ulOption;
    //get the origin or destination results panel
    pnlResults = Dom.getAncestorByTagName(sltCountries.id, "SPAN");
    pnlLocation = Dom.getPreviousSibling(pnlResults);
    //get an array of text elements in the origin or destination panel
    txtElements = Dom.getChildrenBy(pnlLocation, getInputElements);
    //the selected airport code will be the first text element
    selectedAirportCode = txtElements[1].value;
    //the selected country code will be the id of the option selected in the select element
    selectedCountryCode = sltCountries.options[sltCountries.selectedIndex].value;
    //the selected origin airport code will be the value in the hidden origin input element
    selectedOriginAirportCode = YAHOO.aerlingus.options.getHiddenElement(OUTER_ORIGIN_PANEL).value;
    // Get the div element in which to write airport options
    pnlAirports = Dom.getNextSibling(sltCountries);
    pnlAirports.innerHTML = '';
    countryOptions = ALL_OPTIONS;
    //if origin airport code == '' then we just show all origin airports in origin and destination options
    //or if we have opened the origin options drop down then we always show all origin airports in origin options
    //if an origin is selected then we will develop the destination airport options for this option
    if(selectedOriginAirportCode != '' && sltCountries.id != ORIGIN_COUNTRY_SELECT_ELEMENT){
        selectedAirportCode = YAHOO.aerlingus.options.getHiddenElement(OUTER_DESTINATION_PANEL).value;
        countryOptions = DESTINATION_OPTIONS;
    }
    ulOption = YAHOO.aerlingus.options.getAirportULOption(countryOptions, selectedCountryCode,selectedAirportCode);
    //ie6 fix to stop select elements from coming in front of the results
    YAHOO.aerlingus.ie6Utils.makeWindowed(pnlAirports);  
    pnlAirports.appendChild(ulOption);
}
 
/***********************************************************************
* Returns a UL element with required LI airport elements
* @method YAHOO.aerlingus.options.getAirportULOption()
* @param airportCountryCombos, selectedCountryCode,selectedAirportCode
* @return ul element
************************************************************************/
YAHOO.aerlingus.options.getAirportULOption = function(countryOptions, selectedCountryCode,selectedAirportCode){
	var airportCountryCombos,ulOption,priorityAirportCountryCombos,i,len;
	airportCountryCombos = YAHOO.aerlingus.options.sort.getSortedAirportsByMeaning(countryOptions);
    ulOption = document.createElement('ul');
    priorityAirportCountryCombos = YAHOO.aerlingus.options.priorityAirports.createPriorityAirportCountryCombos(countryOptions,selectedCountryCode);
    ulOption = YAHOO.aerlingus.options.priorityAirports.addPriorityLIOptions(ulOption, priorityAirportCountryCombos,selectedAirportCode);
    for (i = 0, len = airportCountryCombos.length; i < len; ++i) {
        //if there is a country selected then show its airports or else show all airports
        if(airportCountryCombos[i].obj1.country.code == selectedCountryCode || selectedCountryCode == ALL_COUNTRIES_VALUE){
            ulOption = YAHOO.aerlingus.options.appendLIOption(ulOption, airportCountryCombos[i],selectedAirportCode,'',selectedCountryCode);
        }
    }
    return ulOption;
}

/******************************************************
* returns priority airport country - airport combos 
* @method YAHOO.aerlingus.options.priorityAirports.createPriorityAirportCountryCombos()
* @param countryOptions, countryCode
* @return priorityAirportCountryCombos
*******************************************************/
YAHOO.aerlingus.options.priorityAirports.createPriorityAirportCountryCombos = function(countryOptions,countryCode){
    var priorityAirportCountryCombos = YAHOO.aerlingus.options.sort.getSortedPriorityAirportsByMeaning(countryOptions, countryCode);
    return priorityAirportCountryCombos;
}

/******************************************************
* returns ul element with priority li options 
* @method YAHOO.aerlingus.options.priorityAirports.addPriorityLIOptions()
* @param ulOption, priorityAirportCountryCombos, selectedAirportCode
* @return ulOption
*******************************************************/
YAHOO.aerlingus.options.priorityAirports.addPriorityLIOptions = function(ulOption, priorityAirportCountryCombos,selectedAirportCode){
    var i,liOption,len;
    for (i = 0, len = priorityAirportCountryCombos.length; i < len; ++i) {
        ulOption = YAHOO.aerlingus.options.appendLIOption(ulOption, priorityAirportCountryCombos[i],selectedAirportCode,PRIORITY_PREFIX,'');        
    }
    //if we have any priority airports then we show the break
    if(priorityAirportCountryCombos.length > 0){
        liOption = document.createElement('li');
        liOption.id = SCROLL_FOR_MORE_ID;
        liOption.title = '';
        liOption.innerHTML = SCROLL_FOR_MORE_VALUE;
        ulOption.appendChild(liOption);
    }
    return ulOption;
}

/******************************************************
* returns ul element with li options 
* @method YAHOO.aerlingus.options.appendLIOption()
* @param ulOption, airportCountryCombo, selectedAirportCode, priorityStr
* @return ulOption
*******************************************************/
YAHOO.aerlingus.options.appendLIOption = function(ulOption, airportCountryCombo,selectedAirportCode, priorityStr,selectedCountryCode){
    var option,airportCode,airportMeaning,stateCode,countryCode,countryMeaning,addOption,xtraCountryAirports,i,liOption;
    option = airportCountryCombo;
    airportCode = option.obj2.airport.code
    airportMeaning = option.obj2.airport.meaning
    stateCode = option.obj2.airport.state.state.code
    countryCode = option.obj1.country.code;
    countryMeaning = option.obj1.country.meaning;
    //START - fix for airports like belfast in both NN and GB - if all countries selected then we don't want to add airport twice
    addOption = true;
    //selectedCountryCode is only used here for this fix
    if(selectedCountryCode == ALL_COUNTRIES_VALUE){
        xtraCountryAirports = new YAHOO.util.LocalDataSource(YAHOO.aerlingus.options.extraCountryAirports[countryCode]);
        for(i=0;i<xtraCountryAirports.liveData.length;i++){
            if(xtraCountryAirports.liveData[i] == airportCode){
                addOption = false;
                break;
            }
        }
    }
    if(addOption){
        //END - fix for airports like belfast in both NN and GB 
        //EXAMPLE LI: <li id="DUB" title="Dublin (DUB)"><span>IE</span>Dublin (DUB)</li>
        liOption = document.createElement('li');
        liOption.id = priorityStr + airportCode;
        liOption.title = airportMeaning +" ("+airportCode+"), "+countryMeaning;
        liOption.innerHTML = "<span>"+stateCode+" "+countryCode+"</span>"+airportMeaning +" ("+airportCode+")";
        ulOption.appendChild(liOption);
        //if an airport is selected then we want to show it selected in the list
        if(selectedAirportCode == liOption.id || PRIORITY_PREFIX + selectedAirportCode == liOption.id){
            liOption.className = "selected";
        }
    }
    return ulOption;
}
 
/******************************************************
* coutry selected click event handler
* @method YAHOO.aerlingus.options.selectCountry_Change()
* @param event
*******************************************************/
YAHOO.aerlingus.options.selectCountry_Change = function(e) { 
    var container = YAHOO.util.Event.getTarget(e);
    YAHOO.aerlingus.options.populateAirportOptions(container);
}
 
/**************************************************************
* airport selected click event handler
* @method YAHOO.aerlingus.options.selectAirport_Click()
* @param event
***************************************************************/
YAHOO.aerlingus.options.selectAirport_Click = function(e) { 
    var liElement,pnlResults,pnlLocation,txtElements;
    liElement = YAHOO.util.Event.getTarget(e);
    if(liElement.id != SCROLL_FOR_MORE_ID){
	    //if an LI has been selected then we want to clear previously selected element and highlight this one
	    if(liElement.nodeName.toUpperCase() == "LI") {
	        YAHOO.aerlingus.options.clearSelectedAirport(liElement);
	        liElement.className = "selected";
	    }
	    pnlResults = Dom.getAncestorByTagName(liElement.id, "SPAN");
	    pnlLocation = Dom.getPreviousSibling(pnlResults);
	    txtElements = Dom.getChildrenBy(pnlLocation, getInputElements);
	    //populate text field with selected value
	    YAHOO.aerlingus.options.populateField(liElement.title, liElement.id, txtElements[0]);
	    //close the results panel 
	    YAHOO.aerlingus.options.closeResults_Click(e);
	    ////if a business route is selected then enable fare category select options
		if(YAHOO.aerlingus.fareCategory.isBusinessRoute()){
			YAHOO.aerlingus.fareCategory.disableFareCategory(false);
		}    
	    //if an origin airport has been selected then we need to generate the destination options at this stage
	    if(pnlResults.id == 'pnlOriginResults')
	        YAHOO.aerlingus.options.generateDestinationOptions(txtElements);
    }
}
 
/**************************************************************
* airport selected mouse event handler
* @method YAHOO.aerlingus.options.selectAirport_Mouse()
* @param event
**************************************************************/
YAHOO.aerlingus.options.selectAirport_Mouse = function(e) {
    var container = YAHOO.util.Event.getTarget(e);    
	if(container.id != SCROLL_FOR_MORE_ID){
		if(container.nodeName.toUpperCase() == "LI") { 
	        YAHOO.aerlingus.options.clearSelectedAirport(container);
	        container.className = 'selected'; 
    	}
    }
} 
 
/************************************************
* Clear any previously selected li item
* @method YAHOO.aerlingus.options.clearSelectedAirport()
* @param LI element
*************************************************/
YAHOO.aerlingus.options.clearSelectedAirport = function(container)
{   
    var ulElement,listItems,element,i;
    ulElement = Dom.getAncestorByTagName(container.id, "UL");
    listItems = ulElement.getElementsByTagName("li");
    for(i = 0;i< listItems.length; i++)
    {
        element = Dom.get(listItems[i].id);
        if(element.className=='selected')
            element.className = '';
    }  
}
 
/*****************************************************
* Populates origin and destination text fields based
* on hidden airport code values on page load
* @method YAHOO.aerlingus.options.populateFields_Load()
******************************************************/
YAHOO.aerlingus.options.populateFields_Load = function(){
    var txtSearch = Dom.get(ORIGIN_SEARCH_ELEMENT);
    YAHOO.aerlingus.options.populateFields(txtSearch);
    txtSearch = Dom.get(DESTINATION_SEARCH_ELEMENT);
    YAHOO.aerlingus.options.populateFields(txtSearch);
}

/*****************************************************
* Populates origin and destination text fields based
* on hidden airport code values
* @method YAHOO.aerlingus.options.populateFields()
******************************************************/
YAHOO.aerlingus.options.populateFields = function(txtSearch){
    var pnlLocation,txtElements,selectedCode,selectedMeaning,countryMeaning;
    pnlLocation = Dom.getAncestorByTagName(txtSearch, 'DIV');
    txtElements = Dom.getChildrenBy(pnlLocation, getInputElements);
    //get origin airport code from hidden origin field
    selectedCode = txtElements[1].value;
    //get origin airport meaning based on airport code
    selectedMeaning = YAHOO.aerlingus.options.getAirportMeaningFromCode(selectedCode);
    countryMeaning = YAHOO.aerlingus.options.getCountryMeaningOfSelectedAirport(selectedCode);
    //if an origin airport was previously selected then we set the corresponding meaning value in the origin text element
    if(selectedCode != ''){
        txtSearch.value = YAHOO.aerlingus.options.htmlEntityDecode(selectedMeaning +' ('+selectedCode+'), '+countryMeaning);
        if(txtSearch.id == ORIGIN_SEARCH_ELEMENT){
            //we also want to generate the destination options
            YAHOO.aerlingus.options.generateDestinationOptions(txtElements);
        }
    }
    //Search Type (Flexible: Yes/No) Update Script
    YAHOO.aerlingus.searchType.setDefaultSearchType();
    //disables fare category options for flexible searches
    YAHOO.aerlingus.fareCategory.disableFareCatForFlexible
} 

/************************************************
* Populate text field with selected option value
* @method YAHOO.aerlingus.options.populateField()
* @param string, text element
*************************************************/
YAHOO.aerlingus.options.populateField = function(selectedValue, selectedID, txtElement)
{
    txtElement.value = YAHOO.aerlingus.options.htmlEntityDecode(selectedValue);
    var hdnElement = Dom.getNextSiblingBy(txtElement, getInputElements);
    hdnElement.value = YAHOO.aerlingus.options.removePriorityPrefix(selectedID);
    //Search Type (Flexible: Yes/No) Update Script 
    YAHOO.aerlingus.searchType.setDefaultSearchType();
    //disables fare category options for flexible searches
    YAHOO.aerlingus.fareCategory.disableFareCatForFlexible
}
 
YAHOO.aerlingus.options.loadInit = function() {
	var pnlSearchTypeRadioGroup,searchTypeRadioElements,originPositionListener,destinationPositionListener,pnlPromotionalFlightsRadioGroup,promotionalFlightsRadioElements;
	pnlSearchTypeRadioGroup = Dom.get(SEARCH_TYPE_BUTTON_PANEL);
	if(pnlSearchTypeRadioGroup!=null){
    	searchTypeRadioElements = Dom.getChildrenBy(pnlSearchTypeRadioGroup, getInputElements);
    	SEARCH_TYPE_RADIO_ONE = searchTypeRadioElements[0];
	    SEARCH_TYPE_RADIO_TWO = searchTypeRadioElements[1];
	    YAHOO.util.Event.addListener(SEARCH_TYPE_RADIO_ONE, "click",YAHOO.aerlingus.fareCategory.flexibleDate_Click);
	    //YAHOO.util.Event.addListener(SEARCH_TYPE_RADIO_TWO, "click",YAHOO.aerlingus.fareCategory.flexibleDate_Click);
    }
    originPositionListener = new YAHOO.util.KeyListener(ORIGIN_SEARCH_ELEMENT, { keys:[40,38]}, { fn:YAHOO.aerlingus.options.handleSearchKeyPress } );
    originPositionListener.enable();
    destinationPositionListener = new YAHOO.util.KeyListener(DESTINATION_SEARCH_ELEMENT, { keys:[40,38] }, { fn:YAHOO.aerlingus.options.handleSearchKeyPress } );
    destinationPositionListener.enable();
    
    if(IS_CORPORATE){
    	pnlPromotionalFlightsRadioGroup = Dom.get(PROMOTIONAL_FLIGHTS_BUTTON_PANEL);
    	if(pnlPromotionalFlightsRadioGroup!=null){
    	    promotionalFlightsRadioElements = Dom.getChildrenBy(pnlPromotionalFlightsRadioGroup, getInputElements);
    	    if(pnlPromotionalFlightsRadioGroup){
    		    CORPORATE_RATE_RADIO_ONE = promotionalFlightsRadioElements[0];
    		    CORPORATE_RATE_RADIO_TWO = promotionalFlightsRadioElements[1];
    	        YAHOO.util.Event.addListener(CORPORATE_RATE_RADIO_ONE, "click",YAHOO.aerlingus.promotionalFlights.corporateRate_Click);
    		    YAHOO.util.Event.addListener(CORPORATE_RATE_RADIO_TWO, "click",YAHOO.aerlingus.promotionalFlights.corporateRate_Click);
    	    }
    	}
    	YAHOO.aerlingus.promotionalFlights.corporate_Load();
    }
}
 
/*******************************************
* Populate ALL_OPTIONS with JSON data. An
* async request is made to get content and if
* the data is not retrieved then continued 
* requests will be made every 2 seconds until
* we get the data from the file
* @method YAHOO.aerlingus.options.getJSONData()
********************************************/
YAHOO.aerlingus.options.getJSONData = function(){
    // Define the callbacks for the asyncRequest
    var callbacks,options;
    callbacks = {
        success : function (o) {
            // Process the JSON data returned from the server
            options = [];
            try {
                options = YAHOO.lang.JSON.parse(o.responseText);
                // The returned data was parsed into an array of objects.
                ALL_OPTIONS = options;
                YAHOO.aerlingus.options.autoComplete.initAutoComplete('txtOriginSearch', 'pnlOriginAutoComplete', ORIGIN, ALL_OPTIONS);
                YAHOO.aerlingus.options.autoComplete.initAutoComplete('txtDestinationSearch', 'pnlDestinationAutoComplete', DESTINATION, ALL_OPTIONS);
                if(ORIGIN_NO_DATA){
                    ORIGIN_NO_DATA = false;
                    //we have the data now so we can re open results
                    YAHOO.aerlingus.options.reOpenResults(OUTER_ORIGIN_RESULTS_PANEL, ORIGIN_LOADING_PANEL);
                }
                else if(DESTINATION_NO_DATA){
                    DESTINATION_NO_DATA = false;
                    //we have the data now so we can re open results
                    YAHOO.aerlingus.options.reOpenResults(OUTER_DESTINATION_RESULTS_PANEL, DESTINATION_LOADING_PANEL);
                }
                //after we get the json data may need to populate fields with previously selected values
                YAHOO.aerlingus.options.populateFields_Load()
            }
            catch (x) {
                setTimeout('YAHOO.aerlingus.options.getJSONData()',10000);
                return;
            }
        },
        failure : function (o) {
            if (!YAHOO.util.Connect.isCallInProgress(o)) {
                setTimeout('YAHOO.aerlingus.options.getJSONData()',10000);
            }
        },
        timeout : 10000
    }
    // Make the call to the server for JSON data
    YAHOO.util.Connect.asyncRequest('GET',JSON_OPTIONS_LOCATON+"/"+AIRPORT_OPTIONS_FILE, callbacks);
}
 
/*******************************************
* Open the dynamic drop down with country
* and airport results as the data is now
* available 
* @method YAHOO.aerlingus.options.reOpenResults()
* @param div element, div element
********************************************/
YAHOO.aerlingus.options.reOpenResults = function(outerResultsPanel, loadingPanel){
    YAHOO.aerlingus.options.openResults(Dom.get(outerResultsPanel),Dom.get(loadingPanel));
}
 
/*******************************************************
* Language change selection which requires the change 
* language JSON options to be loaded 
* @method YAHOO.aerlingus.options.selectLanguage_Change()
* @param event
*********************************************************/
YAHOO.aerlingus.options.selectLanguage_Change = function(e){
    //we need to remove the autocomplete instances as new 
    //instances will be created for the new language selected
    var autoComp,currentLocale;
    autoComp = AUTOCOMPORIGININSTANCE;
    autoComp.destroy();
    autoComp = AUTOCOMPDESTINATIONINSTANCE;
    autoComp.destroy();
    AUTOCOMPORIGININSTANCE = undefined;
    AUTOCOMPDESTINATIONINSTANCE = undefined;
    currentLocale = CURRENT_LOCALE;
    AIRPORT_OPTIONS_FILE = currentLocale + '_airportOptions.jsp';
    YAHOO.aerlingus.options.getJSONData();
    YAHOO.aerlingus.options.closeAllResults();
}
 
/*******************************************************
* Language load selection which requires the load 
* language JSON options to be loaded 
* @method YAHOO.aerlingus.options.selectLanguage_Load()
*********************************************************/
YAHOO.aerlingus.options.selectLanguage_Load = function(){
	var currentLocale,selectedValue;
	currentLocale = CURRENT_LOCALE;
    selectedValue = currentLocale.substring(0,2);
    AIRPORT_OPTIONS_FILE = selectedValue + '_airportOptions.jsp';
    YAHOO.aerlingus.options.getJSONData();
    YAHOO.aerlingus.options.closeAllResults();
}
 
YAHOO.aerlingus.options.showModal = function() { 
    //Instantiate the Dialog
    YAHOO.aerlingus.options.infoModal = new YAHOO.widget.Dialog("infoModal", 
    { width : "30em",
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true
    });
    var origin,destination;
    origin = Dom.get(ORIGIN_SEARCH_ELEMENT).value;
    destination = Dom.get(DESTINATION_SEARCH_ELEMENT).value;
    YAHOO.aerlingus.options.infoModal.setHeader("Airport Options Selection"); 
    YAHOO.aerlingus.options.infoModal.setBody("You have selected the following:<br/>Origin: ["+origin+"]<br/>Destination: ["+destination+"]"); 
    // Render the Dialog
    YAHOO.aerlingus.options.infoModal.render();
    YAHOO.aerlingus.options.infoModal.show();
}
 
/* START Event Listeners */
 
//on is an alias for addListener 
YAHOO.util.Event.on(window, "load", YAHOO.aerlingus.options.loadInit);
YAHOO.util.Event.addListener("showModal", "click", YAHOO.aerlingus.options.showModal);
YAHOO.util.Event.onDOMReady(function(){ 
    if(Dom.get(ORIGIN_SEARCH_ELEMENT)){
	    YAHOO.aerlingus.options.loadDependentFiles();
	    YAHOO.aerlingus.calendar.initialiseDates_Load();
	    YAHOO.aerlingus.options.showHideEnterCode_Load();
	    YAHOO.util.Event.addListener(SELECTED_DEPARTURE_DAY, "change", YAHOO.aerlingus.calendar.selectDeparture_Change);
	    YAHOO.util.Event.addListener(SELECTED_DEPARTURE_MONTH, "change", YAHOO.aerlingus.calendar.selectDeparture_Change);
	    YAHOO.util.Event.addListener(SELECTED_RETURN_DAY, "change", YAHOO.aerlingus.calendar.selectReturn_Change);
	    YAHOO.util.Event.addListener(SELECTED_RETURN_MONTH, "change", YAHOO.aerlingus.calendar.selectReturn_Change);
	    YAHOO.util.Event.addListener(RETURN_TYPE, "click", YAHOO.aerlingus.calendar.selectFlightType_Click );
	    YAHOO.util.Event.addListener(ONEWAY_TYPE, "click", YAHOO.aerlingus.calendar.selectFlightType_Click );
		//Promo code check box listener 
		YAHOO.util.Event.addListener(CHK_PROMO_CODE, "click",YAHOO.aerlingus.options.showHideEnterCode_Click);
		//Promo code text box listeners 
		YAHOO.util.Event.addListener(TXT_PROMO_CODE, "focus",YAHOO.aerlingus.options.enterPromoCode_Focus);
		YAHOO.util.Event.addListener(TXT_PROMO_CODE, "blur",YAHOO.aerlingus.options.enterPromoCode_Blur);
	    YAHOO.aerlingus.calendar.selectFlightType_Load();
	    YAHOO.aerlingus.calendar.setCalendarDeparture_Load();
	    YAHOO.aerlingus.calendar.setCalendarReturn_Load();
        var departureEvent = YAHOO.util.Event;    
        var returnEvent = YAHOO.util.Event;
        var showDepartureBtn = Dom.get(SHOW_DEPARTURE);
        var showReturnBtn = Dom.get(SHOW_RETURN);
        departureEvent.on(showDepartureBtn, "click", function(e) {
    	    YAHOO.aerlingus.calendar.calendarOpen(e);
        });
        returnEvent.on(showReturnBtn, "click", function(e) {
    	    YAHOO.aerlingus.calendar.calendarOpen(e);
        });
    }
});

YAHOO.aerlingus.options.showHideEnterCode_Click = function(e){
	var chkBox = YAHOO.util.Event.getTarget(e);
	YAHOO.aerlingus.options.showHideEnterCode(chkBox);
}

YAHOO.aerlingus.options.showHideEnterCode_Load = function(){
	var chkBox = DOM.get(CHK_PROMO_CODE);
	YAHOO.aerlingus.options.showHideEnterCode(chkBox);
}

YAHOO.aerlingus.options.showHideEnterCode = function(chkBox){
	var txtEnterCode = DOM.get(TXT_PROMO_CODE);
	if(chkBox.checked)
		txtEnterCode.style.display = BLOCK;
	else
		txtEnterCode.style.display = NONE;
}

YAHOO.aerlingus.options.enterPromoCode_Focus = function(e){
	var txtBox = YAHOO.util.Event.getTarget(e);
	txtBox.value = '';
}

YAHOO.aerlingus.options.enterPromoCode_Blur = function(e){
	var txtBox = YAHOO.util.Event.getTarget(e);
	if(txtBox.value == '')
		txtBox.value = ENTER_CODE_DEFAULT_TEXT;
	else
		txtBox.value =  txtBox.value.toUpperCase();
		
}

/********************************************************************
 * load dependent files
 * @method YAHOO.aerlingus.options.loadDependentFiles
 ********************************************************************/
YAHOO.aerlingus.options.loadDependentFiles = function(){
	var loader = new YAHOO.util.YUILoader({
		require: ['connection','json','datasource','autocomplete'], // what components? 
		base: YUI_BASE_DIR,//where do they live?
		onSuccess: YAHOO.aerlingus.options.getJSONData 
	}); 
    loader.insert();
}


YAHOO.util.Event.addListener(ORIGIN_DROP_BUTTON, "click", YAHOO.aerlingus.options.openResults_Click);
YAHOO.util.Event.addListener(DESTINATION_DROP_BUTTON, "click", YAHOO.aerlingus.options.openResults_Click);
YAHOO.util.Event.addListener("closeOriginResults", "click", YAHOO.aerlingus.options.closeResults_Click);
YAHOO.util.Event.addListener("closeDestinationResults", "click", YAHOO.aerlingus.options.closeResults_Click);
//attach click handler as a listener for any click on the sltOriginCountry div
YAHOO.util.Event.addListener(ORIGIN_COUNTRY_SELECT_ELEMENT, "change", YAHOO.aerlingus.options.selectCountry_Change);
//attach click handler as a listener for any click on the sltDestinationCountry div
YAHOO.util.Event.addListener(DESTINATION_COUNTRY_SELECT_ELEMENT, "change", YAHOO.aerlingus.options.selectCountry_Change);
//attach click handler as a listener for any click on the ORIGIN_AIRPORT_RESULTS_PANEL div
YAHOO.util.Event.addListener(ORIGIN_AIRPORT_RESULTS_PANEL, "click", YAHOO.aerlingus.options.selectAirport_Click);
//attach click handler as a listener for any click on the ORIGIN_AIRPORT_RESULTS_PANEL div
YAHOO.util.Event.addListener(DESTINATION_AIRPORT_RESULTS_PANEL, "click", YAHOO.aerlingus.options.selectAirport_Click);
//attach mouse handler as a listener for any click on the ORIGIN_AIRPORT_RESULTS_PANEL div 
YAHOO.util.Event.on(ORIGIN_AIRPORT_RESULTS_PANEL, "mouseover", YAHOO.aerlingus.options.selectAirport_Mouse);
//attach mouse handler as a listener for any click on the ORIGIN_AIRPORT_RESULTS_PANEL div 
YAHOO.util.Event.on(DESTINATION_AIRPORT_RESULTS_PANEL, "mouseover", YAHOO.aerlingus.options.selectAirport_Mouse);
//attach blur event listener so we can create destination options
YAHOO.util.Event.addListener(ORIGIN_SEARCH_ELEMENT, "blur",YAHOO.aerlingus.options.searchOriginElement_Blur);
YAHOO.util.Event.addListener(DESTINATION_SEARCH_ELEMENT, "blur",YAHOO.aerlingus.options.searchDestinationElement_Blur);
 
YAHOO.util.Event.addListener(ORIGIN_SEARCH_ELEMENT, "focus",YAHOO.aerlingus.options.searchElement_Focus);
YAHOO.util.Event.addListener(DESTINATION_SEARCH_ELEMENT, "focus",YAHOO.aerlingus.options.searchElement_Focus);

YAHOO.util.Event.addListener(RESET_DESTINATION_ELEMENT, "click",YAHOO.aerlingus.options.resetOptions_Click);
YAHOO.util.Event.addListener(RESET_ORIGIN_ELEMENT, "click",YAHOO.aerlingus.options.resetOptions_Click);

/* END Event Listeners */

/***************************************************************
* Returns the auto complete instance associated with a text field
* @method YAHOO.aerlingus.options.getAutoCompleteInstance()
* @param element
* @return auto complete instance
****************************************************************/
YAHOO.aerlingus.options.getAutoCompleteInstance = function(txtElement){
    var autoComp;
    if(txtElement.id == ORIGIN_SEARCH_ELEMENT)
        autoComp = AUTOCOMPORIGININSTANCE;
    else if(txtElement.id == DESTINATION_SEARCH_ELEMENT)
        autoComp = AUTOCOMPDESTINATIONINSTANCE;
    return autoComp;
}
 
/***************************************************************
* A user may just know the code of the airport, type it in the 
* search box and then move on. In this case a valid airport code 
* will be replaced by the airport
* @method YAHOO.aerlingus.options.replaceCodeWithAirport()
* @param string
* @return boolean
****************************************************************/
YAHOO.aerlingus.options.replaceCodeWithAirport = function(txtElement, countryOptions){
    var i,j,countryOpt,airport,len;
    //iterate through all countries
    for (i = 0, len = countryOptions.length; i < len; ++i) {
        countryOpt = countryOptions[i];
        //iterate through origin country airports
        for (j = 0, sublen = countryOpt.country.airports.length; j < sublen; ++j) {
            airport = countryOpt.country.airports[j].airport;
            //if airport code is same as selected origin airport code
            if(trim(airport.code,' ') == trim(txtElement.value.toUpperCase(),' ')){
                //populate text field with selected value
                YAHOO.aerlingus.options.populateField(airport.meaning +' ('+airport.code+'), '+countryOpt.country.meaning, airport.code, txtElement);
                return true;
                break;
            }
        }
    }
    return false;
}
 
/***************************************************************
* A user has just entered a string and we want to use the first
* airport in the auto complete results as the selected airport
* @method YAHOO.aerlingus.options.replaceStringWithAirport()
* @param string
* @return boolean
****************************************************************/
YAHOO.aerlingus.options.replaceStringWithAirport = function(txtElement){
    //if its not a valid airport code entered then we will just present the first element of the auto complete options list for this text element
    if(trim(txtElement.value,' ') != '' && txtElement.value.length > 2){
        var autoComp,autoCompList,liElements,airportOptionText,airportOptionCode;
        autoComp = YAHOO.aerlingus.options.getAutoCompleteInstance(txtElement);
        if(autoComp != undefined){
            autoComp.sendQuery(txtElement.value); 
            if(autoComp.isContainerOpen()){
                //ie opens the container when we send the query
                autoComp.collapseContainer();
            }
            autoCompList = autoComp.getListEl();
            liElements = Dom.getChildrenBy(autoCompList, getLIElements);
            airportOptionText = liElements[0].innerHTML;
            airportOptionCode = YAHOO.aerlingus.options.getCodeFromAirportOptionText(airportOptionText);
            YAHOO.aerlingus.options.populateField(airportOptionText, airportOptionCode, txtElement);
            return true;
        }
    }
    return false;
}
 
/***************************************************************
* Returns the airport code value from a string of 
* "airport meaning (airport code), country code"
* @method YAHOO.aerlingus.options.getCodeFromAirportOptionText()
* @param string airport option text
* @return string airport code
****************************************************************/
YAHOO.aerlingus.options.getCodeFromAirportOptionText = function(airportOptionText){
    return airportOptionText.substring(airportOptionText.indexOf('(') + parseInt(1),airportOptionText.indexOf(')'));
}
 
/********************************************************
* Checks if the destination text field should be cleared.
* It needs to be cleared if the value in the destination
* field is not relevant for the origin 
* @method YAHOO.aerlingus.options.clearDestinationField()
* @param hdnOriginTextElement
* @return boolean
*********************************************************/
YAHOO.aerlingus.options.clearDestinationField = function(hdnOriginTextElement){
    var selectedDestinationAirportCode,i,j,k,l,airport,countryOpt,countryOptions,innerCountryOpt,innerAirport,airportDests;
    selectedDestinationAirportCode = YAHOO.aerlingus.options.getHiddenElement(OUTER_DESTINATION_PANEL).value;
    if(selectedDestinationAirportCode != ''){
        countryOptions = ALL_OPTIONS;
        //iterate through all countries
        for (i = 0, alen = countryOptions.length; i < alen; ++i) {
            countryOpt = countryOptions[i];
            //iterate through origin country airports
            for (j = 0, blen = countryOpt.country.airports.length; j < blen; ++j) {
                airport = countryOpt.country.airports[j].airport; 
                //if destination airport code is same as selected origin airport code
                if(trim(airport.code,' ') == hdnOriginTextElement.value){
                    //then we need to iterate through the destination airports
                    airportDests = airport.destinations;
                    for (k = 0, cLen = airportDests.length; k < cLen; ++k) {
                        innerCountryOpt = airportDests[k];
                        for (l = 0, dLen = innerCountryOpt.country.airports.length; l < dLen; ++l) {
                            innerAirport = innerCountryOpt.country.airports[l].airport;
                            //if a destination airport from the origin selected is equal to the destination already in the destination field then return false
                            //we don't want to clear the contents of the destination field 
                            if(innerAirport.code == selectedDestinationAirportCode){
                                return false;
                            }
                        }
                    }
                }
            }
        }
    }
    return true;
}
 
/******************************************************************
* returns the country code from the airport selected by code
* @method YAHOO.aerlingus.options.getCountryCodeOfSelectedAirport()
* @param selectedAirportCode
* @return selectedCountryCode
*******************************************************************/
YAHOO.aerlingus.options.getCountryCodeOfSelectedAirport = function(selectedAirportCode){
    var selectedCountryCode,selectedCountry;
    selectedCountryCode = '';
    if(selectedAirportCode != ''){
        //get the country of the selected airport including airports
        selectedCountry = YAHOO.aerlingus.options.getCountryOfSelectedAirport(selectedAirportCode);
        if(selectedCountry != undefined)
            selectedCountryCode = selectedCountry.code;
    }
    return selectedCountryCode;
}
 
/******************************************************************
* returns the country code from the airport selected by code
* @method YAHOO.aerlingus.options.getCountryMeaningOfSelectedAirport()
* @param selectedAirportCode
* @return selectedCountryMeaning
*******************************************************************/
YAHOO.aerlingus.options.getCountryMeaningOfSelectedAirport = function(selectedAirportCode){
    var selectedCountryMeaning,selectedCountry;
    selectedCountryMeaning = '';
    if(selectedAirportCode != ''){
        //get the country of the selected airport including airports
        selectedCountry = YAHOO.aerlingus.options.getCountryOfSelectedAirport(selectedAirportCode);
        selectedCountryMeaning = selectedCountry.meaning;
    }
    return selectedCountryMeaning;
}
 
/*******************************************
* returns the country and its airports of the 
* selected airport
* @method YAHOO.aerlingus.options.getCountryOfSelectedAirport()
* @param string
* @return country array
********************************************/
YAHOO.aerlingus.options.getCountryOfSelectedAirport = function(airportCode){
    var countryOptions,i,j,airportOption,countryOpt,len;
    countryOptions = ALL_OPTIONS;
    //iterate through origin countries
    outer_loop:
    for (i = 0, len = countryOptions.length; i < len; ++i) {
       countryOpt = countryOptions[i];
       //iterate through origin country airports
       for (j = 0, sublen = countryOpt.country.airports.length; j < sublen; ++j) {
           airportOption = countryOpt.country.airports[j];
           //if current airport code is same as code passed in as arg then we want to return the
           //country of this airport
           if(trim(airportOption.airport.code, ' ') == airportCode){
            return countryOpt.country;
           }
       }
    }
    return undefined;
}
 
/************************************************************
* Returns the airport meaning based on the airport code provided
* @method YAHOO.aerlingus.options.getAirportMeaningFromCode()
* @param airport code
* @return airport meaning
*************************************************************/
YAHOO.aerlingus.options.getAirportMeaningFromCode = function(airportCode){
    var countryOptions,i,countryOpt,j,airportOption,len;
    countryOptions = ALL_OPTIONS;
    //iterate through origin countries
    outer_loop:
    for (i = 0, len = countryOptions.length; i < len; ++i) {
       countryOpt = countryOptions[i];
       //iterate through origin country airports
       for (j = 0, sublen = countryOpt.country.airports.length; j < sublen; ++j) {
           airportOption = countryOpt.country.airports[j];
           //if current airport code is same as code passed in as arg then we want to return the
           //meaning of this airport
           if(trim(airportOption.airport.code, ' ') == airportCode){
            return airportOption.airport.meaning;
           }
       }
    }
    return '';
}
 
/*******************************************
* @method getInputElements()
* @param element
* @return INPUT element(s)
********************************************/
getInputElements = function(element) {
    return(element.tagName=="INPUT");
}
 
/*******************************************
* @method getLIElements()
* @param element
* @return LI element(s)
********************************************/
getLIElements = function(element) {
    return(element.tagName=="LI");
}
 
/*******************************************
* @method getSpanElements()
* @param element
* @return SPAN element(s)
********************************************/
getSpanElements = function(element) {
    return(element.tagName=="SPAN");
}
 
/*******************************************
* @method getDivElements()
* @param element
* @return DIV element(s)
********************************************/
getDivElements = function(element) {
    return(element.tagName=="DIV");
}


/* START - Client side sorting */
 
YAHOO.aerlingus.options.sort.getSortedAirportsByMeaning = function(countryOptions) {
    var sortedAirports,countryOpt,airports,j,len,i;
    sortedAirports = [];
    for (i = 0, len = countryOptions.length; i < len; ++i) {
        countryOpt = countryOptions[i];
        airports = countryOptions[i].country.airports;
        for (j = 0, sublen = airports.length; j < sublen; ++j) {
            sortedAirports[sortedAirports.length++] = new YAHOO.aerlingus.options.makePair(countryOpt,airports[j]);
        }
    }
    return sortedAirports.sort(YAHOO.aerlingus.options.sort.sortByMeaning);
}
 
YAHOO.aerlingus.options.sort.getSortedPriorityAirportsByMeaning = function(countryOptions, countryCode) {
    var sortedAirports,priorityAirports,i,countryOpt,j,k,airportOpt;
    sortedAirports = [];
    priorityAirports = new YAHOO.util.LocalDataSource(YAHOO.aerlingus.options.priorityAirportCodes[countryCode]);
    for (i = 0; i < countryOptions.length; i++) {
        countryOpt = countryOptions[i];
        //if the country code is same as countryCode
        if(countryOpt.country.code == countryCode){
            //then we want to iterate through the airports and remove the ones that are not priorities
            for (j = 0, sublen = countryOpt.country.airports.length; j < sublen; ++j) {
                airportOpt = countryOpt.country.airports[j];
                for (k = 0; k < priorityAirports.liveData.length; k++){
                    if(priorityAirports.liveData[k] == airportOpt.airport.code){
                        sortedAirports[sortedAirports.length++] = new YAHOO.aerlingus.options.makePair(countryOpt,airportOpt);
                    }
                }
            }
            break;
        }
    }
    return sortedAirports.sort(YAHOO.aerlingus.options.sort.sortByMeaning);
}

YAHOO.aerlingus.options.sort.sortByMeaning = function(a, b) {
    var x,y;
    x = a.obj2.airport.meaning.toLowerCase();
    y = b.obj2.airport.meaning.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
 
/*END - Client side sorting */
 

function trim(str, chars) {
 return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
 chars = chars || "\\s";
 return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
 chars = chars || "\\s";
 return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
 
/******************************************************
* Converts HTML encoding of foreign language characters
* to normal characters e.g &#193; = Á
* @method YAHOO.aerlingus.options.htmlEntityDecode()
* @param string code 
* @return string value
*******************************************************/
YAHOO.aerlingus.options.htmlEntityDecode = function(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}
 
/****************************************************************
* resends autocomplete query when down arrow is pressed on the 
* search text field to show auto complete options
* @method YAHOO.aerlingus.options.handleSearchKeyPress()
* @param type, args, obj
*****************************************************************/
YAHOO.aerlingus.options.handleSearchKeyPress = function(type, args, obj) {
    switch (args[0]) {
        case 40:    //DOWN
            var txtElement,autoComp;
            txtElement = YAHOO.util.Event.getTarget(args[1]);
            autoComp = YAHOO.aerlingus.options.getAutoCompleteInstance(txtElement);
            if(autoComp != undefined)
                if(!autoComp.isContainerOpen()){
                    autoComp.sendQuery(txtElement.value);
                }
            break;
    }
}
 
YAHOO.aerlingus.options.removePriorityPrefix = function(value){
    var prefixRegex,matchIndex;
    prefixRegex = PRIORITY_PREFIX;
    matchIndex = value.search(prefixRegex);
    if(matchIndex != -1)
        value = value.substring(4,value.length);
    return value;
}

/* START - Auto Complete Funcs */
 
/************************************************
* @method YAHOO.aerlingus.options.autoComplete.makePair()
* @param code, meaning
*************************************************/
YAHOO.aerlingus.options.makePair = function(obj1, obj2) { 
 this.obj1=obj1; 
 this.obj2=obj2; 
} 
 
/****************************************************************
* @method YAHOO.aerlingus.options.autoComplete.generateAutoCompleteData()
* @param array of options, string 
* @return list of auto complete options
*****************************************************************/
YAHOO.aerlingus.options.autoComplete.generateAutoCompleteData = function(airportCountryCombos, ond) {
    var autoCompleteData,count,countryOpt,airportOpt,airport,code,meaning,i;
    autoCompleteData = [];
    count = 0;
    //iterate through origin airports 
    for (i = 0, leni = airportCountryCombos.length; i < leni; ++i) {
        countryOpt = airportCountryCombos[i].obj1;
        airportOpt = airportCountryCombos[i].obj2;
        airport = airportOpt.airport;
        //make a list of code/meaning pairs
        code = YAHOO.aerlingus.options.htmlEntityDecode(airport.code);
        meaning = YAHOO.aerlingus.options.htmlEntityDecode(airport.meaning + ' ('+airport.code+'), '+countryOpt.country.meaning);
        autoCompleteData[count] = new YAHOO.aerlingus.options.makePair(code, meaning);
        count++;
    }
    return autoCompleteData;
}
 
/****************************************************************
* Will move a priority airport up in the list and move the corresponding
* airport down where the priority airport should be alphabetically 
* @method YAHOO.aerlingus.options.switchRow()
* @param priorityPair, currIndex, priorityIndex, autoCompleteData
* @return list of auto complete options
*****************************************************************/
YAHOO.aerlingus.options.switchRow = function(priorityPair, currIndex, priorityIndex, data){
 var switchPair = data[priorityIndex];
 data[priorityIndex] = priorityPair;
 data[currIndex] = switchPair;
 return data;
}
 
/********************************************************************
* This function develops the auto complete options and sets up the
* handler to enable the selected option to be stored in a hidden field
* @method YAHOO.aerlingus.options.autoComplete.initAutoComplete()
* @param input element, auto complete panel, string, array of options  
*********************************************************************/
YAHOO.aerlingus.options.autoComplete.initAutoComplete = function(txtElement, pnlContents, ond, options) {
    var autoCompleteData,dataSource,autoComp,hiddenField, myAC,airportCountryCombos,elLI,oData,result,itemSelectHandler,itemMouseOverHandler,dataReturnHandler,resultsArray,pnlOND,pnlResults,pnlAutoComplete,pnlEntryError,originPositionListener,destinationPositionListener;
    autoCompleteData = [];
    try{
        //options sorted by airport meaning with country information included 
        airportCountryCombos = YAHOO.aerlingus.options.sort.getSortedAirportsByMeaning(options);
        autoCompleteData = new YAHOO.aerlingus.options.autoComplete.generateAutoCompleteData(airportCountryCombos, ond);
    }catch(x){
        return;
    }
    //define the datasource object
    dataSource = new YAHOO.widget.DS_JSArray(autoCompleteData);
    dataSource.responseSchema = {fields : ["obj2", "obj1"]};
    autoComp;
    //we need to destroy any previously created auto complete destination 
    //instance before creating a new one as it will interfere with any new instance we create 
    if(ond == DESTINATION){
        if(undefined != AUTOCOMPDESTINATIONINSTANCE){
            autoComp = AUTOCOMPDESTINATIONINSTANCE;
            autoComp.destroy();
        }
    }
    //define the AutoComplete object with the origin or destination elements
    autoComp = new YAHOO.widget.AutoComplete(txtElement, pnlContents, dataSource);
    //auto highlight must be true for type ahead to work
    autoComp.autoHighlight = false;
    autoComp.typeAhead = true;
    //Whether or not to use an iFrame to layer over Windows form elements in IE. Set to true only when the results container will be on top of a <select> field in IE and thus exposed to the IE z-index bug (i.e., 5.5 < IE < 7).
    autoComp.useIFrame = true;
    autoComp.animVert = false;
    autoComp.animHoriz = false;
    autoComp.maxResultsDisplayed = 20;
    autoComp.resultTypeList = false
    //number of characters typed before auto complete dialog opens
    autoComp.minQueryLength = 3;
    //use of rop shadow behind auto complete dialog
    autoComp.useShadow = false;
    // Match results that *contain* the query string as well as results that start with query string
    autoComp.applyLocalFilter = true; 
    autoComp.queryMatchContains = true;
    //the airport code is going to be placed in a hidden field
    hiddenField = YAHOO.aerlingus.options.getHiddenElement(OUTER_ORIGIN_PANEL);
    if(ond == DESTINATION)
        hiddenField = YAHOO.aerlingus.options.getHiddenElement(OUTER_DESTINATION_PANEL);
    //handles selections made on an li element and places the code value in a hidden field
    itemSelectHandler = function(sType, aArgs) {
        myAC = aArgs[0]; // reference back to the AC instance
        elLI = aArgs[1]; // reference to the selected LI element
        oData = aArgs[2]; // object literal of selected item's result data
        // update hidden form field with the selected item's ID
        hiddenField.value = YAHOO.aerlingus.options.removePriorityPrefix(oData.obj1);
    };
    itemMouseOverHandler = function(sType, sQuery) {
        //search txt element
        txtElement = sQuery[0]._elTextbox;        
        //rollover li text value
        result = sQuery[1]._sResultMatch;
        //put result in search text box
        txtElement.value = result;
    };
    dataReturnHandler = function(oSelf , sQuery , oResults) {
        resultsArray = sQuery[2]; // reference back to the AC instance
        txtElement = sQuery[0]._elTextbox;
        pnlOND = Dom.getAncestorByTagName(txtElement.id, "DIV");
        pnlResults = Dom.getNextSibling(pnlOND);
        pnlAutoComplete = Dom.getNextSibling(pnlResults);
        pnlEntryError = Dom.getNextSibling(pnlAutoComplete);
        //display error dialog box
        if(resultsArray.length == 0){
        	YAHOO.aerlingus.ie6Utils.makeWindowed(pnlEntryError);
            Dom.setStyle(pnlEntryError, 'visibility', 'visible');
        }else{
            Dom.setStyle(pnlEntryError, 'visibility', 'hidden');
        }
    };
    autoComp.itemSelectEvent.subscribe(itemSelectHandler);
    autoComp.dataReturnEvent.subscribe(dataReturnHandler);
    autoComp.itemMouseOverEvent.subscribe(itemMouseOverHandler);
    //store the auto complete instance so we have it to destroy later when we need to update it
    if(ond == ORIGIN && AUTOCOMPORIGININSTANCE == undefined){
        AUTOCOMPORIGININSTANCE = autoComp;
        //we need to set the blur, focus and key press events back on the origin element as it has been removed by calling destroy() above
        YAHOO.util.Event.addListener(ORIGIN_SEARCH_ELEMENT, 'blur',YAHOO.aerlingus.options.searchOriginElement_Blur);
        YAHOO.util.Event.addListener(ORIGIN_SEARCH_ELEMENT, 'focus',YAHOO.aerlingus.options.searchElement_Focus);
        originPositionListener = new YAHOO.util.KeyListener(ORIGIN_SEARCH_ELEMENT, { keys:[40,38] }, { fn:YAHOO.aerlingus.options.handleSearchKeyPress } );
        originPositionListener.enable();
    }else if(ond == DESTINATION){
        AUTOCOMPDESTINATIONINSTANCE = autoComp;
        //we need to set the blur, focus and key press events back on the destination element as it has been removed by calling destroy() above
        YAHOO.util.Event.addListener(DESTINATION_SEARCH_ELEMENT, 'blur',YAHOO.aerlingus.options.searchDestinationElement_Blur);
        YAHOO.util.Event.addListener(DESTINATION_SEARCH_ELEMENT, 'focus',YAHOO.aerlingus.options.searchElement_Focus);
        destinationPositionListener = new YAHOO.util.KeyListener(DESTINATION_SEARCH_ELEMENT, { keys:[40,38] }, { fn:YAHOO.aerlingus.options.handleSearchKeyPress } );
        destinationPositionListener.enable();
    }
}
 
/* END - Auto Complete Funcs */
 
/* START: Search Type Functions */ 
 
/********************************************************************
* Sets the search type (fixed/flexible) based on whether the route
* selected is a fixed route or not. fixedSearchRoutes array defines
* fixed routes
* @method YAHOO.aerlingus.searchType.setDefaultSearchType()
*********************************************************************/
YAHOO.aerlingus.searchType.setDefaultSearchType = function(){
 var pnlRadioGroup,radioElements;
 pnlRadioGroup = Dom.get(SEARCH_TYPE_BUTTON_PANEL);
 if(pnlRadioGroup!=null){
 radioElements = Dom.getChildrenBy(pnlRadioGroup, getInputElements);
 if(!radioElements[0].disabled){
		if(YAHOO.aerlingus.fareCategory.isBusinessRoute()){
			YAHOO.aerlingus.fareCategory.disableFareCategory(false);
		}else{
			YAHOO.aerlingus.fareCategory.disableFareCategory(true);
		}
		YAHOO.aerlingus.fareCategory.fareType_Load();
    }
    }
}

/********************************************************************
* Sets the search type (fixed/flexible) based on value entered
* @method YAHOO.aerlingus.searchType.setSearchType()
*********************************************************************/
YAHOO.aerlingus.searchType.setFlexibleSearchType = function(value){
 var pnlRadioGroup,radioElements;
 pnlRadioGroup = Dom.get(SEARCH_TYPE_BUTTON_PANEL);
 radioElements = Dom.getChildrenBy(pnlRadioGroup, getInputElements);
 if(value){
	 radioElements[0].checked = true;
 }else{
	 radioElements[1].checked = true;
 }
}

 
/********************************************************************
* Returns the product value of the origin and destination airport 
* code selections e.g Dublin -> Shannon: Product value = DUBSNN
* @method YAHOO.aerlingus.searchType.getSelectedRouteCode()
* @return string selectedRouteCode
*********************************************************************/
YAHOO.aerlingus.searchType.getSelectedRouteCode = function(){
 var hiddenOriginValue,hiddenDestinationValue,selectedRouteCode;
 hiddenOriginValue = YAHOO.aerlingus.options.getHiddenElement(OUTER_ORIGIN_PANEL).value;
 hiddenDestinationValue = YAHOO.aerlingus.options.getHiddenElement(OUTER_DESTINATION_PANEL).value;
 selectedRouteCode = hiddenOriginValue + hiddenDestinationValue;
 return selectedRouteCode;
}
 
/********************************************************************
* Returns true if the selected route code e.g DUBSNN is equal to 
* one defined in the fixedSearchRoutes array
* @method YAHOO.aerlingus.searchType.isFixedSearchRoute()
* @return boolean
*********************************************************************/
YAHOO.aerlingus.searchType.isFixedSearchRoute = function(){
 var selectedRouteCode,len,i;
 selectedRouteCode = YAHOO.aerlingus.searchType.getSelectedRouteCode();
 len = fixedSearchRoutes.length;
 for (i = 0; i < len; i++) {
  if (fixedSearchRoutes[i]==selectedRouteCode) {
   return true;
  }
 }
 return false;
}

/********************************************************************
* Disables the flex search yes radio option if the user has selected 
* promotional flights yes. Enables if no selected
* @method YAHOO.aerlingus.promotionalFlights.corporateRate_Click()
*********************************************************************/
YAHOO.aerlingus.promotionalFlights.corporateRate_Click = function(e){
	var radioElement,pnlSearchTypeRadioGroup,searchTypeRadioElements;
	radioElement = YAHOO.util.Event.getTarget(e);
	pnlSearchTypeRadioGroup = Dom.get(SEARCH_TYPE_BUTTON_PANEL);
	searchTypeRadioElements = Dom.getChildrenBy(pnlSearchTypeRadioGroup, getInputElements);
	if (radioElement.value == "true") {
		searchTypeRadioElements[0].disabled=true;
		searchTypeRadioElements[1].checked=true;
		if(YAHOO.aerlingus.fareCategory.isBusinessRoute()){
			YAHOO.aerlingus.fareCategory.disableFareCategory(false);
		}
	}else{
		searchTypeRadioElements[0].disabled=false;
		searchTypeRadioElements[0].checked=true;
		YAHOO.aerlingus.fareCategory.selectFareCategory(0);
		if(YAHOO.aerlingus.fareCategory.isBusinessRoute()){
			YAHOO.aerlingus.fareCategory.disableFareCategory(false);
		}else{
			YAHOO.aerlingus.fareCategory.disableFareCategory(true);
		}
	}
}


/********************************************************************
* Default settings for corporate page load
* @method YAHOO.aerlingus.promotionalFlights.corporate_Load()
*********************************************************************/
YAHOO.aerlingus.promotionalFlights.corporate_Load = function(){
	var pnlPromotionalFlightsRadioGroup,promotionalFlightsRadioElements,pnlSearchTypeRadioGroup,searchTypeRadioElements;
	pnlPromotionalFlightsRadioGroup = Dom.get(PROMOTIONAL_FLIGHTS_BUTTON_PANEL);
	promotionalFlightsRadioElements = Dom.getChildrenBy(pnlPromotionalFlightsRadioGroup, getInputElements);
	promotionalFlightsRadioElements[0].checked=true;
	promotionalFlightsRadioElements[1].checked=false;
	YAHOO.aerlingus.searchType.setFlexibleSearchType(false);
}

/********************************************************************
* Disables/Enables fare category drop down options on flex click
* @method YAHOO.aerlingus.fareCategory.flexibleDate_Click()
*********************************************************************/
YAHOO.aerlingus.fareCategory.flexibleDate_Click = function(e){
	YAHOO.aerlingus.fareCategory.selectFareCategory(0);
}

/********************************************************************
 * We need to set the Flexible date to no if fare type on page load
 * is set to business
* @method YAHOO.aerlingus.fareCategory.fareType_Load()
*********************************************************************/
YAHOO.aerlingus.fareCategory.fareType_Load = function(){
	var selectElement = Dom.get(FARE_CATEGORY_SELECT_ELEMENT);
	if (selectElement.selectedIndex == 1)
		//select flexible date option No
		YAHOO.aerlingus.searchType.setFlexibleSearchType(false);
	else
		//select flexible date option Yes
		YAHOO.aerlingus.searchType.setFlexibleSearchType(true);
}


/********************************************************************
* @method YAHOO.aerlingus.fareCategory.fareType_Change()
*********************************************************************/
YAHOO.aerlingus.fareCategory.fareType_Change = function(e){
	var selectElement = YAHOO.util.Event.getTarget(e);
	if (selectElement.selectedIndex == 1)
		//select flexible date option No
		YAHOO.aerlingus.searchType.setFlexibleSearchType(false);
	else
		//select flexible date option Yes
		YAHOO.aerlingus.searchType.setFlexibleSearchType(true);
		
}

YAHOO.util.Event.addListener(FARE_CATEGORY_SELECT_ELEMENT, "change", YAHOO.aerlingus.fareCategory.fareType_Change);

 
/* END: Search Type Functions */ 
 
/* START: Fare Category Functions */ 
 
/********************************************************************
* Selects indexed fare category drop down option
* @method YAHOO.aerlingus.fareCategory.selectFareCategory()
* @param boolean
*********************************************************************/
YAHOO.aerlingus.fareCategory.selectFareCategory = function(index){
	var fareCategorySelectElement,len,i,fareCat;
	fareCategorySelectElement = Dom.get(FARE_CATEGORY_SELECT_ELEMENT);
	fareCategorySelectElement.options[index].selected=true;
}

/********************************************************************
* Disables/Enables fare category drop down options
* @method YAHOO.aerlingus.fareCategory.disableFareCategory()
* @param boolean
*********************************************************************/
YAHOO.aerlingus.fareCategory.disableFareCategory = function(disable){
 var fareCategorySelectElement,len,i,fareCat;
 fareCategorySelectElement = Dom.get(FARE_CATEGORY_SELECT_ELEMENT);
 if (disable == false){
  //enable the fare category drop down
  fareCategorySelectElement.disabled=false;
 } else {
  // select the "lowest" option
  len = fareCategorySelectElement.length;
  for (i = 0; i < len; i++) {
   fareCat = fareCategorySelectElement.options[i].value;
   if (fareCat == 0){
    fareCategorySelectElement.options[i].selected=true;
    break;
   }
  }
  // disable the fare category drop down
  fareCategorySelectElement.disabled=true;
 }
}

YAHOO.aerlingus.fareCategory.disableBusiness = function(){
   var onlyBusinessRoutes = YAHOO.aerlingus.fareCategory.isBusinessRoute();
   YAHOO.aerlingus.fareCategory.disableFareCategory(!onlyBusinessRoutes);
}
 
/********************************************************************
* Returns true if the selected route code e.g DUBSNN is equal to 
* one defined in the businessRoutes array
* @method YAHOO.aerlingus.searchType.isBusinessRoute()
* @return boolean
*********************************************************************/
YAHOO.aerlingus.fareCategory.isBusinessRoute = function(){
 var selectedRouteCode,len,i;
 selectedRouteCode = YAHOO.aerlingus.searchType.getSelectedRouteCode();
 len = businessRoutes.length;
 for (i = 0; i < len; i++) {
  if (businessRoutes[i]==selectedRouteCode) {
   return true;
  }
 }
 return false;
}
 
/********************************************************************
* Disables the fare category dropdown if the user has selected 
* flexible search. Note: unlike disableFareCategory, this function 
* will never enable the fare category dropdown
* @method YAHOO.aerlingus.fareCategory.disableFareCatForFlexible()
*********************************************************************/
YAHOO.aerlingus.fareCategory.disableFareCatForFlexible = function(){
 var fareCategorySelectElement,pnlRadioGroup,radioElements;
 fareCategorySelectElement = Dom.get(FARE_CATEGORY_SELECT_ELEMENT);
 pnlRadioGroup = Dom.get(SEARCH_TYPE_BUTTON_PANEL);
 radioElements = Dom.getChildrenBy(pnlRadioGroup, getInputElements);
 if(!YAHOO.aerlingus.fareCategory.isBusinessRoute()){
  if (radioElements[0].checked == true) {
   fareCategorySelectElement.disabled=true;
  }
 }
}
 
/* END: Fare Category Functions */


/********************************************************************
 * 
 * @method YAHOO.aerlingus.calendar.initialiseDates_Load
 ********************************************************************/
YAHOO.aerlingus.calendar.initialiseDates_Load = function(){
	var todaysDate = new Date(), depMonthElement, retMonthElement, thisMonth, i, longMonths, oOptionDep, oOptionRet, depDayElement, retDayElement;
	longMonths= MONTHS_LONG;
	thisMonth = parseInt(todaysDate.getMonth());
	depMonthElement = Dom.get(SELECTED_DEPARTURE_MONTH);
	retMonthElement = Dom.get(SELECTED_RETURN_MONTH);
	for(i=0;i<12;i++){
		oOptionDep = document.createElement('option');
		oOptionRet = document.createElement('option');
		oOptionDep.value = (thisMonth+i)%12;
		oOptionRet.value = (thisMonth+i)%12;
		oOptionDep.title = longMonths[(thisMonth+i)%12];
		oOptionRet.title = longMonths[(thisMonth+i)%12];
		oOptionDep.innerHTML = longMonths[(thisMonth+i)%12];
		oOptionRet.innerHTML = longMonths[(thisMonth+i)%12];
	    depMonthElement.appendChild(oOptionDep);
	    retMonthElement.appendChild(oOptionRet);
	}
	depDayElement = Dom.get(SELECTED_DEPARTURE_DAY);
	retDayElement = Dom.get(SELECTED_RETURN_DAY);
	YAHOO.aerlingus.calendar.updateNumberOfDays(depMonthElement, depDayElement);
	YAHOO.aerlingus.calendar.updateNumberOfDays(retMonthElement, retDayElement);	
}

/*********************************************************************
 * Update number of days in the month selected
 * @method YAHOO.aerlingus.calendar.updateNumberOfDays
 *********************************************************************/
YAHOO.aerlingus.calendar.updateNumberOfDays = function(monElement, dayElement){
	var monthSelected = monElement.value;
	var intMonthSelected = parseInt(monthSelected,10);
	// check to see if the month is for this year or next year,
	// e.g if it's less than todays month it in next year so change the year to the following year
	var currDate = new Date();
	var currMonth = (currDate.getUTCMonth());
	var currYear = currDate.getYear();
	if (intMonthSelected < currMonth) {
		var numOfDays = YAHOO.aerlingus.utils.getLenMonth(currYear + 1, intMonthSelected);
	} else {
		var numOfDays = YAHOO.aerlingus.utils.getLenMonth(currYear, intMonthSelected);
	}
	// change the days in the corresponding day combo box
	// to equal the number of days for the selected month
	YAHOO.aerlingus.calendar.populateDays(numOfDays, dayElement); 
}

/*********************************************************************
 * Helper method to populate the number of days for the selected month
 * @method YAHOO.aerlingus.calendar.populateDays
 *********************************************************************/
YAHOO.aerlingus.calendar.populateDays = function (numOfDays, daySel) {
	var len, selectedDay, today;
	len = daySel.length;
	today = new Date();
	//if there are no days already in the f=drop down then we must be 
	//coming to it from load so we set todays day as selected
	if(len != 0)
		selectedDay = daySel.value;
	else{
		selectedDay = today.getDate()+1;
	}
	// clear the array
	for (var i = 0; i < len; i++) {
		daySel.options[i] = null;
	}
	daySel.length = numOfDays;
	// populate the array with the days
	for(var i = 0; i < numOfDays; i++) {
		daySel.options[i] = new Option(i+1);
		daySel.options[i].value = (i+1);
		if (i == (selectedDay - 1)) {
			daySel.options[i].selected = true
		}
	}
}

/********************************************************************
 * if the flight type is set to oneway on load then we need to 
 * disable the return dates drop downs
 * @method YAHOO.aerlingus.calendar.selectFlightType_Load
 ********************************************************************/
YAHOO.aerlingus.calendar.selectFlightType_Load = function(){
	var onewayTypeElement = Dom.get(ONEWAY_TYPE);
	if(onewayTypeElement!=null){
	    var returnDayElement = Dom.get(SELECTED_RETURN_DAY);
	    var returnMonthElement = Dom.get(SELECTED_RETURN_MONTH);
	    if(onewayTypeElement.checked == true){
		    returnDayElement.disabled = true;
		    returnMonthElement.disabled = true;
	    }else{
		    returnDayElement.disabled = false;
		    returnMonthElement.disabled = false;		
	    }
	}
}

/********************************************************************
 * if the flight type is set to oneway on radio click then we need to 
 * disable the return dates drop downs
 * @method YAHOO.aerlingus.calendar.selectFlightType_Click
 ********************************************************************/
YAHOO.aerlingus.calendar.selectFlightType_Click = function(e){
	var elTarget = YAHOO.util.Event.getTarget(e);
	var returnDayElement = Dom.get(SELECTED_RETURN_DAY);
	var returnMonthElement = Dom.get(SELECTED_RETURN_MONTH);
	if(elTarget.id == ONEWAY_TYPE){
		returnDayElement.disabled = true;
		returnMonthElement.disabled = true;
	}else{
		returnDayElement.disabled = false;
		returnMonthElement.disabled = false;		
	}
		
}

/********************************************************************
 * when the dom is ready we want to set the departure dates on the 
 * calendar to those selected in the departure drop downs
 * @method YAHOO.aerlingus.calendar.setCalendarDeparture_Load
 ********************************************************************/
YAHOO.aerlingus.calendar.setCalendarDeparture_Load = function(){
	var departureDay = parseInt(Dom.get(SELECTED_DEPARTURE_DAY).value);
	var departureMonth = parseInt(Dom.get(SELECTED_DEPARTURE_MONTH).value);
	var departureYear = YAHOO.aerlingus.calendar.getYear(departureDay, departureMonth);
	YAHOO.aerlingus.calendar.setDepartureDate(departureDay, departureMonth, departureYear);
}

/********************************************************************
 * when the dom is ready we want to set the return dates on the 
 * calendar to those selected in the return drop downs
 * @method YAHOO.aerlingus.calendar.setCalendarReturn_Load
 ********************************************************************/
YAHOO.aerlingus.calendar.setCalendarReturn_Load = function(){
	var returnDay = parseInt(Dom.get(SELECTED_RETURN_DAY).value);
	var returnMonth = parseInt(Dom.get(SELECTED_RETURN_MONTH).value);
	var returnYear = YAHOO.aerlingus.calendar.getYear(returnDay, returnMonth);
	YAHOO.aerlingus.calendar.setReturnDate(returnDay, returnMonth, returnYear);
}

/*********************************************************************
 * When user selects the departure date we update the return date if it
 * is set less than the selected depart date
 * @method YAHOO.aerlingus.calendar.selectDepartureDay_Change
 *********************************************************************/
YAHOO.aerlingus.calendar.selectDeparture_Change = function(){
	var departureDay = parseInt(Dom.get(SELECTED_DEPARTURE_DAY).value);
	var departureMonth = parseInt(Dom.get(SELECTED_DEPARTURE_MONTH).value);
	var departureMonthIndex = parseInt(Dom.get(SELECTED_DEPARTURE_MONTH).selectedIndex);
	var departureYear = YAHOO.aerlingus.calendar.getYear(departureDay, departureMonth);
	var returnDay = Dom.get(SELECTED_RETURN_DAY).value;
	var returnMonth = Dom.get(SELECTED_RETURN_MONTH).value;
	var returnMonthIndex = Dom.get(SELECTED_RETURN_MONTH).selectedIndex;
	var returnYear = YAHOO.aerlingus.calendar.getYear(returnDay, returnMonth);
	if ((departureMonth == returnMonth) && (returnDay < departureDay) ){
		YAHOO.aerlingus.calendar.updateReturnDates(departureDay, returnMonth);
	}else if(departureMonthIndex > returnMonthIndex){
		YAHOO.aerlingus.calendar.selectDepartureMonth_Change();
	}
	YAHOO.aerlingus.calendar.updateNumberOfDays(Dom.get(SELECTED_DEPARTURE_MONTH),Dom.get(SELECTED_DEPARTURE_DAY));
	YAHOO.aerlingus.calendar.setDepartureDate(departureDay, departureMonth, departureYear);
}

/*********************************************************************
 * When user selects the departure month we update the return date if it
 * is set less than the selected depart day
 * @method YAHOO.aerlingus.calendar.selectDepartureMonth_Change
 *********************************************************************/
YAHOO.aerlingus.calendar.selectDepartureMonth_Change = function(){
	var dayCombo = Dom.get(SELECTED_DEPARTURE_DAY);
	var monthCombo = Dom.get(SELECTED_DEPARTURE_MONTH);
	// get the month selected index and the month value
	var depMonthSelectedIndex = monthCombo.selectedIndex;
	var depMonthSelected = monthCombo.value;
	var intMonthSelected = parseInt(depMonthSelected,10);
	var retMonthSelectedIndex = Dom.get(SELECTED_RETURN_MONTH).selectedIndex;
	if (retMonthSelectedIndex < depMonthSelectedIndex){
		YAHOO.aerlingus.calendar.updateReturnDates(dayCombo.value, Dom.get(SELECTED_DEPARTURE_MONTH).value);
		YAHOO.aerlingus.calendar.updateNumberOfDays(Dom.get(SELECTED_RETURN_MONTH),Dom.get(SELECTED_RETURN_DAY));
	}
	// need to call selectDepartureDay_Change() to alter the return day if it is before the depart day
	YAHOO.aerlingus.calendar.selectDeparture_Change();
}

/*********************************************************************
 * When user selects the return date we update the number of days in 
 * the month
 * @method YAHOO.aerlingus.calendar.selectReturnMonth_Change
 *********************************************************************/
YAHOO.aerlingus.calendar.selectReturn_Change = function(){
	var returnDay = Dom.get(SELECTED_RETURN_DAY).value;
	var returnMonth = Dom.get(SELECTED_RETURN_MONTH).value;
	var returnYear = YAHOO.aerlingus.calendar.getYear(returnDay, returnMonth);
	YAHOO.aerlingus.calendar.updateNumberOfDays(Dom.get(SELECTED_RETURN_MONTH),Dom.get(SELECTED_RETURN_DAY));	
	YAHOO.aerlingus.calendar.setReturnDate(returnDay, returnMonth, returnYear);
}

/*********************************************************************
 * Update number of days in the month selected
 * @method YAHOO.aerlingus.calendar.updateNumberOfDays
 *********************************************************************/
YAHOO.aerlingus.calendar.updateNumberOfDays = function(monElement, dayElement){
	var monthSelected = monElement.value;
	var intMonthSelected = parseInt(monthSelected,10);
	// check to see if the month is for this year or next year,
	// e.g if it's less than todays month it in next year so change the year to the following year
	var currDate = new Date();
	var currMonth = (currDate.getUTCMonth());
	var currYear = currDate.getYear();
	if (intMonthSelected < currMonth) {
		var numOfDays = YAHOO.aerlingus.calendar.getLenMonth(currYear + 1, intMonthSelected);
	} else {
		var numOfDays = YAHOO.aerlingus.calendar.getLenMonth(currYear, intMonthSelected);
	}	
	// change the days in the corresponding day combo box
	// to equal the number of days for the selected month
	YAHOO.aerlingus.calendar.populateDays(numOfDays, dayElement);
}

/*********************************************************************
 * Set selected departure date
 * @method YAHOO.aerlingus.calendar.setDepartureDate
 *********************************************************************/
YAHOO.aerlingus.calendar.setDepartureDate = function(departureDay, departureMonth, departureYear){
	var depDate = new Date();
	var monthLen = YAHOO.aerlingus.calendar.getLenMonth(departureYear, departureMonth);
	depDate.setMonth(departureMonth);
	//if we select a month from month drop down and the day value goes back to one coz
	//month is shorter than previously selected then we need to update the return date
	//for the calendar to get it right
	if(monthLen < departureDay)
		depDate.setDate(1);
	else
		depDate.setDate(departureDay);
	depDate.setFullYear(departureYear);
	DEPARTURE_DATE = YAHOO.aerlingus.calendar.formatDate(depDate);
}

/*********************************************************************
 * Set selected return date
 * @method YAHOO.aerlingus.calendar.setReturnDate
 *********************************************************************/
YAHOO.aerlingus.calendar.setReturnDate = function(returnDay, returnMonth, returnYear){
	var retDate = new Date();
	var monthLen = YAHOO.aerlingus.calendar.getLenMonth(returnYear, returnMonth);
	retDate.setMonth(returnMonth);
	//if we select a month from month drop down and the day value goes back to one coz
	//month is shorter than previously selected then we need to update the return date
	//for the calendar to get it right
	if(monthLen < returnDay)
		retDate.setDate(1);
	else
		retDate.setDate(returnDay);
	retDate.setFullYear(returnYear);
	RETURN_DATE = YAHOO.aerlingus.calendar.formatDate(retDate);
}


/*********************************************************************
 * Helper method to return the year based on the selected day and month
 * @method YAHOO.aerlingus.calendar.getYear 
 * @return full year
 *********************************************************************/
YAHOO.aerlingus.calendar.getYear = function(day, month){
	var date = new Date();
	if(month < date.getMonth() || (month == date.getMonth() && day < date.getDate())){
		return date.getFullYear() + 1;
	}else{
		return date.getFullYear();
	}
}

/*********************************************************************
 * Helper method to populate the number of days for the selected month
 * @method YAHOO.aerlingus.calendar.populateDays
 *********************************************************************/
YAHOO.aerlingus.calendar.populateDays = function (numOfDays, daySel) {
	var len, selectedDay, today;
	len = daySel.length;
	today = new Date();
	//if there are no days already in the f=drop down then we must be 
	//coming to it from load so we set todays day as selected
	if(len != 0)
		selectedDay = daySel.value;
	else{
		selectedDay = today.getDate()+1;
	}
	// clear the array
	for (var i = 0; i < len; i++) {
		daySel.options[i] = null;
	}
	daySel.length = numOfDays;
	// populate the array with the days
	for(var i = 0; i < numOfDays; i++) {
		daySel.options[i] = new Option(i+1);
		daySel.options[i].value = (i+1);
		if (i == (selectedDay - 1)) {
			daySel.options[i].selected = true
		}
	}
}

/*********************************************************************
 * Helper method to get the number of days in a month
 * @method YAHOO.aerlingus.calendar.getLenMonth
 * @return days of month
 *********************************************************************/
YAHOO.aerlingus.calendar.getLenMonth = function(year, month){
	month++;
	var days;
	if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) {
		days=31;
	} else if (month==4 || month==6 || month==9 || month==11) {
		days=30;
	}	else if (month==2) {
		if (YAHOO.aerlingus.calendar.isLeapYear(year)) {
			days=29;
		}	else {
			days=28;
		}
	}
	return (days);
}

/*********************************************************************
 * Helper method to determine if is leap year
 * @method YAHOO.aerlingus.calendar.isLeapYear
 * @return true if leap year and false if not
 *********************************************************************/
YAHOO.aerlingus.calendar.isLeapYear = function(Year) {
	if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
		return (true);
	} else {
		return (false);
	}
}


/*********************************************************************
 * Helper method to update return dates if less than departure dates
 * @method YAHOO.aerlingus.calendar.updateReturnDates
 *********************************************************************/
YAHOO.aerlingus.calendar.updateReturnDates = function(departureDay, departureMonth){
	Dom.get(SELECTED_RETURN_DAY).value = departureDay;
	Dom.get(SELECTED_RETURN_MONTH).value = departureMonth;
	var departureYear = YAHOO.aerlingus.calendar.getYear(departureDay, departureMonth);
	YAHOO.aerlingus.calendar.setReturnDate(departureDay, departureMonth, departureYear);
}

YAHOO.aerlingus.calendar.formatDate = function(date){
	var formattedDate = date.getMonth()+1 +"/"+date.getDate()+"/"+date.getFullYear(); // format "07/24/2009"
	return formattedDate;
}

/********************************************************************
 * Lazy loading of the calendar js and css files
 * @method YAHOO.aerlingus.calendar.calendarOpen
 ********************************************************************/
YAHOO.aerlingus.calendar.calendarOpen = function(e){
	var elTarget = YAHOO.util.Event.getTarget(e);
	if(!CALENDAR_DEPENDENCIES_LOADED){
	    var loader = new YAHOO.util.YUILoader({
		    require: ['container','calendar'], // what components? 
		    base: YUI_BASE_DIR,//where do they live?
		    onSuccess: function() {
            	YAHOO.aerlingus.calendar.showCalendar(elTarget);
		        CALENDAR_DEPENDENCIES_LOADED = true;
		    }

	    }); 
        loader.insert();
	}else
    	YAHOO.aerlingus.calendar.showCalendar(elTarget);
}

YAHOO.aerlingus.calendar.showCalendar = function(elTarget){
    if(elTarget.id == SHOW_DEPARTURE)
	    YAHOO.aerlingus.calendar.loadCalendar(SELECTED_DEPARTURE_DAY, DEPARTURE_LABEL, "dContainer", SELECTED_DEPARTURE_MONTH, DEPARTURE_DATE,elTarget);
    else if(elTarget.id == SHOW_RETURN)
	    YAHOO.aerlingus.calendar.loadCalendar(SELECTED_RETURN_DAY, RETURN_LABEL, "rContainer", SELECTED_DEPARTURE_MONTH, DEPARTURE_DATE,elTarget);
}

/********************************************************************
 * Lazy loading of the depart or return calendar when calendar icon
 * clicked
 * @method YAHOO.aerlingus.calendar.calendarOpen
 ********************************************************************/
YAHOO.aerlingus.calendar.loadCalendar = function(selectedDirectionDay, directionLabel, container, selectedDirectionMonth, directionDate, showBtn){
    var dialog,calendar;
	var minDate = new Date();
	var maxDate = new Date();
	maxDate.setMonth(maxDate.getMonth() + 11);
	var monthLen = YAHOO.aerlingus.calendar.getLenMonth(maxDate.getYear(), maxDate.getMonth());
	maxDate.setDate(monthLen); 
    var MIN_DATE = YAHOO.aerlingus.calendar.formatDate(minDate);
    var MAX_DATE = YAHOO.aerlingus.calendar.formatDate(maxDate);
    if (!dialog) {
        //we want to set the context of which of the elements the popup calendar will appear under
        var daySelectElement = Dom.get(selectedDirectionDay);
        dialog = new YAHOO.widget.Dialog(container, {
            visible:false, 
            context:[daySelectElement, "tl", "bl"], 
            draggable:false,
            close:true
        });
        // Hide Calendar if we click anywhere in the document other than the calendar
        YAHOO.util.Event.on(document, "click", function(e) {
            var el =  YAHOO.util.Event.getTarget(e);
            var dialogEl = dialog.element;
            if (el != dialogEl && !Dom.isAncestor(dialogEl, el) && el != showBtn && !Dom.isAncestor(showBtn, el)) {
                dialog.hide();
            }
        });
        var lblValue = Dom.get(directionLabel).innerHTML;
        dialog.setHeader(lblValue);
        dialog.setBody('<div id="cal"></div>');
        dialog.render(document.body);

        dialog.showEvent.subscribe(function() {
            if (YAHOO.env.ua.ie) {
                // Since we're hiding the table using yui-overlay-hidden, we 
                // want to let the departureDialog know that the content size has changed, when
                // shown
                dialog.fireEvent("changeContent");
            }
        });
    }	
    // Lazy Calendar Creation - Wait to create the Calendar until the first time the button is clicked.
    if (!calendar) {  
        calendar = new YAHOO.widget.CalendarGroup("cal1",container,{PAGES:NUM_CALENDAR_PAGES, LOCALE_WEEKDAYS:"medium", LOCALE_MONTHS:"long"});
        //calendar = new YAHOO.widget.Calendar("cal",{iframe:false,hide_blank_weeks:true});
        calendar.cfg.setProperty("WEEKDAYS_MEDIUM",WEEKDAYS_MEDIUM);
        calendar.cfg.setProperty("MONTHS_LONG",MONTHS_LONG); 
        calendar.cfg.setProperty("MINDATE", MIN_DATE);
        calendar.cfg.setProperty("MAXDATE", MAX_DATE);
        calendar.render();

        calendar.selectEvent.subscribe(function() {
            if (calendar.getSelectedDates().length > 0) {
                var selDate = calendar.getSelectedDates()[0];
            } else {
                //set today's date
                var selDate=new Date();
            }
            // Pretty Date Output, using Calendar's Locale values: Fri, 8 Feb 2008
            var wStr = calendar.cfg.getProperty("WEEKDAYS_MEDIUM")[selDate.getDay()];
            var dStr = selDate.getDate();
            var mStr = calendar.cfg.getProperty("MONTHS_SHORT")[selDate.getMonth()];
            var yStr = selDate.getFullYear();
            Dom.get(selectedDirectionDay).value = dStr;
            Dom.get(selectedDirectionMonth).value = selDate.getMonth();
            dialog.hide();
            if(container == "dContainer")
            	YAHOO.aerlingus.calendar.selectDeparture_Change(Dom.get(selectedDirectionMonth));
            else if(container == "rContainer")
            	YAHOO.aerlingus.calendar.selectReturn_Change(Dom.get(selectedDirectionMonth));
        });
        calendar.renderEvent.subscribe(function() {
            // Tell departureDialog it's contents have changed, which allows 
            // container to redraw the underlay (for IE6/Safari2)
            dialog.fireEvent("changeContent");
        });
    }
    calendar.cfg.setProperty("SELECTED", directionDate);
    var selDate = calendar.getSelectedDates();
    if (selDate.length > 0) {
        // Set the pagedate to show the selected date if it exists
        calendar.cfg.setProperty("pagedate", selDate[0]);
        calendar.render();
    }
    dialog.show(); 
}

/***********************************
 * 
 * A version of doSearch for Static HTML Files
 * 
 ***********************************/
function doStaticSearch(){
	//define static URL 
	var URL = 'http://www.aerlingus.com/cgi-bin/obel01im1/'

	var urlParameters = getURLParameters();
	if(CURRENT_LOCALE)
		urlParameters += '&locale='+CURRENT_LOCALE;
	var eiUrl = URL + 'bookonline/email.jsp?'+urlParameters;
	window.open(eiUrl);
}
