// CALENDAR CONSTANT
// These MUST be set in order for the calendar to populate the form fields.
// These must be available to the calendar scripts.(global);
var CAL_FORM="flight-finder-form";
//var LEAVING_YEAR="leaving-year";
//var LEAVING_MONTH="leaving-month";
//var LEAVING_DAY="leaving-day";
//var LEAVING_DATE="leaving-date";
//var LEAVING_TIME="leaving-time";
//var RETURNING_YEAR="returning-year";
//var RETURNING_MONTH="returning-month";
//var RETURNING_DAY="returning-day";
//var RETURNING_DATE="returning-date";
//var RETURNING_TIME="returning-time";
var ROUND_TRIP_TRAVEL="rbTripType1";
var ONE_WAY_TRAVEL="rbTripType2";

// The UMNR Window (Unaccompanied Minors)
// This is global so that we can ensure that it is shown. 
var UMNR_WINDOW;
/** Global window name for Lynx notice window */
var LYNX_WINDOW;


/**
 * CHECK UMNR
 * Check that the widget is configured to send a kid off unaccompanied. 
 * If so, display the UMNR checkbox and the popup note. If the popup is 
 * already displayed, bring it to the front.
 * Otherwise, hide the checkbox and popup.
 * @return void
 * @called internally from method employing DHTML
 */
function checkForUMNR(fromHomepage) {
    var umnrDiv = document.getElementById('umnr-div');
    if(isMinorUnaccompanied()) {
        showUMNRPopup(true);
        /** Changed By: Billy Bacon to fix ugly wrapping of agreement text (11-May-2007) */
        //document.getElementById("umnr-div").className="flight-finder-float";
        if(umnrDiv) umnrDiv.className="flight-finder-agreement";
    } else {
        showUMNRPopup(false);
        if(umnrDiv) umnrDiv.className="hide";
    }
}


/**
 * Reason: Since this functionality was used in several places, it made sense
 * to make it its own utility method in an effort to promote re-use.
 *
 * @author Billy Bacon
 * @since 24-Apr-2007
 */

function updateReturningInformation(objDomId) {
    
    var onewaytravel = document.getElementById(ONE_WAY_TRAVEL).checked;
    var obj = document.getElementById(objDomId);

    if(onewaytravel) {
        // User is booking a one way trip
        var href = obj.getAttribute("href");
        var onclick = obj.getAttribute("onclick");

        if(href && href != "" && href != null) obj.setAttribute('href_bak', href);
        
        if(onclick != null){
            obj.setAttribute('onclick_bak', onclick);
            obj.setAttribute('onclick', "void(0);");
        }

        obj.removeAttribute('href');
        obj.style.color="gray";

        // Disable the returning time drop-down menu so user cannot select.
	// Commented by GAVS for Fare Families project
        // updateSelectMenu('returning-time', onewaytravel);

    } else {
        // User is booking a round trip.
        if(obj.attributes['onclick_bak']!=null)
            obj.setAttribute('onclick', obj.attributes['onclick_bak'].nodeValue);
        
        if(obj.attributes['href_bak']!=null)
            obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
        
        obj.style.color="blue";

        // Enable the returning time drop-down menu so user can select a return time.
	// Commented by GAVS for Fare Families project
        // updateSelectMenu('returning-time', onewaytravel);

    }
}

/**
 * Utility method which will enable/disable an HTML form drop-down menu.
 *
 * @author Billy Bacon
 * @since 23-Apr-2007
 */
function updateSelectMenu(objDomId, disable){
    document.getElementById(objDomId).disabled = disable;
}

/**
 * Clears any existing values for the leaving date form fields and then
 * initializes them to the current date (TODAY).
 *
 * @author Billy Bacon
 * @since 23-Apr-2007
 */
function initLeavingDate() {
    // Reset month/year to current date
    document.getElementById(LEAVING_DAY).value = '';
    document.getElementById(LEAVING_DATE).value = '';
    setMonthYear(LEAVING_MONTH, LEAVING_DAY, LEAVING_YEAR, LEAVING_DATE);
}

