
function searchFormButtonClick(evt) {

	var validator = new SearchValidator();
	if(validator.validate()){

    	showSearchInterstitial();
    	Event.stop(evt);
    	// firefox fails to render the gradient and IE fails to animate the gif
    	// unless we give it a little time to jumpstart
    	var pleaseWaitImg = $('pleaseWaitImg');
    	setTimeout(function() {  $('searchform').submit(); pleaseWaitImg.src = pleaseWaitImg.src; }, getTimeOut());
    }else{
    	Event.stop(evt);
    	showErrors(validator);
    }
}

var errorMap = new Array();
var errorElems = new Array();
function showErrors(validator){

	if($('serverErrors')){
		$('serverErrors').style.display = 'none';
	}
	if($('clientInModuleErrors')){
		$('clientInModuleErrors').style.display = '';
	}
	for(i=0; i<errorElems.length; i++){
		errorElems[i].removeClassName('error');
	}
	$('clientErrorUL').innerHTML = "";
	$(validator.errorHash.values()[0].element).focus();
	validator.errorHash.values().each(function(entry) {
		for (var i=0; i<entry.errorList.length; i++){
    		var html = "\n<li class='error'>" +  errorMap[entry.errorList[i]] + "</li>";
    		$('clientErrorUL').innerHTML += html;
    	}
    	$(entry.label).addClassName("error");
    	errorElems[errorElems.length] = $(entry.label);
    });
}

function getNodeText(e) {
    return (/INPUT/i.test(e.nodeName) ? e.value : getSelectionText(e))
}

function getSelectionText(e) {
    var value, index = e.selectedIndex;
    if (index >= 0) {
        var opt = e.options[index];
        value = opt.text || opt.value;
    }
    return value;

}

function selectCell(evt) {
    var e = Event.element(evt);
    var nl = e.getElementsByTagName('a');
    Event.stop(evt);
    if(nl && nl.length > 0) {
        nl.item(0).click();
    }
}

function showInterstitialSetup() {
    var body = $('theBody');
    if(!body) {
        //for whatever reason, this is an issue in SAFARI
        var f = document.getElementsByTagName('body');
        if(f.length > 0) {
            body = f[0];
        }

    }
    Element.hide('bodyDiv');
    Element.show('interstitial');
    if(body) {
        Element.setStyle(body, {background: '#719ccc url("/images/bg2.gif") repeat-x'});
    }
    window.scrollTo(0, 0);
    if ($('dqmbar')) Element.hide('dqmbar');
}
//The Please Wait image animation doesnt work in IE unless the time out is set specifically.
function setAnimationTimeOut() {
    var pleaseWaitImg = $('pleaseWaitImg');
    setTimeout(function() {
        pleaseWaitImg.src = pleaseWaitImg.src;
    }, getTimeOut());
}

function getTimeOut(){
    var to = 100;
    if (navigator.appVersion.match(/\bMSIE\b/)) {
        to = 1000;
    }
    return to;
}

function buildInterstitialMessage(s) {
    var first = s.indexOf('|');
    var callToAction = "";
    if(first != -1) {
        callToAction = "<h4 class=\"callToAction\">" + s.substring(0, first) + "</h4>";
        s= s.substring(first);
    }
    return callToAction + s.replace(/\|/g, "");
}

function displayDateRange(d1, d2, showRange) {
    if(!showRange) {
        return d1;
    }
    if(isFlexWeekends()){
        var dr1 = $("dateData");
        dr1.innerHTML="";
        return messageab.flexWeekEndsIn;
    }
    return d1 + " - " + d2;
}
function isFlexWeekends(){
    var fw= $('weekendsIn') ;
    if (fw && fw.checked){
        return true;
    }
    else{
        return false;
    }
}


function bindSavedPreferenceViewLink() {
    if(!$('viewPrefLink')) {
        return;
    }

    Event.observe("viewPrefLink", 'click', function() {
        if(Element.visible("contactPhoneRow")) {
            Element.hide("viewLeft");
            Element.show("viewRight");
        } else {
            Element.hide("viewRight");
            Element.show("viewLeft");
        }
        Element.toggle("contactPhoneRow");
        Element.toggle("emergencyContactRow");
        Element.toggle("ssrRow");
    });

}

function getInterstitialText(node) {
    var t = getNodeText(node);

    if(node.lookupValue && node.lookupValue.length > 0) {
        if(window.searchMgr.lookups[t] == node.lookupValue) {
            var r=node.lookupValue;
            return r;
        }
    }
    return t;

}

function updateInterstitialText () {

    var f = $("interstitialFrom");
    var t = $("interstitialTo");
    var d1 = $("departField0");
    var r1 = $("returnField0");
    var zonesearch = $('zone') && $('zone').checked;
    var zonevalue = $('zonevalue');

    if(d1 && $F(d1).length > 0) {
        f.innerHTML = getInterstitialText(d1);
    }
    if(zonesearch) {
        t.innerHTML = getInterstitialText(zonevalue);
    } else if(r1 && $F(r1).length > 0) {
        t.innerHTML = getInterstitialText(r1);
    }

}

function showSearchInterstitial() {

    var t1 = $("departureDateInterstitial");
    var t2 = $("returnDateInterstitial");
    var dr = $("dateRange");
    var drv = "";
    var oneway = $('owOption') && $('owOption').checked;
    var f = $("interstitialFrom");
    var t = $("interstitialTo");
    var d1 = $("departField0");
    var r1 = $("returnField0");
    var zonesearch = $('zone') && $('zone').checked;
    var zonevalue = $('zonevalue');

    updateInterstitialText();

    if(t1 && $F(t1).length > 0) {
        drv = t1.value;
    }
    if(t2 && $F(t2).length > 0) {
        drv = displayDateRange(drv, t2.value, !oneway);
    }
    dr.innerHTML = drv;

    if ($('mcOption').checked) {
        $('interstitialSearch').innerHTML = messagerb.multicity;
    } else if (oneway) {
        $('interstitialSearch').innerHTML = messagerb.oneway;
    } else {
        $('interstitialSearch').innerHTML = messagerb.roundtrip;
    }
    if ($('awardtravel') && $('awardtravel').checked) {
        $('interstitialSearch').innerHTML = messagerb.awardtravel;
    }
   if (($('mileageUpgradeCheckbox') && ($('mileageUpgradeCheckbox').checked)) ) {
        $('interstitialSearch').innerHTML = messagerb.roundtrip;
    }
    /* Test that interstitial text is populated.  If not, rerun lookup every 2 seconds for 10 seconds */
     for (i=1; i<=10; i++){
        if ( ($F(d1).length>0 && f.innerHTML.indexOf("(")==-1) || ($F(r1).length>0 && t.innerHTML.indexOf("(")==-1)) {
            setTimeout("updateInterstitialText()",i*2000);
        }else{
            break;
        }
    }
    showInterstitialSetup();
}


function showPurchaseInterstitial(evt) {

	// need to this if-else logic here to jump-start the animated GIF
    // on IE (see bug 62275 for details)
    if(!purchaseSubmitted) {
        purchaseSubmitted = true;
        Element.hide("interstitialSummary");

        if($('marketingMessage') && purchaseInterstitialMessage != null && purchaseInterstitialMessage.length > 0) {
            $('marketingMessage').innerHTML = buildInterstitialMessage(purchaseInterstitialMessage);
        }
        Element.show("marketingMessageOuter");
        showInterstitialSetup();
        var to = 100;
        var pleaseWaitImg = $('pleaseWaitImg');
        setTimeout(function() {
            pleaseWaitImg.src = pleaseWaitImg.src;
        }, to);
        return true;
    } else {
        return false;
    }

}

function updatePurchasePrice() {
	updateInput = document.createElement("input")
	updateInput.setAttribute("type", "hidden")
	updateInput.setAttribute("name", "_eventId_update_price");
	updateInput.setAttribute("value", "true");
	$("purchaseForm").appendChild(updateInput);
	$("purchaseForm").submit();
}



function doHttpGetRequest(url) {
    location.href = url;
}

function bindFareDetailsLinks() {
    $$("a.fareRulesLink").each(function(node) {
        Event.observe(node, 'click', function(evt) {
            var a = node.nextSibling;
            Effect.toggle(a, 'slide');
        });
    });
}

function bindFareRulesLinks() {
    $$('.fareRuleLink').each(function(node) {
        Event.observe(node, 'click', function(evt) {
            Event.stop(evt);
            return popupWindow(node.getAttribute("href"), 'equipment', 775, 725, 'no', 'yes', 'no', 'no', 'no');
        });
    });
}

function selectMCDiv(f) {
    var s = Element.getStyle(f, 'background');
    // if we're already on this element, then skip the logic below
    if(s && s.length > 0) {
        return;
    }
    ['slice1Locations', 'slice2Locations', 'slice3Locations', 'slice4Locations', 'slice5Locations'].each(
            function(node) {
                if(!$(node)) {
                    return;
                }
                Element.setStyle(node + 'Container', {background: ''});
                Element.setStyle(node + 'Hdr', {background: ''});
            });
    Element.setStyle(f + 'Hdr', {background: 'url(/images/module/mchdrbg.gif) top no-repeat'});
    Element.setStyle(f + 'Container', {background: 'url(/images/module/mcbg.gif) bottom no-repeat'});
}

function closeWindow() {
    window.close();
    return true;
}

function updateSelectedHotel(hotelIndex, roomIndex) {
     return true;
}


Validator = Class.create();
Validator.prototype = {
	initialize : function(){

	},

	isEmpty : function(val) {
	    if( val.match(/^\s*$/)) {
		 	return true;
		}
		return false;
	},

	containsNoNumeric : function(val){
		return val.match(/^\s*\D+\s*$/);
	},

	containsNoAlphaNumeric : function(val){
		return val.match(/^\s*\d+\s*$/);
	}

}

SearchValidator = Class.create();
Object.extend(Object.extend(SearchValidator.prototype, Validator.prototype),  {

	validateTo : function(val) {

		if(this.isEmpty(val)){
			return "error.searchrequest.arriverequired";
		}
		if(!this.containsNoNumeric(val)){
			return "error.searchrequest.arriveinvalid";
		}

		return "validated";
	} ,

	validateFrom : function(val){
		if(this.isEmpty(val)){
			return "error.searchrequest.departrequired";
		}
		if(!this.containsNoNumeric(val)){
			return "error.searchrequest.departinvalid";
		}

		return "validated";
	}

});




