//alert('loading PropSearch');
function fillSelect(selectId, data) {
	var subtype = $(selectId);
	var count = 0;
	subtype.options.length = 0;
	$for (data, function(key, value) {
		//subtype.options[count] = new Option(value,key);
		if (key=="" && count >0) {
			var elOptOld = subtype.options[0];  
			var elOptNew = new Option(value,key)
			try {
			subtype.options.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
			}
			catch(ex) {
			subtype.options.add(elOptNew, 0); // IE only
			}
		} else {
			subtype.options.add(new Option(value,key));
		}
		subtype.options[count].className = 'price_select';
		count = count + 1;
	});
	subtype.selectedIndex = 0;
}
function fillSelectWithTitle(selectId, data, emptyTitle) {
	fillSelect(selectId, data);
	var subtype = $(selectId);
	if (subtype.options[0]) {
		subtype.options[0].text = emptyTitle;
		/*subtype.options[0].style.color = "rgb(230, 0, 92)";*/
		/*subtype.options[0].style.fontWeight = "bold";*/
	}
}
function fillSubtype(searchTypeValue) {
	if (searchTypeValue == '1') {
		fillSelect('subtype_1', $('typeOfContract_1_1').checked ? searchSubtype1_1 : searchSubtype1_2);
	} else if (searchTypeValue == '2') {
		fillSelect('subtype_2', $('typeOfContract_2_1').checked ? searchSubtype2_1 : searchSubtype2_2);
	} else if (searchTypeValue == '99') {
		fillSelect('subtype_99', $('typeOfContract_99_1').checked ? searchSubtype99_1 : searchSubtype99_2);
	}
	onSearchSubTypeChange();
}
function fillRealSubtypes() {
	var searchTypeValue = $('searchType').value;
	if ($('subtype_' + searchTypeValue).value) {
		fillSelect('realestate_subtype_' + searchTypeValue,realSubtypes[$('subtype_' + searchTypeValue).value]);
	} else {
		fillSelect('realestate_subtype_' + searchTypeValue,realSubtypes[searchTypeValue]);
	}
	if (searchTypeValue == 1) {
		if ($('subtype_' + searchTypeValue).value == 199 ||
			$('realestate_subtype_' + searchTypeValue).options.length <= 2) {
			$('realestate_subtype_1').style.display='none';
		} else {
			$('realestate_subtype_1').style.display='inline';
		}
	}
}
function onSearchSubTypeChange() {
	var searchTypeValue = $('searchType').value;
	if (searchTypeValue == '1') {
		subtypeValue = $('subtype_1').value;
		if (subtypeValue && (subtypeValue == '108' || subtypeValue == '199')) {
			//disable all advanced dropdowns
			$('extsearchbox_price').style.visibility = 'hidden';
			$('extsearchbox_room').style.visibility = 'hidden';
			$('extsearchbox_area').style.visibility = 'hidden';
		} else {
			//enable all advanced dropdowns
			$('extsearchbox_price').style.visibility = 'visible';
			$('extsearchbox_room').style.visibility = 'visible';
			$('extsearchbox_area').style.visibility = 'visible';
		}
	}
}
function fillPrices(searchTypeValue) {
	switch (searchTypeValue) {
		case '6':
		case '99':
			break;
		case '3':
		case '4':
		case '5':
			fillSelectWithTitle('price_from_' + searchTypeValue, price[$('searchType').value],textFrom);
			fillSelectWithTitle('price_to_' + searchTypeValue, price[$('searchType').value],textTo);
			break;
		default:
			fillSelectWithTitle('price_from_' + searchTypeValue, $('typeOfContract_' + searchTypeValue + '_1').checked ? price[$('searchType').value][1] : price[$('searchType').value][2],textFrom);
			fillSelectWithTitle('price_to_' + searchTypeValue, $('typeOfContract_' + searchTypeValue + '_1').checked ? price[$('searchType').value][1] : price[$('searchType').value][2],textTo);
	}
}
function applySelectValues(searchTypeValue) {
	fillSubtype(searchTypeValue);
	fillPrices(searchTypeValue);
}
function changeSearchType(_value) {

	var hiddenFieldId, id_to_hide, id_to_show, tab_to_inactive, tab_to_active;
	var td1ToInactive, td2ToInactive, td3ToInactive;
	var td1ToActive, td2ToActive, td3ToActive;
	var leftNeighbor;
	
	hiddenFieldId='searchType';
	id_to_hide = 'div_searchtype_' + $(hiddenFieldId).value;

	var currentTab = positions[parseInt($(hiddenFieldId).value)];
	var activeTab = positions[_value];

	// make the currently selected TAB inactive
	td1ToInactive = document.getElementById('advSearchTab_' + $(hiddenFieldId).value + '_1');
	td2ToInactive = document.getElementById('advSearchTab_' + $(hiddenFieldId).value + '_2');
	td3ToInactive = document.getElementById('advSearchTab_' + $(hiddenFieldId).value + '_3');	

	td2ToInactive.className = 'search_buttoninactive';
	td2ToInactive.innerHTML = '<div id="advSearchText_' + $(hiddenFieldId).value + '" class="search_buttoninactive_text"><a href="javascript:void(0);" onclick="changeSearchType(' + $(hiddenFieldId).value + ')" class="searchnavioben">' + searchTypesArray[parseInt($(hiddenFieldId).value)] + '</a></div>';

	if (currentTab == 1) {
		td1ToInactive.innerHTML = search_left_inactive;		
	} else {
		td1ToInactive.innerHTML = '';
	} 
	
	if (currentTab + 1 != activeTab) {
		td3ToInactive.innerHTML = search_right_inactive;		
	} else {
		td3ToInactive.innerHTML = '';		
	}
	
	// make inactive the right border of the tab which is at the left of the active
	if (activeTab > 1) {
		leftNeighbor = document.getElementById('advSearchTab_' + (activeTab - 1) + '_3');
		leftNeighbor.innerHTML = '';
	}
	
	// make active the right border of the tab which was at the left of the active
	if (currentTab > 1) {
		leftNeighbor = document.getElementById('advSearchTab_' + (currentTab - 1) + '_3');
		leftNeighbor.innerHTML = search_right_inactive;
	}	
	
	// make the currently selected TAB inactive
	td1ToActive = document.getElementById('advSearchTab_' + _value + '_1');
	td2ToActive = document.getElementById('advSearchTab_' + _value + '_2');
	td3ToActive = document.getElementById('advSearchTab_' + _value + '_3');

	td1ToActive.innerHTML = search_left_active;
	td2ToActive.className = 'search_buttonactive';
	td2ToActive.innerHTML = '<div id="advSearchText_' + _value + '" class="search_buttonactive_text">' + searchTypesArray[parseInt(_value)] + '</div>';
	td3ToActive.innerHTML = search_right_active;
	
	// set the currently selected type of just actived value	
	$(hiddenFieldId).value=_value;
	
	id_to_show = 'div_searchtype_' + $(hiddenFieldId).value;

	if (id_to_hide != id_to_show) {
		$(id_to_hide).style.display='none';
		$(id_to_show).style.display='inline';
		applySelectValues(_value);
	}

/*	OLD CODE

	var hiddenFieldId, id_to_hide, id_to_show, tab_to_inactive, tab_to_active;
	hiddenFieldId='searchType';
	if ($(hiddenFieldId).value != _value) {
		tab_to_inactive = 'searchTab' + $(hiddenFieldId).value;
		id_to_hide = 'div_searchtype_' + $(hiddenFieldId).value;
		$(hiddenFieldId).value = _value;
		tab_to_active = 'searchTab' + $(hiddenFieldId).value;
		id_to_show = 'div_searchtype_' + $(hiddenFieldId).value;
		setTabActive(tab_to_inactive,false);
		setTabActive(tab_to_active,true);
		$(id_to_hide).style.display='none';
		$(id_to_show).style.display='inline';
		applySelectValues(_value);
	} */
}
function onTypeAvailChange(_type) {
	var value = ($('typeAvail_' + _type).value == '3') ? false:true;
	$('date_avail_'+_type+'_day').disabled = value;
	$('date_avail_'+_type+'_month').disabled = value;
	$('date_avail_'+_type+'_year').disabled = value;
}
function onTypeOfContractChange() {
	var searchTypeValue = $('searchType').value;
	applySelectValues(searchTypeValue);
}
function isZip(_value) {
	return _value.substring(0, 1).match(/^\d+$/);
}