/**
 * Clears any existing values for the returning date form fields and then
 * initializes them to the current date (TODAY).
 *
 * @author Billy Bacon
 * @since 23-Apr-2007
 */
function initReturningDate() {
    // Reset month/year to current date
    document.getElementById(RETURNING_DAY).value = '';
    document.getElementById(RETURNING_DATE).value = '';
    setMonthYear(RETURNING_MONTH, RETURNING_DAY, RETURNING_YEAR, RETURNING_DATE);
}

/**
 * Clears all form fields related to the returning date.
 *
 * @author Billy Bacon
 * @since 23-Apr-2007
 */
function clearReturningDate() {
    document.getElementById(RETURNING_MONTH).value = '';
    document.getElementById(RETURNING_DAY).value = '';
    document.getElementById(RETURNING_YEAR).value = '';
    document.getElementById(RETURNING_DATE).value = '';
}

/**
 * Determines if the homepage is being loaded/requested for the very 1st
 * time. This helps in preserving values the user has entered if they've performed
 * a search already and have came back to the page as a result of clicking the browser
 * back button.
 *
 * @author Billy Bacon
 * @since 23-Apr-2007
 */
function isFirstPageLoad() {
    var l = document.getElementById(LEAVING_MONTH).value;
    var r = document.getElementById(RETURNING_MONTH).value;
    
    if(isNaN(l) && isNaN(r)) return true;
    //if l and r are empty strings, isNaN() incorrectly returns false.
    if(l=='' && r=='') return true;
    return false;
}

/** 
 * Function should be called AFTER the Ajax verification of the City names
 */ 
function validateFlightFinder() {
    // Must be a to and from location
    // Must be someone flying
    var fieldsToCheck = {
        formName:["flight-finder-form"],
        required:["flying-from", "returning-from"],
        requiredSelectPair:[["adult","child"]]
    }

    // Check for one way travel
    // Must be an outbound flight
 //   if(document.getElementById("rbTripType2").checked){
   //     fieldsToCheck["notPast"] = [[LEAVING_MONTH,LEAVING_DAY,LEAVING_YEAR]];
   // } else {
        // Ensure the pair of dates is in proper order
     //   fieldsToCheck["datePair"]=[[LEAVING_MONTH,LEAVING_DAY,LEAVING_YEAR],[RETURNING_MONTH,RETURNING_DAY,RETURNING_YEAR]]
   // } 

    // Ensure the leaving airport and landing are not the same
    if((document.getElementById("flying-from").value != "") && (document.getElementById("returning-from").value != "")) {
        fieldsToCheck["mutuallyExclusive"]=[["flying-from", "returning-from"]];
    }

    // Check that the meeting id is 6 chars if it exists
    var meetingId = document.getElementById("meeting-id");
    if(meetingId && meetingId.value.length > 0 ) {
        if(!fieldsToCheck["certainSize"]) {
            fieldsToCheck["certainSize"]= new Array();
        }
        fieldsToCheck["certainSize"]=[["meeting-id",6]];
    }

    /************************************************************************* 
     * COUPONS ARE NOT IMPLEMENTED YET!
     * Check that the coupon number is 7 chars if it exists
     * The promo code is required if the coupon is specified

    var adultEl = document.getElementById("adult");
    totalPeople = parseInt(adultEl.options[adultEl.selectedIndex].value);
    var promoCheck = false;
    for(var i=1; i<totalPeople+1; i++) {
        var coupon = document.getElementById("coupon-number-"+i).value;
        if(coupon.length > 0 ) promoCheck = true;
        if(coupon && coupon.length > 0 ){
            if(!fieldsToCheck["certainSize"]) {
                fieldsToCheck["certainSize"]= new Array();
            }    
            fieldsToCheck["certainSize"].push(["coupon-number-"+i,7]);
        }
    }

    if(promoCheck){
        var promo = document.getElementById("promo-code").value;			
        fieldsToCheck["required"].push(["promo-code"]);
    }
    **************************************************************************/

    if(validate(fieldsToCheck)) {
        if (document.getElementById("child").value + document.getElementById("infant").value > 0){ 
            if(!_checkChildren()) return false;
        }
        
        // Added for BugHost 486
        // Display the alert message only if flying to city is SJO and one way travel is selected
        //Get the 3 chars of returing from city
    var returningCity = document.getElementById("flyingTo2").value;
    var returningCityIndex = returningCity.indexOf("(")+1;
    var returningCity1 = returningCity.substring(returningCityIndex,returningCityIndex+3);
        if(returningCity1  == "SJO" && document.getElementById(ONE_WAY_TRAVEL).checked) {
            if(!confirm("For all travelers, other than Costa Rican citizens, a ticket for onward or return travel is mandatory. This can be an airline, cruise ship, train ticket, etc. A visa will be required for stays over 90 days."))
                return false;
        }

//All validation and parameters are set, go ahead and submit.
       // document.getElementById("flight-finder-form").submit();
	determineBookingEngine();
    }
    return false;
}

