var activeSearchType = '';
var travelersCount = '';
var uiValuesStorage = new Object();
var changedLocationsMap = [];
var activeSearchPanel = 'RT';
var rtSearchPanel;
var mcSearchPanel;
var LOCATION_CODE_LENGTH = 3;
var selectedPreferedAirlines = [];
var selectedLocations = [];

function saveAirSearchParamsToCookies()
{
	//TODO add additional parameters.
	var cookie = '';

	cookie += prepareCookieItem('typeOfSearch', activeSearchType);
	cookie += prepareCookieItem('departureOriginLocationText', getElementById("departureOriginLocationText").value);
	cookie += prepareCookieItem('departureDestLocationText', getElementById("departureDestLocationText").value);
	cookie += prepareCookieItem('returnOriginLocationText', getElementById("returnOriginLocationText").value);
	cookie += prepareCookieItem('returnDestLocationText', getElementById("returnDestLocationText").value);
	cookie += prepareCookieItem('departureOriginLocation', getElementById("departureOriginLocation").value);
	cookie += prepareCookieItem('departureDestLocation', getElementById("departureDestLocation").value);
	cookie += prepareCookieItem('returnOriginLocation', getElementById("returnOriginLocation").value);
	cookie += prepareCookieItem('returnDestLocation', getElementById("returnDestLocation").value);

	cookie += prepareCookieItem('departureDay', getElementById("departureDay").value);
	cookie += prepareCookieItem('departureMonthYear', getElementById("departureMonthYear").value);
	cookie += prepareCookieItem('departureTime', getElementById("departureTime").value);
	cookie += prepareCookieItem('returnDay', getElementById("returnDay").value);
	cookie += prepareCookieItem('returnMonthYear', getElementById("returnMonthYear").value);
	cookie += prepareCookieItem('returnTime', getElementById("returnTime").value);
	cookie += prepareCookieItem('preferedAirline[0]', getElementById("preferedAirline[0]").value);
	cookie += prepareCookieItem('preferedAirline[1]', getElementById("preferedAirline[1]").value);
	cookie += prepareCookieItem('preferedAirline[2]', getElementById("preferedAirline[2]").value);

	cookie += prepareCookieItem('travellersCount', getElementById("travelersCount").value);
	var maxNumberOfTrav = (UIConfig && UIConfig['AIR_PASSENGER_MAX_NUMBER']) ? new Number(UIConfig['AIR_PASSENGER_MAX_NUMBER']) : 8;
	for(var i = 0; i < maxNumberOfTrav; i++)
	{
		var travelerName = "travellerTypes[" + i + "]";
		cookie += prepareCookieItem(travelerName, getElementById(travelerName).value);
	}
	if(getElementById("directFlights") != null)
	{
		cookie += prepareCookieItem('directFlights', getElementById("directFlights").checked);
	}
	setCookie('AirFlightSearchForm', cookie);
}

function getCurrentSearchPanelType()
{
	if (activeSearchType == 'MC')
	{
		return 'MC';
	}
	else
	{
		return 'RT';
	}
}

sinch = {
	FORM : '',
	MC : 'MC',
	RT : 'RT',
	dates : function (from) {
		if (this.checkParams(from)) return;
		var to = this.getTo(from);

		getElementById('departureDay' + to).value = getElementById('departureDay').value = getElementById('departureDay' + from).value;
		getElementById('departureMonthYear' + to).value = getElementById('departureMonthYear').value = getElementById('departureMonthYear' + from).value;
		getElementById('departureTime' + to).value = getElementById('departureTime').value = getElementById('departureTime' + from).value;

		getElementById('returnDay' + to).value = getElementById('returnDay').value = getElementById('returnDay' + from).value;
		getElementById('returnMonthYear' + to).value = getElementById('returnMonthYear').value = getElementById('returnMonthYear' + from).value;
		getElementById('returnTime' + to).value = getElementById('returnTime').value = getElementById('returnTime' + from).value;
	},
	locations : function(from) {
		if (this.checkParams(from)) return;
		var to = this.getTo(from);
		getElementById('departureOriginLocationText' + to).value = getElementById('departureOriginLocationText').value = getElementById('departureOriginLocationText' + from).value;
		getElementById('departureDestLocationText' + to).value   = getElementById('departureDestLocationText').value = getElementById('departureDestLocationText' + from).value;
	},
	all : function(from) {
		this.dates(from);
		this.locations(from);
	},
	checkParams : function(from)
	{
		if (from != this.MC && from != this.RT && from != this.FORM) return true;
		return false;
	},
	getTo: function(from) {
		if (from == this.RT) return this.MC;
		if (from == this.MC) return this.RT;
	}
}

