/*********************************************************************
  Code to support new landing page (used by meta search
 ********************************************************************/

// MetaAir servlet expects dates in yyyymmdd format
Date.prototype.toMetaURL = function() {
    return (this.getFullYear()*10000 + (this.getMonth()+1)*100 + this.getDate()).toString();
};

// NE acts like a namespace
var NE = {

    // flag for full refresh on destination change
    refreshOnNewDest: true,
    
    // code for debugging, normal operation is to silently ignore errors
    debug: function(message) {
        alert(message);
    },
    handleError: function(e) {
        NE.dumpProperties(e, NE.handleError.caller);
    },
    dumpProperties: function(myEvent, caller) {
        if(typeof(myEvent) == 'undefined' || myEvent == null) {
            NE.debug('null');
            return;
        }
        var alerttext = "";
        if(caller) {
            alerttext += caller + "\n";
        }
        for(p in myEvent) {
            if(p.toUpperCase() != p && (typeof(myEvent[p]) == 'string' || typeof(myEvent[p]) == 'number' || typeof(myEvent[p]) == 'boolean')) {
                alerttext += p + " = " + myEvent[p] + "\n";
            }
        }
        NE.debug(alerttext);
    },

    showError: function(id, message) {
        if ($(id)) {
            $(id).setContent(message).show();
        }
    },
    clearErrors: function() {
        $('neFlights').getElements('.error').setContent('').hide();
    },

    invalidAirport: function() {
        NE.providers = [];
        $('PROVIDERS').setHTML('<div></div>');
    },

    dynamicUpdate: function() {
        if ($('PROVIDERS')) {
            // Perform AJAX request
            var uri = "/FlightsController?" + NE.buildQueryString('geo Orig Dest roundtrip');
            new Ajax(uri, {
                update: $('PROVIDERS'),
                evalScripts: true,
                onFailure: function(xhr) {
                    if(xhr.status == 404) {
                        NE.invalidAirport();
                    }
                }
            }).request();
        }
    },

    updateFromAirport: function() {
        // Defer to allow type-ahead to complete
        NE.updateFromAirportDefer.delay(250);
    },
    updateFromAirportDefer: function() {
        var elmt = $('airportFromCode');
        // If there is a new value then update
        if (elmt.value != elmt.previousValue) {
            elmt.value = elmt.value.toUpperCase();
            elmt.previousValue = elmt.value;
	    NE.dynamicUpdate();
            NE.updateAirWatchWidgetSource();
        }
    },

    updateToAirport: function() {
        // Defer to allow type-ahead to complete
        NE.updateToAirportDefer.delay(250);
    },
    updateToAirportDefer: function() {
        var elmt = $('airportToCode');
        // If there is a new value then update
        if (elmt.value != elmt.previousValue) {
            if (!NE.refreshOnNewDest || $('MPU') || $('semFlights')) {
                elmt.value = elmt.value.toUpperCase();
                elmt.previousValue = elmt.value;
                NE.dynamicUpdate();
                NE.updateAirWatchWidgetSource();
            } else {
                NE.redoPage();
            }
        }
    },
    redoPage: function() {
        // create url and refresh
        var url = '/Flights?lander=false&';
        if (NE.getTripType() == 'oneWay') {
            url += NE.buildQueryString('geo Orig Dest roundtrip adults nonstop nearby leaveday leavemonth');
        } else if (NE.getTripType() == 'roundTrip') {
            url += NE.buildQueryString('geo Orig Dest roundtrip adults nonstop nearby leaveday leavemonth retday retmonth');
        } else {
            url += 'multi=yes&' + NE.buildQueryString('geo Orig Dest roundtrip adults nonstop nearby');
        }
        window.location.assign(url);
        return false;
    },

    getGeoCode: function() {
        var geos = /g(\d+)/.exec(window.location);
        if (geos) {
            return geos[1];
        } else {
            var code = $('neFlightGeo').value;
            return code || 1;
        }
    },
    
    // build query string from form fields. If limitParams is specified, only those
    // parameter names will be included in the query.
    // This function does _not_ do any validation
    // @param limitParams array of strings, or space/comma delimited string
    buildQueryString: function(limitParams) {
        if(typeof(limitParams) == 'string') {
            limitParams = limitParams.split(/[,\s]+/);
        }
        
        // commerce can't yet handle early or night, translate appropriately
        var adjustTimeOfDay = function(timeStr) {
            if (timeStr == 'early') {
                timeStr = 'morning';
            } else if (timeStr == 'night') {
                timeStr = 'evening';
            }
            return escape(timeStr);
        };
        
        var sInMonthYear = $('leaveMonth').value.split(/\//);
        var sOutMonthYear = $('retMonth').value.split(/\//);
        var paramMap = {
            'geo': NE.getGeoCode(),
            'Orig': $('airportFromCode').value,
            'Dest': $('airportToCode').value,
            'inMonth': escape(sInMonthYear[0] + " " + sInMonthYear[1]),
            'inDay': escape($('leaveDay').value),
            'outMonth':  escape(sOutMonthYear[0] + " " + sOutMonthYear[1]),
            'outDay':  escape($('retDay').value),
            'adults':  escape($('adults').value),
            'leavetime':  adjustTimeOfDay($('leaveTime').value),
            'rettime':  adjustTimeOfDay($('retTime').value),
            //server treats anything other than empty string as true
            'nonstop':  escape($('nonstopOnly').checked ? 'yes' : ''),
            //server treats anything other than empty string as true
            'nearby':  escape($('fromNearby').checked || $('toNearby').checked ? 'yes' : ''),
            'roundtrip': (NE.getTripType() == 'roundTrip' ? 'yes' : 'no'),
            leaveday: escape($('leaveDay').value),
            leavemonth: escape($('leaveMonth').value),
            retday: escape($('retDay').value),
            retmonth: escape($('retMonth').value)
        };
        if($('lander')) {
            paramMap.lander = $('lander').value;
        }


        var queryString = [];
        for(k in paramMap) {
            if(typeof(limitParams) == 'undefined' || limitParams.indexOf(k) > -1) {
                queryString.push(k + '=' + paramMap[k]);
            }
        }
        return queryString.join('&');
    },

    slots: undefined,
    slotsByName: {},

    getSlotByName: function(lName) {
        return NE.slotsByName[lName];
    },

    Slot: function(lx, ly, lw, lh) {
        this.x = lx;
        this.y = ly;
        this.w = lw;
        this.h = lh;
        this.name = null;
        this.occupied = null;

        this.hasOpenWindow = function() {
            try {
                return this.occupied != null && !this.occupied.closed;
            } catch(e) {
                // may be a mozilla permissions problem
                this.occupied = null;
                return false;
            }
        };
    },

    makeSlots: function() {
        var nW = 525;
        var nH = 460;
        var nXI = 24;
        var nYI = 24;
        //move all the pop windows away from the dhtml popup
        var nX = 205;
        var nY = 5;

        if (screen.width > 1024) {
            nW = 800;
            nH = 600;
            nXI = 80;
            nYI = 40;
        } else if (screen.width > 800) {
            nW = 620;
            nH = 500;
            nXI = 60;
            nYI = 30;
        }
        NE.slots = [];
        for (var i=0; i<20; i++) {
            NE.slots[i] = new NE.Slot(nX,nY,nW,nH);
            nX = nX + nXI;
            nY = nY + nYI;
        }
    },

    getOpenSlot: function(n) {
        if (n<=0) {
            n=1;
        }
        for (var i=n-1; i>=0; i-=1) {
            if (!NE.slots[i].hasOpenWindow()) {
                return NE.slots[i];
            }
        }
        for (i=n; i<NE.slots.length; i++) {
            if (!NE.slots[i].hasOpenWindow()) {
                return NE.slots[i];
            }
        }
        return null;
    },

    focusSlots: function() {
        for (var i=0; i<NE.slots.length; i++) {
            if (NE.slots[i].hasOpenWindow()) {
                try {
                    NE.slots[i].occupied.focus();
                } catch(e) {
                    NE.handleError(e);
                }
            }
        }
    },

    providers: [],
    addProvider: function(provider) {
        NE.providers.push(provider);
    },

    Provider: function(lName, lCheckbox, lUrl) {
        this.name = lName;
        this.checkbox = lCheckbox;
        this.url = lUrl;
        this.lastDates = "";
        this.bOpened = false;

        this.hasOpenWindow = function() {
            var s = NE.getSlotByName(this.name);
            return s != null && s.hasOpenWindow();
        };
    },

    buildDate: function(month, day) {
        var monthYear = $(month).value.split(/\//);
        return new Date( monthYear[1], monthYear[0]-1 , $(day).value );
    },
    
    doFareCalendarSearch: function(e) {
   	if($('airportFromCode').value.length==0 || $('airportToCode').value.length==0)
	{
		return false;
	}

        // redirecting, build appropriate url
        var url = "/FareCalendar";

        url += "-a_airport0." + $('airportFromCode').value +
               "-a_airport1." + $('airportToCode').value +"&m=11952";

        if (window.opener && !window.opener.closed)
        {
            window.opener.focus();
            window.opener.location.assign(url);
            window.close();
        } else {
            window.focus();
            window.location.assign(url);
        }

        return false;
    },

    doLightSearch: function(e) {
        // make sure input is valid
        if ($("neFlights") && !NE.validateInput()) {
            return false;
        }

        // redirecting, build appropriate url
        var url = "/CheapFlights";
        
        url += "?airport0=" + $('airportFromCode').value +
               "&airport1=" + $('airportToCode').value;
        if ($('leaveMonth') && $('leaveDay'))
        {
               url += "&date0=" + NE.buildDate('leaveMonth', 'leaveDay').toMetaURL() +
               "&time0=" + $('leaveTime').value;
        }
        if ($('retMonth') && $('retDay'))
        {
            url += "&date1=" + NE.buildDate('retMonth', 'retDay').toMetaURL() +
                   "&time1=" + $('retTime').value;
        }
        url +="&m=11952";
                
        if (window.opener && !window.opener.closed)
        {
            window.opener.focus();
            window.opener.location.assign(url);
            window.close();
        } else {
            window.focus();
            window.location.assign(url);
        }
        
        return false;
    },
   
    doSearch: function(e) {
        
        // stop propagation (ie6 needs this)
        new Event(e).stop();

        // make sure input is valid
        if (!NE.validateInput()) {
            return false;
        }

        // redirecting, build appropriate url
        var geo = NE.getGeoCode();
        var url = "/CheapFlights" +
            "?geo=" + geo +
            "&travelers=" + ($('adults').value) +
            "&cos=" + $('cabin').value +
            "&nonstop=" + ($('nonstopOnly').checked ? 'yes' : 'no');
        
        if (NE.getTripType() == 'multiCity') {
            var activeFlights = $$('#multiCityForm .activeFlight');
            var ind = 0;
            for (var i = 0, ilen = activeFlights.length; i < ilen; i++) {
                // skip over blank rows
                if ($('fromTxt'+i+'Code').value != '') {
                    url += "&airport" + (ind*2) + "=" + $('fromTxt'+i+'Code').value +
                           "&nearby" + (ind*2) + "=" + ($('fromChk'+i).checked ? 'yes' : 'no') +
                           "&airport" + (ind*2+1) + "=" + $('toTxt' + i + 'Code').value +
                           "&nearby" + (ind*2+1) + "=" + ($('toChk'+i).checked ? 'yes' : 'no') +
                           "&date" + ind + "=" + NE.buildDate('dateMonth'+i, 'dateDay'+i).toMetaURL() +
                           "&time" + ind + "=" + $('timeOfDay'+i).value;
                    ind += 1;
                }
            }
        } else {
            url += "&airport0=" + $('airportFromCode').value +
                   "&nearby0=" + ($('fromNearby').checked ? 'yes' : 'no') +
                   "&airport1=" + $('airportToCode').value +
                   "&nearby1=" + ($('toNearby').checked ? 'yes' : 'no') +
                   "&date0=" + NE.buildDate('leaveMonth', 'leaveDay').toMetaURL() +
                   "&time0=" + $('leaveTime').value;
            if (NE.getTripType() == 'roundTrip') {
                url += "&date1=" + NE.buildDate('retMonth', 'retDay').toMetaURL() +
                       "&time1=" + $('retTime').value;
            }
        }
    
        if (NE.canPopupProviders()) {
            // pop up windows currently not supported for multi-city nor for business/first class
            // try to pop up windows. if popup fails, pass along provider information
            var sUserData = NE.buildQueryString('inMonth inDay outMonth outDay adults leavetime rettime nonstop nearby roundtrip');
            var provCnt = 0;
            var canPopUp = true;
            for (var i=0; i< NE.providers.length; i++) {
                if (NE.providers[i].checkbox.checked) {
                    if (canPopUp) {
                        canPopUp = NE.popOne(i, sUserData);
                    }
                    if (!canPopUp) {
                        url += "&provider" + provCnt + "=" + NE.providers[i].name;
                        provCnt += 1;
                    }
                }
            }
        }
        if ($('MPU'))
        {
            url +="&m=11952";
        }
        
        if ($('MPU') && window.opener && !window.opener.closed)
        {
            window.opener.focus();
            window.opener.location.assign(url);
            window.close();
        } else {
            window.focus();
            window.location.assign(url);
        }
        
        return false;
    },

    _lastDate: null,
    getLastDate: function() {
        if (NE._lastDate == null) {
            var endDate = new Date();
            endDate.setHours(0,0,0,0);
            // 330 days in milliseconds: 330*24*60*60*1000 = 28512000000
            endDate.setTime(endDate.getTime() + 28512000000);
            NE._lastDate = endDate;
        }
        return NE._lastDate;
    },
    
    validateInput: function() {

        // assume no errors
        NE.clearErrors();
        var isValid = true;

        // helper functions for dates
        var date, prev;
        // Today; Force to midnight
        var dToday = new Date();
        dToday.setHours(0,0,0,0);
        // declare locally
        var i, ilen;
        
        var checkDate = function(id, cal, month, day) {
            var calendar = $(cal).calendar;
            if (calendar) {
                var msg = validateDate(calendar);
                if (msg) {
                    NE.showError(id, msg);
                    isValid = false;
                    return;
                }
            } else {
                if (!$(cal).value) {
                    NE.showError(id, sInvalidDates);
                    isValid = false;
                    return;
                }
            }
            date = NE.buildDate(month, day);
            if (date < dToday) {
                NE.showError(id, js_0002); // "Please choose dates in the future."
                isValid = false;
            } else if (prev && prev > date) {
                NE.showError(id, js_0003); // "Please choose a check-out date that is at least one day later than your check-in date."
                isValid = false;
            } else if (date > NE.getLastDate()) {
                NE.showError(id, js_0004); // "Please choose dates that are less than 330 days away."
                isValid = false;
            }
            prev = date;
        };
        
        // helper function for airports
        var checkAirport = function(errId, txtId) {
            var airport = $(txtId).value;
            if (!airport || airport.length != 3) {
                NE.showError(errId,js_0014); // Please use a valid airport code
                isValid = false;
            }
        };

        if (NE.getTripType() == 'multiCity') {
            var activeFlights = $$('#multiCityForm .activeFlight');
            var cnt = 0;
            for (i = 0, ilen = activeFlights.length; i < ilen; i++) {
                // skip over blank rows
                if (($('fromTxt'+i+'Code').value != '') || ($('toTxt'+i+'Code').value != '')) {
                    checkDate('errDate'+i, 'dateTxt'+i, 'dateMonth'+i, 'dateDay'+i);
                    checkAirport('errFromTxt'+i, 'fromTxt'+i+'Code');
                    checkAirport('errToTxt'+i, 'toTxt'+i+'Code');
                    cnt++;
                }
            }
            if (cnt == 0) {
                // all blank, show errors on first row
                checkDate('errDate0', 'dateTxt0', 'dateMonth0', 'dateDay0');
                checkAirport('errFromTxt0', 'fromTxt0Code');
                checkAirport('errToTxt0', 'toTxt0Code');
            }
        } else {
            checkAirport('errAirportFrom', 'airportFromCode');
            checkAirport('errAirportTo', 'airportToCode');
            checkDate('errCheckIn','checkIn','leaveMonth', 'leaveDay');
            if (NE.getTripType() != 'oneWay') {
                checkDate('errCheckOut', 'checkOut', 'retMonth', 'retDay');
            }
        }

        return isValid;
    },

    popOne: function(nIndex, sUserDataVar) {
        try {
            var bReturn = false;
            var bHasWindow = (NE.providers[nIndex].hasOpenWindow());
            var sFinalUrl = NE.providers[nIndex].url + '&' + sUserDataVar;
            var slot;
            if (bHasWindow) {
                slot = NE.getSlotByName(providers[nIndex].name);
            } else {
                slot = NE.getOpenSlot(0);
            }

            var sProps = 'toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes,alwaysraised=true';
            var sMyProps = sProps + ',screenX=' + slot.x + ',screenY=' + slot.y + ',left=' + slot.x + ',top=' + slot.y + ',height=' + slot.h + ',width=' + slot.w;
            var wRef = window.open(sFinalUrl, NE.providers[nIndex].name, sMyProps);

            if(wRef != null) {
                slot.occupied = wRef;
                NE.slotsByName[NE.providers[nIndex].name] = slot;
                wRef.focus();
                NE.providers[nIndex].bOpened = true;
                NE.providers[nIndex].lastDates = sUserDataVar;
                bReturn = true;
            }
        } catch(e) {
            NE.handleError(e);
        }
        return bReturn;
    },

    ready: function() {
        NE.makeSlots();
        if ($('PROVIDERS'))
        {
            NE.addProviders();
        }
        if ($('neButtonAd') && $('neButtonAd').offsetHeight < 60) {
            $('neButtonAd').hide();
        }
        if(window.location.hostname.indexOf('tripadvisor.com') == -1) {
            $$('#flexLink').hide();
        }
    },

    updateProviders: function() {
        NE.providers = [];
        if ($('PROVIDERS'))
        {
            NE.addProviders();
        }
        if (!$('MPU'))
        {
            NE.updateLinks();
        }
    },

    updateLinks: function() {
        if(NE.validateInput()) {
            var sUserData = NE.buildQueryString('inMonth inDay outMonth outDay adults leavetime rettime nonstop nearby roundtrip');
            NE.updateBookingBuddyLink(sUserData);
        }
    },
    
    bookingBuddyShortURL: null,
    oneTimeShortURL: null,
    setBookingBuddyShortURL: function(url) {
        NE.bookingBuddyShortURL = url;
    },
    setOneTimeShortURL: function(url) {
        NE.oneTimeShortURL = url;
    },

    updateAirWatchWidgetSource: function() {
        var awFrame = $('airWatchWidgetFrame');
        if (awFrame != null) {
            var url = "/AirWatchSubscriptionWidget?" + NE.buildQueryString('Orig Dest');
            awFrame.src = url;
        }
    },

    updateBookingBuddyLink: function(sUserData) {
        var bbtease = $('BookingBuddyTeaser');
        if (bbtease != null) {
            var links = bbtease.getElements('a');
            for (var i = 0; i < links.length; i++) {
                links[i].href = NE.bookingBuddyShortURL + '&' + sUserData;
                links[i].target = "_blank";
            }
        }
    },
    updateOneTimeLink: function(sUserData) {
        var ottease = $('OneTimeTextLink');
        if (ottease != null) {
            var links = ottease.getElements('a');
            for (var i = 0; i < links.length; i++) {
                links[i].href=NE.oneTimeShortURL + '&' + sUserData;
                links[i].target = "_blank";
            }
        }
    },
    
    replaceBBDiv: function(newElements) {
        NE.hideBBDiv();
        if ($('SearchMoreInner'))
        {
            var newContent = $('SearchMoreInner').innerHTML + newElements;
            $('SearchMoreInner').setHTML(newContent);
        }
    },
    replaceOTDiv: function(newElements) {
        NE.hideOTDiv();
        if ($('TopTextLinksInner'))
        {
          var newContent = $('TopTextLinksInner').innerHTML + newElements;
          $('TopTextLinksInner').setHTML(newContent);
        }
    },

    hideBBDiv: function() {
        var bbElmt = $('BookingBuddyTeaser');
        if(bbElmt) { 
            bbElmt.remove();
        }
    },
    hideOTDiv: function() {
        var otElmt = $('OneTimeTextLink');
        if(otElmt) {
            otElmt.remove();
        }
    },

    // the old form only supports oneway/roundtrip, this maps into new names
    getTripType: function() {
        if ($('tripType')) {
            return $('tripType').value;
        } else if ($('oneWay').checked) {
            return 'oneWay';
        } else {
            return 'roundTrip';
        }
    },

    changeActiveClass: function(activeTab) {
        $$('#neTabDiv .tab').removeClass('active');
        $(activeTab).addClass('active');
    },
    
    clickRoundTrip: function(e) {
        if ($('tripType').value != 'roundTrip') {
            $('tripType').value = 'roundTrip';
            NE.changeActiveClass('roundTripTab');
            $('roundTripForm').show();
            $('roundTripReturnDate').show();
            $$('#multiCityForm').hide();
            $('neTabDiv').addClass('rndTrip');
            NE.updateProviderDiv();
            NE.dynamicUpdate();
            if(window.location.hostname.indexOf('tripadvisor.com') != -1) {
                $$('#flexLink').show();
            }
            else {
                $$('#flexLink').hide();
            }
        }
        return false;
    },
    
    clickOneWay: function(e) {
        if ($('tripType').value != 'oneWay') {
            $('tripType').value = 'oneWay';
            NE.changeActiveClass('oneWayTab');
            $('roundTripForm').show();
            $('roundTripReturnDate').hide();
            $$('#multiCityForm').hide();
            $('neTabDiv').addClass('rndTrip');
            NE.updateProviderDiv();
            NE.dynamicUpdate();
            $$('#flexLink').hide();
        }
        return false;
    },
    
    clickMultiCity: function(e) {
        if ($('tripType').value != 'multiCity') {
            $('tripType').value = 'multiCity';
            NE.changeActiveClass('multiCityTab');
            $('roundTripForm').hide();
            $$('#multiCityForm').show();
            $('neTabDiv').removeClass('rndTrip');
            NE.updateProviderDiv();
            $$('#flexLink').hide();
        }
        return false;
    },
    
    addAnotherFlight: function(e) {
        var extraFlights = $$('#multiCityForm .extraFlight');
        if (extraFlights.length) {
            extraFlights[0].removeClass('extraFlight');
            extraFlights[0].addClass('activeFlight');
            if (extraFlights.length <= 1) {
                $('neAddFlight').hide();
            }
        }
        new Event(e).stop();
        return false;
    },
    
    // pop up windows currently not supported for multi-city nor for business/first class
    canPopupProviders: function() {
        return NE.getTripType() != 'multiCity' && $('cabin').value == "0";
    },
    
    updateProviderDiv: function() {
        if ($('PROVIDERS'))
        {
            if (NE.canPopupProviders()) {
                $('PROVIDERS').show();
            } else {
                $('PROVIDERS').hide();
            }
        }
    },
    
    hideCalendar: function() {
        if (window.calendar && window.calendar.flyout) {
            window.calendar.flyout.hide(false);
        }
    },
    
    onAirportFocus: function(elem) {
        NE.hideCalendar();
        elem.select();
    },
    
    multiSetDefault: function(num) {
        if (($('fromTxt'+num+'Code').value == '') && ($('toTxt'+(num-1)+'Code').value != '')) {
            $('fromTxt'+num).value = $('toTxt'+(num-1)).value;
            $('fromTxt'+num+'Code').value = $('toTxt'+(num-1)+'Code').value;
        }
        NE.onAirportFocus($('fromTxt'+num));
    },
    
    // if the date field is blank, look for an earlier one that is filled in and default
    // to one week later
    maybeDefaultDate: function(num) {
      var elmt = $('dateTxt'+num);
      if (!elmt.overlay) new ta.overlays.CalendarOverlay(elmt.getParent('.cal'), {autoShowCal: true});
      if(!elmt.value) {
          for (var prev = num-1; prev >= 0; prev--) {
              if ($('dateTxt'+prev).value) {
                  var date = NE.buildDate('dateMonth'+prev, 'dateDay'+prev);
                  for(var i = 0; i < 7; i++) {
                      date.setMilliseconds(86400000);
                  }
                  $('dateDay'+num).value = date.getDate() + '';
                  $('dateMonth'+num).value = (date.getMonth()+1) + '/' + date.getFullYear();
                  return;
              }
          }
      }
    },
    
    farewatchKeyPress: function(e, pid) {
        if ((new Event(e)).key == 'enter') {
            NE.farewatchShowForm(pid);
            return false;
        } else {
            return true;
        }
    },
    
    farewatchShowForm: function(pid) {
        showDHTMLPopup('AirWatchAlertDhtmlPopup', 
                       '/AirWatchAlertDhtmlPopup?pid=' + escape(pid) +
                       '&email=' + escape(($('airwatchEmailAddress')).value) + 
                       '&from=' + escape(($('airportFromCode')).value) +
                       '&to=' + escape(($('airportToCode')).value), true);
    },
    
    farewatchShowFormGated: function(pid) {
        showDHTMLPopup('AirWatchAlertDhtmlPopup', 
                       '/AirWatchAlertDhtmlPopup?pid=' + escape(pid) +
                       '&Version=1' +                       
                       '&email=' + escape(($('airwatchEmailAddress')).value) + 
                       '&from=' + escape(($('airportFromCode')).value) +
                       '&to=' + escape(($('airportToCode')).value), true);
    },

    farewatchKeyPressEmail: function(e, pid, email, origin, destination) {
        if ((new Event(e)).key == 'enter') {
            showDHTMLPopup('AirWatchAlertDhtmlPopup', 
                       '/AirWatchAlertDhtmlPopup?pid=' + escape(pid) +
                       '&email=' + escape(email) + 
                       '&from=' + escape(origin) +
                       '&to=' + escape(destination), true);
            return false;
        } else {
            return true;
        }
    },
    
    farewatchShowFormEmail: function(pid, email) {
        showDHTMLPopup('AirWatchAlertDhtmlPopup', 
                       '/AirWatchAlertDhtmlPopup?pid=' + escape(pid) +
                       '&email=' + escape(email) + 
                       '&from=' + escape(($('airportFromCode')).value) +
                       '&to=' + escape(($('airportToCode')).value), true);
    },

    farewatchShowFormEmailGeneric: function(pid, email, origin, destination) {
        showDHTMLPopup('AirWatchAlertDhtmlPopup', 
                       '/AirWatchAlertDhtmlPopup?pid=' + escape(pid) +
                       '&email=' + email + 
                       '&from=' + origin +
                       '&to=' + destination, true);
    },
           
    goToFareCalendar: function() {
        var url = "/FareCalendar" +
                "?airport0=" + $('airportFromCode').value +
            "&airport1=" + $('airportToCode').value +
            "&date0=" + NE.buildDate('leaveMonth', 'leaveDay').toMetaURL();
        window.location.assign(url);
        return false;
    }
};

rules['#neFlights'] = function(elmt) {
    if (!$('FLIGHTS_C'))
    {
    	$$('#CHECK_FARES_BTN').addEvent('click', NE.doSearch);
    	$$('#adults').addEvent('change', NE.updateLinks);
    	$$('#leaveTime').addEvent('change', NE.updateLinks);
    	$$('#retTime').addEvent('change', NE.updateLinks);
    	$$('#fromNearby').addEvent('change', NE.updateLinks);
    	$$('#toNearby').addEvent('change', NE.updateLinks);
    	$$('#nonstopOnly').addEvent('change', NE.updateLinks);
    	$$('#checkIn').onSelectDefer = NE.updateLinks;
    	$$('#checkOut').onSelectDefer = NE.updateLinks;
    	$$('#cabin').addEvent('change', NE.updateProviderDiv);
    
    	$$('#roundTripTab').addEvent('click', NE.clickRoundTrip);
    	$$('#oneWayTab').addEvent('click', NE.clickOneWay);
    	$$('#multiCityTab').addEvent('click', NE.clickMultiCity);
    	if ($$('#multiCityForm .extraFlight').length) {
        	$$('#neAddFlight').addEvent('click', NE.addAnotherFlight);
    	} else {
    		$$('#neAddFlight').hide();
    	}
    }
    // keep track of original values to detect changes
    var afc = $('airportFromCode');
    if (afc) {
    	afc.previousValue = afc.value;
        $('airportFrom').addEvents({
            'airportupdate': NE.updateFromAirport
        });
    }
    var atc = $('airportToCode');
    if (atc) {
    	atc.previousValue = atc.value;
        $('airportTo').addEvents({
            'airportupdate': NE.updateToAirport
        });
    }
};

window.addEvent(TAReadyEvent, NE.ready);

rules['input.flightTypeAhead[type=text]'] = function(elmt) {
    var action = elmt.className.match(/\bact(\w+)\b/);
    if (action) {
        new Autocompleter.Ajax.Flights(elmt, "/TypeAheadJson?action="+action[1], {
            ajaxOptions: {method:'get'},
            postVar: 'query',
            className: 'autocompleter-choices flights',
            inheritWidth: false,
            selectOnBlur: true,
            onSelect: function(elmt, resObj) {
                elmt.value = resObj.name;
                $(elmt.id + 'Code').value = resObj.value;
            }
        });
    }
};

//this is a bit of a hack to get the correct end date into the calendars
rules['#neFlights span.cal'] = function(elmt) {
    elmt.lastDate = NE.getLastDate();
};


function clickOneWayPopunder()
{
    if (window.opener==null || window.opener.closed)
    {
        window.location="/Flights?roundtrip=no&"+NE.buildQueryString();
    } else {
        window.opener.location="/Flights?roundtrip=no&"+NE.buildQueryString();
        window.close();   
    }
}

function clickMultiCityPopunder()
{
    if (window.opener==null || window.opener.closed)
    {
        window.location="/Flights?multi=yes&"+NE.buildQueryString();
    } else {
        window.opener.location="/Flights?multi=yes&"+NE.buildQueryString();
        window.close();   
    }
}

function clickFlightsButton(id)
{
    var loc = "/Flights";
    if (id>0)
    {
        loc = "/Flights-g"+id;
    }
    if (window.opener==null || window.opener.closed)
    {
        window.location=loc;
    }
    else
    {
        window.opener.location=loc;
        window.close();   
    }
}