function setRangeAvail() {
//	var searchTypeValue = $('searchType').value;
//	var funct = function(exists) {
//		//$('time_dist_range_'+searchTypeValue).disabled = !exists;
//		$('time_dist_range_'+searchTypeValue).disabled = false;
//	};
//	var cityName = $('city_'+searchTypeValue).value;
//	var countryId = $('country_'+searchTypeValue).value;
//	var regionId = $('region_'+searchTypeValue).value;
//	if (cityName && countryId == 214) {
//		if (isZip(cityName)) {
//			pubFacade.isZipCodeExists(countryId,regionId,cityName,
//				{callback:funct});
//		} else {
//			try {
//				pubFacade.isCityExists(countryId,regionId,cityName,
//					{callback:funct});
//			} catch (ex) {
//				// Error while calling isCityExists function
//			}
//		}
//	} else {
//		//$('time_dist_range_'+searchTypeValue).disabled = true;
//		$('time_dist_range_'+searchTypeValue).disabled = false;
//	}
}
function onCityNameChange() {
	getCityLocation();
	setRangeAvail();
}
function onCityZipRadioChange() {
	/*var searchTypeValue = $('searchType').value;
	if ($('rad_city_' + searchTypeValue).checked) {
		$('city_select_' + searchTypeValue).style.display = "inline";
		$('zip_select_' + searchTypeValue).style.display = "none";
		$('div_city_' + searchTypeValue).style.display = "inline";
		$('div_zip_' + searchTypeValue).style.display = "none";
	} else {
		$('city_select_' + searchTypeValue).style.display = "none";
		$('zip_select_' + searchTypeValue).style.display = "inline";
		$('div_city_' + searchTypeValue).style.display = "none";
		$('div_zip_' + searchTypeValue).style.display = "inline";
	}*/
}
function getRegionFromServer(countryId) {
	pubFacade.retrieveRegions(countryId,
		{callback:function(list){
			if (list) {
				regions[countryId] = list;
				fillRegions();
			} else {
				regions[countryId] = new Array();
				fillRegions();
			}
		}
	});
}
function fillRegions() {
	/*var searchTypeValue = $('searchType').value;
	countryId=$('country_' + searchTypeValue).value;
	if  ( countryId && (countryId != '0')) {
		if (!regions[countryId]) {
			regions[countryId] = getRegionFromServer(countryId);
			return;
		}
		fillSelect('region_' + searchTypeValue, regions[countryId]);
	} else {
		$('region_' + searchTypeValue).options.length = 0;
	}
	fillCitiesAndZips();*/
}
function fillCitiesAndZips() {
//	fillCities();
//	fillZips();
}
function getCitiesFromServer(countryId,regionId) {
	/*pubFacade.retrieveCities(countryId,regionId,
		{callback:function(list){
			if (list) {
				if (regionId && (regionId != '0')) {
					citiesByRegion[regionId] = list;
				} else {
					citiesByCountry[countryId] = list;
				}
				fillCities();
			} else {
				if (regionId && (regionId != '0')) {
					citiesByRegion[regionId] = new Array();
				} else {
					citiesByCountry[countryId] = new Array();
				}
				regions[countryId] = new Array();
				fillCities();
			}
		}
	});*/
}
function fillCities() {
	/*var searchTypeValue = $('searchType').value;
	countryId=$('country_' + searchTypeValue).value;
	regionId=$('region_' + searchTypeValue).value;
	if  ( countryId && (countryId != '0')) {
		if  ( regionId && (regionId != '0')) {
			if (!citiesByRegion[regionId]) {
				getCitiesFromServer(countryId,regionId);
				return;
			}
			fillSelect('city_select_' + searchTypeValue, citiesByRegion[regionId]);
		} else {
			if (!citiesByCountry[countryId]) {
				getCitiesFromServer(countryId,'');
				return;
			}
			fillSelect('city_select_' + searchTypeValue, citiesByCountry[countryId]);
		}
	} else {
		$('city_select_' + searchTypeValue).options.length = 0;
	}*/
}
function getZipFromServer(countryId,regionId) {
	/*pubFacade.retrieveZipCodes(countryId,regionId,'',
		{callback:function(list){
			if (list) {
				if (regionId && (regionId != '0')) {
					zipsByRegion[regionId] = list;
				} else {
					zipsByCountry[countryId] = list;
				}
				fillZips();
			} else {
				if (regionId && (regionId != '0')) {
					zipsByRegion[regionId] = new Array();
				} else {
					zipsByCountry[countryId] = new Array();
				}
				regions[countryId] = new Array();
				fillZips();
			}
		}
	});*/
}
function fillZips() {
	/*var searchTypeValue = $('searchType').value;
	countryId=$('country_' + searchTypeValue).value;
	regionId=$('region_' + searchTypeValue).value;
	if  ( countryId && (countryId != '0')) {
		if  ( regionId && (regionId != '0')) {
			if (!citiesByRegion[regionId]) {
				getZipFromServer(countryId,regionId);
				return;
			}
			fillSelect('zip_select_' + searchTypeValue, zipsByRegion[regionId]);
		} else {
			if (!citiesByCountry[countryId]) {
				getZipFromServer(countryId,'');
				return;
			}
			fillSelect('zip_select_' + searchTypeValue, zipsByCountry[countryId]);
		}
	} else {
		$('zip_select_' + searchTypeValue).options.length = 0;
	}*/
}
function fillCityName() {
	var searchTypeValue = $('searchType').value;
	var index = $('city_select_' + searchTypeValue).selectedIndex;
	if (index != -1) {
		$('city_' + searchTypeValue).value = $('city_select_' + searchTypeValue).options[index].text;
	}
}
function fillZipName() {
	var searchTypeValue = $('searchType').value;
	var index = $('zip_select_' + searchTypeValue).selectedIndex;
	if (index != -1) {
		$('zip_' + searchTypeValue).value = $('zip_select_' + searchTypeValue).options[index].text;
	}
}
function fillFormFromHiddenFields(_type) {
	//setTabActive('searchTab'+_type,true);
	if ((_type != 3) && (_type != 4) && (_type != 5)) {
		if ($('typeOfContract').value) {
			if ($('typeOfContract').value == 1)
				$('typeOfContract_'+_type+'_1').checked = true;
			else
				$('typeOfContract_'+_type+'_2').checked = true;
		}
	}
	onTypeOfContractChange();
	if ($('country').value) {
		$('country_'+_type).value = $('country').value;
	}
	if ($('region').value) {
		$('region_'+_type).value = $('region').value;
	}
	if ($('zip').value) {
		/*$('rad_zip_'+_type).checked = true
		onCityZipRadioChange();*/
		$('city_'+_type).value = $('zip').value;
	} else {
		$('city_'+_type).value = $('city').value;
	}
	
	if ($('range').value) {
		$('time_dist_range_'+_type).value=$('range').value+':1';
	}

/*	if ($('coordinateX').value) {
		parameters['coordinateX'] = $('coordinateX').value;
	}
	if ($('coordinateY').value) {
		parameters['coordinateY'] = $('coordinateY').value;
	}
*/
	
//	if ($('timeRange').value) {
//		$('time_dist_range_'+_type).value=$('timeRange').value+':2';
//	}
	if ($('radius').value) {
		if($('map_radius')) {
		$('map_radius').value=$('radius').value;
	    }	
	}	
	
	if ($('searchSubType').value) {
		$('subtype_'+_type).value = $('searchSubType').value;
		onSearchSubTypeChange();
	}
	if ($('priceFrom').value) {
		$('price_from_'+_type).value = $('priceFrom').value;
	}else if($('price_from_'+_type)!=null){
		$('price_from_'+_type).selectedindex = 0;
	}
	
	if ($('priceTo').value) {
		$('price_to_'+_type).value = $('priceTo').value;
	} else if($('price_to_'+_type)!=null) {
		$('price_to_'+_type).selectedindex = 0;
	}
	
	if ((_type == '1') || (_type == '4')) {
		if ($('amountOfRoomsFrom').value) {
			$('rooms_from_'+_type).value = $('amountOfRoomsFrom').value;
		} else {
			$('rooms_from_'+_type).selectedIndex = 0;
		}
		if ($('amountOfRoomsTo').value) {
			$('rooms_to_'+_type).value = $('amountOfRoomsTo').value;
		} else {
			$('rooms_to_'+_type).selectedIndex = 0;
		}
	}
	
	if ($('areaFrom').value) {
		if ((_type == '1') || (_type == '2') || (_type == '7')){
			$('area_from_'+_type).value = $('areaFrom').value;
		}else {
			$('area_from_'+_type).selectedIndex = 0;
		}
	}
	if ($('areaTo').value) {
		if ((_type == '1') || (_type == '2') || (_type == '7')){
			$('area_to_'+_type).value = $('areaTo').value;
		}else{
			$('area_to_'+_type).selectedindex = 0;
		}
		
	}
	if ($('publicationAge').value) {
		$('publication_age_'+_type).value = $('publicationAge').value;
	}
	if (_type != '99') {
		if ($('availabilityType').value) {
			$('typeAvail_'+_type).value = $('availabilityType').value;
		}
		if ($('year').value) {
			$('date_avail_'+_type+'_year').value = $('year').value;
			$('typeAvail_'+_type).value = '3';
		}
		if ($('month').value) {
			$('date_avail_'+_type+'_month').value = $('month').value;
			$('typeAvail_'+_type).value = '3';
		}
		if ($('day').value) {
			$('date_avail_'+_type+'_day').value = $('day').value;
			$('typeAvail_'+_type).value = '3';
		}
		onTypeAvailChange(_type);
	}
	if ($('description').value) {
		$('description_'+_type).value = $('description').value;
	}
	/*if ($('durationHoliday').value) {
		$('duration_4').value = $('durationHoliday').value;
	}*/
	if ($('persons').value) {
		$('persons_4').value = $('persons').value;
	}
	if ($('durationWG').value) {
		$('duration_5').value = $('durationWG').value;
	}
	if ($('furnitured').value) {
		$('furnitured_5').value = $('furnitured').value;
	}
	
	//onTypeAvailChange('1');
	//onTypeAvailChange('2');
	//onTypeAvailChange('3');
	//onTypeAvailChange('4');
	//onTypeAvailChange('5');
	//onTypeAvailChange('6');
	//onTypeAvailChange('7');
	//onTypeAvailChange('99');
}