/*
 * Correct value of departure date control.
 */
function correctDepartureDate(suffix)
{
	var departureDayId = "departureDay" + suffix;
	var departureMonthYearId = "departureMonthYear" + suffix;
	var departureTimeId = 'departureTime' + suffix;
	var returnDayId = "returnDay" + suffix;
	var returnMonthYearId = "returnMonthYear" + suffix;

	var departureDate = getDateControlValue(departureDayId, departureMonthYearId);
	var returnDate = getDateControlValue(returnDayId, returnMonthYearId, UP_ROUNDING_MODE);
	var currentDate = new Date();
	if (returnDate.getTime() <= departureDate.getTime())
	{
		setDateControlValue(departureDayId, departureMonthYearId, returnDate.add(Date.DAY, -1 * AUTO_FILLING_RANGE));
		correctionDaysList(departureDayId, getElementById(departureMonthYearId).value, Date.patterns.MonthYear);
		changeDateOfWeek(departureDayId, departureMonthYearId);
		validateAirSearchDates(departureDayId, departureMonthYearId, departureTimeId, 'departureMonthYearBlock' + suffix,dateRange);
	}
}

/*
 * Correct value of return date control.
 */
function correctReturnDate(suffix)
{
	var departureDayId = "departureDay" + suffix;
	var departureMonthYearId = "departureMonthYear" + suffix;
	var returnDayId = "returnDay" + suffix;
	var returnMonthYearId = "returnMonthYear" + suffix;
	var returnTimeId = 'returnTime' + suffix;

	var departureDate = getDateControlValue(departureDayId, departureMonthYearId, DOWN_ROUNDING_MODE);
	var returnDate = getDateControlValue(returnDayId, returnMonthYearId);
	if (returnDate.getTime() <= departureDate.getTime())
	{
		setDateControlValue(returnDayId, returnMonthYearId, departureDate.add(Date.DAY, AUTO_FILLING_RANGE));
		correctionDaysList(returnDayId, getElementById(returnMonthYearId).value, Date.patterns.MonthYear);
		changeDateOfWeek(returnDayId, returnMonthYearId);
		validateAirSearchDates(returnDayId, returnMonthYearId, returnTimeId, 'returnMonthYearBlock' + suffix,dateRange);
	}
}

function changeDateControl(objDateCtrl)
{
	var dateControlId = objDateCtrl.id;
	var dayId = null;
	var monthYearId = null;
	var timeId = null;
	var blockId = null;

	if (dateControlId.indexOf('departure') != -1)
	{
		monthYearId = 'departureMonthYear' + activeSearchPanel;
		dayId = 'departureDay' + activeSearchPanel;
		timeId = 'departureTime' + activeSearchPanel;
		blockId = 'departureMonthYearBlock' + activeSearchPanel;
		correctReturnDate(activeSearchPanel);
	}
	else if (dateControlId.indexOf('return') != -1)
	{
		monthYearId = 'returnMonthYear' + activeSearchPanel;
		dayId = 'returnDay' + activeSearchPanel;
		timeId = 'returnTime' + activeSearchPanel;
		blockId = 'returnMonthYearBlock' + activeSearchPanel;
		//autoUpReturnDateField(dayId, monthYearId);
	}

	correctionDaysList(dayId, getElementById(monthYearId).value, Date.patterns.MonthYear);
	//if (dateControlId.indexOf('departure') != -1) {correctReturnDate(activeSearchPanel);}
	//else if (dateControlId.indexOf('return') != -1) {correctDepartureDate(activeSearchPanel);}
	
	changeDateOfWeek(dayId, monthYearId);
	
	
	if(Ext.get(timeId).dom.onchange)
	{
		Ext.get(timeId).dom.onchange();
	}
	else
	{
		validateAirSearchDates(dayId, monthYearId, timeId, blockId,dateRange);
	}
	
}