SearchManager = Class.create();
SearchManager.prototype = {
    initialize : function(asiaPOS, apacPOS, marketingMessage, discountsRb, locationLookup, nonpenaltyFareClass, jalAwardBooking) {
        this.discountsRb = discountsRb;
        this.lookups = {};
        this.nonPenaltyFareClassText = nonpenaltyFareClass;
	this.jalAwardBooking = jalAwardBooking;
        //Handles case where page is loaded without triggering events
        Field.activate("departField0");
        Event.observe('departField0', 'keypress', handleNonNumericInput);
        Event.observe('returnField0', 'keypress', handleNonNumericInput);
        Event.observe('departureDate', 'keypress', handleDateInput);
        Event.observe('returnDate', 'keypress', handleDateInput);
        this.asiaPOS = asiaPOS;
        this.apacPOS = apacPOS;
        if ($('infantlookup')) {
            Event.observe('infantlookup', "click", this.toggleInfantSeating.bindAsEventListener(this));
        }
        //Event.observe('searchform', 'submit', showSearchInterstitial);
        Event.observe('searchForFlightButton', 'click', searchFormButtonClick)
        var mu = $('mileageUpgradeCheckbox');
        if (mu) {
            Event.observe(mu, "click", this.showMileageUpgradeTypes.bindAsEventListener(this));
            this.showMileageUpgradeTypes(null);
        }

        if ($('awardCarrier')) {
            this.initAwardCarriersToggle();
        }
        if ($('sbp') || $('sbs') || $('sbbp') || $('awardtravel')) {
            this.initSearchByToggle();
            this.toggleSearchByOptions(null);
        }
        if ( $('adultsCombo') || $('awardTravelAdultsCombo')
                || $('seniorsCombo') || $('awardTravelSeniorsCombo')
                || $('childrenCombo') || $('awardTravelChildrenCombo') ) {
            this.initNumberOfPassengers();
            this.assignNumberOfPassengers(null);
        }
        if ($('flexibleDates')) {
            Event.observe('flexibleDates', 'click', this.handleFlexibleDates.bindAsEventListener(this));
            this.handleFlexibleDates();
        }
        if ($('zone')) {
            Event.observe('zone', 'click', this.handleZones.bindAsEventListener(this));
            this.handleZones();
        }
        if ($('holidays')) {
            Event.observe('holidays', 'click', this.handleHolidays.bindAsEventListener(this));
            this.handleHolidays();
        }
        if ($('iaw')) {
            Event.observe('iaw', 'click', this.handleRadiusSearch.bindAsEventListener(this));
            this.handleRadiusSearch();
        }
        if ($('weekendsIn')) {
            Event.observe('weekendsIn', 'click', this.handleWeekendsIn.bindAsEventListener(this));
            this.handleWeekendsIn();
        }
        this.initTripType();
        if($('marketingMessage') && marketingMessage != null && marketingMessage.length > 0) {
            $('marketingMessage').innerHTML = buildInterstitialMessage(marketingMessage);
        }

        if($('discountYes')) {
            try {
                this.initDiscounts();
                this.hityes = false;
            } catch (e) {
            }
        }

        if ($('mcOption').checked) {
            try {
                this.setupMulticityListeners();
                selectMCDiv('slice1Locations');
            } catch(e) {
            }

        }
        if(locationLookup) {
            this.setupLocationLookup();
        }
    },
    setupLocationLookup : function() {
        if(/INPUT/i.test($('departField0').nodeName)) {
            Event.observe("departField0", "blur", this.handleLocationLookupForDepartField.bind(this));
            this.handleLocationLookupForDepartField();
        }
        if(/INPUT/i.test($("returnField0").nodeName)) {
            Event.observe("returnField0", "blur", this.handleLocationLookupForArriveField.bind(this));
            this.handleLocationLookupForArriveField();
        }
    },
    handleLocationLookupForArriveField : function() {
        this.handleLocationLookup("returnField0", "interstitialArrive");
    },


    handleLocationLookup : function(fieldName) {
        var o = this;
        var t = $F(fieldName);
        if(t.length < 3) {
            return;
        }
        $(fieldName).lookupValue = null;
        if(o.lookups[t]) {
            var l = o.lookups[t];
            if(l && l.length >= 1) {
                $(fieldName).lookupValue = l;
            }
            return;
        }
        var f = function(req) {
            var resp = eval("(" + req.responseText + ")");
            // just display entered string if multiple results are found (don't know which was intended)
            if(resp && resp.results && resp.results.length == 1) {
                    $(fieldName).lookupValue = resp.results[0].name + " (" + resp.results[0].code.substring(2) + ")";
                o.lookups[resp.q] = $(fieldName).lookupValue;
            } else if(resp && resp.q){
                $(fieldName).lookupValue = null;
            }
        };
        o.lookups[t] = null;
        this.sendLookup(f, t);

    },

    handleLocationLookupForDepartField : function() {
        this.handleLocationLookup('departField0', 'interstitialDepart');
    },
    sendLookup: function(f, field) {
        var thisURL=document.location.href;
        location_array=thisURL.split("/");

        var locationURI = "/search/location.nw";

        if(location_array[0] == "https:") {
            locationURI = "/secure/location.nw";
        }

        var url = location_array[0] + "//" + location_array[2] + locationURI;
        var pars = "q=" + field + "&rnd=" + Math.random();
        var ajax = new Ajax.Request(url, {
            method: 'get',
            parameters: pars,
            onComplete: f
        });

    },
    setupMulticityListeners: function() {
        var f = function() { selectMCDiv('slice1Locations'); }
        Event.observe('returnField0', 'focus', f);
        Event.observe('departField0', 'focus', f);
        Event.observe('departureDate', 'focus', f);
        Event.observe('departTime0', 'focus', f);

        f = function() { selectMCDiv('slice2Locations'); };
        Event.observe('departField1', 'focus', f);
        Event.observe('returnField1', 'focus', f);
        Event.observe('returnDate', 'focus', f);
        Event.observe('departTime1', 'focus', f);
        Event.observe('departField1', 'keypress', handleNonNumericInput);
        Event.observe('returnField1', 'keypress', handleNonNumericInput);


        f = function() { selectMCDiv('slice3Locations'); };
        Event.observe('departField2', 'focus', f);
        Event.observe('returnField2', 'focus', f);
        Event.observe('returnDate2', 'focus', f);
        Event.observe('departTime2', 'focus', f);
        Event.observe('departField2', 'keypress', handleNonNumericInput);
        Event.observe('returnField2', 'keypress', handleNonNumericInput);
        Event.observe('returnDate2', 'keypress', handleDateInput);

        f = function() {selectMCDiv('slice4Locations'); }
        Event.observe('departField3', 'focus', f);
        Event.observe('returnField3', 'focus', f);
        Event.observe('returnDate3', 'focus', f);
        Event.observe('departTime3', 'focus', f);
        Event.observe('departField3', 'keypress', handleNonNumericInput);
        Event.observe('returnField3', 'keypress', handleNonNumericInput);
        Event.observe('returnDate3', 'keypress', handleDateInput);


        f = function() {selectMCDiv('slice5Locations'); };
        Event.observe('departField4', 'focus', f);
        Event.observe('returnField4', 'focus', f);
        Event.observe('returnDate4', 'focus', f);
        Event.observe('departTime4', 'focus', f);
        Event.observe('departField4', 'keypress', handleNonNumericInput);
        Event.observe('returnField4', 'keypress', handleNonNumericInput);
        Event.observe('returnDate4', 'keypress', handleDateInput);

    },
    handleFlexibleDates : function() {
        var ch = $('flexibleDates').checked;
        var i = $('iaw').checked;
        var fw = $('weekendsIn').checked;
        var zone = $('zone');
        var h = false;
        var uncheckOptions = new Array();
        if($('holidays')){
            h = $('holidays').checked;
        }
        if(ch){
            if (i) {
                uncheckOptions.push('iaw');
        }
            if (fw && fw.checked) {
                uncheckOptions.push('weekendsIn');
        }
            if (h) {
                uncheckOptions.push('holidays');
        }
        }
        toggleCheckBox(false,uncheckOptions);

        //weekend depends on one-way
        var isOneway = $('owOption') && $('owOption').checked;
        enableControls(!ch && !isOneway, ['weekendsIn', 'weekendsInSelect']);
        //radius depends on mileage upgrade
        var isMileageUpgrade = $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked;
        enableControls(!ch && !isMileageUpgrade, ['iaw', 'airportRadiusSelect']);

        enableControls(!ch, ['zone', 'zonevalue', 'mcOption', 'sbs', 'sbbp', 'awardtravel']);
    },
    handleHolidays : function() {
        var ch = $('holidays').checked;
        var fd = $('flexibleDates').checked;
        var i = $('iaw').checked;
        var fw = $('weekendsIn').checked;
        var zone = $('zone');
        var dd = $('departureDate');
        var dt0 = $('departTime0');
        var uncheckOptions = new Array();
        if(ch){
            if (i) {
                uncheckOptions.push('iaw');
            }
            if (fw && fw.checked) {
                uncheckOptions.push('weekendsIn');
        }
            if (fd) {
                uncheckOptions.push('flexibleDates');
        }
            if (dt0) {
                uncheckOptions.push('departTime0');
        }
            if(dd) {
                unCheckOptions.push('departureDate')
        }
        }
        toggleCheckBox(false,uncheckOptions);
        enableControls(!ch, ['zone', 'zonevalue', 'departureDate', 'returnDate', 'returnDate1', 'returnDate2', 'returnDate3', 'returnDate4', 'departTime0', 'departTime1', 'departTime2', 'departTime3', 'departTime4', 'flexibleDates', 'iaw', 'airportRadiusSelect', 'weekendsIn', 'weekendsInSelect', 'mcOption']);
    },
    handleZones : function() {
        var zone = $('zone').checked;
        var i = $('iaw').checked;
        var fd = $('flexibleDates') && $('flexibleDates').checked;
        var fw = $('weekendsIn');
        var h = false;
        var uncheckOptions = new Array();
        if($('holidays')){
            h = $('holidays');
        }
        if (zone) {
            uncheckOptions.push('returnField0');
            if (i) {
                uncheckOptions.push('iaw');
        }
            if (fd) {
                uncheckOptions.push('flexibleDates');
        }
            if (fw) {
                uncheckOptions.push('weekendsIn');
        }
            if (h) {
                uncheckOptions.push('holidays');
        }
        }
        toggleCheckBox(false,uncheckOptions);
        //weekend depends on one-way
        var isOneway = $('owOption') && $('owOption').checked;
        enableControls(!zone && !isOneway, ['weekendsIn', 'weekendsInSelect']);
        //radius depends on mileage upgrade
        var isMileageUpgrade = $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked;
        enableControls(!zone && !isMileageUpgrade, ['iaw', 'airportRadiusSelect']);
        enableControls(!zone, ['flexibleDates', 'divTo', 'returnField0', 'mcOption', 'sbs', 'sbbp', 'awardtravel']);
    },
    handleRadiusSearch : function() {
        var ch = $('iaw').checked;
        var fd = $('flexibleDates');
        var fw = $('weekendsIn');
        var zone = $('zone');
        var h = false;
        var uncheckOptions = new Array();
        if($('holidays')){
            h = $('holidays');
        }
        if (ch) {
            if (fd && fd.checked) {
                uncheckOptions.push('flexibleDates');
            }
            if (fw && fw.checked) {
                uncheckOptions.push('weekendsIn');
            }
            if (h) {
                uncheckOptions.push('holidays');
            }
        }

        toggleCheckBox(false,uncheckOptions);

        //weekends depends on one-way and award search
        var isOneway = $('owOption') && $('owOption').checked;
        var isAward = $('awardtravel') && $('awardtravel').checked;
        enableControls(!ch && !isOneway && !isAward, ['weekendsIn', 'weekendsInSelect']);
        //Disable zone, flexdates for award search
        enableControls(!ch && !isAward, ['zone', 'zonevalue', 'flexibleDates']);


        enableControls(!ch , ['mileageUpgradeCheckbox']);
        enableControls(!ch, ['mcOption', 'sbbp', 'sbs']);
    },
    handleWeekendsIn : function() {
        var ch = $('weekendsIn').checked;
        var fd = $('flexibleDates');
        var iw = $('iaw');
        var zone = $('zone');
        var h = false;
        var uncheckOptions = new Array();
        if($('holidays')){
            h = $('holidays');
        }
        if(ch){
            if (iw && iw.checked) {
                uncheckOptions.push('iaw');
            }
            if (fd && fd.checked) {
                uncheckOptions.push('flexibleDates');
        }
            if (h) {
                uncheckOptions.push('holidays');
        }

        }
        toggleCheckBox(false,uncheckOptions);
        //radius depends on mileage upgrade
        var isMileageUpgrade = $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked;
        enableControls(!ch && !isMileageUpgrade, ['iaw', 'airportRadiusSelect']);

        enableControls(!ch , ['owOption']);
        enableControls(!ch, ['zone', 'zonevalue', 'flexibleDates', 'mcOption', 'sbs', 'sbbp', 'awardtravel']);
    },

    initNumberOfPassengers: function() {
        if ($('awardTravelAdultsCombo')) {
            Event.observe('awardTravelAdultsCombo', "change", this.assignNumberOfPassengers.bindAsEventListener(this));
        }
        if ($('adultsCombo')) {
            Event.observe('adultsCombo', "change", this.assignNumberOfPassengers.bindAsEventListener(this));
        }

        if ($('awardTravelSeniorsCombo')) {
            Event.observe('awardTravelSeniorsCombo', "change", this.assignNumberOfPassengers.bindAsEventListener(this));
        }
        if ($('seniorsCombo')) {
            Event.observe('seniorsCombo', "change", this.assignNumberOfPassengers.bindAsEventListener(this));
        }

        if ($('awardTravelChildrenCombo')) {
            Event.observe('awardTravelChildrenCombo', "change", this.assignNumberOfPassengers.bindAsEventListener(this));
        }
        if ($('childrenCombo')) {
            Event.observe('childrenCombo', "change", this.assignNumberOfPassengers.bindAsEventListener(this));
        }
    },

    assignNumberOfPassengers: function(event) {
        if ( $('awardTravelAdultsCombo') && Element.visible('awardTravelAdultsCombo') ) {
            if ($('adults')) {
                $('adults').value = $('awardTravelAdultsCombo').value;
            }
        }
        else if ( $('adultsCombo') && Element.visible('adultsCombo') ) {
            if ($('adults')) {
                $('adults').value = $('adultsCombo').value;
            }
        }

        if ( $('awardTravelSeniorsCombo') && Element.visible('awardTravelSeniorsCombo') ) {
            if ($('seniors')) {
                $('seniors').value = $('awardTravelSeniorsCombo').value;
            }
        }
        else if ( $('seniorsCombo') && Element.visible('seniorsCombo') ) {
            if ($('seniors')) {
                $('seniors').value = $('seniorsCombo').value;
            }
        }

        if ( $('awardTravelChildrenCombo') && Element.visible('awardTravelChildrenCombo') ) {
            if ($('children')) {
                $('children').value = $('awardTravelChildrenCombo').value;
            }
        }
        else if ( $('childrenCombo') && Element.visible('childrenCombo') ) {
            if ($('children')) {
                $('children').value = $('childrenCombo').value;
            }
        }
    },

    toggleElementsForAwardTravel: function(isAwardTravel) {
        if ( $('awardTravelAdultsCombo') && $('adultsCombo') ) {
            if (isAwardTravel) {
                $('awardTravelAdultsCombo').show();
                $('adultsCombo').hide();
            } else {
                $('awardTravelAdultsCombo').hide();
                $('adultsCombo').show();
            }
        }

        if ( $('awardTravelSeniorsCombo') && $('seniorsCombo') ) {
            if (isAwardTravel) {
                $('awardTravelSeniorsCombo').show();
                $('seniorsCombo').hide();
            } else {
                $('awardTravelSeniorsCombo').hide();
                $('seniorsCombo').show();
            }
        }

        if ( $('awardTravelChildrenCombo') && $('childrenCombo') ) {
            if (isAwardTravel) {
                $('awardTravelChildrenCombo').show();
                $('childrenCombo').hide();
            } else {
                $('awardTravelChildrenCombo').hide();
                $('childrenCombo').show();
            }
        }

        this.assignNumberOfPassengers(null);
    },

    initSearchByToggle: function() {
        if ($('sbbp')) {
            Event.observe('sbbp', "click", this.toggleSearchByOptions.bindAsEventListener(this));
        }
        if ($('sbp')) {
            Event.observe('sbp', "click", this.toggleSearchByOptions.bindAsEventListener(this));
        }
        if ($('awardtravel')) {
            Event.observe('awardtravel', "click", this.toggleSearchByOptions.bindAsEventListener(this));
        }
        if ($('sbs')) {
            Event.observe('sbs', "click", this.toggleSearchByOptions.bindAsEventListener(this));
        }
    },

    toggleSearchByOptions: function(event) {
        var isAward = null;
        if ($('awardtravel')) {
            isAward = $('awardtravel').checked;
        }
        var mu = $('mileageUpgradeCheckbox');
        var pc = $('perkChoiceCheckbox');
        var muOrCm = false;
        if (mu && mu.checked) {
            this.showMileageUpgradeTypes(null);
            muOrCm = true;
        }
        if (pc && pc.checked) {
            this.showCashAndMiles(null);
            muOrCm = true;
        }
        // need to check mu.checked & cm.checked as well when enabling/disabling cabinClassSelect, fareClassSelect, iil, iis
        enableControls(!isAward && !muOrCm, ['cabinClassSelect', 'fareClassSelect','iil', 'iis']);
        enableControls(!isAward && !$('mcOption').checked, ['flexibleDates', 'zone', 'zonevalue', 'iaw', 'airportRadiusSelect']);
        enableControls(!isAward && $('rtOption').checked, ['weekendsIn', 'weekendsInSelect','zone']);
        //non-stop option not valid for search by schedule
        enableControls(!$('sbs').checked, ['nonstopCheck']);
        if($('sbs').checked){
        	$('nonstopCheck').checked = false;
        }
        if (isAward) {
            enableControls(!$('mcOption').checked, ['iaw', 'airportRadiusSelect']);
            enableControls(!isAward && $('rtOption').checked, ['weekendsIn', 'weekendsInSelect','zone']);
            toggleCheckBox(false,['flexibleDates','weekendsIn','zone']);
            if($('revenueCarrier')){
            	$('revenueCarrier').hide();
            }

            this.toggleElementsForAwardTravel(true);
        }
        if ($('sbbp').checked || $('sbs').checked) {
            enableControls(false, ['flexibleDates','weekendsIn', 'weekendsInSelect', 'iaw', 'airportRadiusSelect', 'zone', 'zonevalue']);
            toggleCheckBox(false,['iaw']);
            // remove non penalty fares option if present (will always be last)
            var fcSelect = $('fareClassSelect');
            var i = fcSelect.options.length - 1;
            var fcOption = fcSelect.options[i];
            if (fcOption.value == 'nonpenalty') {
                fcSelect.options[i] = null;
            }
            if($('revenueCarrier')){
            	$('revenueCarrier').show();
            }

            this.toggleElementsForAwardTravel(false);
        }
        else if ($('sbp').checked) {
            var isMulticity = $('mcOption') && $('mcOption').checked;
            var isRoundtrip = $('rtOption') && $('rtOption').checked;
            //Disable radius, zone, flex for multi city
            enableControls(!isMulticity, ['iaw','zone','flexibleDates', 'airportRadiusSelect', 'zonevalue']);
            //disable weekends for one-way and mcity; enable only for round trip
            enableControls(isRoundtrip, ['weekendsIn', 'weekendsInSelect']);
            // add non penalty fares option as second option, if not present
            var fcSelect = $('fareClassSelect');
            var i = 1;
            var fcOption = fcSelect.options[i];
            if (fcOption.value != 'nonpenalty') {
                fcOption = new Element("OPTION");
                fcOption.value = 'nonpenalty';
                fcOption.text = this.nonPenaltyFareClassText;
                Element.insert(fcSelect.options[0], {after:fcOption})
            }
            if($('revenueCarrier')){
            	$('revenueCarrier').show();
            }

            this.toggleElementsForAwardTravel(false);
        }
    },
    initAwardCarriersToggle: function() {
        if ($('sbbp')) {
            Event.observe($('sbbp'), "click", this.toggleSbsAwardCarriers.bindAsEventListener(this));
        }
        if ($('sbp')) {
            Event.observe($('sbp'), "click", this.toggleSbsAwardCarriers.bindAsEventListener(this));
        }
        if ($('awardtravel')) {
            Event.observe($('awardtravel'), "click", this.toggleSbsAwardCarriers.bindAsEventListener(this));
        }
        if ($('sbs')) {
            Event.observe($('sbs'), "click", this.toggleSbsAwardCarriers.bindAsEventListener(this));
         }
    } ,

    toggleSbsAwardCarriers: function(event) {
        var ac = $('awardCarrier');
        if (!ac) {
            return;
        }
        if ($('awardtravel') && $('awardtravel').checked) {
            Element.show(ac);
        } else {
            Element.hide(ac);
            if ($('awardCarrierSelect')) {
                $('awardCarrierSelect').value = '';
            }
        }
    } ,

    toggleDestination: function(event) {
        Element.show($('divTo'));
    } ,

    info: function() {
        return "search manager";
    } ,

/**
 * Creates the listener for the trip type radio buttons (Roundtrip, one way
 * multi-city).
 */
    initTripType: function() {

        if ($('additionalrows')){
            Event.observe($('additionalrows'), "click", this.showAdditionalRows.bindAsEventListener(this));
        }

        this.toggleTripType();

    } ,

/**
 * Shows or Hides the infant seating information when the infant link is clicked.
 */
    toggleInfantSeating: function(event) {
        Element.show('moreoptions');
        Element.hide('infantlookup');
    } ,

    showAdditionalRows: function (event) {
        var c = $F('additionalrows');

        if (c == 0) {
            Element.hide('slice4Times');
            Element.hide('slice4Locations');
            Element.hide('slice5Times');
            Element.hide('slice5Locations');
        }
        if( c == 1) {
            Element.show('slice4Times');
            Element.show('slice4Locations');
            Element.hide('slice5Times');
            Element.hide('slice5Locations');
        }
        if ( c == 2) {
            Element.show('slice4Times');
            Element.show('slice4Locations');
            Element.show('slice5Times');
            Element.show('slice5Locations');
            Element.hide('addrows');
        }
    },

    showMileageUpgradeTypes: function(event) {

        if ($('selectMileageUpgradeType' == null)) {
            return;
        }
        var c = $('mileageUpgradeCheckbox').checked;

        if (c) {
            Element.show('selectMileageUpgradeType');
            $('iil').value = 0;
            $('iis').value = 0;

        } else {
            Element.hide('selectMileageUpgradeType');
        }
        //radius depends on flex, zone and weekend
        var isWeekendsIn = $('weekendsIn') && $('weekendsIn').checked;
        var isFlexDate = $('flexibleDates') && $('flexibleDates').checked;
        var isZone = $('zone') && $('zone').checked;
        enableControls(!c && !isWeekendsIn && !isFlexDate && !isZone, ['airportRadiusSelect', 'iaw']);

        if($('perkChoiceCheckbox') != null){
        	enableControls(!c, ['perkChoiceCheckbox']);
        }
        /* If award travel is turned on, we should not enable fare class and cabin class or infant dropdowns */
        enableControls(!c && ($('awardtravel')==null || !$('awardtravel').checked), ['cabinClassSelect', 'fareClassSelect', 'iil', 'iis']);
    },

    showCashAndMiles: function(event) {
        if ($('enterCashAndMiles') == null) {
            return;
        }

        var c = $('cashAndMilesCheckbox').checked;
        if($('perkChoiceCheckbox') != null){
        	var p = $('perkChoiceCheckbox').checked;
       	}

        if (c) {
            Element.show('enterCashAndMiles');
            var iil = $('iil');
            if (iil) {
                $('iil').value = 0;
                $('iis').value = 0;
            }

        }
        else {
            Element.hide('enterCashAndMiles');
        }

        // If either checkbox is checked, hide discounts
        if(c || p){
            this.hideDiscounts(null);
            $('discountYes').checked = null;
            $('discountNo').checked = 'checked';
        }

        var isWeekendsIn = $('weekendsIn') && $('weekendsIn').checked;
        var isAward = $('awardtravel') && $('awardtravel').checked;
        var isIaw = $('iaw') && $('iaw').checked;

        if ($('perkChoiceCheckbox') != null) {
            // Disable cash and miles if perkChoice is checked
            enableControls(!p, ['cashAndMilesCheckbox']);
            // Disable perkChoice if Cash and Miles is checked
            enableControls(!c, ['perkChoiceCheckbox']);
            //Disable one-way if cash and miles, award or weekends checked
            enableControls(!(c || p) && !(isAward || isWeekendsIn), ['owOption']);
            /* If award travel is turned on, we should not enable fare class or infant dropdowns */
            enableControls(!(c || p) && !isAward, ['fareClassSelect', 'iil', 'iis']);
            //mileage upgrade depends on radius
            enableControls(!(c || p) && !isIaw, ['mileageUpgradeCheckbox']);
            //Disable discounts
            enableControls(!(c || p), ['discountYes', 'discountNo']);
        } else {
            //Disable one-way if cash and miles, award or weekends checked
            enableControls(!c && !(isAward || isWeekendsIn), ['owOption']);
            /* If award travel is turned on, we should not enable fare class or infant dropdowns */
            enableControls(!c && !isAward, ['fareClassSelect', 'iil', 'iis']);
            //mileage upgrade depends on radius
            enableControls(!c && !isIaw, ['mileageUpgradeCheckbox']);
            //Disable discounts
            enableControls(!c, ['discountYes', 'discountNo']);
        }

    },

    conditionalEnableFlex : function() {
        var wi = $('weekendsIn');
        var fd = $('flexibleDates');
        var iw = $('iaw');
        var isAward = $('awardtravel') && $('awardtravel').checked;
        var isSbbp = $('sbbp') && $('sbbp').checked;
        var isSbs = $('sbs') && $('sbs').checked;
        var oneway = $('owOption')
        if (oneway && oneway.checked) {
            enableControls(false, ['weekendsIn', 'weekendsInSelect']);
        } else {
            enableControls(!isAward && !isSbbp && !isSbs, ['weekendsIn', 'weekendsInSelect']);
        }
        if (wi && wi.disabled && fd && fd.disabled && iw && iw.disabled) {
            enableControls(!isSbbp && !isSbs && !isAward, ['flexibleDates']);
            enableControls(!isSbbp && !isSbs, ['iaw', 'airportRadiusSelect']);

        } else if (isAward) {
            enableControls(!isSbbp && !isSbs, ['iaw', 'airportRadiusSelect']);
        }
    },

    disableFlex : function() {
        enableControls(false, ['weekendsIn', 'weekendsInSelect', 'iaw', 'airportRadiusSelect', 'flexibleDates','zonevalue','zone']);
        toggleCheckBox(false,['weekendsIn','flexibleDates','iaw','zone']);
    },
/**
 * Shows or hides the extra depart/arrive location and date fields based
 * on the value of the multi-city radio button.
 */
    toggleTripType: function(event) {
        if ($('mcOption').checked) {
            this.disableFlex();
            enableControls(true, ['awardtravel']);
        } else if ($('rtOption').checked) {
            enableControls(true, ['awardtravel','sbbp']);
            this.conditionalEnableFlex();
        } else if ($('owOption')) {
            if ($('owOption').checked) {
                this.conditionalEnableFlex();
                // see bug 61449 for this req.
                enableControls(false, ['awardtravel']);
                enableControls(true, ['sbbp']);
                if($('awardtravel') && $('awardtravel').checked) {
                    toggleCheckBox(true,['sbp']);
                }
            }
        }
    },

/**
 * Discounts
 */
    initDiscounts: function() {
        Event.observe('discountYes', "click", this.showFirstOfferDropDown.bindAsEventListener(this));
        if($('discountYes').checked){
            // An infant in lap may have been selected; so adjust the options
            var infantInLapPaxCount = 0;
            if ($('iil')) {
                infantInLapPaxCount = $F('iil');
            }
            if (infantInLapPaxCount > 0) {
                if ( this.apacPOS == true
                        || ($('awardtravel') != null && $('awardtravel').checked)
                        || ($('wpmu') && $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked) ) {
                    this.adjustOptionsForInfantInLap($('selectDiscountTypeWithAward'));
                } else {
                    this.adjustOptionsForInfantInLap($('selectDiscountType'));
                }
            }
            this.hityes = true;
            this.loadEventHandlers();
        }
    },

    lazyLoadEventHandlers : function () {
        if (this.hityes) {
            return;
        }
        this.hityes = true;

        this.loadEventHandlers();

        this.hideDiscounts(null);
    },

    loadEventHandlers: function(){
        Event.observe('discountNo', "click", this.showFirstOfferDropDown.bindAsEventListener(this));
        Event.observe('selectDiscountType', "change", this.expandFirstOfferDiscountOption.bindAsEventListener(this));
        if ($('selectDiscountTypeWithAward')) {
            Event.observe('selectDiscountTypeWithAward', "change", this.expandFirstOfferDiscountOption.bindAsEventListener(this));
        }
        $("anotherOfferCheckboxFor_ecert") && Event.observe('anotherOfferCheckboxFor_ecert', "click", this.showAnotherOfferDropDown.bindAsEventListener(this));
        $("anotherOfferCheckboxFor_giftcert") && Event.observe('anotherOfferCheckboxFor_giftcert', "click", this.showAnotherOfferDropDown.bindAsEventListener(this));
        $("anotherOfferCheckboxFor_mice") && Event.observe('anotherOfferCheckboxFor_mice', "click", this.showAnotherOfferDropDown.bindAsEventListener(this));
        $("anotherOfferCheckboxFor_dollarecv") && Event.observe('anotherOfferCheckboxFor_dollarecv', "click", this.showAnotherOfferDropDown.bindAsEventListener(this));
        $("anotherOfferCheckboxFor_salesdollarecv") && Event.observe('anotherOfferCheckboxFor_salesdollarecv', "click", this.showAnotherOfferDropDown.bindAsEventListener(this));
        $("anotherOfferSelectFor_ecert") && Event.observe('anotherOfferSelectFor_ecert', "change", this.expandAnotherOfferDiscountOption.bindAsEventListener(this));
        $("anotherOfferSelectFor_giftcert") && Event.observe('anotherOfferSelectFor_giftcert', "change", this.expandAnotherOfferDiscountOption.bindAsEventListener(this));
        $("anotherOfferSelectFor_mice") && Event.observe('anotherOfferSelectFor_mice', "change", this.expandAnotherOfferDiscountOption.bindAsEventListener(this));
        $("anotherOfferSelectFor_dollarecv") && Event.observe('anotherOfferSelectFor_dollarecv', "change", this.expandAnotherOfferDiscountOption.bindAsEventListener(this));
        $("anotherOfferSelectFor_salesdollarecv") && Event.observe('anotherOfferSelectFor_salesdollarecv', "change", this.expandAnotherOfferDiscountOption.bindAsEventListener(this));
        if ($('sbp')) {
            Event.observe('sbp', "click", this.adjustDiscountsForSearchByChange.bindAsEventListener(this));
        }
        if ($('sbs')) {
            Event.observe('sbs', "click", this.adjustDiscountsForSearchByChange.bindAsEventListener(this));
        }
        if ($('sbbp')) {
            Event.observe('sbbp', "click", this.adjustDiscountsForSearchByChange.bindAsEventListener(this));
        }
        if ($('awardtravel')) {
            Event.observe('awardtravel', "click", this.adjustDiscountsForSearchByChange.bindAsEventListener(this));
        }
        if ($('mileageUpgradeCheckbox')) {
            Event.observe('mileageUpgradeCheckbox', "click", this.adjustDiscountsForMileageUpgradeChange.bindAsEventListener(this));
        }
        Event.observe('adults', "change", this.handlePaxCountChange.bindAsEventListener(this));

        if ($('children')) {
            Event.observe('children', "change", this.handlePaxCountChange.bindAsEventListener(this));
        }
        if ($('seniors')) {
            Event.observe('seniors', "change", this.handlePaxCountChange.bindAsEventListener(this));
        }
        if ($('iil')) {
            Event.observe('iil', "change", this.handlePaxCountChange.bindAsEventListener(this));
            Event.observe('iil', "change", this.handleInfantInLapSelection.bindAsEventListener(this));
        }
        if ($('iis')) {
            Event.observe('iis', "change", this.handlePaxCountChange.bindAsEventListener(this));
        }
        if ($('stateEmployees')) {
            Event.observe('stateEmployees', "change", this.handlePaxCountChange.bindAsEventListener(this));
        }
        if ($('federalEmployees')) {
            Event.observe('federalEmployees', "change", this.handlePaxCountChange.bindAsEventListener(this));
        }
        if ($('military')) {
            Event.observe('military', "change", this.handlePaxCountChange.bindAsEventListener(this));
        }
    },

    showDiscounts: function() {
        try {
            this.lazyLoadEventHandlers();
            Element.show("discountsDiv");
        } catch(e) {
        }
    },

    hideDiscounts: function() {
        try {
            Element.hide("discountsDiv");
            Element.hide('selectDiscountTypeDropDown');
            Element.hide('selectDiscountTypeDropDownWithAward');
            this.hideAllDiscounts(null);
        } catch(e) {
        }
    },

    hideAllDiscounts: function(event) {

        var allOptions = new Array("ecert", "giftcert", "freeecv", "dollarecv", "mice", "salesdollarecv", "salespromoecv", "paper");

        for (var i = 0; i < allOptions.length; i++) {
            var thisOption = allOptions[i];
            try {
                if ($('enter' + thisOption)) {
                    Element.hide('enter' + thisOption);
                }

                if ($('selectAnotherOfferFor_' + thisOption)) {
                    Element.hide('selectAnotherOfferFor_' + thisOption);
                }

                if ($('enterAnotherOffer' + thisOption)) {
                    Element.hide('enterAnotherOffer' + thisOption);
                }

            } catch (e) {
                // We are probably missing "enter<option>" div id in selectedDiscountType element
            }
        }

        try {
            this.clearFreeEcvTable(null);
            this.clearDollarEcvTable('main');
            this.clearDollarEcvTable('combined');
            this.clearSalesDollarEcvTable('main');
            this.clearSalesDollarEcvTable('combined');
            this.clearSalesPromoEcvTable(null);
        } catch (e) {
            // should not happen
        }
    },

    hideAllCombinedDiscounts: function(event) {

        var allOptions = new Array("ecert", "giftcert", "freeecv", "dollarecv", "mice", "salesdollarecv", "salespromoecv", "paper");

        for (var i = 0; i < allOptions.length; i++) {
            var thisOption = allOptions[i];
            try {
                if ($('enterAnotherOffer' + thisOption) != null) {
                    Element.hide('enterAnotherOffer' + thisOption);
                }
            } catch (e) {
                // We are probably missing "enter<option>" div id in selectedDiscountType element
            }
        }

        try {
            this.clearDollarEcvTable('combined');
            this.clearSalesDollarEcvTable('combined');
        } catch (e) {
        }
    },

    showFirstOfferDropDown: function(event) {

        if ($('discountYes').checked) {

            this.showDiscounts();

            var allOptionsSelect = $('selectDiscountType');
            var showAward = false;
            if ( this.apacPOS == true
                    || ($('awardtravel') != null && $('awardtravel').checked)
                    || ($('wpmu') && $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked) ) {
                showAward = true;
                allOptionsSelect = $('selectDiscountTypeWithAward');
            }

            // An infant in lap may have been selected; so adjust the options
            var infantInLapPaxCount = 0;
            if ($('iil')) {
                infantInLapPaxCount = $F('iil');
            }
            if (infantInLapPaxCount > 0) {
                this.adjustOptionsForInfantInLap(allOptionsSelect);
            }

            if ( showAward ) {
                Element.show('selectDiscountTypeDropDownWithAward');
                // if the drop down's choice is bound to a discount type other
                // than none, also expand it
                var selectedOption = $F('selectDiscountTypeWithAward');
                if (selectedOption != 'none') {
                    this.expandFirstOfferDiscountOption(null);
                }
            } else {
                Element.show('selectDiscountTypeDropDown');

                // if the drop down's choice is bound to a discount type other
                // than none, also expand it
                var selectedOption = $F('selectDiscountType');
                if (selectedOption != 'none') {
                    this.expandFirstOfferDiscountOption(null);
                }
            }
        } else if ($('discountNo').checked) {
            this.hideDiscounts();
        }
    },

    expandFirstOfferDiscountOption: function(event) {

        this.hideAllDiscounts(null);

        var atr = false;
        if ( this.apacPOS == true
                || ($('awardtravel') != null && $('awardtravel').checked)
                || ($('wpmu') && $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked) ) {
            atr = true;
        }

        var selectedOption = $F('selectDiscountType');
        if ( atr ) {
            selectedOption = $F('selectDiscountTypeWithAward');
        }

        try {
            if ($('enter' + selectedOption) != null) {
                Element.show('enter' + selectedOption);
                this.adjustEcvVoucherBoxes(null);
            }

            if ($('checkAnotherOfferFor_' + selectedOption)
                    && $('anotherOfferCheckboxFor_' + selectedOption)) {
                if (atr) {
                    // for award travel, disable another offer
                    Element.hide($('checkAnotherOfferFor_' + selectedOption));
                } else {
                    Element.show($('checkAnotherOfferFor_' + selectedOption));
                    if ($('anotherOfferCheckboxFor_' + selectedOption).checked) {
                        // if anotherOfferCheckBox is checked, also expand it
                        this.showAnotherOfferDropDown(null);
                    }
                }
            }

        } catch (e) {
            // We are probably missing "enter<option>" div id in selectedDiscountType element
        }
    },

    showAnotherOfferDropDown: function(event) {
        var selectedOption = $F('selectDiscountType');
        if ( this.apacPOS == true
                || ($('awardtravel') != null && $('awardtravel').checked)
                || ($('wpmu') && $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked) ) {
            selectedOption = $F('selectDiscountTypeWithAward');
        }

        var anotherOffer = $F('anotherOfferCheckboxFor_' + selectedOption);
        var selectAnotherOfferSelectDiv = 'selectAnotherOfferFor_' +
                                          selectedOption;

        this.hideAllCombinedDiscounts(null);

        if ($(selectAnotherOfferSelectDiv) != null) {
            if (anotherOffer) {
                Element.show(selectAnotherOfferSelectDiv);
                // if the drop down's choice is bound to a value other than none,
                // also expand it
                var selectedAnotherOfferOption = $F('anotherOfferSelectFor_' +
                                                    selectedOption);
                if (selectedAnotherOfferOption != 'none') {
                    this.expandAnotherOfferDiscountOption(null);
                }
            } else {
                Element.hide(selectAnotherOfferSelectDiv);
            }
        }
    },

    expandAnotherOfferDiscountOption: function(event) {
        var allOptions = $('selectDiscountType').options;
        var selectedMainOption = $F('selectDiscountType');

        if ( this.apacPOS == true
                || ($('awardtravel') != null && $('awardtravel').checked)
                || ($('wpmu') && $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked) ) {

            allOptions = $('selectDiscountTypeWithAward').options;
            selectedMainOption = $F('selectDiscountTypeWithAward');
        }

        this.hideAllCombinedDiscounts(null);

        if (!$('anotherOfferSelectFor_' + selectedMainOption)) {
            return;
        }

        var selectedAnotherOfferOption = $F('anotherOfferSelectFor_' +
                                            selectedMainOption);

        var selectedAnotherOfferDiv = 'enterAnotherOffer' + selectedAnotherOfferOption;

        try {
            if ($(selectedAnotherOfferDiv)) {
                Element.show(selectedAnotherOfferDiv);
                this.adjustEcvVoucherBoxes(null);
            }
        } catch (e) {
        }

        // don't go into a chain of displaying more drop downs for second offer
        // hide all drop downs that are not the main offer or second offer
        for (var i = 0; i < allOptions.length; i++) {
            var thisOption = allOptions[i];
            try {
                if (thisOption.value != selectedMainOption &&
                    thisOption.value != selectedAnotherOfferOption) {

                    if ($('selectAnotherOfferFor_' + thisOption.value)) {
                        Element.hide('selectAnotherOfferFor_' +
                                     thisOption.value);
                    }

                    if ($('enterAnotherOffer' + thisOption.value)) {
                        Element.hide('enterAnotherOffer' +
                                     thisOption.value);
                    }
                }
            } catch (e) {
                // We are probably missing "enter<option>" div id in selectedDiscountType element
            }
        }
    },

    adjustDiscountsForSearchByChange: function(event) {

        // if mileage upgrade is checked, we are already in atr mode
        // if apacPOS, we are already in atr mode
        if ( ($('wpmu') && $('mileageUpgradeCheckbox')
                && $('mileageUpgradeCheckbox').checked )
                || this.apacPOS) {
            return;
        }

        if ($('discountNo').checked) {
            return;
        }

        this.adjustDiscountsForAwardTravelModeChange(event);
    },

    adjustDiscountsForMileageUpgradeChange: function(event) {

        // if Search By Award Travel is checked, we are already in atr mode
        // if apacPOS, we are already in atr mode
        if ( ($('awardtravel') != null && $('awardtravel').checked)
                || this.apacPOS) {
            return;
        }

        if ($('discountNo').checked) {
            return;
        }

        this.adjustDiscountsForAwardTravelModeChange(event);
    },

    adjustDiscountsForAwardTravelModeChange: function(event) {
        try {

            var allOptions = $('selectDiscountType').options;
            var selectedMainOption = $F('selectDiscountType');

            // We need to hide all award options expanded when sbp or sbs or sbbp is
            // checked
            if ( ($('wpmu') && $('mileageUpgradeCheckbox')
                    && !$('mileageUpgradeCheckbox').checked )
                    || ( $('sbp').checked || $('sbs').checked || $('sbbp').checked ) ) {
                allOptions = $('selectDiscountTypeWithAward').options;
                selectedMainOption = $F('selectDiscountTypeWithAward');
            }

            this.hideDiscounts();
            // These are required since hideDiscounts looks at the main option
            // that is based on the current selection of awardtravel or sbp etc.
            // We want to hide the options that were displayed based on
            // awardtravel, sbp etc. that were selected before the change event
            this.hideAllDiscounts(null);
            this.showFirstOfferDropDown(null);

        } catch (e) {

        }
    },

    handlePaxCountChange: function(e) {
        this.adjustEcvVoucherBoxes(e);
    },
    adjustEcvVoucherBoxes: function(e) {

        var selectedOption = $F('selectDiscountType');

        if ( this.apacPOS == true
                || ($('awardtravel') != null && $('awardtravel').checked)
                || ($('wpmu') && $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked) ) {
            selectedOption = $F('selectDiscountTypeWithAward');
        }

        var selectedAnotherOfferOption;
        if ($('anotherOfferSelectFor_' + selectedOption)) {
            selectedAnotherOfferOption =
            $F('anotherOfferSelectFor_' + selectedOption);
        }

        if (selectedOption == 'freeecv' ||
            selectedAnotherOfferOption == 'freeecv') {
            this.createFreeEcvInputBoxes(null);
        }

        if (selectedOption == 'dollarecv') {
            this.createDollarEcvInputBoxes('main');
        } else if (selectedAnotherOfferOption == 'dollarecv') {
            this.createDollarEcvInputBoxes('combined');
        }

        if (selectedOption == 'salesdollarecv') {
            this.createSalesDollarEcvInputBoxes('main');
        } else if (selectedAnotherOfferOption == 'salesdollarecv') {
            this.createSalesDollarEcvInputBoxes('combined');
        }

        if (selectedOption == 'salespromoecv' ||
            selectedAnotherOfferOption == 'salespromoecv') {
            this.createSalesPromoEcvInputBoxes(null);
        }

    },


/*
This function totals up the number of travelers and returns that value.
*/
    getPaxCount : function (event) {
        if ($("children") == null) {
            return parseInt($F("adults"));
        }
        return $("adults", "children", "seniors", "iil", "iis", "stateEmployees", "federalEmployees", "military").inject(0,
                function(acc, node) {
                    try {
                        return acc + parseInt($F(node));
                    } catch(e) {
                        return acc;
                    }
                });
    },

/*
This function shows the input boxes for free ecvs
*/
    createFreeEcvInputBoxes : function (event) {

        try {
            this.clearFreeEcvTable();
        } catch (e) {
        }

        try {
            var paxcount = this.getPaxCount();
        } catch (e) {
        }

        if (paxcount >= 1) {
            Element.show("freeEcvReferenceCodeLabel");
            Element.show("freeEcvReferenceCodeInput");
        }

        for (var i = 0; i < paxcount; i++) {
            try {
                Element.show("freeEcvNumberLabel" + i);
                Element.show("freeEcvNumberInput" + i);
            } catch(e) {
            }
        }
    },

    clearFreeEcvTable : function(event) {

        Element.hide("freeEcvReferenceCodeLabel");
        Element.hide("freeEcvReferenceCodeInput");

        for (var i = 0; i < 20; i++) {
            try {
                Element.hide("freeEcvNumberLabel" + i);
                Element.hide("freeEcvNumberInput" + i);
            } catch (e) {
            }
        }
    },

/*
This function shows the input boxes for free ecvs
*/
    createDollarEcvInputBoxes : function (dropdownType) {

        try {
            this.clearDollarEcvTable(dropdownType);
        } catch (e) {
        }

        try {
            var paxcount = this.getPaxCount();
        } catch (e) {
        }

        for (var i = 0; i < paxcount; i++) {
            try {
                if (dropdownType == 'main') {
                    Element.show("dollarEcvNumberLabel" + i);
                    Element.show("dollarEcvNumberInput" + i);
                } else if (dropdownType == 'combined') {
                    Element.show("dollarEcvNumberAnotherOfferLabel" + i);
                    Element.show("dollarEcvNumberAnotherOfferInput" + i);
                }
            } catch (e) {
            }
        }
    },

    clearDollarEcvTable : function(dropdownType) {

        for (var i = 0; i < 20; i++) {
            try {
                if (dropdownType == 'main') {
                    Element.hide("dollarEcvNumberLabel" + i);
                    Element.hide("dollarEcvNumberInput" + i);
                } else if (dropdownType == 'combined') {
                    Element.hide("dollarEcvNumberAnotherOfferLabel" + i);
                    Element.hide("dollarEcvNumberAnotherOfferInput" + i);
                }
            } catch (e) {
            }
        }
    },

/*
This function shows the input boxes for sales dollar ecvs
*/
    createSalesDollarEcvInputBoxes : function (dropdownType) {

        try {
            this.clearSalesDollarEcvTable(dropdownType);
            var paxcount = this.getPaxCount();
            for (var i = 0; i < paxcount; i++) {
                if (dropdownType == 'main') {
                    Element.show("salesdollarEcvDataRow" + i);
                    Element.show("salesdollarEcvLabelRow" +i);
                } else if (dropdownType == 'combined') {
                    Element.show("salesdollarAnotherOfferEcvDataRow" + i);
                    Element.show("salesdollarAnotherOfferEcvLabelRow" + i);
                }
            }
            // clear the values for the rest so that they don't get posted
            for (var i = paxcount; i < 20; i++) {
                if (dropdownType == 'main') {
                    $('salesdollarEcvCode' + i).value = '';
                    $('salesdollarEcvRC' + i).value = '';
                } else if (dropdownType == 'combined') {
                    $('salesdollarAnotherOfferEcvCode' + i).value = '';
                    $('salesdollarAnotherOfferEcvRC' + i).value = '';
                }
            }
        } catch (e) {
        }

    },

    clearSalesDollarEcvTable : function(dropdownType) {

        try {
            for (var i = 0; i < 20; i++) {
                if (dropdownType == 'main') {
                    Element.hide("salesdollarEcvDataRow" + i);
                    Element.hide("salesdollarEcvLabelRow" + i);
                } else if (dropdownType == 'combined') {
                    Element.hide("salesdollarAnotherOfferEcvDataRow" + i);
                    Element.hide("salesdollarAnotherOfferEcvLabelRow" + i);
                }
            }
        } catch (e) {
        }

    },

/*
This function shows the input boxes for sales promo ecvs
*/
    createSalesPromoEcvInputBoxes : function (event) {

        this.clearSalesPromoEcvTable();
        try {
            var paxcount = this.getPaxCount();
            Element.show("entersalespromoecv");
            for (var i = 0; i < paxcount; i++) {
                Element.show("salespromoEcvDataRow" + i);
                Element.show("salespromoEcvLabelRow" + i);
            }
            // clear the values for the rest so that they don't get posted
            for (var i = paxcount; i < 20; i++) {
                $('salespromoEcvNumber' + i).value = '';
                $('salespromoEcvRC' + i).value = '';
            }

        } catch (e) {
        }
    },

    clearSalesPromoEcvTable : function(event) {

        for (var i = 0; i < 20; i++) {
            try {
                Element.hide("salespromoEcvDataRow" + i);
                Element.hide("salespromoEcvLabelRow" + i);
            } catch (e) {
            }
        }
        Element.hide("entersalespromoecv");
    },

    handleInfantInLapSelection : function(event) {
        // don't bother adjusting dropdown if discounts are not selected
        if ($('discountNo').checked) {
            return;
        }

        var allOptionsSelect = $('selectDiscountType');
        var selectedMainOption = $F('selectDiscountType');

        if ( this.apacPOS == true
                || ($('awardtravel') != null && $('awardtravel').checked)
                || ($('wpmu') && $('mileageUpgradeCheckbox') && $('mileageUpgradeCheckbox').checked) ) {

            allOptionsSelect = $('selectDiscountTypeWithAward');
            selectedMainOption = $F('selectDiscountTypeWithAward');
        }


        var infantInLapPaxCount = 0;
        if ($('iil')) {
            infantInLapPaxCount = $F('iil');
        }

        if (infantInLapPaxCount > 0) {

            // hide all options first. it is possible that we removed
            // freeecv option while it was getting displayed.
            this.hideDiscounts(null);

            this.adjustOptionsForInfantInLap(allOptionsSelect);

            // since the drop down is reset, refresh the current display.
            this.showFirstOfferDropDown(null);
        } else {
            var containsFreeEcv = false;
            var containsSalesPromoEcv = false;
            // we don't want to add to drop down if they are already present
            for (var i = 0; i < allOptionsSelect.options.length; i++) {
                var thisOption = allOptionsSelect.options[i];
                if (thisOption.value == 'freeecv') {
                    containsFreeEcv = true;
                }
                if (thisOption.value == 'salespromoecv') {
                    containsSalesPromoEcv = true;
                }
            }

            if (!containsFreeEcv) {
                this.addOptionForInfantInLap(allOptionsSelect, this.discountsRb.freeecv, "freeecv");
            }
            if (!containsSalesPromoEcv) {
                this.addOptionForInfantInLap(allOptionsSelect, this.discountsRb.extrasfarediscount, "salespromoecv");
                this.addOptionForInfantInLap(allOptionsSelect, this.discountsRb.extrasticket, "salespromoecv");
            }
        }

    },

    adjustOptionsForInfantInLap : function(allOptionsSelect) {
        this.removeOptionsForInfantInLap(allOptionsSelect);
        // there seems to be a bug where if multiple options have same value,
        // it only gets removed once. Call remove again so that the enci
        // salespromo is removed for NWA Extras Ticket and Fare Discount.
        this.removeOptionsForInfantInLap(allOptionsSelect);
    },

    removeOptionsForInfantInLap : function(allOptionsSelect) {
        var allOptionsList = allOptionsSelect.getElementsByTagName('option');
        var allOptions = $A(allOptionsList);
        allOptions.each(function(thisOption, index) {
            if (thisOption.value == 'freeecv'
                    || thisOption.value == 'salespromoecv') {
                allOptionsSelect.options[index] = null;
            }
        });
    },

    addOptionForInfantInLap : function(selectbox, text, value) {
        var option = document.createElement("OPTION");
        option.text = text;
        option.value = value;
        selectbox.options.add(option);
    },

    info: function() {
        return "discount manager";
    }
}