/**
 * Variable to store city coordinates fetched in location call-back function
 */
var cityCoord;
var cityLocationFlag;
/**
 * Call-back function for GClientGeocoder
 * @param point city location 
 */
function cityLocationCallback1 (point) {
	if(point){
		cityCoord = point;
	}
}

/**
 * Function to fetch city location basing on city address or ZIP code
 */
function getCityLocation() {
	var searchTypeValue = $('searchType').value;
	var cityName = $('city_' + searchTypeValue).value;
	var countrySelect = $('country_' + searchTypeValue);
	var searchString = cityName;
	
	// Save current city value to cityLocationFlag
	cityLocationFlag = cityName;
	
	if(countrySelect) {
		var countryText = countrySelect.options[countrySelect.selectedIndex].text;
		searchString += ', ' + countryText;
	}
		var geocoder = new GClientGeocoder();
	geocoder.getLatLng(searchString, cityLocationCallback1);
}

function fillParameters(parameters) {
	var value;
	var field;
	var _type = $('searchType').value;
	parameters['searchType'] = _type;

	field = $('agency');
	if (field){
		parameters['agency'] = field.value;
	}

	field = $('typeOfContract_'+_type+'_1');
	if (field)
		parameters['typeOfContract'] = field.checked ? 1 : 2;
		
	field = $('country_'+_type);
	value = field.value;
	if (value && (value != '0'))
		parameters['country'] = value;

	field = $('region_'+_type);
	value = field.value;
	if (value && (value != '0'))
		parameters['region'] = value;

		
	if ($('city_'+_type).value != '' && $('city_'+_type).value!=defaultCityValue) {
		/* If the first letter in the textbox is number - then user entered ZIP code */
		if (isZip($('city_'+_type).value)) {
			field = $('city_'+_type);
			value = field.value;
			if (value && (value != '0'))
				parameters['zip'] = value;
		} else {
			field = $('city_'+_type);
			value = field.value;
			if (value && (value != '0'))
				parameters['city'] = value;
		}
	}

	field = $('time_dist_range_'+_type);
	if (!field.disabled) {
		var rType = field.value.split(':')[1];
		value = field.value.split(':')[0];
//		if(value && value!='0') {
//			if(rType==1) {
				parameters['range'] = value;
				parameters['radius'] = value;
//			} else {
//				parameters['timeRange'] = value;
//			}
//		}
	}
    if (parameters['country'] == 214){
    
		field = $('map_radius');
		if(field) {
			value = field.value;
			if (value && (value != '0'))
				parameters['radius'] = value;
		}

		//field = $('circle_search');
		//value = field.value;
		if (typeof(mapLatitude) != "undefined")
			parameters['latitude'] = mapLatitude;
		if (typeof(mapLongitude) != "undefined")
			parameters['longitude'] = mapLongitude;
	}
	field = $('subtype_'+_type);
	if (field) {
		value = field.value;
		if (value && (value != '0'))
			parameters['searchSubType'] = value;
	}
	if ( (_type == '4') || ((_type == '1') && $('extsearchbox_room').style.visibility != 'hidden') ) {
		field = $('rooms_from_'+_type);
		if (field) {
		value = field.value;
		if (value && (value != '0'))
			parameters['amountOfRoomsFrom'] = value;
		}
		
		field = $('rooms_to_'+_type);
		if (field) {
			value = field.value;
			if (value && (value != '0'))
				parameters['amountOfRoomsTo'] = value;
		}
	}
	if ((_type != '1') || ($('extsearchbox_price').style.visibility != 'hidden')) {
		field = $('price_from_'+_type);
		if (field) {
			value = field.value;
			if (value && (value != '0'))
				parameters['priceFrom'] = value;
		}
				
		field = $('price_to_'+_type);
		if (field) {
			value = field.value;
			if (value && (value != '0'))
				parameters['priceTo'] = value;
		}
	}
	
	if ( ((_type == '1') && ($('extsearchbox_area').style.visibility != 'hidden') ) || (_type == '2')  || (_type == '7')) {
		field = $('area_from_'+_type);
		if (field) {
			value = field.value;
			if (value && (value != '0'))
				parameters['areaFrom'] = value;
		}
		field = $('area_to_'+_type);
		if (field) {
			value = field.value;
			if (value && (value != '0'))
				parameters['areaTo'] = value;
		}
	}
	
	/* Only if advanced options are enabled */
	if (advancedSearchFlag) {	
	
		field = $('publication_age_'+_type);
		value = field.value;
		if (value && (value != '-1'))
			parameters['publicationAge'] = value;
			
		if (_type != '99') {
			field = $('typeAvail_'+_type);
			value = field.value;
			if (value && (value != '0')) {
				parameters['availabilityType'] = value;
				if (value == '3') {
				field = $('date_avail_'+_type+'_day');
				value = field.value;
				if (value && (value != '0'))
					parameters['day'] = value;
					
				field = $('date_avail_'+_type+'_month');
				value = field.value;
				if (value && (value != '0'))
					parameters['month'] = value;
					
				field = $('date_avail_'+_type+'_year');
				value = field.value;
				if (value && (value != '0'))
					parameters['year'] = value;
				}
			}
		}
	}
	
	field = $('description_'+_type);
	value = field.value;
		
	var defDescr = defaultDescriptions[_type];
	if (value && (value != '0') && value!=defDescr)
		parameters['description'] = value;					

	if (_type == '4') {
		/*field = $('duration_4');
		value = field.value;
		if (value && (value != '0'))
			parameters['durationHoliday'] = value;
		*/	
		field = $('persons_4');
		value = field.value;
		if (value && (value != '0'))
			parameters['persons'] = value;
			
	} else if (_type == '5') {
		field = $('duration_5');
		value = field.value;
		if (value && (value != '0'))
			parameters['durationWG'] = value;
			
		field = $('furnitured_5');
		value = field.value;
		if (value && (value != '0'))
			parameters['furnitured'] = value;
	}
	
	if(agencyID!='undefined' && agencyID!=null) {
		parameters['agencyID']=agencyID;
	}
	
	// Add coordinateX/coordinateY if available
	 if((cityLocationFlag == parameters['city'] || cityLocationFlag == parameters['zip']) && cityCoord && parameters['range']
	 && parameters['range'] != '0' && (parameters['zip'] || parameters['city'])){
		parameters['coordinateY'] = cityCoord.lat();
		parameters['coordinateX'] = cityCoord.lng();
	} else {
		parameters['coordinateY'] = null;
		parameters['coordinateX'] = null;
		if(parameters['city'] && (cityLocationFlag != parameters['city'] || !cityCoord) 
				&& !(parameters['range'] && parameters['range'] == '0')) {
			parameters['coordsNotFound'] = 'true';
		}
	}

}
function fillParametersFromHiddenField(parameters) {
	if ($('searchTypeInit').value) {
		parameters['searchType'] = $('searchTypeInit').value;
	}
	if ($('typeOfContract').value) {
		parameters['typeOfContract'] = $('typeOfContract').value;
	}
	if ($('country').value) {
		parameters['country'] = $('country').value;
	}
	if ($('region').value) {
		parameters['region'] = $('region').value;
	}
	if ($('zip').value) {
		parameters['zip'] = $('zip').value;
	} 
	if ($('city').value) {
		parameters['city'] = $('city').value;
	}
	if ($('range').value) {
		parameters['range'] = $('range').value;
	}
	
	if ($('coordinateX').value) {
		parameters['coordinateX'] = $('coordinateX').value;
	}
	
	if ($('coordinateY').value) {
		parameters['coordinateY'] = $('coordinateY').value;
	}
	
//	if ($('timeRange').value) {
//		parameters['timeRange'] = $('timeRange').value;
//	}
	if ($('radius').value) {
		parameters['radius'] = $('radius').value;
	}	
	if ($('searchSubType').value) {
		parameters['searchSubType'] = $('searchSubType').value;
	}
	if ($('priceFrom').value) {
		parameters['priceFrom'] = $('priceFrom').value;
	}
	if ($('priceTo').value) {
		parameters['priceTo'] = $('priceTo').value;
	}
	if ($('amountOfRoomsFrom').value) {
		parameters['amountOfRoomsFrom'] = $('amountOfRoomsFrom').value;
	}
	if ($('amountOfRoomsTo').value) {
		parameters['amountOfRoomsTo'] = $('amountOfRoomsTo').value;
	}
	if ($('areaFrom').value) {
		parameters['areaFrom'] = $('areaFrom').value;
	}
	if ($('areaTo').value) {
		parameters['areaTo'] = $('areaTo').value;
	}
	if ($('publicationAge').value) {
		parameters['publicationAge'] = $('publicationAge').value;
	}
	if ($('availabilityType').value) {
		parameters['availabilityType'] = $('availabilityType').value;
	}
	if ($('day').value) {
		parameters['day'] = $('day').value;
	}
	if ($('month').value) {
		parameters['month'] = $('month').value;
	}
	if ($('year').value) {
		parameters['year'] = $('year').value;
	}
	if ($('description').value) {
		parameters['description'] = $('description').value;
	}
	/*if ($('durationHoliday').value) {
		parameters['durationHoliday'] = $('durationHoliday').value;
	}*/
	if ($('persons').value) {
		parameters['persons'] = $('persons').value;
	}
	if ($('durationWG').value) {
		parameters['durationWG'] = $('durationWG').value;
	}
	if ($('furnitured').value) {
		parameters['furnitured'] = $('furnitured').value;
	}
	if ($('userID').value) {
		parameters['userID'] = $('userID').value;
	}
	if ($('agencyID').value) {
		parameters['agencyID'] = $('agencyID').value;
	}
}
function fillParametersWithPaginationAndOrder(parameters) {
	fillParametersWithPagination(parameters);
	fillParametersWithOrder(parameters);
}
function fillParametersWithPagination(parameters) {
	if ($('pagesize').value) {
		parameters['pagesize'] = $('pagesize').value;
	}
	if ($('page').value) {
		parameters['page'] = $('page').value;
	}
}
function fillParametersWithOrder(parameters) {
	if ($('orderasc').value) {
		parameters['orderasc'] = $('orderasc').value;
	}
	if ($('orderfields').value) {
		parameters['orderfields'] = $('orderfields').value;
	}
}