//validate return date is more then depart date
function validateReturnDate(suffix)
{
	var dateBlock = Ext.get('returnMonthYearBlock' + suffix);

	var departureDayId = "departureDay" + suffix;
	var departureMonthYearId = "departureMonthYear" + suffix;
	var returnDayId = "returnDay" + suffix;
	var returnMonthYearId = "returnMonthYear" + suffix;

	var departureDate = getDateControlValue(departureDayId, departureMonthYearId);
	var returnDate = getDateControlValue(returnDayId, returnMonthYearId);
	
	
	
	var msgs = dateBlock.query('.glbErrorText');
	for(var i=0; i<msgs.length; i++)
	{
    	Ext.get(msgs[i]).remove();
  	}

	if (returnDate.getTime() > departureDate.getTime())
	{
		dateBlock.dom.className = '';
		return true;
	}
	else
	{
		var msg = dateInvalidMessages['wrongReturn'];
		dateBlock.dom.className = 'glbErrorHilight';
		dateBlock.insertHtml('afterBegin','<p class="glbErrorText">' + msg + '</p>');

		try {
			var errorKey = dateInvalidMessageKeys['wrongReturn'];
			dcsMultiTrack('DCS.dcsuri','/errors/' + errorKey,'WT.ti',msg,'DCSext.UI_Error',errorKey,'DCSext.error_location',request_uri,'WT.cg_s',cg_s,'WT.si_x','','WT.si_n','');
		} catch(e) {}
	}
	return false;
}


function validateAirSearchDates(dayId, monthYearId, timeId, blockId,dateRange)
{
	if (activeSearchType == 'OW' || validateReturnDate(activeSearchPanel))
	{
		return _validateDateControls(dayId, monthYearId, timeId, blockId,dateRange);
	}
	return false;
}




function initTypeOfSearch(searchType)
{
	// if data loaded searchType might contain fake value
	if (isTypeOfSearchValid(searchType))
	{
		activeSearchType = searchType;
	}
	else
	{
		activeSearchType = 'RT';
	}

	activeSearchPanel = getCurrentSearchPanelType(activeSearchType);

	if(activeSearchType == "MC")
	{
		getElementById('flight-type3').checked = true;
	}
	else if(activeSearchType == "OW")
	{
		getElementById('flight-type2').checked = true;
	}
	else
	{
		getElementById('flight-type1').checked = true;
	};

	if (activeSearchType == "MC")
	{
		getElementById("flightSearchPanelRoundTrip").style.display = "none";
		getElementById("flightSearchPanelMunticity").style.display = "";
	}
	else
	{
		var returnDateFieldSet = getElementById("returnDateFieldSet");

		if (activeSearchType == 'RT')
		{
			returnDateFieldSet.style.display = "";
		}
		if (activeSearchType == 'OW')
		{
			returnDateFieldSet.style.display = "none";
		};

		getElementById("flightSearchPanelMunticity").style.display = "none";
		getElementById("flightSearchPanelRoundTrip").style.display = "";
	};

	initLocationSearchComboBoxes();
	validateAllDateControls();
}

function saveCurrentTypeOfSearch()
{
	if (getElementById('flight-type2').checked)
	{
		activeSearchType = 'OW';
		activeSearchPanel = 'RT';
	}
	else if (getElementById('flight-type3').checked)
	{
		activeSearchType = activeSearchPanel = 'MC';
	}
	else
	{
		activeSearchType = activeSearchPanel = 'RT';
	}
}

function isTypeOfSearchValid(typeOfSearch)
{
	if (typeOfSearch == 'RT' || typeOfSearch == 'OW' || typeOfSearch == 'MC')
	{
		return true;
	}
	return false;
}

function displaySearchPanel(searchType)
{
	if (searchType != activeSearchType)
	{
		sinch.dates(activeSearchPanel);
		saveCurrentTypeOfSearch();
		initTypeOfSearch(searchType);
		customValidateLocation('departureOriginLocation', false);
		customValidateLocation('departureDestLocation', false);
		changeDateOfWeek('departureDay' + activeSearchPanel, 'departureMonthYear' + activeSearchPanel);
		changeDateOfWeek('returnDay' + activeSearchPanel, 'returnMonthYear' + activeSearchPanel);
	}
}