function showAwardCarriers() {
    Effect.Appear('awardCarriers', {duration: 1.0});

}

/**
 * This class is instantiated in the flightbook.jsp class.
 * The constructor fields are the positions of each traveler.
 */
ToggleNameFields = Class.create();
ToggleNameFields.prototype = {
    initialize : function(indexposition) {
        this.indexposition = indexposition - 1;
        this.disabledClass = "lightGray";
        this.initNameToggle();
        this.initLoyaltyCardToggle();
    },

/**
 * Creates the listener for the travel profile pull down boxes.  When the user changes the select box the values currently in it
 * are deleted and fields are disabled.  The indexposition is the position of the traveler that is being clicked on.
 *
 * This should only happen if there are traveler profiles available, for a guest or corporate traveler, that is not the case.
 * (see bug 65207)
 */
    initNameToggle: function() {
        var o = $("travelerIndices" +this.indexposition);
        if (o) {
        	Event.observe('travelerIndices' +this.indexposition, 'change', this.toggleNameFields.bind(this));
        }
    },

    toggleNameFields: function(){
        // This is the traveler that was clicked on.
        var travelerarrayposition = this.indexposition;
        $("travelers[" +travelerarrayposition +"].name.firstName").value = "";
        if($("travelers[" +travelerarrayposition +"].name.middleInitial") != null){
        $("travelers[" +travelerarrayposition +"].name.middleInitial").value = "";
        }
        $("travelers[" +travelerarrayposition +"].name.lastName").value = "";

        //The DOM id of the traveler select drop down box: event.target.id
        //if the Index of selected Traveler is -1 do nothing just return
        if ($("travelerIndices" +this.indexposition).value == -1) {
            $("travelers[" +travelerarrayposition +"].name.firstName").disabled = false;
            $("travelers[" +travelerarrayposition +"].name.firstName").removeClassName(this.disabledClass);
            if($("travelers[" +travelerarrayposition +"].name.middleInitial") != null)
            {
            	$("travelers[" +travelerarrayposition +"].name.middleInitial").disabled = false;
                $("travelers[" +travelerarrayposition +"].name.middleInitial").removeClassName(this.disabledClass);
            }
            $("travelers[" +travelerarrayposition +"].name.lastName").disabled = false;
            $("travelers[" +travelerarrayposition +"].name.lastName").removeClassName(this.disabledClass);
            $("saveProfileChk" +travelerarrayposition).disabled = false;
            $("saveProfileChk" +travelerarrayposition).removeClassName(this.disabledClass);
        }
        else{
            $("travelers[" +travelerarrayposition +"].name.firstName").disabled = true;
            $("travelers[" +travelerarrayposition +"].name.firstName").addClassName(this.disabledClass);
            if($("travelers[" +travelerarrayposition +"].name.middleInitial") != null)
            {
            	$("travelers[" +travelerarrayposition +"].name.middleInitial").disabled = true;
                $("travelers[" +travelerarrayposition +"].name.middleInitial").addClassName(this.disabledClass);
            }
            $("travelers[" +travelerarrayposition +"].name.lastName").disabled = true;
            $("travelers[" +travelerarrayposition +"].name.lastName").addClassName(this.disabledClass);
            $("saveProfileChk" +travelerarrayposition).disabled = true;
            $("saveProfileChk" +travelerarrayposition).checked = false;
            $("saveProfileChk" +travelerarrayposition).addClassName(this.disabledClass);
        }
    },

    initLoyaltyCardToggle: function() {
    	var loyaltycard = $('storedLoyaltyCardProfileIndices' + this.indexposition);
    	if (loyaltycard) {
            var firstName = $('travelers[' + this.indexposition + '].name.firstName');
            if(firstName){
                Event.observe(firstName, 'click', this.disableCurrentLoyaltyCard.bind(this));
            }

            var middleName = $('travelers[' + this.indexposition + '].name.middleInitial');
            if(middleName){
                Event.observe(middleName, 'click', this.disableCurrentLoyaltyCard.bind(this));
            }

            var lastName = $('travelers[' + this.indexposition + '].name.lastName');
            if(lastName){
                Event.observe(lastName, 'click', this.disableCurrentLoyaltyCard.bind(this));
            }
        }
    },

    disableCurrentLoyaltyCard: function() {
		var loyaltycard = $('storedLoyaltyCardProfileIndices' + this.indexposition);
		loyaltycard.disabled = true;
		var addLoyaltyCardCheckbox = $('addAirLoyaltyCardProfileIndices' + this.indexposition);
		addLoyaltyCardCheckbox.disabled = false;
    }
}

