/* =====================================================================================================================
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;

		if ((formObj == FORM_FLT || formObj == LP_FORM_FLT) && !validateAge(formObj, GEN_NO_OF_CHILDREN, GEN_CHILD_AGES, 15, AGE_EXAMPLE_VALUE))
			return;

		if ( (formObj == FORM_PKG || formObj == FORM_HTL || formObj == LP_FORM_PKG || formObj == LP_FORM_HTL) && !checkAge(formObj))
			return;

		if ( (formObj == FORM_CAR || formObj == LP_FORM_CAR) && !validateAge(formObj, GEN_NO_OF_CHILDREN, GEN_CHILD_AGES, 11, AGE_EXAMPLE_VALUE) )
			return;

		if ( formObj == FORM_CRU_FLT && !validateAge(formObj, GEN_NO_OF_CHILDREN, GEN_CHILD_AGES, 17, AGE_EXAMPLE_VALUE) )
			return;

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

	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';
					chooseFlowTransition(formObj, 'detailed-search');
				}
			}

			// alert user of mismatches for the child ages (but will still move her to the detailed search page)
			checkAge(formObj);
		}

		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].selectedIndex = fromForm[START_MONTH_FIELD].selectedIndex
		toForm[START_DAY_FIELD].selectedIndex = fromForm[START_DAY_FIELD].selectedIndex
		toForm[END_MONTH_FIELD].selectedIndex = fromForm[END_MONTH_FIELD].selectedIndex
		toForm[END_DAY_FIELD].selectedIndex = fromForm[END_DAY_FIELD].selectedIndex
	}


// *****************************************************************************************************************
// 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){

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

	/** ------------------------------------------------------------------------------------------------------------
	* Checks the age input and sets them to their input fields
	*/
	function checkAge(formObj){

		if (formObj == FORM_PKG || formObj == LP_FORM_PKG) {
			// package
			childAgeBase = PKG_CHILD_AGE_BASE;
			childrenBase = PKG_CHILDREN_BASE;
			rooms = PKG_ROOMS;
			maxAge = 15;
		} else {
			// hotel
			childAgeBase = HTL_CHILD_AGE_BASE;
			childrenBase = HTL_CHILDREN_BASE;
			rooms = HTL_ROOMS;
			maxAge = 17;
		}

		// clean old values in hidden fields before doing anything
		for (i=1; i <= 4; i++) {
			for (j=1; j <= 3; j++)
				formObj[childAgeBase+i+j].value = '';
		}

		for (j=1; j <= (parseInt(formObj[rooms].value)); j++){
			if (formObj[childrenBase+j].selectedIndex > 0){
				rawChildAges = formObj['RAW_CHILD_AGE'+j].value = trimAllSpaces(formObj['RAW_CHILD_AGE'+j].value);
				if ( !setAgeVariables(formObj, rawChildAges, j, childrenBase, childAgeBase, maxAge) ){
					return false;
				}
			}
		}
		return true;
	}

	/** ------------------------------------------------------------------------------------------------------------
	* 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;
		}
	}

	/** ------------------------------------------------------------------------------------------------------------
	* Validates age input
	*/
	function validateAge(formObj, childrenField, agesField, maxAge, exampleValue){
		agesCorrect = true;
		numberOfChilds = formObj[childrenField].value;
		if (numberOfChilds == 0) {
			formObj[agesField].value = '';
			return true;
		}

		ages = formObj[agesField].value = trimAllSpaces(formObj[agesField].value);
		ageArray = (ages && ages != exampleValue ? ages.split(',') : new Array());
		if (numberOfChilds == ageArray.length) {
			for (i=0; i < ageArray.length && agesCorrect; i++) {
				if (isNaN(ageArray[i]))
					agesCorrect = false;
				else if (ageArray[i] < 0 || ageArray[i] > maxAge)
					agesCorrect = false;
			}
		} else
			agesCorrect = false;

		if (!agesCorrect)
			alert(ALERT_AGE_VALIDATION);

		return agesCorrect;
	}

	/** ------------------------------------------------------------------------------------------------------------
	* 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;
			}
		}
	}

	/** ------------------------------------------------------------------------------------------------------------
	* 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;
	}




// *****************************************************************************************************************
// 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) {
		if (formObj[ (bound == 'start' ? GEN_START_CITY : GEN_END_CITY) ].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 (i=0; i <= 4; i++){
			if ( i > 1 ) {
				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 (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));
	}





// *****************************************************************************************************************
// 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) {
        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[FLT_AIRLINE_ID+(i-1)].value = AIRLINE_CONTROL_FORM[FLT_AIRLINE_ID+i].value;
        }
        AIRLINE_CONTROL_COUNTER--;

        AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+AIRLINE_CONTROL_COUNTER].value = '';
        AIRLINE_CONTROL_FORM[FLT_AIRLINE_ID+AIRLINE_CONTROL_COUNTER].value = '';

        updateAirlineVisibility();
	}

	/** ------------------------------------------------------------------------------------------------------------
	* Sets an airline from pop-up
	*/
	function setAirline(sAirlineID, sAirlineName) {
        AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+AIRLINE_CONTROL_COUNTER].value = sAirlineName;
        AIRLINE_CONTROL_FORM[FLT_AIRLINE_ID+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;
		setAirline(aid, aname);
		selection.options.selectedIndex = 0;
	}

	/** ------------------------------------------------------------------------------------------------------------
	* Shows the selected airlines in their divs
	*/
	function updateAirlineVisibility() {
		for (i=0; i < 5; i++) {
			getDiv('airline'+i+'div').innerHTML = '- ' + AIRLINE_CONTROL_FORM[FLT_AIRLINE_NAME+i].value + ' <a href="javascript:removeAirline(' + i + ');">'+AIRLINE_REMOVE_LINK_NAME+'&nbsp;&raquo;</a><br/>';
			display('airline'+i+'div', (AIRLINE_CONTROL_COUNTER > i));
		}

		AIRLINE_CONTROL_FORM[FLT_NUM_OF_AIRLINES].value = AIRLINE_CONTROL_COUNTER;
	}

	/** ------------------------------------------------------------------------------------------------------------
	* 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);
        }
    }
    
    // *****************************************************************************************************************
    // Free 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;
			}
		}
	}