function displayTravelers(travelersCount, maxTravelers)
{
	for(var i = 0; i < maxTravelers; i++)
	{
		var studentControl = getElementById('travelersStudent['+ i +']');
		var youthControl = getElementById('travelersUnder26['+ i +']');
		var teacherControl = getElementById('travelersTeacher['+ i +']');
		var travelerTypeControl = getElementById('travellerTypes['+ i + ']');
		var travelerRow = getElementById("travelerRow" + i);

		if(i < travelersCount)
		{
			if (travelerRow.style.display == 'none')
			{
				studentControl.checked = false;
				youthControl.checked = false;
				teacherControl.checked = false;
				studentControl.disabled = false;
				youthControl.disabled = false;
				teacherControl.disabled = false;
			}
			travelerRow.style.display = '';
		}
		else
		{
			travelerTypeControl.value = '';
			travelerRow.style.display = 'none';
		}
	}
	
	changeTravelersCheckboxesAvail();
}

function initTravelersCeckboxes(maxTravelers)
{
	if (travelersCount != null && travelersCount != "")
	{
		maxTravelers = travelersCount;
	}

	for(var i = 0; i < maxTravelers; i++)
	{
		var studentControl = getElementById('travelersStudent['+ i +']');
		var youthControl = getElementById('travelersUnder26['+ i +']');
		var teacherControl = getElementById('travelersTeacher['+ i +']');

		studentControl.checked = ((travelerTypes[i] == 'STU') || (travelerTypes[i] == 'SYT'));
		youthControl.checked = ((travelerTypes[i] == 'YTH') || (travelerTypes[i] == 'SYT'));
		teacherControl.checked = (travelerTypes[i] == 'OTH');
	}
}

function changeTravelersCheckboxesAvail()
{
	var travellersAmount = document.getElementById('travelersCount').value;
	
	var isStudentOrYouthSelected = false;
	var isTeacherSelected = false;

	for (var i = 0; i < travellersAmount; i++)
	{
		var studentControl = getElementById('travelersStudent['+ i +']');
		var youthControl = getElementById('travelersUnder26['+ i +']');
		var teacherControl = getElementById('travelersTeacher['+ i +']');
		
		isStudentOrYouthSelected = studentControl.checked || youthControl.checked;
		if (isStudentOrYouthSelected)
		{
			break;
		}
		isTeacherSelected = teacherControl.checked;
		if (isTeacherSelected)
		{
			break;
		}
	}
	
	for (var i = 0; i < travellersAmount; i++)
	{
		var studentControl = getElementById('travelersStudent['+ i +']');
		var youthControl = getElementById('travelersUnder26['+ i +']');
		var teacherControl = getElementById('travelersTeacher['+ i +']');
		
		if (isStudentOrYouthSelected)
		{
			teacherControl.checked = false;
			teacherControl.disabled = true;
		}
		else if (isTeacherSelected)
		{
			studentControl.checked = false;
			studentControl.disabled = true;
			youthControl.checked = false;
			youthControl.disabled = true;
		}
		else
		{
			studentControl.disabled = false;
			youthControl.disabled = false;
			teacherControl.disabled = false;
		}
	}
}