var parameters;
var locFlag;

function doSearch(loc) {
    //var parameters = new Array();
	parameters = new Array();
	locFlag = loc;
	parameters['action'] = searchStyle;
	
	// Get city location 
	getCityLocation();
	// Wait Google Maps callback for 1s
	setTimeout("continueSearch();", 1000);
	return false;
}

function continueSearch() {
	fillParameters(parameters);
	$for (parameters, function(key, value) {
		parameters[key]=encodeURIComponent(parameters[key]);

	});
	redirect('/' + locFlag + '/index/search', parameters);
}

function doCreateSearchAgent(isAuthenticated,loc) {
	var parameters = new Array();
	fillParameters(parameters);
	var url = contextPath + '/'+loc+'/index/secure/agent?no_rewrite=1&from=';
	url += escape(window.location.href);
	url += '&parameters=';
	url += encodeURI(getParamString(parameters));
	//alert(window.location.href + '\n\n' + encodeURI(getParamString(parameters)));
	if(isAuthenticated) {
		window.location.href = url;
	} else {
		window.location.href=contextPath+'/'+loc+'/index/register?search_agent=1&redirectUrl='+encodeURIComponent(url);
	}
	return false;
}

function setPage(_page) {
	$('page').value = _page;
	var parameters = new Array();
	parameters['action'] = searchStyle;
	fillParametersFromHiddenField(parameters);
	fillParametersWithPaginationAndOrder(parameters);
		$for (parameters, function(key, value) {
		parameters[key]=encodeURIComponent(parameters[key]);
	});
	redirect('/index/search',parameters);
	return false;
}
function doOrder(_order, loc,isAsc) {
	var _isAsc = true;
	$('orderfields').value = _order;
	if($('orderfields').value==_order) {
		_isAsc=!($('orderasc').value=="true");
	}
	$('orderasc').value = (isAsc!=null && isAsc!='undefined') ? isAsc : _isAsc;
	$('page').value = 1;
	var parameters = new Array();
	parameters['action'] = searchStyle;
	fillParametersFromHiddenField(parameters);
	fillParametersWithPaginationAndOrder(parameters);
	$for (parameters, function(key, value) {
		parameters[key]=encodeURIComponent(parameters[key]);
	});
	redirect('/' +loc+ '/index/search',parameters);
	return false;
}