/**
 * Ajax response handler after City validation servlet
 */
function handleFlightResponse(resp){
    if(resp.indexOf("401") != -1){
        // Bad From City
        alert("Flying From city is invalid");
        document.getElementById("flying-from").focus();
    } else if(resp.indexOf("402") != -1) {
        // Bad To City
        alert("Flying To city is invalid");
        document.getElementById("returning-from").focus();
    } else {
        validateFlightFinder();
    }
}


/**
 * PROMO CODE
 * If the coupon box has any input, show the promo code box.
 * Otherwise hide the Promo Code box.
 * @param the coupon element
 * @called onBlur of the coupon element (when the element loses focus)
 */
function showHidePromo(coupon){
    if(coupon.value && coupon.value != "") {
        document.getElementById("promo-code-div").className="promo-float";
    } else {
        document.getElementById("promo-code-div").className="hide";
    }
}

/**
 * Initializes the Flight Finder calendars with appropriate dates, and sets
 * focus on the leaving from (city) textfield.
 *
 * @author Billy Bacon
 * @since 02-May-2007
 */
function initFlightFinder() {
  
    // Load the calendars
  //  preLoadCalendar();
	
    // Check for existing values. If page is being loaded for the first time, we need
    // to initialize the date fields otherwise preserve any existing values the user
    // entered in case they click their browser back button. - BB: 02-MAY-2007
    //if(isFirstPageLoad()) {
      //  initLeavingDate();
        //initReturningDate();
//    }

    // Set focus to Flying From textfield on page load.
//    if(document.getElementById('flying-from')) document.getElementById('flying-from').focus();
}

/**
 * Check that the vacation form fields are in order
 */
function doVacationValidate() {
    var fieldsToCheck = {
        formName:["vacation-finder-form"],
        required:["vacation-flying-from","vacation-returning-from"],
        datePair:[["vacation-leaving-month","vacation-leaving-day","vacation-leaving-year"],["vacation-returning-month","vacation-returning-day","vacation-returning-year"]],
        requiredSelectPair:[["vacation-adult","vacation-child"]],
        mutuallyExclusive:[["vacation-flying-from","vacation-returning-from"]]
    }

    if(validate(fieldsToCheck)){
        return setVacationParams();
    }

    return false;
}

/**
 * Update/set vacation parameters.
 */