function  initLocationSearchComboBoxes()
{
	var departureOriginLocationId = 'departureOriginLocation';
	var departureDestLocationId = 'departureDestLocation';

	if (activeSearchPanel == 'RT')
	{
		var dubOriginsRT = {origin : 'departureOriginLocationTextRT', dest : ['departureOriginLocationText', 'departureOriginLocationTextMC']};
		var dubDestsRT = {origin : 'departureDestLocationTextRT', dest : ['departureDestLocationText', 'departureDestLocationTextMC']};

		createLocationSearchComboBox('departureOriginLocationTextRT', departureOriginLocationId, locationLoadingTitle, true, 'AirportLocationsSearch.do?isDepartureLocationLookup=true', dubOriginsRT);
		createLocationSearchComboBox('departureDestLocationTextRT', departureDestLocationId, locationLoadingTitle, true, 'AirportLocationsSearch.do?isDepartureLocationLookup=false', dubDestsRT);
	}

	if (activeSearchPanel == 'MC')
	{
		var dubOriginsMC = {origin : 'departureOriginLocationTextMC', dest : ['departureOriginLocationText', 'departureOriginLocationTextRT']};
		var dubDestsMC = {origin : 'departureDestLocationTextMC', dest : ['departureDestLocationText', 'departureDestLocationTextRT']};

		createLocationSearchComboBox('departureOriginLocationTextMC', departureOriginLocationId, locationLoadingTitle, true, 'AirportLocationsSearch.do?isDepartureLocationLookup=true', dubOriginsMC);
		createLocationSearchComboBox('departureDestLocationTextMC', departureDestLocationId, locationLoadingTitle, true, 'AirportLocationsSearch.do?isDepartureLocationLookup=false', dubDestsMC);

		createLocationSearchComboBox('returnOriginLocationText', 'returnOriginLocation', locationLoadingTitle, true, 'AirportLocationsSearch.do?isDepartureLocationLookup=false');
		createLocationSearchComboBox('returnDestLocationText', 'returnDestLocation', locationLoadingTitle, true, 'AirportLocationsSearch.do?isDepartureLocationLookup=true');
	}
}

function initDatesControls()
{
	correctionDaysList('departureDayMC', getElementById('departureMonthYearMC').value, Date.patterns.MonthYear);
	correctionDaysList('returnDayMC', getElementById('returnMonthYearMC').value, Date.patterns.MonthYear);
	correctionDaysList('departureDayRT', getElementById('departureMonthYearRT').value, Date.patterns.MonthYear);
	correctionDaysList('returnDayRT', getElementById('returnMonthYearRT').value, Date.patterns.MonthYear);
	changeDateOfWeek("departureDayMC", "departureMonthYearMC");
	changeDateOfWeek("returnDayMC", "returnMonthYearMC");
	changeDateOfWeek("departureDayRT", "departureMonthYearRT");
	changeDateOfWeek("returnDayRT", "returnMonthYearRT");
}

function checkLocations()
{
	var result = true;
	if(!customValidateLocation("departureOriginLocation", true))
	{
		result = false;
	}
	if(!customValidateLocation("departureDestLocation", true))
	{
		result = false;
	}
	if(getElementById('flight-type3') && getElementById('flight-type3').checked)
	{
		if(!customValidateLocation("returnOriginLocation", true))
		{
			result = false;
		}
		if(!customValidateLocation("returnDestLocation", true))
		{
			result = false;
		}
	}
	return result;
}

function validateAllDateControls()
{
	var owRes = validateAirSearchDates('departureDay'+activeSearchPanel, 'departureMonthYear'+activeSearchPanel, 'departureTime'+activeSearchPanel, 'departureMonthYearBlock'+activeSearchPanel, dateRange);
	if (activeSearchType != 'OW' && owRes)
	{
		return _validateDateControls('returnDay'+activeSearchPanel, 'returnMonthYear'+activeSearchPanel, 'returnTime'+activeSearchPanel, 'returnMonthYearBlock'+activeSearchPanel, dateRange);
	}
	return owRes;
}

function checkSearchForm()
{
	var result = checkLocations() && validateAllDateControls();
	setTimeout("isValidationRequired = true;", 250);
	return result;

}

function epm_submitSearchForm(obj)
{
	isValidationRequired = false;
	sinch.all(getCurrentSearchPanelType());
	if (checkSearchForm() && controls.checkAndLock())
	{
		objectSwapping.swap(obj);
		mapTravelerTypes();
		saveAirSearchParamsToCookies();
		document.forms['AirFlightSearchForm'].submit();
	}
}

function mapTravelerTypes()
{
	travellersAmount = document.getElementById('travelersCount').value;

	for (i = 0; i < travellersAmount; i++)
	{
		studentFlag = document.getElementById('travelersStudent['+ i +']').checked;
		youthFlag = document.getElementById('travelersUnder26['+ i +']').checked;
		teacherFlag = document.getElementById('travelersTeacher['+ i +']').checked;

		if (studentFlag && !youthFlag)
		{
			document.getElementById('travellerTypes['+ i + ']').value = 'STU';
		}

		if (!studentFlag && youthFlag)
		{
			document.getElementById('travellerTypes['+ i + ']').value = 'YTH';
		}

		if (studentFlag && youthFlag)
		{
			document.getElementById('travellerTypes['+ i + ']').value = 'SYT';
		}

		if (!studentFlag && !youthFlag)
		{
			if (teacherFlag)
			{
				document.getElementById('travellerTypes['+ i + ']').value = 'OTH';
			}
			else
			{
				document.getElementById('travellerTypes['+ i + ']').value = 'ADT';
			}
		}
	}
}