function setOrder(value, loc) {
	var values = value.split(":");
	return doOrder(values[0],loc,values[1]);
}

function setSelect(el,value) {
	var sc=el.options;
	for(var i=0;i<sc.length;i++) {
		if(sc[i].value==value) {
			sc[i].selected=true;
			break;
		}
	}
}

setSelect($('sDoOrder'),$('orderfields').value+":"+$('orderasc').value);
if($('sDoOrder1')) {
	setSelect($('sDoOrder1'),$('orderfields').value+":"+$('orderasc').value);
}

var mouseX = 0;
var mouseY = 0;
var isIE = document.all?true:false;
if (!isIE) document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = getMousePosition;
function getScrollY() {
      var scrOfY = 0;
      if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
      } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
      } else if( document.documentElement &&
          (document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
      }
      return scrOfY;
 }
function getScrollX() {
      var scrOfX = 0;
      if( typeof( window.pageXOffset ) == 'number' ) {
        //Netscape compliant
        scrOfX = window.pageXOffset;
      } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfX = document.body.scrollLeft;
      } else if( document.documentElement &&
          (document.documentElement.scrollLeft ) ) {
        //IE6 standards compliant mode
        scrOfX = document.documentElement.scrollLeft;
      }
      return scrOfX;
 }
function getMousePosition(e) {
	if (isIE) {
		mouseX = getScrollX() + event.clientX;
	    mouseY = getScrollY() + event.clientY;
	} else {
		mouseX = e.pageX;
    	mouseY = e.pageY;
	}
}
fillFormFromHiddenFields($('searchType').value);