FlightSummaryManager = Class.create();
FlightSummaryManager.prototype = {
	//originalLPs contains all possible loyalty programs
	//storedLoyaltyProfiles is a 2d array which contains the stored loyalty
	// programs for all the travelers
    initialize : function(storedLoyaltyProfiles, cardSelections, originalLPs) {

        if ($("noUpsellCostSummary")) {
            //When upsells are available, the noUpsellCostSummary will be present
            this.initUpsellDisplay();
        }

        if (storedLoyaltyProfiles != null && storedLoyaltyProfiles.length > 0) {
            this.storedLoyaltyProfiles = storedLoyaltyProfiles;
            // if travelerProfiles dropdown does not exist, this is a non-arranger
            // corporate traveler, and we don't need to filter the loyalty cards
            if ($$('.travelerProfiles').length > 0) {
                this.initTravelerProfileDropDown();
                this.disableStoredLoyaltyCards(storedLoyaltyProfiles, cardSelections);
            } else {
                var targetDropDown = "storedLoyaltyCardProfileIndices0";
                if ($(targetDropDown)) {
                    $(targetDropDown).disabled = false;
                    $(targetDropDown).select('option').each(function(el, i) {
                        if (i > 0) {
                            el.remove();
                        }
                    });

                    //Find the LoyaltyPrograms corresponding to the selected traveler
                    var currentStoredLoyaltyProfiles = this.storedLoyaltyProfiles[0];
                    if (currentStoredLoyaltyProfiles.length == 0) {
                        $(targetDropDown).disabled = true;
                    } else {
                        var count = 1
                        currentStoredLoyaltyProfiles.each(function(lpnode) {
                            if (lpnode != null) {
                                var newOpt = new Option(lpnode.name + " " +
                                                        lpnode.number, lpnode.id);
                                $(targetDropDown).options[count++] = newOpt;
                            }
                        });
                        $(targetDropDown).selectedIndex = 1;
                    }
                }

            }
        }

        // we need to handle the add new loyalty programs div still
        this.originalLoyaltyPrograms = originalLPs;
        this.initAddNewLoyaltyCard();
        this.initLoyaltyCardSelects();
        this.addEventHandlers();
    },
    addEventHandlers : function(){

    	var i=0;
    	while(true){

			var traveler = 'travelers[' + i + ']';
			var firstName = traveler + '.name.firstName';
			var middleInitial =  traveler + '.name.middleInitial';
			var lastName = traveler + '.name.lastName';

			//there should always be a first name.. if not found then we know
			//there are no more travelers. middle initial and last name may be
			//optional for some countries
			if($(firstName)){
				Event.observe(firstName, 'keypress', handleNonNumericInput);
			}else{
				break;
			}
			if($(middleInitial)){
				Event.observe(middleInitial, 'keypress', handleNonNumericInput);
			}
			if($(lastName)){
				Event.observe(lastName, 'keypress', handleNonNumericInput);
			}


			i++;

		}
		        addEventHandlerForContacts();

                if($('destPhoneNumber')){
                    showExtension(this, 'dest');
                    Event.observe('destPhoneNumber', 'keypress', handlePhoneInput);
                    Event.observe('destPhoneType', 'change', showExtension.bindAsEventListener(this, 'dest'));
                }
                if($('destExtension')){
                    Event.observe('destExtension', 'keypress', handleNumericInput);
                }
                if($('email')){
                    Event.observe('email', 'keypress', handleEmailInput);
                }
                if($('tripDetailsEmailField')){
                    Event.observe('tripDetailsEmailField', 'keypress', handleEmailInput);
                }
                if($('retypeEmail')){
                    Event.observe('retypeEmail', 'keypress', handleEmailInput);
                }

    },

    /**
     * This method will check the loyalty card select boxes and if they only have
     * one element, it will pre-select that element
     */
    initLoyaltyCardSelects: function() {
    	$$('.loyaltyCardSelect').each(function(item){
    		// If the select box has only one element, select it.
            // the reason we check for two is b/c the first one is the "Select..." option
            if($(item).length == 2) {
            	$(item).selectedIndex = 1;
            }
    	});
    },
/**
 * Creates the listener for the add new loyalty card check boxes
 */
    initAddNewLoyaltyCard: function() {
        $$('.addNewLoyaltyCards').each(function(node, index) {
            Event.observe(node, 'click', this.toggleAddNewLoyaltyCard.bindAsEventListener(this));
        }.bind(this));
    },

/**
 * Shows or hides the div containing the new frequent flyer input fields, and populates
 * the newLoyaltyPrograms dropdown with the appropriate options for the current user
 */
    toggleAddNewLoyaltyCard: function(event) {
        var el = event.element();
        var type = el.hasClassName('newAirLoyaltyCards')?'air':el.hasClassName('newHotelLoyaltyCards')?'hotel':'car';
        var index = el.id.split('Indices')[1];
        var targetdiv = "addFrequentFlyerDiv" + index + type;
        if(el.checked){
            Element.show(targetdiv);
        } else {
            Element.hide(targetdiv);
        }

        if(type == 'air'){
            var targetLoyaltyDropdown = "newLoyaltyPrograms" + index;
            var targetTravelerDropdown = "travelerIndices" + index;
            // If there is a travelers dropdown, we need to populate the newLoyaltyPrograms
            // dropdown with only the programs for which the traveler doesn't already have stored cards
            // This logic was moved here from populateTravelersLoyaltyCard to work around a bug
            // in IE where the newLoyaltyPrograms dropdown was displaying even if the div was hidden
            if ($(targetTravelerDropdown)) {
                // Remove all the FF programs from the drop down and
                // re-populate with the original FF program list, as the previous
                // list of options may have been pruned for the last traveler.
                $(targetLoyaltyDropdown).select('option').each(function(program) {
                   program.remove();
                });

                //only add programs if there isn't already a stored card of that type
                var selectedTravelerIndex = $(targetTravelerDropdown).value;
                var count = 0;
                this.originalLoyaltyPrograms.each(function(program) {
                    var add = true;
                    if(selectedTravelerIndex > -1){
                        this.storedLoyaltyProfiles[selectedTravelerIndex].each(function(el){
                            if(el != null && program.displayVal == el.name){
                                add = false;
                            }
                        });
                    }
                    if(add){
                        var option = new Element('option');
                        option.text = program.displayVal;
                        option.value = program.value;
                        $(targetLoyaltyDropdown).options[count++]=option;
                    }
                }.bind(this));
            }

            // If the select box has only one element, select it.
            // the reason we check for two is b/c the first one is the "Select..." option
            if($(targetLoyaltyDropdown).length == 2) {
            	$(targetLoyaltyDropdown).selectedIndex = 1;
            }
        }
    },

/**
 * If the page encountered an error, show those add new Loyalty Divs
 * that contain new Loyalty Card data
 */
    showAddLoyaltyDivsIfPreviouslyFilled: function() {
        $$('.newAirLoyaltyCards').each(function(node, index) {
            if (node.checked) {
                var targetdiv = "addFrequentFlyerDiv" + index + "air";
                Element.show(targetdiv);
            }
        });
        $$('.newHotelLoyaltyCards').each(function(node, index) {
	        if (node.checked) {
                var targetdiv = "addFrequentFlyerDiv" + index + "hotel";
                Element.show(targetdiv);
            }
        });
        $$('.newCarLoyaltyCards').each(function(node, index) {
	        if (node.checked) {
                var targetdiv = "addFrequentFlyerDiv" + index + "car";
                Element.show(targetdiv);
            }
        });
    },


/**
 * Disables the stored loyaltyCards dropdown on page load
 */
    disableStoredLoyaltyCards: function(storedLoyaltyProfiles, cardSelections) {
        $$('.storedLoyaltyCards').each(function(node, index) {
            var theSelectedIndex = node.selectedIndex>0?node.selectedIndex - 1:0;
            var targetDropDown = node;
            if (node.selectedIndex == 0) {
                $(targetDropDown).disabled = true;
            } else {
                if ($$('.travelerProfiles').length > 0) {
                    // find selected value of corresponding traveler dropdown (this is the traveler's index)
                    var travelerProfileDropdowns = $$('.travelerProfiles');
                    var selectedTravelerIndex = travelerProfileDropdowns[index].value;

                    if (selectedTravelerIndex > -1) {
                        // get list of loyalty cards for selected traveler
                        var currentStoredLoyaltyProfiles = storedLoyaltyProfiles[selectedTravelerIndex];
                        if (currentStoredLoyaltyProfiles.length == 0) {
                            // no loyalty cards for this traveler
                            $(targetDropDown).disabled = true;
                        } else {
                            // clear current options from target loyalty card dropdown
                            $(targetDropDown).select('option').each(function(el, i){
                                if(i>0){
                                    el.remove();
                                }
                            });
                            // populate target loyalty card dropdown with traveler's cards
                            currentStoredLoyaltyProfiles.each(function(lpnode, lpindex) {
                                var newOpt = new Option(lpnode.name + " " +
                                                lpnode.number, lpnode.id);
                                var selLength = $(targetDropDown).options.length;
                                $(targetDropDown).options[selLength] = newOpt;
                                if (lpnode.id == cardSelections[index]) {
                                    theSelectedIndex = selLength;
                                }
                            });
                            if (theSelectedIndex > 0) {
                                $(targetDropDown).selectedIndex = theSelectedIndex;
                            }
                        }
                    }
                }
            }
        });
    },

/**
 * Registers an event for each Traveler Profile drop down to populate the corresponding loyaltyCards
 */
    initTravelerProfileDropDown: function() {
        $$('.travelerProfiles').each(function(node, index) {
            Event.observe(node, 'change', this.populateTravelersLoyaltyCard.bindAsEventListener(this, index));
        }.bind(this));
    },

/**
 * On selection of a Traveler profile populates the corresponding drop down with its stored loyalty cards
 */
    populateTravelersLoyaltyCard: function(event, index) {
        var elem = event.element();
        var targetDropDown = "storedLoyaltyCardProfileIndices" + index;;
        //The selected Traveler Index
        var selectedTraveler = $F(elem);

        //if the Index of selected Traveler is -1, disable target dropdown
        if (selectedTraveler == -1) {
            $(targetDropDown).disabled = true;
            $(targetDropDown).selectedIndex = 0;
        } else if ($(targetDropDown)) {
            //Enable the target drop down: targetDropDown
            $(targetDropDown).disabled = false;
            //Remove all the previous options from the select box except
            //for the first option.
            $(targetDropDown).select('option').each(function(el, i){
                if(i>0){
                    el.remove();
                }
            });

            //Find the LoyaltyPrograms corresponding to the selected traveler
            var currentStoredLoyaltyProfiles = this.storedLoyaltyProfiles[selectedTraveler];
            if (currentStoredLoyaltyProfiles.length == 0) {
                $(targetDropDown).disabled = true;
            } else {
                var count = 1
                currentStoredLoyaltyProfiles.each(function(lpnode) {
                	if(lpnode != null){
	                    var newOpt = new Option(lpnode.name + " " +
	                                            lpnode.number, lpnode.id);
	                    $(targetDropDown).options[count++]=newOpt;
                	}
                });
                $(targetDropDown).selectedIndex = 1;
            }
        }
        // uncheck add new card check box and hide add new card div
        $("addAirLoyaltyCardProfileIndices" + index).checked = false;
        Element.hide("addFrequentFlyerDiv" + index + "air");
        window.focus();
    },

    initUpsellDisplay: function() {
        try {
            Event.observe($('nonStopUpsell'), "click", this.changeUpsellViewNonStop.bindAsEventListener(this));
        } catch (err) {}
        try {
            Event.observe($('firstClassUpsell'), "click", this.changeUpsellViewFirstClass.bindAsEventListener(this));
        } catch (err) {}
        try {
            Event.observe($('mileageUpgradeUpsell'), "click", this.changeUpsellViewMileageUpgrade.bindAsEventListener(this));
        } catch (err) {}
        try {
            Event.observe($('noUpsell'), "click", this.changeUpsellViewNoUpsell.bindAsEventListener(this));
        } catch (err) {}
    },

    changeUpsellViewNonStop: function(event) {
        if($("nonStopUpsellRefundable")) {
            Element.show("nonStopUpsellRefundable");
        }
        if($("mileageUpgradeUpsellRefundable")) {
            Element.hide("mileageUpgradeUpsellRefundable");
        }
        if($("selecteditineraryRefundable")) {
            Element.hide("selecteditineraryRefundable");
        }
        Element.hide("noUpsellFlightDetails");
        Element.hide("mileageUpgradeUpsellFlightDetails");
        Element.hide("firstClassUpsellFlightDetails");
        Element.show("nonStopUpsellFlightDetails");
        Element.hide("noUpsellCostSummary");
        Element.show("nonStopUpsellCostSummary");
        Element.hide("mileageUpgradeUpsellCostSummary");
        Element.hide("firstClassUpsellCostSummary");
        Element.hide("selectedItineraryFareLink1a");
        Element.hide("selectedItineraryFareLink1b");
        Element.hide("selectedItineraryFareLink2");
        if($("nonStopUpsellFlightDetails1a")) {
            Element.show("nonStopUpsellFlightDetails1a");
            Element.show("nonStopUpsellFlightDetails1b");
        }
        Element.show("nonStopUpsellFlightDetails2");
        if($("mileageUpgradeUpsellFlightDetails1a")) {
            Element.hide("mileageUpgradeUpsellFlightDetails1a");
            Element.hide("mileageUpgradeUpsellFlightDetails1b");
        }
        Element.hide("mileageUpgradeUpsellFlightDetails2");
        if($("firstClassUpsellFlightDetails1a")) {
            Element.hide("firstClassUpsellFlightDetails1a");
            Element.hide("firstClassUpsellFlightDetails1b");
        }
        Element.hide("firstClassUpsellFlightDetails2");
    },

    changeUpsellViewFirstClass: function(event) {
        if($("nonStopUpsellRefundable")) {
            Element.hide("nonStopUpsellRefundable");
        }
        if($("mileageUpgradeUpsellRefundable")) {
            Element.hide("mileageUpgradeUpsellRefundable");
        }
        if($("selecteditineraryRefundable")) {
            Element.hide("selecteditineraryRefundable");
        }
        Element.hide("noUpsellFlightDetails");
        Element.hide("mileageUpgradeUpsellFlightDetails");
        Element.show("firstClassUpsellFlightDetails");
        Element.hide("nonStopUpsellFlightDetails");
        Element.hide("noUpsellCostSummary");
        Element.hide("nonStopUpsellCostSummary");
        Element.hide("mileageUpgradeUpsellCostSummary");
        Element.show("firstClassUpsellCostSummary");
        Element.hide("selectedItineraryFareLink1a");
        Element.hide("selectedItineraryFareLink1b");
        Element.hide("selectedItineraryFareLink2");
        if($("nonStopUpsellFlightDetails1a")) {
            Element.hide("nonStopUpsellFlightDetails1a");
            Element.hide("nonStopUpsellFlightDetails1b");
        }
        Element.hide("nonStopUpsellFlightDetails2");
        if($("mileageUpgradeUpsellFlightDetails1a")) {
            Element.hide("mileageUpgradeUpsellFlightDetails1a");
            Element.hide("mileageUpgradeUpsellFlightDetails1b");
        }
        Element.hide("mileageUpgradeUpsellFlightDetails2");
        if($("firstClassUpsellFlightDetails1a")) {
            Element.show("firstClassUpsellFlightDetails1a");
            Element.show("firstClassUpsellFlightDetails1b");
        }
        Element.show("firstClassUpsellFlightDetails2");
    },

    changeUpsellViewMileageUpgrade: function(event) {
        if($("nonStopUpsellRefundable")) {
            Element.hide("nonStopUpsellRefundable");
        }
        if($("mileageUpgradeUpsellRefundable")) {
            Element.show("mileageUpgradeUpsellRefundable");
        }
        if($("selecteditineraryRefundable")) {
            Element.hide("selecteditineraryRefundable");
        }
        Element.hide("noUpsellFlightDetails");
        Element.show("mileageUpgradeUpsellFlightDetails");
        Element.hide("firstClassUpsellFlightDetails");
        Element.hide("nonStopUpsellFlightDetails");
        Element.hide("noUpsellCostSummary");
        Element.hide("nonStopUpsellCostSummary");
        Element.show("mileageUpgradeUpsellCostSummary");
        Element.hide("firstClassUpsellCostSummary");
        Element.hide("selectedItineraryFareLink1a");
        Element.hide("selectedItineraryFareLink1b");
        Element.hide("selectedItineraryFareLink2");
        if($("nonStopUpsellFlightDetails1a")) {
            Element.hide("nonStopUpsellFlightDetails1a");
            Element.hide("nonStopUpsellFlightDetails1b");
        }
        Element.hide("nonStopUpsellFlightDetails2");
        if($("mileageUpgradeUpsellFlightDetails1a")) {
            Element.show("mileageUpgradeUpsellFlightDetails1a");
            Element.show("mileageUpgradeUpsellFlightDetails1b");
        }
        Element.show("mileageUpgradeUpsellFlightDetails2");
        if($("firstClassUpsellFlightDetails1a")) {
            Element.hide("firstClassUpsellFlightDetails1a");
            Element.hide("firstClassUpsellFlightDetails1b");
        }
        Element.hide("firstClassUpsellFlightDetails2");
    },

    changeUpsellViewNoUpsell: function(event) {
        if($("nonStopUpsellRefundable")) {
            Element.hide("nonStopUpsellRefundable");
        }
        if($("mileageUpgradeUpsellRefundable")) {
            Element.hide("mileageUpgradeUpsellRefundable");
        }
        if($("selecteditineraryRefundable")) {
            Element.show("selecteditineraryRefundable");
        }
        Element.show("noUpsellFlightDetails");
        Element.hide("mileageUpgradeUpsellFlightDetails");
        Element.hide("firstClassUpsellFlightDetails");
        Element.hide("nonStopUpsellFlightDetails");
        Element.show("noUpsellCostSummary");
        if($("nonStopUpsellCostSummary")) {
            Element.hide("nonStopUpsellCostSummary");
            Element.hide("mileageUpgradeUpsellCostSummary");
            Element.hide("firstClassUpsellCostSummary");
        }
        Element.show("selectedItineraryFareLink1a");
        Element.show("selectedItineraryFareLink1b");
        Element.show("selectedItineraryFareLink2");
        if($("nonStopUpsellFlightDetails1a")) {
            Element.hide("nonStopUpsellFlightDetails1a");
            Element.hide("nonStopUpsellFlightDetails1b");
        }

        Element.hide("nonStopUpsellFlightDetails2");
        if($("mileageUpgradeUpsellFlightDetails1a")) {
            Element.hide("mileageUpgradeUpsellFlightDetails1a");
            Element.hide("mileageUpgradeUpsellFlightDetails1b");
        }
        Element.hide("mileageUpgradeUpsellFlightDetails2");
        if($("firstClassUpsellFlightDetails1a")) {
            Element.hide("firstClassUpsellFlightDetails1a");
            Element.hide("firstClassUpsellFlightDetails1b");
        }
        Element.hide("firstClassUpsellFlightDetails2");
    }
}

