/* =====================================================================================================================
This javascript contains all the functions used by the search pages (quick, refine and detailed search)
(Created 2007-02-13 by Johan Solbreck for SEO purpose...)
===================================================================================================================== */

// *****************************************************************************************************************
// Search specific wait message handling
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Do some stuff depending on search type
*/
function searchShowWaitMsgAndSubmit(formObj, type) {
    if ((formObj == FORM_FLT || formObj == LP_FORM_FLT) && type == 'QS')
        formObj[END_DATE_RANGE].value = formObj[START_DATE_RANGE].value;

    TLUtils.populateTripChildAgesFromDD();

    //if (SFAgeInput && !SFAgeInput.validateAges(formObj, (formObj == FORM_HTL || formObj == LP_FORM_HTL || formObj == FORM_CRU_FLT ? 17 : (formObj == FORM_FLT || formObj == LP_FORM_FLT ? CHD_MAX_AGE_FLIGHT : CHD_MAX_AGE_PACKAGE))))
    if (SFAgeInput && !SFAgeInput.validateAges(formObj, (formObj == FORM_FLT || formObj == LP_FORM_FLT ? CHD_MAX_AGE_FLIGHT : (formObj == FORM_HTL || formObj == LP_FORM_HTL || formObj == FORM_CRU_FLT ? 17 : CHD_MAX_AGE_PACKAGE))))
        return;

    transferChildAgesForOldStyleInput(formObj);

    if (formObj != null)
        formObj.submit();
}

/*
 * Transfer old style child ages [ (1,3) ]to the hidden input fields
 * HC_CHILD_AGE_xy
 */
function transferChildAgesForOldStyleInput(formObj) {
    if (formObj['HC_CHILDREN_1'] || formObj['PKG_CHILDREN_1']) {
        var isHotel = formObj['HC_CHILDREN_1'];
        var numChildrenPrefix, childAgePrefix;
        if (isHotel) {
            numChildrenPrefix = "HC_CHILDREN_";
            childAgePrefix = "HC_CHILD_AGE_";
        } else {
            numChildrenPrefix = "PKG_CHILDREN_";
            childAgePrefix = "PKG_CHILD_AGE_";
        }
        for (var i=1; i <= 4; i++) {
            var childAgeArr = null;
            if (formObj[numChildrenPrefix+i] && formObj[numChildrenPrefix+i].value && !formObj["RAW_CHILD_AGE"+i].disabled)
                childAgeArr = formObj["RAW_CHILD_AGE"+i].value.split(",");
            // alert(i+": " + childAgeArr)
			for (var j=1; j <= 3; j++) {
   				formObj[childAgePrefix+i+j].value = (childAgeArr && childAgeArr.length >= j && childAgeArr[j-1] ? childAgeArr[j-1] : "");
   				// alert((childAgePrefix+i+j) +": "+formObj[childAgePrefix+i+j].value);
            }
		}
    }
}


function prefillSubmit(formObj, type) {
    if (formObj == FORM_FLT || formObj == LP_FORM_FLT) {
        if (type == 'QS')
            formObj[FLOW_INITIAL_STATE].value = 'FltPrefillSearch';
        else if (type == 'RS') {
            if (formObj[FLOW_INITIAL_STATE])
                formObj[FLOW_INITIAL_STATE].value = 'FltSearch';
            formObj[FLOW_ACTION].value='detailed-search';
        }
    } else if (formObj == FORM_PKG || formObj == FORM_HTL || formObj == LP_FORM_PKG || formObj == LP_FORM_HTL) {
        if (formObj == FORM_PKG || formObj == LP_FORM_PKG) {
            if (type == 'QS')
                formObj[FLOW_INITIAL_STATE].value = 'PkgPrefillSearch';
            else if (type == 'RS') {
                if (formObj[FLOW_INITIAL_STATE])
                    formObj[FLOW_INITIAL_STATE].value = 'PkgSearch';
                formObj[FLOW_ACTION].value='detailed-search';
            }
        } else if (formObj == FORM_HTL || formObj == LP_FORM_HTL) {
            if (type == 'QS')
                formObj[FLOW_INITIAL_STATE].value = 'HtlPrefillSearch';
            else if (type == 'RS') {
                if (formObj[FLOW_INITIAL_STATE])
                    formObj[FLOW_INITIAL_STATE].value = 'HtlSearch';
                formObj[FLOW_ACTION].value='detailed-search';
            }
        }
    }

    // set action attribute (not hidden input field!) to /main to prevent getting the wait message...
    if (formObj.getAttribute("action"))
        formObj.setAttribute("action", "/main");

    formObj.submit();
}



// *****************************************************************************************************************
// Quick Search specific functions
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Set ups the shared fields between products for each product
* NOTE! Calling this method requires that the calendarAndDates.js file is included on the same page and that the
* 		initCalendar() function has been called
*/
function qsInitSelectBoxes(defaultDMonth, defaultRMonth, defaultDDay, defaultRDay){
    var depBase = getDiv('DIV_DEPARTURE').innerHTML;
    var retBase = getDiv('DIV_RETURN').innerHTML;

    getDiv('fltDSelBox').innerHTML = depBase.replace(/{FORM_NAME}/g, FORM_FLT['formname'].value);
    getDiv('fltDSelBox').innerHTML = getDiv('fltDSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'45\'');
    getDiv('fltRSelBox').innerHTML = retBase.replace(/{FORM_NAME}/g, FORM_FLT['formname'].value);
    getDiv('fltRSelBox').innerHTML = getDiv('fltRSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'50\'');

    setSelectIdxFromValue(FORM_FLT[START_MONTH_FIELD], defaultDMonth);
    setSelectIdxFromValue(FORM_FLT[END_MONTH_FIELD], defaultRMonth);
    setSelectIdxFromValue(FORM_FLT[START_DAY_FIELD], defaultDDay);
    setSelectIdxFromValue(FORM_FLT[END_DAY_FIELD], defaultRDay);
    changeDates('start', FORM_FLT);

    getDiv('pkgDSelBox').innerHTML = depBase.replace(/{FORM_NAME}/g, FORM_PKG['formname'].value);
    getDiv('pkgDSelBox').innerHTML = getDiv('pkgDSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'215\'');
    getDiv('pkgRSelBox').innerHTML = retBase.replace(/{FORM_NAME}/g, FORM_PKG['formname'].value);
    getDiv('pkgRSelBox').innerHTML = getDiv('pkgRSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'220\'');

    setSelectIdxFromValue(FORM_PKG[START_MONTH_FIELD], defaultDMonth);
    setSelectIdxFromValue(FORM_PKG[END_MONTH_FIELD], defaultRMonth);
    setSelectIdxFromValue(FORM_PKG[START_DAY_FIELD], defaultDDay);
    setSelectIdxFromValue(FORM_PKG[END_DAY_FIELD], defaultRDay);
    changeDates('start', FORM_PKG);

    getDiv('htlDSelBox').innerHTML = depBase.replace(/{FORM_NAME}/g, FORM_HTL['formname'].value);
    getDiv('htlDSelBox').innerHTML = getDiv('htlDSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'105\'');
    getDiv('htlRSelBox').innerHTML = retBase.replace(/{FORM_NAME}/g, FORM_HTL['formname'].value);
    getDiv('htlRSelBox').innerHTML = getDiv('htlRSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'110\'');

    setSelectIdxFromValue(FORM_HTL[START_MONTH_FIELD], defaultDMonth);
    setSelectIdxFromValue(FORM_HTL[END_MONTH_FIELD], defaultRMonth);
    setSelectIdxFromValue(FORM_HTL[START_DAY_FIELD], defaultDDay);
    setSelectIdxFromValue(FORM_HTL[END_DAY_FIELD], defaultRDay);
    changeDates('start', FORM_HTL);

    getDiv('carDSelBox').innerHTML = depBase.replace(/{FORM_NAME}/g, FORM_CAR['formname'].value);
    getDiv('carDSelBox').innerHTML = getDiv('carDSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'410\'');
    getDiv('carRSelBox').innerHTML = retBase.replace(/{FORM_NAME}/g, FORM_CAR['formname'].value);
    getDiv('carRSelBox').innerHTML = getDiv('carRSelBox').innerHTML.replace(/tabindex=99999/ig, 'tabindex=\'420\'');

    setSelectIdxFromValue(FORM_CAR[START_MONTH_FIELD], defaultDMonth);
    setSelectIdxFromValue(FORM_CAR[END_MONTH_FIELD], defaultRMonth);
    setSelectIdxFromValue(FORM_CAR[START_DAY_FIELD], defaultDDay);
    setSelectIdxFromValue(FORM_CAR[END_DAY_FIELD], defaultRDay);
    changeDates('start', FORM_CAR);
}