var propId=new Array();
function checkProperty(id) {
	var i=strIndexOf(propId,id);
	if(i>=0) {
		propId.splice(i,1);
	} else {
		propId.push(id);
	}
}

function strIndexOf(array,id) {
	var i=0;
	while(i<array.length) {
		if(array[i].toString()==id.toString()){
			return i;
		}
		i++;
	}
	return -1;
}

function checkCheckBoxes(isChecked) {
	var c = document.getElementsByName("checkboxes");
	if (c && c.length) {					
		for (var i = 0; i < c.length; i++) {
			if(c[i].value!=0) {
				var j=strIndexOf(propId,c[i].value);
				if(isChecked && j<0) {
					propId.push(c[i].value);
				} else if(!isChecked) {
					propId.splice(j,1);
				}
			}
			c[i].checked = isChecked;
		}
	}
}
	
function checkOrUncheckkAll(checkbox) {
	if (checkbox.checked) {
		checkCheckBoxes(true);
	} else {
		checkCheckBoxes(false);
	}
}

var USER_NOT_FOUND = 2, PROPERTY_NOT_FOUND = 3, ERROR = 4;
var AUTH_EXCEPTION = 'AuthenticationCredentialsNotFoundException';
var NOTHING_TO_ADD, USER_NOT_FOUND_MSG, PROPERTY_NOT_FOUND_MSG, ERROR_MSG, FAVORITES_UPDATED_MSG, LOGING_REQUIRED_MSG,LOADING;
function addfavoritesByIds(ids, isAuthenticated, loc) {
	DWRUtil.useLoadingMessage(LOADING);
	if (!isAuthenticated) {
		window.location.href = contextPath +
			"/"+loc+"/index/register?search_agent=1&redirectUrl=" + 
			encodeURIComponent(window.location.href);
		return;
	}
	secureFacade.addFavorites(ids, { 
		callback:function(results) {
			var hasError = false;
			$for (results, function(key, value) {
				switch(value) {
					case USER_NOT_FOUND: alert(USER_NOT_FOUND_MSG);hasError=true; break;
					case PROPERTY_NOT_FOUND: alert(PROPERTY_NOT_FOUND_MSG);hasError=true; break;
					case ERROR: alert(ERROR_MSG);hasError=true; break;
				}
			});
			
			if(!hasError) {
				alert(FAVORITES_UPDATED_MSG);
			}
		}, 
		errorHandler:function(errorString, exception) {
			if(exception.javaClassName.indexOf(AUTH_EXCEPTION)>=0) {
				alert(LOGING_REQUIRED_MSG);
			}
		}
	});
}
function addFavorites(isAuthenticated, loc) {
	if(propId.length==0) {
		alert(NOTHING_TO_ADD);
		return;
	}
	addfavoritesByIds(propId, isAuthenticated, loc);
}
function fillAutocompleteData(startChars,maxResults) {
	if (isZip(startChars)) {
		getZipsFromServer(startChars,maxResults);
	} else {
		getCitiesFromServer(startChars,maxResults);
	}
}
function onAutocompleteSelect() {
	onCityNameChange();
}
function getArrayFromList(list) {
	var result = new Array();
	for(var key in list) {
		result[key] = new Array();
		var temp = list[key].split('/');
		for (var i=0;i<temp.length;i++) {
			var temp2 = temp[i].split(':');
			if (temp2.length == 2) {
				result[key][temp2[0]]=
				customUnescape(temp2[1]);
			}
		}
	}
	return result;
}
function getCitiesFromServer(startChars,maxResults) {
	var parameters = new Array();
	fillParameters(parameters);
	var paramstring = getParamString(parameters);
	pubFacade.retrieveCitiesAndPropertiesCount(startChars,maxResults,paramstring,
		{callback:function(list){
			if (list) {
				autocompleteArray = getArrayFromList(list);
				showInfo = false;
				optionalShowAutocomplete(startChars);
			}
		}
	});
}
function getZipsFromServer(startChars,maxResults) {
	var parameters = new Array();
	fillParameters(parameters);
	var paramstring = getParamString(parameters);
	pubFacade.retrieveZipsAndPropertiesCount(startChars,maxResults,paramstring,
		{callback:function(list){
			if (list) {
				autocompleteArray = getArrayFromList(list);
				showInfo = false;
				optionalShowAutocomplete(startChars);
			}
		}
	});
}
function hide(e,value) {
	if(value==e.value) {
		e.value='';
	}
}
function show(e,value) {
	if(e.value=='') {
		e.value=value;
	}
}
function getSearchRadius() {
	var select = document.getElementById('time_dist_range_1');
	var radius;
	if(select) {
		var value = select.options[select.selectedIndex].value;
		var selectedOption = value.split(':');
		radius = selectedOption[0];
	}
	searchRadius = new Number(radius);
	searchRadius *= 1000;
}
function isLowIEVersion() {
 try{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if (version < 7.0) 
   {
	return true;
   } else {
	return false;
   }
}
  catch(e) {};

  return false;
}

var onLoadFn = window.onload;

window.onload = function () {
	//getCityLocation();
	
	// check if city location was fetched
	var url = '' + window.location;
	var isCityLocation = url.indexOf("coordsNotFound:true");
	if(isCityLocation != -1) {
		var warningDiv = $('coordsNotFoundDiv');
		if(warningDiv) {
			warningDiv.style.display = "block";
		}
	}
	
	// Load old onload function
	if (onLoadFn) {
		onLoadFn();
	}
}