function addEventHandlerForContacts() {

    if($('primaryPhone')){
        showExtension(this, 'primary');
        Event.observe('primaryPhone', 'keypress', handlePhoneInput);
        Event.observe('primaryPhoneType', 'change', showExtension.bindAsEventListener(this, 'primary'));
    }
    if($('primaryPhoneExt')){
        Event.observe('primaryPhoneExt', 'keypress', handleNumericInput);
    }
    if($('secondaryPhone')){
        showExtension(this, 'secondary');
        Event.observe('secondaryPhone', 'keypress', handlePhoneInput);
        Event.observe('secondaryPhoneType', 'change', showExtension.bindAsEventListener(this, 'secondary'));
    }
    if($('secondaryPhoneExt')){
        Event.observe('secondaryPhoneExt', 'keypress', handleNumericInput);
    }
    if($('ecFirstName')){
        Event.observe('ecFirstName', 'keypress', handleNonNumericInput);
    }
    if($('ecLastName')){
        Event.observe('ecLastName', 'keypress', handleNonNumericInput);
    }
    if($('ecPhone')){
        showExtension(this, 'ec');
        Event.observe('ecPhone', 'keypress', handlePhoneInput);
        Event.observe('ecPhoneType', 'change', showExtension.bindAsEventListener(this, 'ec'));
    }
    if($('ecExtension')){
        Event.observe('ecExtension', 'keypress', handleNumericInput);
    }
}