/** ------------------------------------------------------------------------------------------------------------
* Calls to this method comes from Link content.
* This method is used, DO NOT REMOVE!
*/
function qsOpenProduct(product, onload){
    // close all
    for (i=0; i < QS_PRODUCT_ARRAY.length; i++) {
        if (getDiv(QS_PRODUCT_ARRAY[i]))
            display(QS_PRODUCT_ARRAY[i], false);
    }

    // on load handling (product zero might be a product with redirect task...)
    if (onload) {
        product = '';
        for (i=0; i < QS_PRODUCT_ARRAY.length; i++) {
            if (getDiv(QS_PRODUCT_ARRAY[i])) {
                product = QS_PRODUCT_ARRAY[i];
                break;
            }
        }
    }

    // open selected
    if (product) {
        display(product, true);
        qsSwitchRadioMenu(product);
        qsSwitchProductDesc(product);
        qsTransferProductValues(QS_PRODUCT_PREVIOUS);
        QS_PRODUCT_PREVIOUS = product;
    }
}

/** ------------------------------------------------------------------------------------------------------------
* This method fixes radioselects for radioMenu vid reload, dvs det lager som visas ska också vara förbockat.
*/
function qsSwitchRadioMenu(product){
    for(i=0;i < document.radioMenu.radioLayer.length;i++){
        if(document.radioMenu.radioLayer[i].value == product){
            document.radioMenu.radioLayer[i].checked = true;
        }
    }
}

/** ------------------------------------------------------------------------------------------------------------
* This method switch the product description in the QS
*/
function qsSwitchProductDesc(product){
    descDiv = getDiv('qsProductDesc');
    if (descDiv) {
        prodDesc = eval('QS_PRODUCT_DESC_ARRAY.'+product);
        if (prodDesc)
            descDiv.innerHTML = prodDesc;
        else
            descDiv.innerHTML = '';
    }
}

/** ------------------------------------------------------------------------------------------------------------
* This method populates the offices for cars when a city is selected
*/
function qsHandleCarCitySelect(defaultOptionText, startCountry, startLocation) {
    citySelBox = FORM_CAR['qsCarCitySelect'];
    countryCode = citySelBox.value.split('-')[0];
    cityCode = citySelBox.value.split('-')[1];

    FORM_CAR['qsCarOfficeSelect'].length = 0;
    FORM_CAR['qsCarOfficeSelect'][0] = new Option(defaultOptionText, '');
    for (i=0; i < CAR_OFFICES_ARRAY.length; i++) {
        if (CAR_OFFICES_ARRAY[i][0] == cityCode)
            FORM_CAR['qsCarOfficeSelect'][FORM_CAR['qsCarOfficeSelect'].length] = new Option(CAR_OFFICES_ARRAY[i][2], CAR_OFFICES_ARRAY[i][1]);
    }

    FORM_CAR[startCountry].value = countryCode;
    FORM_CAR[startLocation].value = cityCode+';'+citySelBox[ citySelBox.selectedIndex ].text;
}

/** ------------------------------------------------------------------------------------------------------------
* This method populates the selected office in the form when a car office is selected
*/
function qsHandleCarOfficeSelect(pickupField) {
    officeSelBox = FORM_CAR['qsCarOfficeSelect'];
    FORM_CAR[pickupField].value = officeSelBox.value+';'+officeSelBox[ officeSelBox.selectedIndex ].text;
}


/** ------------------------------------------------------------------------------------------------------------
* This method transfers values between the flight and the package forms
*/
function qsTransferProductValues(oldProduct) {
    if (oldProduct != 'flight' && oldProduct != 'package')
        return;

    if (oldProduct == 'flight') {
        fromForm = FORM_FLT;
        toForm = FORM_PKG;
    } else {
        fromForm = FORM_PKG;
        toForm = FORM_FLT;
    }


    // transfer cities (except non-iata destintions
    if (fromForm[GEN_START_CITY].value) {
        toForm[GEN_START_CITY].value = fromForm[GEN_START_CITY].value;
        toForm[GEN_START_CITY_TEXT].value = fromForm[GEN_START_CITY_TEXT].value;
    }
    if(fromForm[GEN_END_CITY].value && !fromForm[GEN_END_CITY].value.match('^TL-') && !(toForm[GEN_END_CITY].value && toForm[GEN_END_CITY].value.match('^TL-'))) {
        toForm[GEN_END_CITY].value = fromForm[GEN_END_CITY].value;
        toForm[GEN_END_CITY_TEXT].value = fromForm[GEN_END_CITY_TEXT].value;
    }

    // transfer dates
    toForm[START_MONTH_FIELD].value = fromForm[START_MONTH_FIELD].value;
    toForm[START_DAY_FIELD].value = fromForm[START_DAY_FIELD].value;
    toForm['startDate'].value = fromForm['startDate'].value;
    toForm[END_MONTH_FIELD].value = fromForm[END_MONTH_FIELD].value;
    toForm[END_DAY_FIELD].value = fromForm[END_DAY_FIELD].value;
    toForm['endDate'].value = fromForm['endDate'].value;
}

/** ------------------------------------------------------------------------------------------------------------
* This method switches products in refine search (changes flow engine values)
*/
function rsSetSwitchProductOnload(formObj) {
    if (!formObj || !formObj['switchProduct'])
        return;

    var radioNodeList = formObj['switchProduct'];
    for (var i=0; i < radioNodeList.length; i++) {
        if (radioNodeList[i].checked) {
            rsSwitchProduct(radioNodeList[i]);
            break;
        }
    }
}
function rsSwitchProduct(radioOption) {
    var formObj = radioOption.form;
    var newProduct = radioOption.value;
    if (newProduct == "flt") {
        formObj["name"].value = "FGSearchFlight";
        formObj["formname"].value = "searchflight";
        formObj["initialState"].value = "FltCheckBookingQSLogic";
    } else if (newProduct == "fltHtl") {
        formObj["name"].value = "FGPackageSearch";
        formObj["formname"].value = "pkgsearch";
        formObj["initialState"].value = "PkgCheckBookingQSLogic";
        // no one way we want no...
        if (formObj['TripTypeCheckbox'])
            formObj['TripTypeCheckbox'].checked = false;
        updateTripType(formObj, false);
    }
    display("productHtlDiv", (newProduct == "fltHtl"));
    display("fltTripTypeDiv", (newProduct != "fltHtl"));
    display("fltTravellersDiv", (newProduct != "fltHtl"));
    display("fltTravellersDivBreak", (newProduct == "fltHtl"));
}

// *****************************************************************************************************************
// Calendar and dates functions
// *****************************************************************************************************************

// ---------------------------------------------------
// QUICK, REFINE AND DETAILED SEARCH SHARED FUNCTIONS
// ---------------------------------------------------

/** ------------------------------------------------------------------------------------------------------------
* Re-builds the day select box with the correct number of days of selected month
* NOTE! This function is used in QS, RS and DS
*/
function rebuildDaySelect(calForm, bound, daysAbbr){
    /*
    monthSelBoxName = (bound == 'start' ? START_MONTH_FIELD : END_MONTH_FIELD);
    selBoxName = (bound == 'start' ? START_DAY_FIELD : END_DAY_FIELD);

    oldValue = (calForm[selBoxName].selectedIndex) + 1;
    currentValueInSelBox = calForm[monthSelBoxName].value;
    newMonthMaxDay = DAYS_IN_MONTHS_ARRAY[ tlIntParser(currentValueInSelBox.substring(4, 6))-1 ];
    // Handling of leap year
    if (newMonthMaxDay == 28) {
        tmpYearValue = tlIntParser( currentValueInSelBox.substring(0,4) )-2000;
        if (tmpYearValue%4 == 0)
            newMonthMaxDay = 29;
    }

    newValue = (oldValue > newMonthMaxDay ? newMonthMaxDay : oldValue);
    calForm[selBoxName].length = 0; // clear old list
    for (i=1; i <= newMonthMaxDay; i++) {
        optionName = i + (daysAbbr ? ' '+getShortDayOfWeek(currentValueInSelBox, i) : '');
        calForm[selBoxName][i-1] = new Option(optionName, getTwoDigitMonth(i));
        if (newValue == i)
            calForm[selBoxName][i-1].selected = 'true';
    }
    */
    rebuildDaySelectWithFields(calForm, bound, daysAbbr, START_DAY_FIELD, END_DAY_FIELD, START_MONTH_FIELD, END_MONTH_FIELD);
}