function getDateErrorMessage(monthYearId)
{
	if (monthYearId.indexOf('return') != -1)
	{
		return dateInvalidMessages['return'];
	}
	else
	{
		return dateInvalidMessages['departure'];
	}
}

function getDateErrorMessageKey(monthYearId)
{
	if (monthYearId.indexOf('return') != -1)
	{
		return dateInvalidMessageKeys['return'];
	}
	else
	{
		return dateInvalidMessageKeys['departure'];
	}
}

function loadAirSearchParamsFromCookies()
{
	var cookie = getCookie("AirFlightSearchForm");
	if (cookie == null)
	{
		return;
	};

	activeSearchType = staUnescape(getCookieItem("typeOfSearch", cookie));
	activeSearchPanel = getCurrentSearchPanelType();

	if ("" == activeSearchType)
	{
		return;
	}

	if (getElementById("departureOriginLocationText" + activeSearchPanel).value == '')
	{
		getElementById("departureOriginLocationText" + activeSearchPanel).value = selectedLocations['departureOriginLocationText'] = staUnescape(getCookieItem("departureOriginLocationText", cookie));
		getElementById("departureOriginLocation").value = staUnescape(getCookieItem("departureOriginLocation", cookie));
	}
	if (getElementById("departureDestLocationText" + activeSearchPanel).value == '')
	{
		getElementById("departureDestLocationText" + activeSearchPanel).value = selectedLocations['departureDestLocationText'] = staUnescape(getCookieItem("departureDestLocationText", cookie));
		getElementById("departureDestLocation").value = staUnescape(getCookieItem("departureDestLocation", cookie));
	}
	if (getElementById("returnOriginLocationText").value == '')
	{
		getElementById("returnOriginLocationText").value = selectedLocations['returnOriginLocationText'] = staUnescape(getCookieItem("returnOriginLocationText", cookie));
		getElementById("returnOriginLocation").value = staUnescape(getCookieItem("returnOriginLocation", cookie));
	}
	if (getElementById("returnDestLocationText").value == '')
	{
		getElementById("returnDestLocationText").value = selectedLocations['returnDestLocationText'] = staUnescape(getCookieItem("returnDestLocationText", cookie));	
		getElementById("returnDestLocation").value = staUnescape(getCookieItem("returnDestLocation", cookie));
	}

	/* Repopulation of date. */
	var departureDayId = "departureDay" + activeSearchPanel;
	var departureMonthYearId = "departureMonthYear" + activeSearchPanel;
	getElementById(departureDayId).value = staUnescape(getCookieItem("departureDay", cookie));
	getElementById(departureMonthYearId).value = staUnescape(getCookieItem("departureMonthYear", cookie));
	
	var departureTime = staUnescape(getCookieItem("departureTime", cookie));
	
	switch (departureTime) {
	case "A":
	case "M":
	case "N":
	case "E":
		break;
	default:
		departureTime = "A";
	}
	
	getElementById("departureTime" + activeSearchPanel).value = departureTime;

	var returnDayId = "returnDay" + activeSearchPanel;
	var returnMonthYearId = "returnMonthYear" + activeSearchPanel;
	getElementById(returnDayId).value = staUnescape(getCookieItem("returnDay", cookie));
	getElementById(returnMonthYearId).value = staUnescape(getCookieItem("returnMonthYear", cookie));
	
	var returnTime = staUnescape(getCookieItem("returnTime", cookie));
	
	switch (returnTime) {
	case "A":
	case "M":
	case "N":
	case "E":
		break;
	default:
		returnTime = "A";
	}
	
	getElementById("returnTime" + activeSearchPanel).value = returnTime;
	/* end. */

	getElementById("preferedAirline[0]").value = staUnescape(getCookieItem("preferedAirline[0]", cookie));
	getElementById("preferedAirline[1]").value = staUnescape(getCookieItem("preferedAirline[1]", cookie));
	getElementById("preferedAirline[2]").value = staUnescape(getCookieItem("preferedAirline[2]", cookie));


	sinch.all(activeSearchPanel);

	travelersCount = staUnescape(getCookieItem("travellersCount", cookie));

	if ("" == travelersCount)
	{
		return;
	}

	getElementById("travelersCount").value = travelersCount;

	for(var i = 0; i < travelersCount; i++)
	{
		var travelerType = staUnescape(getCookieItem("travellerTypes[" + i + "]", cookie));

		travelerTypes[i] = travelerType;
	}
	if(getElementById("directFlights") != null)
	{
		getElementById("directFlights").checked = getCookieItem("directFlights", cookie) == "true";
	}

}