function submitSpringEventForm(eventId, params) {

	var formObj = document.forms[0];

	var eventIdElem = document.createElement("INPUT");
	eventIdElem.type = "hidden";
	eventIdElem.name = "_eventId";
	eventIdElem.value = eventId;

	formObj.appendChild(eventIdElem);

	for (var param in params){
		var paramElem = document.createElement("INPUT");
		paramElem.type = "hidden";
		paramElem.name = param;
		paramElem.value = params[param];
		formObj.appendChild(paramElem);
	}

	formObj.submit();

}

function submitFlightSummaryForm(eventType){
    if(eventType=="save"){
        $('saveEvent').value = eventType;
        if($('holdEvent')){
            Element.remove('holdEvent');
        }
    }

    if(eventType=="hold"){
        $('holdEvent').value=eventType;
        Element.remove('saveEvent');
    }

    $('flightBookForm').submit();
}

function removeHiddenEventsFlightSummaryForm() {
    if($('holdEvent')){
        Element.remove('holdEvent');
    }

    if($('saveEvent')){
        Element.remove('saveEvent');
    }

    var validator = new FlightSummaryValidator();

    if(validator.validate()){

    	return true;
	} else{
		showErrors(validator);
	}
    return false;
}

BillingManager = Class.create();
BillingManager.prototype = {
    initialize : function(pointOfSale) {
        this.cidIgnoreList = new Array();
        this.cidSupport = new Object();

        try {

			if($("paypalInstructions")) {
                Element.hide("paypalInstructions");
            }

            if ($('storedCardRadio')) {
                Event.observe("storedCardRadio", "click", this.displayStoredCard.bindAsEventListener(this));
                Event.observe("storedCards", "change", this.toggleCid.bindAsEventListener(this));
                this.toggleCid(null);
            }
            if ($('newCardRadio')) {
                Event.observe("newCardRadio", "click", this.displayNewCard.bindAsEventListener(this));
            }

            if($('newTypeOfCard')){
                Event.observe("newTypeOfCard","change",this.toggleNewCardCid.bindAsEventListener(this));
            }

            if($('paypalRadio')) {
                Event.observe("paypalRadio", "click", this.displayPaypal.bindAsEventListener(this));

                //If there was an error and a user is returned to the billing page
                //where paypal radio button was previously selected, traveloptions need to be
                //disabled and the new credit card fields need to show.
                if($('paypalRadio').checked) {
                    this.displayPaypal();
                }
            }

            if ($('discountTypes')) {
                if ($('selectDiscountTypeBilling')) {
                    Event.observe("selectDiscountTypeBilling", "click", this.toggleDiscount.bindAsEventListener(this));
                }

                this.toggleDiscount(null);
            }

            if($('newCardNumber')){
            	Event.observe('newCardNumber', 'keypress', handleNumericInput);
            	if($('newSecurityCode')){
            		Event.observe('newSecurityCode', 'keypress', handleNumericInput);
            	}
            	Event.observe('creditCardName', 'keypress', handleNonNumericInput);
            	Event.observe('newCardCity', 'keypress', handleNonNumericInput);
            }

            //CA pos allows both alpha and numeric, so do not put any filter on it
            if($('newCardPostalCode') && pointOfSale != 'CA'){
            	Event.observe('newCardPostalCode', 'keypress', handleZipCodeInput);
            }

            var anyTravelOptionsSelected = false;
            var inputs = document.getElementsByTagName("input");
            for(i=0; i<inputs.length; ++i) {
                if(inputs[i].name.indexOf("travelOption") == 0 ) {
                    if( $("paypalListItem") ) {
                        Event.observe(inputs[i], "click", this.togglePaypal.bindAsEventListener(this));
                    }

                    // If it's a checkbox and checked
                    if(("checkbox" == inputs[i].type.toLowerCase()) && inputs[i].checked) {
                        anyTravelOptionsSelected = true;
                    }
                    // Otherwise if it's a "Yes" radio button
                    else if(
                        ("radio" == inputs[i].type.toLowerCase()) &&
                        inputs[i].checked &&
                        inputs[i].id.match(/addProductItineraryIndices\d+Yes/)) {

                        anyTravelOptionsSelected = true;
                    }
                }
            }

            //If there was an error and a user is returned to the billing page where a travel option
            //was previously selected, the paypal radio button needs to be disabled
            if (anyTravelOptionsSelected && $("paypalListItem")) {
                Element.hide("paypalListItem");
            }

        } catch (e) {
        }
    },

    addToIgnoreList: function(cid) {
        this.cidIgnoreList.push(cid);
    },

    addToCidSupport: function(type,isSupported){
        this.cidSupport[type] = isSupported;
    },

    displayStoredCard : function() {
        Element.hide("newCreditCards");
        Element.show("storedCreditCards");
        Element.show("purchaseMsg");

        //enable the TravelOptions if any as they may have been disabled by
        //toggling of the paypal radio button
        disableTravelOptions(false);
        //Hide the paypal instructions
        if($("paypalInstructions")) {
            Element.hide("paypalInstructions");
        }
    },

    toggleCid: function(event) {
        if ($("divCid") == null) {
            return;
        }

        var selectedCard = $F('storedCards');
        var found = false;
        for (var i = 0; i < this.cidIgnoreList.length; i++) {
            if (selectedCard == this.cidIgnoreList[i]) {
                found = true;
                break;
            }
        }

        if (found) {
            Element.hide("divCid");
        }
        else {
            Element.show("divCid");
        }
    },

    toggleNewCardCid: function(event) {
        if ($("securityCode") == null) {
            return;
        }
        var selectedCard = $F('newTypeOfCard');
        if (this.cidSupport[selectedCard]) {
            Element.show("securityCode");
        }else{
            Element.hide("securityCode");
        }
    },

    displayNewCard : function() {
        $("storedCreditCards") && Element.hide("storedCreditCards");
        Element.show("newCreditCards");
        Element.hide("payPalNameOnAcct");
        Element.show("CCNameOnCard");
        Element.show("purchaseMsg");
        Element.scrollTo("paymentInfoModule");

        //enable these controls explicityly as they may have been disabled while toggling the paypal radio button.
        enableControls(true, ['newTypeOfCard', 'newCardNumber', 'newSecurityCode', 'expiryMonth', 'expiryYear', 'savebillingprofile', 'alwaysusethiscard']);

        //enable the TravelOptions if any as they may have been disabled by toggling of the paypal radio button
        disableTravelOptions(false);
        //hide the paypalInstructions
        if($("paypalInstructions")) {
            Element.hide("paypalInstructions");
        }
    },

    displayPaypal : function() {
        if($("storedCreditCards")) {
            Element.hide("storedCreditCards");
        }
        Element.show("newCreditCards");
        Element.hide("CCNameOnCard");
        Element.show("payPalNameOnAcct");
        Element.hide("purchaseMsg");
        Element.scrollTo("paymentInfoModule");

        //Disable the following controls as they are not needed for paypal.
        enableControls(false, ['newTypeOfCard', 'newCardNumber', 'newSecurityCode', 'expiryMonth', 'expiryYear', 'savebillingprofile', 'alwaysusethiscard']);

        //set the focus on the Name as it appears on the credit card field
        $("creditCardName").focus();

        //disable the TravelOptions if any
        disableTravelOptions(true);
        //show the paypal instructions
        Element.show("paypalInstructions");

    },

    toggleDiscount : function() {
        if ($('selectDiscountTypeBilling') == null) {
            return;
        }

        var selectedOption = $F('selectDiscountTypeBilling');

        if (selectedOption == 'none') {
            if ($("enterdollarecv")) {
                Element.hide("enterdollarecv");
            }
            if ($("entersalesdollarecv")) {
                Element.hide("entersalesdollarecv");
            }
            if ($("entergiftcert")) {
                Element.hide("entergiftcert");
            }if($("updatePriceButtonElement")){
                Element.hide("updatePriceButtonElement");
            }
        } else if (selectedOption == 'giftcert') {
            if ($("enterdollarecv")) {
                Element.hide("enterdollarecv");
            }
            if ($("entersalesdollarecv")) {
                Element.hide("entersalesdollarecv");
            }
            if ($("entergiftcert")) {
                Element.show("entergiftcert");
            }
        } else if (selectedOption == 'dollarecv' ) {
            if ($("entergiftcert")) {
                Element.hide("entergiftcert");
            }
            if ($("entersalesdollarecv")) {
                Element.hide("entersalesdollarecv");
            }
            if ($("enterdollarecv")) {
                Element.show("enterdollarecv");
            }
        } else if (selectedOption == 'salesdollarecv')   {
            if ($("entergiftcert")) {
                Element.hide("entergiftcert");
            }
            if ($("enterdollarecv")) {
                Element.hide("enterdollarecv");
            }
            if ($("entersalesdollarecv")) {
                Element.show("entersalesdollarecv");
            }
        }
        if(selectedOption == 'dollarecv' || selectedOption == 'giftcert' || selectedOption == 'salesdollarecv') {
               Element.show("updatePriceButtonElement");
        }
    },

    togglePaypal : function() {
        // Do basic check that the PayPal option is available on the page
        // Before trying to toggle it.
        if( $("paypalListItem") ) {
        var anyTravelOptionsSelected = false;
        var inputs = document.getElementsByTagName("input");

        for(i=0; i<inputs.length; ++i) {

            if("checkbox" == inputs[i].type.toLowerCase()) {
                if(inputs[i].name.indexOf("travelOption") == 0 ) {

                    if( inputs[i].checked ){
                        anyTravelOptionsSelected = true;
                    }
                }
            }
        }

        if (anyTravelOptionsSelected) {
            Element.hide("paypalListItem");
        } else {
            Element.show("paypalListItem");
            }
        }
    }
}