function rebuildDaySelectWithFields(calForm, bound, daysAbbr, startDayField, endDayField, startMonthField, endMonthField){
    monthSelBoxName = (bound == 'start' ? startMonthField : endMonthField);
    selBoxName = (bound == 'start' ? startDayField : endDayField);

    oldValue = (calForm[selBoxName].selectedIndex) + 1;
    currentValueInSelBox = calForm[monthSelBoxName].value;

    newMonthMaxDay = DAYS_IN_MONTHS_ARRAY[ tlIntParser(currentValueInSelBox.substring(4, 6))-1 ];

    /* Handling of leap year */
    if (newMonthMaxDay == 28) {
        tmpYearValue = tlIntParser( currentValueInSelBox.substring(0,4) )-2000;
        if (tmpYearValue%4 == 0)
            newMonthMaxDay = 29;
    }

    newValue = (oldValue > newMonthMaxDay ? newMonthMaxDay : oldValue);
    calForm[selBoxName].length = 0; // clear old list
    for (i=1; i <= newMonthMaxDay; i++) {
        optionName = i + (daysAbbr ? ' '+getShortDayOfWeek(currentValueInSelBox, i) : '');
        calForm[selBoxName][i-1] = new Option(optionName, getTwoDigitMonth(i));
        if (newValue == i)
            calForm[selBoxName][i-1].selected = 'true';
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Returns a date below ten with zero prefix (e.g. 8 becomes 08)
*/
function getTwoDigitMonth(number) {
    return (number<10 ? '0' : '') + number;
}


// ----------------------------------
// QUICK AND REFINE SEARCH FUNCTIONS
// ----------------------------------

/** ------------------------------------------------------------------------------------------------------------
* Change the months only in QS and RS
*/
function changeMonths(type, formObj) {
    if (formObj.elements[START_MONTH_FIELD] && formObj.elements[END_MONTH_FIELD]) {
        if (formObj.elements[START_MONTH_FIELD].value > formObj.elements[END_MONTH_FIELD].value && type == 'start')
            formObj.elements[END_MONTH_FIELD].selectedIndex = formObj.elements[START_MONTH_FIELD].selectedIndex;
        else if (formObj.elements[START_MONTH_FIELD].value > formObj.elements[END_MONTH_FIELD].value && type == 'end')
            formObj.elements[START_MONTH_FIELD].selectedIndex = formObj.elements[END_MONTH_FIELD].selectedIndex;
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Change the date and months in QS and RS
*/
function changeDates(type, formName) {
    formObj = eval(formName);
    if (formObj.elements[START_MONTH_FIELD] && formObj.elements[END_MONTH_FIELD]) {
        if (formObj.elements[START_MONTH_FIELD].value > formObj.elements[END_MONTH_FIELD].value && type == 'start')
            formObj.elements[END_MONTH_FIELD].selectedIndex = formObj.elements[START_MONTH_FIELD].selectedIndex;
        else if (formObj.elements[START_MONTH_FIELD].value > formObj.elements[END_MONTH_FIELD].value && type == 'end')
            formObj.elements[START_MONTH_FIELD].selectedIndex = formObj.elements[END_MONTH_FIELD].selectedIndex;

        rebuildDaySelect(formObj, 'start', true);
        rebuildDaySelect(formObj, 'end', true);
    }
}

function changeDatesWithFields(type, formName, startDayField, endDayField, startMonthField, endMonthField) {
    formObj = eval(formName);
    if (formObj.elements[startMonthField] && formObj.elements[endMonthField]) {
        if (formObj.elements[startMonthField].value > formObj.elements[endMonthField].value && type == 'start')
            formObj.elements[endMonthField].selectedIndex = formObj.elements[startMonthField].selectedIndex;
        else if (formObj.elements[startMonthField].value > formObj.elements[endMonthField].value && type == 'end')
            formObj.elements[startMonthField].selectedIndex = formObj.elements[endMonthField].selectedIndex;

        rebuildDaySelectWithFields(formObj, 'start', true, startDayField, endDayField, startMonthField, endMonthField);
        rebuildDaySelectWithFields(formObj, 'end', true, startDayField, endDayField, startMonthField, endMonthField);
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Gets the friendly abbreviation of a day
*/
function getShortDayOfWeek(yearMonth, day){
    newDate = new Date();
    newDate.setFullYear( yearMonth.substring(0,4), tlIntParser(yearMonth.substring(4,6))-1, day );
    dayIdx = (newDate.getDay() == 0 ? 6 : newDate.getDay()-1);

    return DAYS_IN_WEEK[dayIdx];
}


// ----------------------------------
// CALENDAR FUNCTIONS (ONLY DS)
// ----------------------------------

/** ------------------------------------------------------------------------------------------------------------
* Initialise the calendars with default values set in including page
*/
function initCalendar(calForm, defaultStartYearMonth, defaultStartDay, defaultStartTime, defaultEndYearMonth, defaultEndDay, defaultEndTime){
    if (calForm) {
        // fix months
        startMonthIdx = getIdxInSelectBox(calForm, START_MONTH_FIELD, defaultStartYearMonth);
        endMonthIdx = getIdxInSelectBox(calForm, END_MONTH_FIELD, defaultEndYearMonth);
        calForm[START_MONTH_FIELD][startMonthIdx].selected = true;
        calForm[END_MONTH_FIELD][endMonthIdx].selected = true;
        fillCalendar(calForm, 'startCal', startMonthIdx);
        fillCalendar(calForm, 'endCal', endMonthIdx);

        // fix days
        rebuildDaySelect(calForm, 'start', false);
        rebuildDaySelect(calForm, 'end', false);
        startDayIdx = getIdxInSelectBox(calForm, START_DAY_FIELD, defaultStartDay);
        endDayIdx = getIdxInSelectBox(calForm, END_DAY_FIELD, defaultEndDay);
        calForm[START_DAY_FIELD][startDayIdx].selected = true;
        calForm[END_DAY_FIELD][endDayIdx].selected = true;
        for (i=0; i < 42; i++) {
            if (tlIntParser(calForm.elements['startCal'+i].value,10) == tlIntParser((startDayIdx+1),10))
                dayIdxStart = calForm.elements['startCal'+i];
            if (tlIntParser(calForm.elements['endCal'+i].value,10) == tlIntParser((endDayIdx+1),10))
                dayIdxEnd = calForm.elements['endCal'+i];
        }
        paintCalendar(calForm, 'start', 'START_DAY_FIELD', 'D_Month', 'startCal', startDayIdx);
        paintCalendar(calForm, 'end', 'END_DAY_FIELD', 'R_Month', 'endCal', endDayIdx);

        // fix time
        if (calForm[START_TIME_FIELD] && calForm[END_TIME_FIELD]) {
            startTimeIdx = getIdxInSelectBox(calForm, START_TIME_FIELD, defaultStartTime);
            endTimeIdx = getIdxInSelectBox(calForm, END_TIME_FIELD, defaultEndTime);
            calForm[START_TIME_FIELD][startTimeIdx].selected = true;
            calForm[END_TIME_FIELD][endTimeIdx].selected = true;
        }
        handleTimeFieldEnabled(calForm, defaultStartTime, defaultEndTime);
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Paints background of calender whether before today, todays or after today
*	- boundType		startCal|endCal
*/
function paintCalendar(calForm, bound, selBoxDayName, selBoxMonthName, boundPrefix, dayIdx){
    d = new Date();
    dDay = d.getDate();
    dMonth = d.getMonth()+1;
    dYear = d.getFullYear();

    for (i=0; i < 42; i++) {
        holiday = isHoliday(calForm[selBoxMonthName].value.slice(0, 4), calForm[selBoxMonthName].value.slice(4, 6), calForm.elements[boundPrefix+i].value)
        if((calForm.elements[boundPrefix+i].value != "") && holiday){
            calForm.elements[boundPrefix+i].parentNode.className = 'cal-redday';
            calForm.elements[boundPrefix+i].className = 'cal-redday-input';
            calForm.elements[boundPrefix+i].title = holiday;
            if (tlIntParser(calForm.elements[boundPrefix+i].value,10) == tlIntParser((dayIdx+1),10))
                calForm.elements[boundPrefix+i].className = 'cal-selected-redday-input';
        }else if((calForm.elements[boundPrefix+i].value != "") && (calForm.elements[boundPrefix+i].value < dDay) && (calForm[selBoxMonthName].value.slice(4, 6) == dMonth) && (calForm[selBoxMonthName].value.slice(0, 4) == dYear)){
            calForm.elements[boundPrefix+i].parentNode.className = 'cal-beforeToDay';
            calForm.elements[boundPrefix+i].className = 'cal-beforeToDay-input';
            calForm.elements[boundPrefix+i].title = '';
            if (tlIntParser(calForm.elements[boundPrefix+i].value,10) == tlIntParser((dayIdx+1),10))
                calForm.elements[boundPrefix+i].className = 'cal-selected-input';
        }else if((calForm.elements[boundPrefix+i].value == dDay) && (calForm[selBoxMonthName].value.slice(4, 6) == dMonth) && (calForm[selBoxMonthName].value.slice(0, 4) == dYear)){
            calForm.elements[boundPrefix+i].parentNode.className = 'cal-toDay';
            calForm.elements[boundPrefix+i].className = 'cal-toDay-input';
            calForm.elements[boundPrefix+i].title = '';
            if (tlIntParser(calForm.elements[boundPrefix+i].value,10) == tlIntParser((dayIdx+1),10))
                calForm.elements[boundPrefix+i].className = 'cal-selected-input';
        }else{
            calForm.elements[boundPrefix+i].parentNode.className = 'cal-weekday';
            calForm.elements[boundPrefix+i].className = 'cal-weekday-input';
            calForm.elements[boundPrefix+i].title = '';
            if (tlIntParser(calForm.elements[boundPrefix+i].value,10) == tlIntParser((dayIdx+1),10))
                calForm.elements[boundPrefix+i].className = 'cal-selected-input';
        }
    }

}

function isHoliday(sYear,sMonth,sDay) {
    if (!HOLIDAYS || HOLIDAYS.length == 0)
        return null;

    sFullDate = sYear+''+sMonth+''+( (parseInt(sDay) < 10 ? '0':'') + sDay );
    for (holIdx=0;holIdx<HOLIDAYS.length;holIdx++) {
        if (HOLIDAYS[holIdx].DATE == sFullDate)
            return HOLIDAYS[holIdx].TITLE;
    }
    return null;
}

/** ------------------------------------------------------------------------------------------------------------
* Populates the calendar with days
*	- boundType		startCal|endCal
*	- selMonthIdx		0 = this month, 1 next month and so on
*/
function fillCalendar(calForm, boundPrefix, selMonthIdx){
    for (i=0;i<42;i++){
        if (MONTH_ARRAY[selMonthIdx][i]!=0)
            calForm.elements[boundPrefix+i].value = MONTH_ARRAY[selMonthIdx][i];
        else
            calForm.elements[boundPrefix+i].value = '';
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Handles a new month selection
*	- boundType		start|end
*/
function monthChanged(calForm, bound) {
    if (calForm) {
        /*
        selBoxName = (bound == 'start' ? START_MONTH_FIELD : END_MONTH_FIELD);
        boundPrefix = (bound == 'start' ? 'startCal' : 'endCal');
        fillCalendar(calForm, boundPrefix, calForm[selBoxName].selectedIndex);

        // change the days
        rebuildDaySelect(calForm, bound, false);
        dayChanged(calForm, bound);

        // if start month is changed and end month is before start month, change the end month to the same as start month
        if (bound == 'start') {
            if (calForm[START_MONTH_FIELD].selectedIndex > calForm[END_MONTH_FIELD].selectedIndex) {
                calForm[END_MONTH_FIELD].selectedIndex = calForm[START_MONTH_FIELD].selectedIndex;
                monthChanged(calForm, 'end');
            }
        }
        */
        monthChangedWithFields(calForm, bound, START_DAY_FIELD, END_DAY_FIELD, START_MONTH_FIELD, END_MONTH_FIELD, true);
    }

}

function monthChangedWithFields(calForm, bound, startDayField, endDayField, startMonthField, endMonthField, fillCal) {
    if (calForm) {
        selBoxName = (bound == 'start' ? startMonthField : endMonthField);
        if (fillCal) {
            boundPrefix = (bound == 'start' ? 'startCal' : 'endCal');
            fillCalendar(calForm, boundPrefix, calForm[selBoxName].selectedIndex);
        }

        // change the days
        rebuildDaySelect(calForm, bound, false, startDayField, endDayField, startMonthField, endMonthField);
        dayChanged(calForm, bound, startDayField, endDayField, startMonthField, endMonthField, fillCal);

        // if start month is changed and end month is before start month, change the end month to the same as start month
        if (bound == 'start') {
            if (calForm[startMonthField].selectedIndex > calForm[endMonthField].selectedIndex) {
                calForm[endMonthField].selectedIndex = calForm[startMonthField].selectedIndex;
                monthChangedWithFields(calForm, 'end', startDayField, endDayField, startMonthField, endMonthField, fillCal);
            }
        }
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Handles a new day selection in select box
*	- boundType		start|end
*/
function dayChanged(calForm, bound) {
    if (calForm) {
        /*
        selBoxDayName = (bound == 'start' ? START_DAY_FIELD : END_DAY_FIELD);
        selBoxMonthName = (bound == 'start' ? START_MONTH_FIELD : END_MONTH_FIELD);
        boundPrefix = (bound == 'start' ? 'startCal' : 'endCal');
        dayIdx = calForm[selBoxDayName].selectedIndex;

        paintCalendar(calForm, bound, selBoxDayName, selBoxMonthName, boundPrefix, dayIdx);
        */
        dayChangedWithFields(calForm, bound, START_DAY_FIELD, END_DAY_FIELD, START_MONTH_FIELD, END_MONTH_FIELD, true);
    }
}

function dayChangedWithFields(calForm, bound, startDayField, endDayField, startMonthField, endMonthField, paintCal) {
    if (calForm) {
        selBoxDayName = (bound == 'start' ? startDayField : endDayField);
        selBoxMonthName = (bound == 'start' ? startMonthField : endMonthField);
        boundPrefix = (bound == 'start' ? 'startCal' : 'endCal');
        dayIdx = calForm[selBoxDayName].selectedIndex;

        if (paintCal)
            paintCalendar(calForm, bound, selBoxDayName, selBoxMonthName, boundPrefix, dayIdx);
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Handles a new day click in calendar
*	- boundType		start|end
*	- dayIdx		number of input field clicked (needs to be mapped to index value in MONTH_ARRAY to know eay of month)
*/
function dayChangedClick(calForm, bound, dayIdx) {
    if (calForm) {
        monthSelBoxName = (bound == 'start' ? START_MONTH_FIELD : END_MONTH_FIELD);
        selBoxName = (bound == 'start' ? START_DAY_FIELD : END_DAY_FIELD);

        if ( isValidDay(calForm, monthSelBoxName, dayIdx) ) {
            dayValueIdx = MONTH_ARRAY[calForm[monthSelBoxName].selectedIndex][dayIdx];
            calForm[selBoxName].selectedIndex = (dayValueIdx-1);
            dayChanged(calForm, bound);
        }
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Checks if the user clicked on an empty field (field with no day number) in the calendar
*/
function isValidDay(calForm, monthSelBoxName, dayIdx) {
    dayValueIdx = MONTH_ARRAY[calForm[monthSelBoxName].selectedIndex][dayIdx];
    return (dayValueIdx != 0);
}

/** ------------------------------------------------------------------------------------------------------------
* Hides and disables the time fields if no time value has been set in including page
*/
function handleTimeFieldEnabled(calForm, defaultStartTime, defaultEndTime) {
    if (!defaultStartTime && calForm[START_TIME_FIELD]) {
        calForm[START_TIME_FIELD].disabled = 'true';
        display('calStartTime', false);
    }

    if (!defaultEndTime && calForm[END_TIME_FIELD]) {
        calForm[END_TIME_FIELD].disabled = 'true';
        display('calEndTime', false);
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Shows or hides the end date calendar
*/
function displayEndCalendar(show) {
    display('calEndDateCalendar', show);
}





// *****************************************************************************************************************
// Age functions
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Enables the age fields
*/
function enableAge(ageFieldIdx, childAgeBase, formObj){
    enableAge2(ageFieldIdx, childAgeBase, 'RAW_CHILD_AGE', formObj);
}

function enableAge2(ageFieldIdx, childAgeBase, childAgeTextBase, formObj){

    childAgeSelect = (childAgeBase+ageFieldIdx);
    childAgeText = (childAgeTextBase+ageFieldIdx);
    if ((formObj[childAgeSelect].selectedIndex) > 0){
        formObj[childAgeText].disabled = false;
    } else {
        formObj[childAgeText].disabled = true;
        formObj[childAgeText].value = AGE_EXAMPLE_VALUE;
    }
}

function AgeInputContainer() {
    this.AGES_INPUTS = new Array();
    this.EXAMPLE_TEXT = new Array();
    this.setExampleText = function (exampleText) { this.EXAMPLE_TEXT = exampleText; };
    this.registerAgeInput = function (formObj, ageNumberFieldName, agesFieldName) { this.AGES_INPUTS[this.AGES_INPUTS.length] = new AgeInputObject(formObj, ageNumberFieldName, agesFieldName); };
    this.validateAges = function (formObj, maxAge) {
        for (var i=0; i < this.AGES_INPUTS.length; i++) {
            if (formObj != this.AGES_INPUTS[i].getFormObject())
                continue;
            var totalAges = this.AGES_INPUTS[i].getNumberOfAgesInput().value;
            var input = this.AGES_INPUTS[i].getAgesInput();
            totalAges = (isNaN(totalAges) ? 0 : parseInt(totalAges));
            if (totalAges > 0) {
                var ageError = false;
                if (this.EXAMPLE_TEXT && this.EXAMPLE_TEXT == input.value)
                    ageError = true;
                else {
                    var ageArray = (input.value ? input.value.split(',') : new Array());
                    if (ageArray.length != totalAges) {
                        ageError = true;
                    } else {
                        for (var a=0; a < ageArray.length; a++){
                            if ((ageArray[a] != "0" && !ageArray[a]) || isNaN(ageArray[a]) || (parseInt(ageArray[a]) > maxAge)) {
                                ageError = true;
                                break;
                            }
                            else if(ageArray[a].indexOf(".") != -1){
                            	ageError = true;
                                break;
                            }
                        }
                    }
                }
                if (ageError) {
                    alert(ALERT_CHILDREN_AGE);
                    return false;
                }
            }
        }
        return true;
    };
}
function AgeInputObject(formObj, ageNumberFieldName, agesFieldName) {
    this.FORM_OBJECT = formObj;
    this.AGE_NUMBER = ageNumberFieldName;
    this.AGES = agesFieldName;
    this.getFormObject = function() { return this.FORM_OBJECT; };
    this.getNumberOfAgesInput = function() { return this.FORM_OBJECT[this.AGE_NUMBER]; };
    this.getAgesInput = function() { return this.FORM_OBJECT[this.AGES]; };
}
SFAgeInput = new AgeInputContainer();


/** ------------------------------------------------------------------------------------------------------------
* Sets the age value to their input fields
*/
function setAgeVariables(inForm, inValue, inRoom, childrenBase, childAgeBase, maxAge){
    var ageArray;
    ageArray = inValue.split(',');
    if (ageArray.length == inForm[childrenBase+inRoom].selectedIndex){
        for (i=1; i < ageArray.length+1; i++){
            if (!isNaN(ageArray[i-1]) && (parseInt(ageArray[i-1] ) < (maxAge+1))){
                inForm[childAgeBase+inRoom+i].value = ageArray[i-1];
            } else {
                alert(ALERT_CHILDREN_AGE);
                return false;
            }
        }
        return true;
    } else {
        alert( ALERT_CHILDREN_AGE_PER_ROOM.replace('${roomNumber}', inRoom) );
        return false;
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Sets the correct child values in the child age input fields on page load
*/
function fillChildAgesOnLoad(formObj) {
    childrenBaseField = (formObj == FORM_HTL ? HTL_CHILDREN_BASE : PKG_CHILDREN_BASE);
    ageBaseField = (formObj == FORM_HTL ? HTL_CHILD_AGE_BASE : PKG_CHILD_AGE_BASE);
    for (i=1; i <= 4; i++) {
        enableAge(i, childrenBaseField, formObj);

        childAgeStr = '';
        for (j=1; j <= 3; j++) {
            ageValue = formObj[ageBaseField+i+j].value
            if (ageValue != '' && !isNaN(ageValue))
                childAgeStr += (!childAgeStr ? '' : ',') + formObj[ageBaseField+i+j].value;
        }
        if (childAgeStr) {
            formObj['RAW_CHILD_AGE'+i].value = childAgeStr;
            formObj['RAW_CHILD_AGE'+i].disabled = false;
        }
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Sets the correct child values in the child age input fields on page load
*/
function fillChildAgesOnLoadNas(formObj) {
    childrenBaseField = PKG_CHILDREN_BASE;
    ageBaseField = 'HTL_CHILDREN_AGES_';
    childAgeStr = '';
    for (i=1; i <= 4; i++) {
        enableAge(i, childrenBaseField, formObj);
        childAgeStr = formObj['HTL_CHILDREN_AGES_'+i].value;
        if (childAgeStr) {
            formObj['RAW_CHILD_AGE'+i].value = childAgeStr;
            formObj['RAW_CHILD_AGE'+i].disabled = false;
        }
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Enables the child age field depending on children value
*/
function enableChildAgeField(formObj) {
    fieldValue = formObj[GEN_NO_OF_CHILDREN].value;
    formObj[GEN_CHILD_AGES].disabled = (!fieldValue || fieldValue == '0' ? true : false);
    if (formObj[GEN_CHILD_AGES].disabled)
        formObj[GEN_CHILD_AGES].value = AGE_EXAMPLE_VALUE;
}

function drawChildAgeDD(childCount) {
	ChildDD.drawDDs(childCount, childAgesArray);	
}



// *****************************************************************************************************************
// City and destination functions
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Sets the correct values for start and end destinations
*
* 	@type: 0=departure list, 1=text field
*/
function resetDestinationInput(formObj, bound, type) {
    depSelBoxObj = formObj[GEN_START_CITY];
    depTextObj = formObj[GEN_START_CITY_TEXT];
    arrSelBoxObj = formObj[GEN_END_CITY];
    arrTextObj = formObj[GEN_END_CITY_TEXT];

    if (bound == 'start') {
        if (type == 0) {
            if (depTextObj)
                depTextObj.value = '';
        } else if (depTextObj && trimSpaces(depTextObj.value) != '')
            depSelBoxObj.selectedIndex = 0;
    } else {
        if (type == 0) {
            if (arrTextObj)
                arrTextObj.value = '';
        } else if (arrTextObj && trimSpaces(arrTextObj.value) != '')
            arrSelBoxObj.selectedIndex = 0;
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Sets value from multiple select box (in case of several options for text search)
*/
function checkDestinationsOnChange(formObj, bound, clearValueAction) {
    var oldStyle = !formObj["TRIP_DEPARTURE_LOCATION_1"];
    if (formObj[ (bound == 'start' ? (oldStyle?GEN_START_CITY:"TRIP_DEPARTURE_LOCATION_1") : (oldStyle?GEN_END_CITY:"TRIP_ARRIVAL_LOCATION_1")) ].value == clearValueAction) {
        formObj.action.value = clearValueAction;
        showWaitMsgAndSubmit(formObj);
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Sets the correct destination values on load for DS and RS
*/
function fixDestinationsOnLoad(formObj, startCode, endCode){

    depSelBoxObj = formObj[GEN_START_CITY];
    depTextObj = formObj[GEN_START_CITY_TEXT];
    depFriendly = formObj[GEN_START_CITY_FRIENDLY];
    if (depTextObj && depSelBoxObj && startCode){
        inSelBox = false;
        for (i=0; i < depSelBoxObj.options.length; i++){
            if (depSelBoxObj.options[i].value == startCode.toUpperCase()){
                depSelBoxObj.options.selectedIndex = i;
                inSelBox = true;
                break;
            }
        }

        if (!inSelBox){
            if (depFriendly && depFriendly.value) {
                addOptionToSelectBox(depSelBoxObj, startCode.toUpperCase(), depFriendly.value, true);
            } else {
                depTextObj.value = startCode.toUpperCase();
                depSelBoxObj.selectedIndex = 0;
            }
        }
    }

    arrSelBoxObj = formObj[GEN_END_CITY];
    arrTextObj = formObj[GEN_END_CITY_TEXT];
    arrFriendly = formObj[GEN_END_CITY_FRIENDLY];
    if (arrTextObj && arrSelBoxObj && endCode) {
        inSelBox = false;
        for (i=0; i < arrSelBoxObj.options.length; i++){
            if (arrSelBoxObj.options[i].value == endCode.toUpperCase()){
                arrSelBoxObj.options.selectedIndex = i;
                inSelBox = true;
                break;
            }
        }
        if (!inSelBox){
            if (arrFriendly && arrFriendly.value) {
                addOptionToSelectBox(arrSelBoxObj, endCode.toUpperCase(), arrFriendly.value, true);
            } else {
                arrTextObj.value = endCode.toUpperCase();
                arrSelBoxObj.selectedIndex = 0;
            }
        }
    }
}





// *****************************************************************************************************************
// Room functions
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Shows or hides room divs depending on how many rooms the user selected
*/
function showRooms(formObj){
    if (!formObj)
        return;

    var divPrefix, divPostfix;
    if (formObj == FORM_PKG || formObj == LP_FORM_PKG) {
        roomsValue = formObj[PKG_ROOMS].value;
        divPrefix = 'pkg';
        divPostfix = (formObj == LP_FORM_PKG ? 'LP' : '');
    } else if (formObj == FORM_HTL || formObj == LP_FORM_HTL) {
        roomsValue = formObj[HTL_ROOMS].value;
        divPrefix = 'hotel';
        divPostfix = (formObj == LP_FORM_HTL ? 'LP' : '');
    }

    for (var i=1; i <= 4; i++){
        display( divPrefix + 'Room' + i, (i <= roomsValue) );
        if (divPrefix + 'Room' + i + 'Div_4' + divPostfix){
            display( divPrefix + 'Room' + i + 'Div_4' + divPostfix, (i <= roomsValue) );
        }
        if (i>roomsValue) {
            if (divPrefix=="pkg"&&formObj['PKG_CHILDREN_'+i])
                formObj['PKG_CHILDREN_'+i].selectedIndex=0;
            else if (divPrefix=="hotel"&&formObj['HC_CHILDREN_'+i])
                formObj['HC_CHILDREN_'+i].selectedIndex=0;
        }
	}

    if (getDiv(divPrefix + 'RoomHeaderDiv' + divPostfix))
        display (divPrefix + 'RoomHeaderDiv' + divPostfix, (roomsValue > 1));

    if (formObj != FORM_HTL && formObj != LP_FORM_HTL && getDiv(divPrefix + 'RoomsWarningDiv' + divPostfix))
        display(divPrefix + 'RoomsWarningDiv' + divPostfix, (roomsValue > 1));
}

/** ------------------------------------------------------------------------------------------------------------
* Shows or hides room divs depending on how many rooms the user selected (old style... For those forms that do not use dropdowns for child age)
*/
function showRoomsOldStyle(formObj){
    if (!formObj)
        return;

    var divPrefix, divPostfix;
    if (formObj == FORM_PKG || formObj == LP_FORM_PKG) {
        roomsValue = formObj[PKG_ROOMS].value;
        divPrefix = 'pkg';
        divPostfix = (formObj == LP_FORM_PKG ? 'LP' : '');
    } else if (formObj == FORM_HTL || formObj == LP_FORM_HTL) {
        roomsValue = formObj[HTL_ROOMS].value;
        divPrefix = 'hotel';
        divPostfix = (formObj == LP_FORM_HTL ? 'LP' : '');
    }

    for (var i=1; i <= 4; i++){
        display( divPrefix + 'Room' + i + 'Div_0' + divPostfix, (i <= roomsValue) );
        display( divPrefix + 'Room' + i + 'Div_1' + divPostfix, (i <= roomsValue) );
        display( divPrefix + 'Room' + i + 'Div_2' + divPostfix, (i <= roomsValue) );
        display( divPrefix + 'Room' + i + 'Div_3' + divPostfix, (i <= roomsValue) );
        if (divPrefix + 'Room' + i + 'Div_4' + divPostfix){
            display( divPrefix + 'Room' + i + 'Div_4' + divPostfix, (i <= roomsValue) );
        }
        if (i>roomsValue) {
            if (divPrefix=="pkg"&&formObj['PKG_CHILDREN_'+i])
                formObj['PKG_CHILDREN_'+i].selectedIndex=0;
            else if (divPrefix=="hotel"&&formObj['HC_CHILDREN_'+i])
                formObj['HC_CHILDREN_'+i].selectedIndex=0;
        }
	}

    if (getDiv(divPrefix + 'RoomHeaderDiv' + divPostfix))
        display (divPrefix + 'RoomHeaderDiv' + divPostfix, (roomsValue > 1));

    if (formObj != FORM_HTL && formObj != LP_FORM_HTL && getDiv(divPrefix + 'RoomsWarningDiv' + divPostfix))
        display(divPrefix + 'RoomsWarningDiv' + divPostfix, (roomsValue > 1));
}

function showRooms2 (formObj){
    if (!formObj)
        return;

    var divPrefix, divPostfix;
    if (formObj == FORM_PKG || formObj == LP_FORM_PKG) {
        roomsValue = formObj[PKG_ROOMS].value;
        divPrefix = 'pkg';
        divPostfix = (formObj == LP_FORM_PKG ? 'LP' : '');
    } else if (formObj == FORM_HTL || formObj == LP_FORM_HTL) {        
        roomsValue = formObj['HTL_ROOMS_1'].value;
        divPrefix = 'hotel';
        divPostfix = (formObj == LP_FORM_HTL ? 'LP' : '');
    }

    for (i=2; i <= 4; i++){
        display( divPrefix + 'Room' + i + divPostfix, (i <= roomsValue) );
	}

    if (getDiv(divPrefix + 'RoomHeaderDiv' + divPostfix))
        display (divPrefix + 'RoomHeaderDiv' + divPostfix, (roomsValue > 1));

    if (formObj != FORM_HTL && formObj != LP_FORM_HTL && getDiv(divPrefix + 'RoomsWarningDiv' + divPostfix))
        display(divPrefix + 'RoomsWarningDiv' + divPostfix, (roomsValue > 1));
}

function handleMultipleLocationChange(selectObj, locationBaseParentDivId) {
    if (selectObj && (!selectObj.value || "newdest" == selectObj.options[selectObj.options.selectedIndex].value || "choose_another_dep" == selectObj.options[selectObj.options.selectedIndex].value || "choose_another_dest" == selectObj.options[selectObj.options.selectedIndex].value)) {
        display("input_"+locationBaseParentDivId, true);
        display("multiSel_"+locationBaseParentDivId, false);
        selectObj.options.length = 0; // clear multiselect options
    }
}


// *****************************************************************************************************************
// Airline functions
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Opens a window to pick airline in
*/
function airlinePicker() {
    window.open('/main?type=General&name=AirlinePicker&letter=A', 'AirlinePicker', 'width=260, height=530, toolbar=no, titlebar=no, scrollbars');
}

/** ------------------------------------------------------------------------------------------------------------
* Removes an airline from the list
*/
function removeAirline(index) {
    var oldStyle = !AIRLINE_CONTROL_FORM["TRIP_PREFERRED_TRIP_CARRIER_10"];
    for(i = index + 1; i < AIRLINE_CONTROL_COUNTER; i++) {
        AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+(i-1)].value = AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+i].value;
        AIRLINE_CONTROL_FORM[(oldStyle?FLT_AIRLINE_ID:"TRIP_PREFERRED_TRIP_CARRIER_1")+(i-1)].value = AIRLINE_CONTROL_FORM[(oldStyle?FLT_AIRLINE_ID:"TRIP_PREFERRED_TRIP_CARRIER_1")+i].value;
    }
    AIRLINE_CONTROL_COUNTER--;

    AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+AIRLINE_CONTROL_COUNTER].value = '';
    AIRLINE_CONTROL_FORM[(oldStyle?FLT_AIRLINE_ID:"TRIP_PREFERRED_TRIP_CARRIER_1")+AIRLINE_CONTROL_COUNTER].value = '';

    updateAirlineVisibility();
}

/** ------------------------------------------------------------------------------------------------------------
* Sets an airline from pop-up
*/
function setAirline(sAirlineID, sAirlineName) {
    var oldStyle = !AIRLINE_CONTROL_FORM["TRIP_PREFERRED_TRIP_CARRIER_10"];
    AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+AIRLINE_CONTROL_COUNTER].value = sAirlineName;
    AIRLINE_CONTROL_FORM[(oldStyle?FLT_AIRLINE_ID:"TRIP_PREFERRED_TRIP_CARRIER_1")+AIRLINE_CONTROL_COUNTER].value = sAirlineID;
    AIRLINE_CONTROL_COUNTER++;
    updateAirlineVisibility();
}

/** ------------------------------------------------------------------------------------------------------------
* Sets an airline from select box
*/
function setAirlineFromSelect(selection) {
    aid = selection.options[selection.selectedIndex].value;
    aname = selection.options[selection.selectedIndex].text;
    if (aid == "OTHER")
        airlinePicker();
    else
        setAirline(aid, aname);
    selection.options.selectedIndex = 0;
}

/** ------------------------------------------------------------------------------------------------------------
* Shows the selected airlines in their divs
*/
function updateAirlineVisibility() {
    for (i=0; i < 5; i++) {
        if(getDiv('airline'+i+'div')){
        getDiv('airline'+i+'div').innerHTML = '<a title="' + AIRLINE_REMOVE_LINK_NAME + '"href="javascript:removeAirline(' + i + ');"><div><img src="/images/fix/airlines/sm'+AIRLINE_CONTROL_FORM["TRIP_PREFERRED_TRIP_CARRIER_1"+i].value + '.gif">' + AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+i].value+'</div></a>';
        display('airline'+i+'div', (AIRLINE_CONTROL_COUNTER > i));
        }
    }

    AIRLINE_CONTROL_FORM[FLT_NUM_OF_AIRLINES].value = AIRLINE_CONTROL_COUNTER;

    if (AIRLINE_CONTROL_FORM["MOST_WANTED_AIRLINE_OPTIONS"])
        AIRLINE_CONTROL_FORM["MOST_WANTED_AIRLINE_OPTIONS"].disabled = (AIRLINE_CONTROL_COUNTER > 4);
}

/** ------------------------------------------------------------------------------------------------------------
* Removes (filters out) a list of airlines from the select box
*/
function excludeAirlinesFromSelectBox(selBox, excludedList){
    excludedAirlines = (excludedList ? excludedList.split(',') : new Array());
    if (selBox && excludedAirlines.length > 0){
        for (i=0; i < selBox.length; i++){
            for (j=0; j < excludedAirlines.length; j++){
                if (excludedAirlines[j] == selBox[i].value){
                    selBox[i] = null;
                    i--;
                }
            }
        }
    }
}





// *****************************************************************************************************************
// Amenities function
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Handle amenities for hotel
*/
function selectAmenity(formObj, searchAll){
    if (searchAll){
        formObj[HTL_AMENITY_POOL].checked = false;
        formObj[HTL_AMENITY_FITNESS].checked = false;
        formObj[HTL_AMENITY_RESTAURANT].checked = false;
        formObj[HTL_AMENITY_CHILD_ACTIVITIES].checked = false;
        formObj[HTL_AMENITY_MEETING_FACILITIES].checked = false;
        formObj[HTL_AMENITY_PETS_ALLOWED].checked = false;
        formObj[HTL_AMENITY_WHEELCHAIR].checked = false;
        formObj[HTL_AMENITY_KITCHEN].checked = false;
    } else
        formObj[HTL_AMENITY_ALL].checked = false;
}





// *****************************************************************************************************************
// Car function
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Builds the city select options
*/
function populateCities(formObj) {
    // --- clear location/office lists first ---
    formObj[CAR_START_PICKUP].length = 0;
    formObj[CAR_END_LOCATION].length = 0;

    // --- get data and object ---
    countryCode = formObj[CAR_START_COUNTRY].value;
    cityObj = formObj[CAR_START_LOCATION];
    if (!countryCode || !cityObj) {
        if (cityObj) cityObj.length = 0;
        return;
    }
    // --- clear old option list ---
    cityObj.length = 0;
    // --- set default select option ---
    cityObj[0] = new Option(CAR_SELECT_CITY_DEFAULT_VALUE, '');
    // --- fill cities ---
    for (i=0; i < cityList[countryCode].length; i++) {
        valuePair = cityList[countryCode][i].split('|');
        cityObj[i+1] = new Option(valuePair[1], valuePair[0]);
    }

    populateReturnLocations(formObj);
}

/** ------------------------------------------------------------------------------------------------------------
* Builds the pick up/office select options
*/
function populatePickUpLocations(formObj){
    // --- get data and object ---
    cityCodeRaw = formObj[CAR_START_LOCATION].value;
    officeObj = formObj[CAR_START_PICKUP];
    if (!cityCodeRaw || cityCodeRaw.indexOf(';') == -1 || !officeObj) {
        if (officeObj) officeObj.length = 0;
        return;
    }
    cityCode = cityCodeRaw.split(';')[0];
    // --- clear old option list ---
    officeObj.length = 0;
    // --- set default select option ---
    officeObj[0] = new Option(CAR_SELECT_PICKUP_DEFAULT_VALUE, '');
    // --- fill offices ---
    for (i=0; i < officeList[cityCode].length; i++) {
        valuePair = officeList[cityCode][i].split('|');
        officeObj[i+1] = new Option(valuePair[1], valuePair[0]);
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Builds the return location/office select options
*/
function populateReturnLocations(formObj){
    countryCode = formObj[CAR_START_COUNTRY].value;
    // --- get data and object ---
    returnCityObj = formObj[CAR_END_LOCATION];
    if (!countryCode || !returnCityObj) {
        if (returnCityObj) returnCityObj.length = 0;
        return;
    }
    // --- clear old option list ---
    returnCityObj.length = 0;
    // --- set default select option ---
    returnCityObj[0] = new Option('', '');
    // --- fill cities ---
    for (i=0; i < returnCityList[countryCode].length; i++) {
        valuePair = returnCityList[countryCode][i].split('|');
        returnCityObj[i+1] = new Option(valuePair[1], valuePair[0]);
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Removes all the countries that doesn't have any cities
*/
function cleanCountryList(formObj){
    countryObj = formObj[CAR_START_COUNTRY];
    for (i=1; i < countryObj.options.length; i++) {
        countryCode = countryObj.options[i].value;
        if (cityList[countryCode] == null || cityList[countryCode].length == 0) {
            countryObj.options[i] = null;
            i--;
        }
    }
}

/** ------------------------------------------------------------------------------------------------------------
* Enables or disables the other return office list. Also alerts the user about the extra one way cost that will
* be applied
*/
function enableOtherReturnList(formObj, isClicked){
    enabled = formObj[CAR_ONEWAY].checked;
    formObj[CAR_END_LOCATION].disabled = !enabled;

    if (formObj[CAR_ONEWAY].checked && isClicked)
        alert(ALERT_CAR_ONEWAY_INFO);
}

/** ------------------------------------------------------------------------------------------------------------
* Sets all the default values in the select boxes when user gets an error or returns to here from availability
* (also starts by cleaning the country list and ends with enable or disable the other return location select)
*/
function initCarForm(formObj, startCountry, startCity, startOffice, returnOffice){
    cleanCountryList(formObj);

    if (startCountry) {
        formObj[CAR_START_COUNTRY].selectedIndex = getIdxInSelectBox(formObj, CAR_START_COUNTRY, startCountry);
        populateCities(formObj);
        populateReturnLocations(formObj);
    }

    if (startCity) {
        formObj[CAR_START_LOCATION].selectedIndex = getIdxInSelectBox(formObj, CAR_START_LOCATION, startCity);
        populatePickUpLocations(formObj);
    }

    if (startOffice)
        formObj[CAR_START_PICKUP].selectedIndex = getIdxInSelectBoxStartsWith(formObj, CAR_START_PICKUP, startOffice);

    if (returnOffice)
        formObj[CAR_END_LOCATION].selectedIndex = getIdxInSelectBoxStartsWith(formObj, CAR_END_LOCATION, returnOffice);

    enableOtherReturnList(formObj, false);

    enableChildAgeField(formObj);
}

// *****************************************************************************************************************
// Quicksearch calendar function
// *****************************************************************************************************************

/** ------------------------------------------------------------------------------------------------------------
* Opens a window to pick date in
*
**/
function SelectDate(startEnd, formName, monthObj, dayObj, inUrl) {
    formNameControl = formName;
    monthControl = monthObj;
    dayControl = dayObj;

    myDate = eval(monthObj.value).toString();
    myYear = myDate.substring(0,4);
    myMonth = myDate.substring(4,6);
    myDay = eval(dayObj.value).toString();
    myUrl = inUrl + "&year=" + myYear + "&month=" + myMonth + "&day=" + myDay + "&formName=" + formName + "&startEnd=" + startEnd;
    calWin = window.open(myUrl, 'Calendar', 'width=260, height=265, toolbar=no, titlebar=no, scrollbars=no');
    calWin.moveTo(220,180)
}

/** ------------------------------------------------------------------------------------------------------------
* Function called from the window with the datePicker
*
**/
function setDate(inYear, inMonth, inDay) {

    var i=0;
    var selboxnumber;

    // It has to be two numbers in the month
    if(parseInt(inMonth) < 10)
        inMonth = "0" + parseInt(inMonth);

    // Select month
    while(monthControl.options[i])
    {
        if(monthControl.options[i].value == inYear + "" + inMonth)
        {
            monthControl.options[i].selected = true;
            break;
        }
        i++;
    }

    // Now select the day
    i = 0;
    while(dayControl.options[i])
    {
        if(dayControl.options[i].value == inDay)
        {
            dayControl.options[i].selected = true;
            break;
        }
        i++;
    }

    if (formNameControl == FORMNAME_FLT_SEARCH) {
        // Update return month and day in search flight form
        if (monthControl == eval('document.'+FORMNAME_FLT_SEARCH+'.'+FORM_PARAM_D_MONTH)){
            selboxnumber = '1';
        } else {
            selboxnumber = '2';
        }
        changeDates(selboxnumber, 'document.'+FORMNAME_FLT_SEARCH);
        changeDates(selboxnumber, 'document.'+FORMNAME_FLT_SEARCH);

    } else if (formNameControl == FORMNAME_HTL_SEARCH) {
        if (monthControl == eval('document.'+FORMNAME_HTL_SEARCH+'.'+FORM_PARAM_D_MONTH)){
            selboxnumber = '1';
        } else {
            selboxnumber = '2';
        }
        changeDates(selboxnumber, 'document.'+FORMNAME_HTL_SEARCH);
        changeDates(selboxnumber, 'document.'+FORMNAME_HTL_SEARCH);

    } else if (formNameControl == FORMNAME_PKG_SEARCH) {
        if (monthControl == eval('document.'+FORMNAME_PKG_SEARCH+'.'+FORM_PARAM_D_MONTH)){
            selboxnumber = '1';
        } else {
            selboxnumber = '2';
        }
        changeDates(selboxnumber, 'document.'+FORMNAME_PKG_SEARCH);
        changeDates(selboxnumber, 'document.'+FORMNAME_PKG_SEARCH);

    } else if (formNameControl == FORMNAME_CAR_SEARCH) {
        if (monthControl == eval('document.'+FORMNAME_CAR_SEARCH+'.'+FORM_PARAM_D_MONTH)){
            selboxnumber = '1';
        } else {
            selboxnumber = '2';
        }
        changeDates(selboxnumber, 'document.'+FORMNAME_CAR_SEARCH);
        changeDates(selboxnumber, 'document.'+FORMNAME_CAR_SEARCH);
    }
}


// *****************************************************************************************************************
// Search page functions
// *****************************************************************************************************************

function updateTripType (formObj, inValue) {
    var oldStyle = !formObj["TRIP_TRIPTYPE_1"];
    display('returnCalTbl', !inValue)
    if (inValue)
        formObj[(oldStyle?TRIPTYPE:"TRIP_TRIPTYPE_1")].value = TRIPTYPE_ONEWAY;
    else
        formObj[(oldStyle?TRIPTYPE:"TRIP_TRIPTYPE_1")].value = TRIPTYPE_ROUNDTRIP;
}

function updateDateRange (inRange, inValue){
    document.getElementById(inRange).value = 'H0';
    if (inValue)
        document.getElementById(inRange).value = 'H1';
}

// *****************************************************************************************************************
// Freeclie form search function
// *****************************************************************************************************************

/**
 * Function that opens the genLocationSearch
 * @param productType the type of product, flight, hotel or package
 * @param ignoreProductType if the product type should be ignored in the database request
 * @param fieldname the name of the textfield that the result should append to
 */
function showFindLocation(productType, iataname, fieldname) {

    var htmlLink = '/main?type=General&name=GenLocationSearch';
      //var htmlLink = htmlLinkContext + '/flow/GFindLocation/GFindLocationStart.do';
      var querystr="&productType="+productType+"&fieldName="+fieldname+"&fieldNameIATA="+iataname;
      //window.open(htmlLink,'showFindLocation','scrollbars=yes,resizable=yes,width=617,height=400');
      window.open(htmlLink+querystr,'airlines','scrollbars=yes,resizable=yes,width=617,height=400');

}

/**
 * Refers to fltSearch,
 * Sets the fetched value to the specific field in the parant window
 * @param name the name of the city/airport selected by the user
 * @param code the IATA-code of the city/airport
 * @param iatafieldtoset the hidden field that the IATA-code are going to be stored in
 * @param fieldtoset  the name of the field visible to the user
 */
function setParentValues(name, code, iatafieldtoset, fieldtoset){
    window.opener.setValues(name,code,iatafieldtoset,fieldtoset);
     window.close();
}

/**
 * Refers to fltSearch,
 * Sets the code and the name to the two fields
 * @param name the name of the city/airport selected by the user
 * @param code the IATA-code of the city/airport
 * @param iatafieldtoset the hidden field that the IATA-code are going to be stored in
 * @param fieldtoset  the name of the field visible to the user
 */
function setValues(name, code, iatafieldtoset, fieldtoset) {
  //alert("fieldtoset="+fieldtoset);
  var fieldform1 = eval(fieldtoset);
  var iatafield = eval(iatafieldtoset);
  fieldform1.value = name;
  iatafield.value = code;
}

// *****************************************************************************************************************
// Cruise function
// *****************************************************************************************************************

function changeCruiseFlightDates(formObj) {

    var _DAY = 24*60*60*1000;

    formObj[START_MONTH_CRU_FLT_FIELD].selectedIndex = formObj[START_MONTH_FIELD].selectedIndex;
    rebuildDaySelectWithFields(formObj, 'start', true, START_DAY_CRU_FLT_FIELD, '', START_MONTH_CRU_FLT_FIELD, '');
    formObj[START_DAY_CRU_FLT_FIELD].selectedIndex = formObj[START_DAY_FIELD].selectedIndex;

    var startYearMonth = formObj[START_MONTH_CRU_FLT_FIELD].options[formObj[START_MONTH_CRU_FLT_FIELD].selectedIndex].value;
    var startDay = formObj[START_DAY_CRU_FLT_FIELD].options[formObj[START_DAY_CRU_FLT_FIELD].selectedIndex].value;

    // add two days to selected cruise date
    var d = new Date();
    d.setTime(0); // clear current date
    d.setFullYear(startYearMonth.substr(0,4), (tlIntParser(startYearMonth.substr(4,2))-1), startDay);
    d.setMilliseconds(d.getMilliseconds()+(_DAY*2));

    var returnYear = d.getFullYear()+"";
    var returnMonth = (d.getMonth()+1)+"";
    if (returnMonth < 10)
        returnMonth = "0"+returnMonth;
    var returnYearMonth = returnYear+""+returnMonth;

    var returnDay = d.getDate();
    if (returnDay < 10)
        returnDay = "0"+returnDay;

    // set year, month and day in flight return select boxes
    var i;
    for (i=0; i < formObj[END_MONTH_CRU_FLT_FIELD].options.length; i++) {
        if (formObj[END_MONTH_CRU_FLT_FIELD].options[i].value == returnYearMonth) {
            formObj[END_MONTH_CRU_FLT_FIELD].selectedIndex = i;
            break;
        }
    }
    rebuildDaySelectWithFields(formObj, 'end', true, '', END_DAY_CRU_FLT_FIELD, '', END_MONTH_CRU_FLT_FIELD);
    for (i=0; i < formObj[END_DAY_CRU_FLT_FIELD].options.length; i++) {
        if (formObj[END_DAY_CRU_FLT_FIELD].options[i].value == returnDay) {
            formObj[END_DAY_CRU_FLT_FIELD].selectedIndex = i;
            break;
        }
    }
}

var ChildDD = {
		drawDDs: function(childCount, childAgesArray, rowid) {					  
			var childCountArr = $('.dtaRawChildAge' + rowid).val().split(',');			
			var out = '';            

			for(var i=0; i<childCount; i++) {
				var idkey = TRIP_CHILD_AGES + '_DD' + (i+1) + '_' + rowid;
				var tabindex = parseInt($('.dtaTripChildren'+rowid).attr('tabindex')) + i;
				out += '<div data-role="fieldcontain" class="flow-text-age-left">';
				out += '<label for="'+idkey+'" class="hidden"></label>';
				out += '<select class="dtaTripChildrenAgeDD" data-rowid="'+rowid+'" name="'+idkey+'" id="'+idkey+'" tabindex="'+tabindex+'">';				
				out += '<option value="-" selected="selected">-</option>';
				out += '<option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option>';
				out += '<option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option>';
				out += '<option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option>';
				
				//For later ...
//				if(QS_HAS_FLIGHT == "true") {
//					out += '<option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option>';
//                }		         
                out += '</select>';
                out += '</div>';                
                $('#dtaTripChildrenAgeDynamic'+rowid).append(out).trigger("create");
                if(childAgesArray != null) {
                	$("select#"+idkey)[0].selectedIndex = parseInt(childAgesArray[i])+1;
                	if (IS_MOBILE_SESSION == "true") { 
                        $("select#"+idkey).selectmenu("refresh");
                    }
                }
                out = '';
			}                    

			if(childCount > 0) {
				$('#dtaTripChildrenAgeDynamic'+rowid).prepend($('#dtaTripChildrenAgeDynamicHeader').html());				
			}	

		return out;
	}
};


//Activate the event handlers on the children DDs
$(document).ready(function() {
	TLUtils.activateChildAge();
});