function getControlValue(control)
{
	if(control == null)
	{
		return null;
	}
	return control.value;
}

function setControlValue(control, controlValue)
{
	if(controlValue != null)
	{
		control.value=controlValue;
	}
}

function countSelected(select,maxNumber)
{
	for(var i=0; i<select.options.length; i++)
	{
		if(!select.options[i].selected && selectedPreferedAirlines.indexOf(i)!=-1)
		{
	   		selectedPreferedAirlines.splice(selectedPreferedAirlines.indexOf(i), 1);
    	}
	}

	for(var i=0; i<select.options.length; i++)
	{
    	if(select.options[i].selected && selectedPreferedAirlines.indexOf(i)==-1)
     	{
        	selectedPreferedAirlines.push(i);
		}

		if(selectedPreferedAirlines.length > maxNumber)
  		{
			var result = true;
  			select.options[i].selected = false;
			selectedPreferedAirlines.pop();
		}
	}

	for(var i = 0; i < 3; i++)
	{
		var preferedAirlineControl = getElementById("preferedAirline[" + i + "]");
		if(i < selectedPreferedAirlines.length)
		{
			preferedAirlineControl.value = select.options[selectedPreferedAirlines[i]].value;
		}
		else
		{
			preferedAirlineControl.value = "";
		}
	}
	if(result == true)
    {
        select.focus();
    }
}

function customValidateLocation(locationControlId, validationOnEmptyRequired)
{
	changedLocationsMap[locationControlId] = true;
	var suffix = getCurrentSearchPanelType();
	if (locationControlId.indexOf('return') != -1)
	{
		suffix = 'MC';
	}
	return validateLocation(locationControlId, validationOnEmptyRequired, LOCATION_CODE_LENGTH, locationMaxLengthMessages, locationInvalidMessages, locationRequiredMessages, suffix);
}

function initPrefAirlinesSelect()
{
	var selectedPrefAirlinesCodes = new Array();

	var prefAirlinesControl = getElementById('preferedAirline');

	if (prefAirlinesControl == null)
	{
		return false;
	}

	for(var i = 0; i < 3; i++)
	{

		var prefAirline = getElementById('preferedAirline[' + i + ']').value;
		if(prefAirline != null && prefAirline != '')
		{
			selectedPrefAirlinesCodes.push(prefAirline);
		}
	}
	for(var i = 0; i < prefAirlinesControl.options.length; i++)
	{
		if(selectedPrefAirlinesCodes.indexOf(prefAirlinesControl.options[i].value) != -1)
		{
			prefAirlinesControl.options[i].selected = true;
			selectedPreferedAirlines.push(i);
		}
	}
}

function initSelectedLocations()
{
	selectedLocations["departureOriginLocationText"] = Ext.get("departureOriginLocationText").dom.value;
	selectedLocations["departureDestLocationText"] = Ext.get("departureDestLocationText").dom.value;

	var returnOriginTextControll = Ext.get("returnOriginLocationText");
	var returnDestTextControll = Ext.get("returnDestLocationText");

	if (returnOriginTextControll != null)
	{
		selectedLocations["returnOriginLocationText"] = returnOriginTextControll.dom.value;
	}
	if (returnDestTextControll != null)
	{
		selectedLocations["returnDestLocationText"] = returnDestTextControll.dom.value;
	}
}