function disableTravelOptions(disable) {

    var inputs = document.getElementsByTagName("input");
    for(i=0; i<inputs.length; ++i) {
        if("checkbox" == inputs[i].type.toLowerCase()) {
            if(inputs[i].name.indexOf("travelOption") == 0 ) {
                inputs[i].disabled = disable;
            }
        }
    }
}


EditPreferenceManager = Class.create();
EditPreferenceManager.prototype = {
    initialize : function() {
        this.initAddLoyaltyCard();
        Field.select('firstname');

        addEventHandlerForContacts();
        showExtension();
    },

    initAddLoyaltyCard: function() {
        Event.observe('addFrequentFlyerButton', "click", this.toggleAddFrequentFlyer.bindAsEventListener(this));
    } ,

    toggleAddFrequentFlyer: function(event) {

        $('adding').value = Element.visible('addFrequentFlyer') ? 'false' : 'true';
        Element.toggle('addFrequentFlyer');
    }
}

MemberRegistrationManager = Class.create();
MemberRegistrationManager.prototype = {
    initialize : function() {
        addEventHandlerForContacts();
        showExtension();
    }
}

// used to manage a client side cookie tied to an input and checkbox control
CookieManager = Class.create();
CookieManager.prototype = {
    initialize : function(checkboxId, inputId) {
        this.checkboxId = checkboxId;
        this.inputId = inputId;
        Event.observe(this.checkboxId, "click", this.updateWorldPerksIdValue.bindAsEventListener(this));
        var cookie = this.getCookie(this.inputId);
        $(this.inputId).value = (cookie) ? cookie : '';
    },
    updateWorldPerksIdValue : function() {
        var value = '';
        if ($(this.checkboxId).checked) {
            value = $(this.inputId).value;
        }
        //set expiration to end of century to make sure the cookie persists across browser instances.
        var expires = new Date();
        expires.setFullYear(2099, 12, 31);
        expires.setHours(23);
        expires.setMinutes(59);
        expires.setSeconds(59);
        this.setCookie(this.inputId, value, expires);
    },
    getCookieVal  : function (offset) {
        var endstr = document.cookie.indexOf(";", offset);
        if (endstr == -1)
            endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
    },
    getCookie : function (name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
            var j = i + alen;
            if (document.cookie.substring(i, j) == arg)
                return this.getCookieVal(j);
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return null;
    },
    setCookie : function (name, value) {
        var argv = this.setCookie.arguments;
        var argc = this.setCookie.arguments.length;
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : null;
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        document.cookie = name + "=" + escape(value) +
                          ((expires == null) ? "" :
                           ("; expires=" + expires.toGMTString())) +
                          ((path == null) ? "" : ("; path=" + path)) +
                          ((domain == null) ? "" : ("; domain=" + domain)) +
                          ((secure == true) ? "; secure" : "");
    }
}
function selectSeat(row, column) {
    $('selectedRow').value = row;
    $('selectedColumn').value = column;
    var _s = $('eventId_selectSeat');
    _s.click();
}

function skip() {
    $('eventId_continue').click();
}

function switchPax(pax) {
    $('selectedPax').value = pax;
    $('eventId_switchPax').click();
}

function switchFlight(slice, segment, leg) {
    $('selectedSlice').value = slice;
    $('selectedSegment').value = segment;
    $('selectedLeg').value = leg;
    $('eventId_switchFlight').click();
}
PleaseWait = Class.create();
PleaseWait.prototype = {
    initialize : function(elem) {
        this.current = 0;
        this.interval = setInterval(this.loop.bind(this), 500);
        this.elem = elem;
    },
    loop : function() {
        var num = "";
        var e = $(this.elem);
        for (var i = 0; i < this.current; i++) {
            num = '.' + num;
        }
        if (e) $(this.elem).innerHTML = num;
        if (this.current == 3) {
            this.current = 0;
        } else {
            this.current++;
        }
    }
}

function showCalendar(url) {
    Element.hide('awardPromoCalendarShowDiv');
    Element.show('calendarDisplayDiv');
    Element.show('awardPleaseWait');
    new PleaseWait('pleasewait');
    loadCalendar(url, 'calendarDisplayDiv');
}

function changeCalendar(url, calId) {
    // prevent double clicking before page loads
    disableCalHeaderLinks(calId);
    new PleaseWait('pleasewait');
    loadCalendar(url, 'calendarDisplayDiv');
}

function disableCalHeaderLinks(calId) {
    var h = $('calendar' + calId + "Prev");
    if (h) Element.setStyle(h, {visibility : 'hidden'});
    h = $('calendar' + calId + 'Next');
    if (h) Element.setStyle(h, {visibility : 'hidden'});
    h = $('calendarHeader' + calId);
    // TODO: make this a resource
    if (h) h.innerHTML = "Loading calendar...";
}

function watchArrowsOnCalendarKey(awardCal) {

    var image = new Array;
    if (awardCal == "true"){
        image = ['psrestriction', 'pseconomyonly', 'psfirstclassonly', 'ppmaybeavailable', 'noflights'];
    } else if (awardCal == "false"){
        image = ['psrestriction', 'psfirstclassonly', 'ppmaybeavailable'];
    }
    image.each(function(node) {
        Event.observe(node + 'Img', 'click', function(evt) {
            if(Element.visible(node + 'Section')) {
                new Effect.BlindUp(node + 'Section');
                $(node + 'Img').src = '/images/awardcalendar/downarrow.gif';
            } else {
                new Effect.BlindDown(node + 'Section');
                $(node + 'Img').src = '/images/awardcalendar/uparrow.gif';
            }
        })
    })



}

function loadCalendar(url, div) {
    try {

        var newUrl = url + "&departDayOfMonth=" + awardOutboundDayOfMonth + "&returnDayOfMonth=" + awardReturnDayOfMonth;
        var myAjax = new Ajax.Updater(
                div,
                newUrl, { method: 'get', evalScripts: true });
    } finally {
        return false;
    }
}


var awardOutboundDayOfMonth = -1;
var awardReturnDayOfMonth = -1;

function updateOutboundDate(dayId, dayOfMonth, displayResource) {
    var displayText = displayResource;
    var resIx = displayResource.indexOf("{1}");
    if( resIx != -1 ) {
        displayText = displayResource.substring(0,resIx) + dayOfMonth + displayResource.substring(resIx+3);
    }
    if (dayId.match(/^depart_/)) {
        awardOutboundDayOfMonth = dayOfMonth;
        $(selectedDepartureId).removeClassName("awardSelected");
        var index = dayId.indexOf("_");
        var newVal = dayId.substring(index + 1);
        $('acDepartDay').innerHTML = displayText;
        $('selectedDepartureDate').value = newVal;
        selectedDepartureId = dayId;
    }
    if (dayId.match(/^return_/)) {
        awardReturnDayOfMonth = dayOfMonth;
        $(selectedReturnId).removeClassName("awardSelected");
        var index = dayId.indexOf("_");
        var newVal = dayId.substring(index + 1);
        $('selectedReturnDate').value = newVal;
        selectedReturnId = dayId;
        $('acReturnDay').innerHTML = displayText;
    }
    $(dayId).addClassName("awardSelected");
}

PrintManager = Class.create();
PrintManager.prototype = {
    initialize : function() {

        this.initPrintButton();
    },

    initPrintButton : function() {
        Event.observe('printButton', "click", this.showPrintWindow.bindAsEventListener(this));
    },

    showPrintWindow : function(event) {

        window.print();
        Event.stop( event );
    }
}


ExpiryDateManager = Class.create();
ExpiryDateManager.prototype = {
    initialize : function() {
        this.initCreditCardTypeToggle();
        this.toggleCreditCardType(null);
    },

    initCreditCardTypeToggle: function() {
        Event.observe('newTypeOfCard', "change", this.toggleCreditCardType.bindAsEventListener(this));
    } ,

    toggleCreditCardType: function(event) {
        // detect if the cid fields are on the page
        if ($('cidccamex') == null) {
            return;
        }
        Element.hide($('cidccamex'));
        Element.hide($('cidccdisc'));
        Element.hide($('cidvisa'));
        Element.hide($('cidmastercard'));
        var selectedCreditCardTypeOption = $F('newTypeOfCard');
        if (selectedCreditCardTypeOption == 'TP') {
            //            Element.show($('cidmastercard'));
        } else if (selectedCreditCardTypeOption == 'AX') {
            Element.show($('cidccamex'));
        } else if (selectedCreditCardTypeOption == 'DC') {
            //            Element.show($('cidmastercard'));
        } else if (selectedCreditCardTypeOption == 'DS') {
            Element.show($('cidccdisc'));
        } else if (selectedCreditCardTypeOption == 'JC') {
            //            Element.show($('cidmastercard'));
        } else if (selectedCreditCardTypeOption == 'CA') {
            Element.show($('cidmastercard'));
        } else if (selectedCreditCardTypeOption == 'VI'
                || selectedCreditCardTypeOption == 'WP') {
            Element.show($('cidvisa'));
        }
    } ,


    info: function() {
        return "Expiry Date manager";
    }


}

/*
This is similar to Script.aculo.us's autocompleter, this version
overwrites the keypress event handler; we don't want to stop the
default behavior of the tab key (event.stop is removed)
-db
 */
Ajax.NwaAutocompleter = Class.create();
Object.extend(Object.extend(Ajax.NwaAutocompleter.prototype, Autocompleter.Base.prototype), {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;

  },

  getUpdatedChoices: function() {
    entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB: /* this case added for NWA, event.stop(event) is removed from tab key */
           this.selectEntry();
           this.hide();
           this.active = false;
           return;
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
      }
     else
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
         (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  }
}

);


ValidationError = Class.create();
ValidationError.prototype = {
	initialize : function(){
		this.label = "";
		this.element = "";
		this.errorList = new Array();

	}
}


Validator = Class.create();
Validator.prototype = {

	initialize : function(){
		this.errorHash = new Hash();
	},

	isEmpty : function (val){

		return val.match(/^\s*$/) != null;

	},


	containsNoNumeric : function (val){

		return val.match(/^\s*\D+\s*$/) != null;

	},

	containsAsciiNoNumeric : function (val){

		return val.match(/^[\x20-\x7E && [^\d]]+$/) != null;

	},

	containsNoAlphaDashSlash : function (val){

		return val.match(/^\s*\d+\s*$/) != null;

	},

	containsNoAlpha : function (val){

		return val.match(/^\s*\d+[\/-]\d+[\/-]\d+\s*$/) != null;

	},

	containsNoAlphaSlash : function (val){

		return val.match(/^\s*\d+[-\s]?\d+[-\s]?\d+\s*$/) != null;

	},


	addError : function(label, element, error){
		var valError = this.errorHash[element];
		if(valError){
			valError.errorList[errorList.length] = error;
		}else{
			valError = new ValidationError();
			valError.label = label;
			valError.element = element;
			valError.errorList[0] = error;
			if(!(/1\.5/.test(Prototype.Version))){
				this.errorHash.set(element,valError);
			}else{
				this.errorHash[element] = valError;
			}
		}

	}

}


SearchValidator = Class.create();
Object.extend(Object.extend(SearchValidator.prototype, Validator.prototype), {

	validateFrom : function(label, element, valEmpty){
		if(valEmpty && this.isEmpty($(element).value)){
			this.addError(label, element,  'error.searchrequest.departrequired');
			return false;
		}

		if(!this.containsNoNumeric($(element).value)){
			this.addError(label, element,  'error.searchrequest.departinvalid');
			return false;
		}
		return true;
	},

	validateTo : function(label, element, valEmpty){
		if(valEmpty && this.isEmpty($(element).value)){
			this.addError(label, element,  'error.searchrequest.arriverequired');
			return false;
		}

		if(!this.containsNoNumeric($(element).value)){
			this.addError(label, element, 'error.searchrequest.arriveinvalid');
			return false;
		}
		return true;
	},

	validateMulticity : function(departLabel, departElem, arriveLabel, arriveElem, dateLabel, dateElem){

		var departEmpty = this.isEmpty($(departElem).value);
		var arriveEmpty = this.isEmpty($(arriveElem).value);

		if(departEmpty && arriveEmpty){
			return true;
		}
		else {

			if(!departEmpty && arriveEmpty){
				this.addError(arriveLabel, 'error.searchrequest.invalidmulticitycombination');
				return false;
			}
			if(departEmpty && !arriveEmpty){
				this.addError(departLabel, 'error.searchrequest.invalidmulticitycombination');
				return false;
			}

			return this.validateFrom(departLabel, departElem) && this.validateTo(arriveLabel, arriveElem) && this.validateDate(dateLabel, dateElem);
		}

	},

	validateDate : function(label, element, valEmpty){
		if(valEmpty && this.isEmpty($(element).value)){
			this.addError(label, element,  'error.searchrequest.daterequired');
			return false;
		}

		if(!this.containsNoAlpha($(element).value)){
			this.addError(label, element,  'error.searchrequest.invaliddate');
			return false;
		}
		return true;
	},


	validate : function(){

		this.validateFrom('departField0Label', 'departField0', true);
		if (!$('returnField0').disabled){
			this.validateTo('returnField0Label', 'returnField0', true);
		}
		this.validateDate('departureDateLabel', 'departureDate', true);
		//if this is not multicity validate return date now, else validate
		//as part of multicity
		if(!$('departField1')){
			this.validateDate('returnDateLabel', 'returnDate', true);
		}

		for(i=1; i<5; i++){
			var departFieldElem = 'departField' + i;
			var arriveFieldElem = 'returnField' + i;
			var dateElem = 'returnDate' + i;
			//special case because there is no returnDate1
			if(i == 1){
				dateElem = 'returnDate';
			}
			var departFieldLabel = departFieldElem + "Label";
			var arriveFieldLabel = arriveFieldElem + "Label";
			var dateLabel = dateElem + "Label";
			if($(departFieldElem)){
				this.validateMulticity(departFieldLabel, departFieldElem, arriveFieldLabel, arriveFieldElem, dateLabel, dateElem);
			}else{
				break;
			}

		}
		if(this.errorHash.keys().length > 0){
			return false;
		}
		return true;
	}
});