function setVacationParams()  { 
    var url = "";

    var from = document.getElementById("vacation-flying-from").value;
    var to = document.getElementById("vacation-returning-from").value;

    var fromDay = document.getElementById("vacation-leaving-day").value;
    var fromMonth = document.getElementById("vacation-leaving-month").value;
    var fromYear = document.getElementById("vacation-leaving-year").value;

    fromMonth =_getNumericMonth(fromMonth);
    var fromDate = fromMonth + "/";

    if(fromDay < 10) fromDate += "0";
    fromDate += fromDay + "/" + fromYear;

    var toDay = document.getElementById("vacation-returning-day").value;
    var toMonth = document.getElementById("vacation-returning-month").value;
    var toYear = document.getElementById("vacation-returning-year").value;

    toMonth =_getNumericMonth(toMonth);
    var toDate = toMonth + "/";

    if(toDay < 10) toDate += "0";
    toDate += toDay + "/" + toYear;






    var comboType = "AHC";
    
    if(document.getElementById("flight-hotel").checked ) {
        comboType="AH";
    } else if(document.getElementById("flight-car").checked ) {
        comboType="AC";
    }

    var adults = document.getElementById("vacation-adult").value;
    var children = document.getElementById("vacation-child").value;

    url += "&fromLocation=" + from;
    url += "&toLocation=" + to;
    url += "&fromDate=" + fromDate;
    url += "&toDate=" + toDate;
    url += "&combinationType=" + comboType;
    url += "&adultsNum=" + adults;
    var numKids = parseInt(children);

    for(var i = 0; i < numKids;i++)
        url += "&minorAge" + (i+1) +  "=7";

    url += "&doSearch=T";
    url += "&airCompany=F9";
    url += "&backUrl=http%3A%2F%2Fwww%2Efrontierairlines%2Ecom%2Fhome%2Edo";

    document.getElementById("vacationURLParams").value = url;
    return true;
}


/**
 * Function which determines if a minor is flying without an adult.
 * @return true if the number of adults flying is 0 and the number of children flying is greater than 0, false otherwise.
 *
 * @author Billy Bacon 
 * @since 24-Aug-2007
 */
function isMinorUnaccompanied() {
    if(document.getElementById("adult") && document.getElementById("child")) {
        return ((document.getElementById("adult").value<1) && (document.getElementById("child").value > 0));
    } else {
        return false;
    }
}
function showRedeemMiles()
{
var tempRedeem=document.getElementById('redeem_miles').checked;
if(tempRedeem){
        var flyingFrom = document.getElementById("flyingFrom1").value;
        var flyingTo = document.getElementById("flyingTo2").value;
        if(flyingFrom != "" && flyingTo != "") {
            var flyingFromCode = flyingFrom.substring(flyingFrom.indexOf("(")+1,flyingFrom.indexOf(")"));
            var flyingToCode = flyingTo.substring(flyingTo.indexOf("(")+1,flyingTo.indexOf(")"));
            document.getElementById("redeemFlyingFrom").value = flyingFromCode;
            document.getElementById("redeemReturningFrom").value = flyingToCode;
	    
	    var departureDate = $("#leaving").datepicker("getDate");
            if(departureDate != "") {
                var departureDate1 = departureDate.getMonth()+1 + "/" + departureDate.getDate() + "/" + departureDate.getFullYear();
                document.getElementById("redeemLeavingDate").value = departureDate1;
                document.getElementById("redeemLeavingDay").value = departureDate.getDate();
                document.getElementById("redeemLeavingMonth").value = departureDate.getMonth()+1;
                document.getElementById("redeemLeavingYear").value = departureDate.getFullYear();

            	var returnDate = $("#returning").datepicker("getDate");
                if(returnDate != "") {
                    var returnDate1 = returnDate.getMonth()+1 + "/" + returnDate.getDate() + "/" + returnDate.getFullYear();
                    document.getElementById("redeemReturnDate").value = returnDate1;
                    document.getElementById("redeemReturnDay").value = returnDate.getDate();
                    document.getElementById("redeemReturnMonth").value = returnDate.getMonth()+1;
                    document.getElementById("redeemReturnYear").value = returnDate.getFullYear();
                    document.getElementById("redeemDirection").value = "returntravel";
                } else {
                    document.getElementById("redeemReturnDate").value = "";
                    document.getElementById("redeemReturnDay").value = "";
                    document.getElementById("redeemReturnMonth").value = "";
                    document.getElementById("redeemReturnYear").value = "";
                    document.getElementById("redeemDirection").value = "onewaytravel";
                }
            }
            document.getElementById("redeemAdults").value = document.getElementById("adult").value * 1;
            document.getElementById("redeemChildren").value = document.getElementById("child").value * 1;
            document.getElementById("redeemInfants").value = document.getElementById("infant").value * 1;
            document.getElementById("redeemMeetingId").value = document.getElementById("meeting-id").value;
        }
        document.getElementById("redeemForm").submit();
  }
}




  