FlightSummaryValidator = Class.create();
Object.extend(Object.extend(FlightSummaryValidator.prototype, Validator.prototype), {

	validateFirstName : function(label, element, valEmpty) {

		if(valEmpty && this.isEmpty($(element).value)){
			this.addError(label, element,  'error.name.firstname.required');
			return false;
		}

		if(!this.isEmpty($(element).value) && !this.containsNoNumeric($(element).value)){
			this.addError(label, element,  'error.name.firstname.special');
			return false;
		}
		return true;

	},

	validateLastName : function(label, element, valEmpty) {

		if(valEmpty && this.isEmpty($(element).value)){
			this.addError(label, element,  'error.name.lastname.required');
			return false;
		}

		if(!this.isEmpty($(element).value) && !this.containsNoNumeric($(element).value)){
			this.addError(label, element,  'error.name.lastname.special');
			return false;
		}
		return true;

	},

	validateMiddleName : function(label, element) {

		if(!this.isEmpty($(element).value) && !this.containsNoNumeric($(element).value)){
			this.addError(label, element,  'error.name.middleinitial.invalid');
			return false;
		}
		return true;

	},

	validatePhone : function(label, element, valEmpty) {

		if(valEmpty && this.isEmpty($(element).value)){
			this.addError(label, element,  'error.travelerprofile.required.phone');
			return false;
		}

		if(!this.isEmpty($(element).value) && !this.containsNoAlphaSlash($(element).value)){
			this.addError(label, element,  'error.travelerprofile.invalid.phone');
			return false;
		}
		return true;

	},

	validateEmail : function(label, element, error) {
		var emailInput = $(element).value;
		var atTheRateOf="@";
		var dot=".";
		var lat=emailInput.indexOf(atTheRateOf);
		var lstr=emailInput.length;


		if(this.isEmpty(emailInput)){
			this.addError(label, element,  'error.email.required');
			return false;
		}
		if (emailInput.indexOf(atTheRateOf)==-1 || emailInput.indexOf(atTheRateOf)==0 || emailInput.indexOf(atTheRateOf)==lstr){
		   this.addError(label, element,  error);
		   return false;
		}

		if (emailInput.indexOf(dot)==-1 || emailInput.indexOf(dot)==0 || emailInput.indexOf(dot)==lstr){
		    this.addError(label, element,  error);
		    return false;
		}

		if (emailInput.indexOf(atTheRateOf,(lat+1))!=-1){
		    this.addError(label, element,  error);
		    return false;
		 }
		if (emailInput.substring(lat-1,lat)==dot || emailInput.substring(lat+1,lat+2)==dot){
			this.addError(label, element,  error);
		    return false
		 }

		return true;

	},



	validate : function(){

		var i = 0;
		while(true){

			var traveler = 'travelers[' + i + ']';
			var firstName = $(traveler + '.name.firstName');
			var middleInitial =  $(traveler + '.name.middleInitial');
			var lastName = $(traveler + '.name.lastName');

			if(firstName){
				if(!firstName.disabled){
					this.validateFirstName(firstName.id + 'Label', firstName.id, true);
				}
			}else{
				break;
			}
			if(middleInitial && !middleInitial.disabled){
				this.validateMiddleName(middleInitial.id + 'Label', middleInitial.id);
			}
			if(lastName && !lastName.disabled){
				this.validateLastName(lastName.id + 'Label', lastName.id, true);
			}


			i++;

		}

		try{

			if ($('tripDetailsEmailField')){
			    this.validateEmail('tripDetailsEmailFieldLabel', 'tripDetailsEmailField', 'error.email.invalid');
			}

			if(!$('email').disabled){
				var emailValid = this.validateEmail('emailLabel', 'email', 'error.email.invalid');
				var retypeValid = this.validateEmail('retypeEmailLabel', 'retypeEmail', 'error.retypeEmail.invalid');

				if(emailValid && retypeValid){
					if($('email').value != $('retypeEmail').value){
						this.addError('retypeEmailLabel', 'retypeEmail', 'error.email.nomatch');
					}
				}
			}

			if(!$('primaryPhone').disabled){
				this.validatePhone('primaryPhoneLabel', 'primaryPhone', true);
			}
			if(!$('primaryExtDiv').disabled){
				this.validatePhone('primaryPhoneExtLabel', 'primaryExtDiv', false);
			}
			if(!$('secondaryPhone').disabled){
				this.validatePhone('secondaryPhoneLabel', 'secondaryPhone', false);
			}
			if(!$('secondaryExtDiv').disabled){
				this.validatePhone('secondaryPhoneExtLabel', 'secondaryExtDiv', false);
			}
			if(!$('ecFirstName').disabled){
				this.validateFirstName('ecFirstNameLabel', 'ecFirstName', false);
			}
			if(!$('ecLastName').disabled){
				this.validateLastName('ecLastNameLabel', 'ecLastName', false);
			}

			if(!$('ecPhone').disabled){
				this.validatePhone('ecPhoneLabel', 'ecPhone', false);
			}
			if(!$('ecExtension').disabled){
				this.validatePhone('ecExtensionLabel', 'ecExtension', false);
			}

			this.validatePhone('destPhoneNumberLabel', 'destPhoneNumber', false);

		}catch(e){};


		if(this.errorHash.keys().length > 0){
			return false;
		}
		return true;

	}

});
ComprehensiveAtrLinkManager = {
    internalLinkHandler: function(el, classNames) {
        var mcNode = $(el.id.split('-')[0]);
        if (mcNode != null){
            var mcOptions = {triggerEvent: 'click', closeEvent: 'click', closeLabel: '', classNames: classNames, headerless:'true', ieShim:false};
            Novo.Microcontent.activate(el, {content: {domNode: mcNode}, options: mcOptions});
        }
        return false;
    },
    mcLinkHandlerNoCheck: function(el) {
        var classNames = {beakLeft: 'atrBeakLeft', beakRight: 'atrBeakRight', headerRight: 'atrHeaderRightNoCheck'};
        return ComprehensiveAtrLinkManager.internalLinkHandler(el, classNames);
    },
	mcLinkHandler : function(el){
        var classNames = {beakLeft: 'atrBeakLeft', beakRight: 'atrBeakRight'};
		return ComprehensiveAtrLinkManager.internalLinkHandler(el, classNames);
	},
    mcRemoveHandler: function() {
        Novo.Microcontent.destroy();
    },
	selectedFlightHandler : function(link){
		var button = $(link.id.split('-')[0]+'-button');
		var shim = $(link.id.split('-')[0]+'-shim');
		if(this.current != null){
			var prev = $(this.current+'-button');
			prev.removeClassName('continueBtn');
			prev.addClassName('continueBtn_hidden');
			var prevshim = $(this.current+'-shim');
			prevshim.removeClassName('shim');
			prevshim.addClassName('shim_hidden');
		}
		button.removeClassName('continueBtn_hidden');
		button.addClassName('continueBtn');
		shim.removeClassName('shim_hidden');
		shim.addClassName('shim');
		this.current = button.id.split('-')[0];
		return false;
	},
	preSubmitHandler : function(el){
		el.getElementsBySelector('.largeText')[0].value = $('combinedSearchMatrix').hasClassName('largeFont');
		el.getElementsBySelector('.showPerkChoiceFares')[0].value = $('combinedSearchMatrix').hasClassName('cash_visible');
	},
	showSelectedFlight : function(){
		if(this.current != null){
			var button = $(this.current+'-button');
			button.removeClassName('continueBtn_hidden');
			button.addClassName('continueBtn');
			var shim = $(this.current+'-shim');
			shim.removeClassName('shim_hidden');
			shim.addClassName('shim');
			$(this.current+'-radio').checked = true;
		}
	},
	getCurrentSelectedIndex : function(){
		if(this.current != null){
			var index = this.current.split('_')[1];
			return index;
		}else{
			return -1;
		}
	},
	getCurrentSelectedAwardLevel : function(){
		if(this.current != null){
			var awardLevel = this.current.split('_')[0];
			return awardLevel;
		}else{
			return '';
		}
	},
	updateLinks : function(newLink){
		$('ajaxUrl').innerHTML = newLink;
	},
    /**
     * This method handles adding hover notes to the fares on the
     * "Continue to Purchase" page.
     */
    revenueFareInfoLinkHandler : function(link) {
        var mcContent = $("atrCostMc");
        var classNames = {beakLeft: 'atrBeakLeft', beakRight: 'atrBeakRight', headerRight: 'atrHeaderRightNoCheck'};
        if(mcContent) {
            var mcOptions = {triggerEvent: 'mouseover', closeEvent: 'mouseout', closeLabel: '', classNames: classNames, headerless:'true', ieShim:false, offsetTop: 40};
            Novo.Microcontent.activate(link, {content: {domNode: mcContent}, options: mcOptions});
        }
    },
    revenueFareInfoLinkHandlerRegistration : function() {
        var links = $$(".atrCost");
        links.each(function(link){
            Event.observe(link, "mouseover", function() {
                ComprehensiveAtrLinkManager.revenueFareInfoLinkHandler(link);
            });
        });
    }
}

ComprehensiveAtrResultsManager = Class.create();
ComprehensiveAtrResultsManager.prototype = {
	initialize : function(){
        this.sorting = false;
        $$('table#combinedSearchMatrix thead tr#tableHeader th.tableHeaderLink').each(function(el){
			var link = el.getElementsBySelector('a')[0];
			var index = link.id.split('_')[1];
			Event.observe(link, 'click', this.sortHandler.bindAsEventListener(this, el, index));
		}.bind(this));
        this.firstShow = true;
        Event.observe($$('#viewPerkChoiceLink a')[0], 'click', this.perkChoiceLinkHandler.bindAsEventListener(this, 'show'));
        Event.observe($('hidePerkChoiceLink'), 'click', this.perkChoiceLinkHandler.bindAsEventListener(this, 'hide'));
        Event.observe($('decreaseFontLink'), 'click', this.fontSizeLinkHandler.bindAsEventListener(this, 'decrease'));
        Event.observe($('increaseFontLink'), 'click', this.fontSizeLinkHandler.bindAsEventListener(this, 'increase'));
        Event.observe($('returnToTopLink'), 'click', this.returnToTopHandler);
        var left = $('combinedAtrSearchResults').positionedOffset().left + $('combinedAtrSearchResults').offsetWidth;
        this.scrollBoundry=$('combinedAtrSearchResults').positionedOffset().top + $('combinedAtrSearchResults').offsetHeight - $('returnToTopLink').offsetHeight - 10;
        $('returnToTopLink').setStyle({left:(left-$('returnToTopLink').offsetWidth-5)+'px'});
        this.scrollHandler();
        Event.observe(window, 'scroll', this.scrollHandler.bind(this));
        if($('combinedSearchMatrix').hasClassName('cash_visible')){
        	$('returnToTopLink').setStyle({border:'solid 2px #C3C3C3'});
        }
	},
	sortHandler : function(e, headCell, index){
		if(!this.sorting){
			this.sorting=true;
			Novo.Microcontent.destroy();
			var order = headCell.hasClassName('asc')?-1:1
			$$('table#combinedSearchMatrix thead tr#tableHeader th.tableHeaderLink').each(function(el){
				el.removeClassName('asc');
				el.removeClassName('desc');
			});

			headCell.addClassName('waiting');
			var callback = function(XmlHttpRequest){
				$('atrSearchResults').update(XmlHttpRequest.responseText);
				if($('atrSearchResults').getElementsBySelector('tr').length == 0){
					location.reload(true);
				}
				headCell.removeClassName('waiting');
				if(order == -1){
					headCell.addClassName('desc');
				}else{
					headCell.addClassName('asc');
				}
				this.sorting=false;
			}
			var request = new Ajax.Request($('ajaxUrl').firstChild.data,
				{
					method: 'post',
					onSuccess: callback.bind(this),
					evalJS:'force',
					parameters : {
						'index':index,
						'order':order,
						'selectedIndex': ComprehensiveAtrLinkManager.getCurrentSelectedIndex(),
						'selectedAwardType': ComprehensiveAtrLinkManager.getCurrentSelectedAwardLevel()
					}
				});
		}
	},
	fontSizeLinkHandler : function(e, direction){
		if(direction == 'increase'){
			$('combinedSearchMatrix').removeClassName('smallFont');
			$('combinedSearchMatrix').addClassName('largeFont');
			$('decreaseFontLink').style.background='url(/images/shared/minus_high.png)';
			$('decreaseFontLink').style.cursor='pointer';
			$('increaseFontLink').style.background='url(/images/shared/plus_low.png)';
			$('increaseFontLink').style.cursor='default';
		}else{
			$('combinedSearchMatrix').removeClassName('largeFont');
			$('combinedSearchMatrix').addClassName('smallFont');
			$('decreaseFontLink').style.background='url(/images/shared/minus_low.png)';
			$('decreaseFontLink').style.cursor='default';
			$('increaseFontLink').style.background='url(/images/shared/plus_high.png)';
			$('increaseFontLink').style.cursor='pointer';
		}
	},
	perkChoiceLinkHandler : function(e, fn){
		if(fn == 'show'){
			$$('#viewPerkChoiceLink a')[0].hide();
			$$('#viewPerkChoiceLink a')[1].hide();
			$('combinedSearchMatrix').removeClassName('cash_hidden');
			$('combinedSearchMatrix').addClassName('cash_visible');
    		$('returnToTopLink').setStyle({border:'solid 2px #C3C3C3'});
			if(this.firstShow){
				var tableBody = $('cabinHeader').innerHTML;
				$('cabinHeader').update(tableBody);
				this.firstShow = false;
			}
		}else{
			$('combinedSearchMatrix').removeClassName('cash_visible');
			$('combinedSearchMatrix').addClassName('cash_hidden');
			$$('#viewPerkChoiceLink a')[0].show();
			$$('#viewPerkChoiceLink a')[1].show();
			$('returnToTopLink').setStyle({border:'none'});
			Novo.Microcontent.destroy();
		}
	},
	returnToTopHandler : function(e){
		window.scrollTo(0, 0);
	},
	scrollHandler : function(e){
		var scrollOffset = document.viewport.getScrollOffsets().top;
		var viewportHeight = document.viewport.getHeight();
		if(window.XMLHttpRequest){//if this is not IE6
			if(scrollOffset > this.scrollBoundry - viewportHeight){
				$('returnToTopLink').style.bottom=null;
				$('returnToTopLink').style.position='absolute';
				$('returnToTopLink').style.top=(newTop<this.scrollBoundry?newTop:this.scrollBoundry) + "px";
			}else{
				$('returnToTopLink').style.top=null;
				$('returnToTopLink').style.position='fixed';
				$('returnToTopLink').style.bottom=0;
			}
		}else{
			var newTop = viewportHeight - $('returnToTopLink').offsetHeight - 10 + scrollOffset;
			$('returnToTopLink').style.top=(newTop<this.scrollBoundry?newTop:this.scrollBoundry) + "px";
		}
	}
}

/**
 * This class handles instrumenting the search results page to offer a filtering
 * by airline mechanism.
 */
SearchResultsFilterManager = Class.create();
SearchResultsFilterManager.prototype = {
	initialize : function(){
		this.carriers = {};
		this.moduleCarriers = {};
		$$(".module").each(function(module) {
			this.parseModule(module);
		}.bind(this));
		this.buildSelectElement();
	},
	parseModule : function(module) {
		carrierListElements = module.select(".carrierList");
		if(carrierListElements.size() == 0) {
			// Nothing to parse, return
			return;
		}

		// Only consider the first for now
		carrierList = carrierListElements.first();
		carrierList.normalize();
		rawList = carrierList.innerText || carrierList.textContent;
		rawList = rawList.strip();
		if(rawList.blank()) {
			return;
		}

		// Create storage for this module's information
		if(this.moduleCarriers[$(module).identify()] == null) {
			this.moduleCarriers[$(module).identify()] = new Array();
		}

		carrierItems = rawList.split("|");
		carrierItems.each(function(rawItem) {
			parts = rawItem.split("=");
			// Save the carrier to name mapping
			this.carriers[parts[0]] = parts[1];

			// Add this carrier to the list of carries that this modules has
			this.moduleCarriers[$(module).identify()].push(parts[0]);
		}.bind(this));

		// Remove duplicates
		this.moduleCarriers[$(module).identify()] = this.moduleCarriers[$(module).identify()].uniq();
	},
	buildSelectElement : function() {
		if($("sortByCarrierSelect") == null){
			return;
		}

		Object.keys(this.carriers).each(function(key){
			var item = this.carriers[key];
			var option = new Element('option');
			option.text = item;
			option.value = key;
			$("sortByCarrierSelect").options.add(option);
		}.bind(this));

		$("sortByCarrierSelect").observe("change", this.filterCarriers.bindAsEventListener(this));
	},
	showSelectElementWithOptions : function() {
		if(Object.keys(this.carriers).size() > 1) {
			$("sortByCarrierContainer").removeClassName("doNotShow");
		}
	},
	filterCarriers : function() {
		selectedCarrier = $F("sortByCarrierSelect");
		if(selectedCarrier == null) {
			return;
		}

		Object.keys(this.moduleCarriers).each(function(moduleId) {
			var mCarriers = this.moduleCarriers[moduleId];
			// If the module has that carrier, show it
			if((selectedCarrier == "0") || (mCarriers.indexOf(selectedCarrier) != -1)) {
				$(moduleId).show();
			}
			else {
				$(moduleId).hide();
			}
		}.bind(this));
	}
}

/**
 * This function binds the click event of the MLT vacation link on the search results page
 * to the submit action of the hiddent MLT Vacation form
 */
function bindMLTLink() {
	var link = $("mltVacationLinkDiv");
	if(link){
		link.removeClassName("doNotShow");
		Event.observe(link, "click", function() {
			$("WVForm").submit();
		});
	}

}
/**
 * This function updates the costsummary part of billing page
 * on change of selection from the dropdown
 */

function updateCostSummary(hasTotalVoucherAmount) {
    if (hasTotalVoucherAmount == 'true') {
        $('resetDiscount').setValue('true');
        var selectedOption = $F('selectDiscountTypeBilling');
        discountInput = document.createElement("input");
        discountInput.setAttribute("type", "hidden");
        discountInput.setAttribute("name", "_eventId_update_discount");
        discountInput.setAttribute("value", "true");
        $("purchaseForm").appendChild(discountInput);
        $("purchaseForm").submit();
    }
}
