// rimuovere appena possibile
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

var countries = {},
	pois = {},
	_timeout = [],
	cities = {},
	current_addresses = {},
	current_hotels = {},
	default_label_hotel = "hotel",
	_elementIds_to_disable = ['outboundDay','outboundMonthYear',
		'returnDay', 'returnMonthYear',
		'adults', 'children', 'rooms' ,'idCurrency'],
		_elementIds_to_hide = ['outboundCalendar', 'returnCalendar']
	;
function country(id, latitude, longitude, zoom){
	this.id = id;
	this.latitude = latitude;
	this.longitude = longitude;
	this.zoom = zoom;
}
function city(id, name){
	this.id = id;
	this.name = name;
	this.latitude = 0;
	this.longitude = 0;
	this.hotels = 0;
	this.title = 'Clicca per selezionare e vedere sulla mappa';
}
function poi(id, city, country, language, description, latitude, longitude){
	this.id = id;
	this.city = city;
	this.country = country;
	this.language = language;
	this.description = description;
	this.latitude = latitude;
	this.longitude = longitude;
}
function getCities(type, value){}
function updateCurrentAddresses(listbox) {
	if(typeof listbox == "undefined"){
		listbox = addressCities_listbox;
	}
	try{
		for(var i = 0, option = "", l = current_addresses.length; i < l; i++){
			if(current_addresses[i].street != null && current_addresses[i].street.length > 0){
				option += "<span style='font-weight: bold;'>" + current_addresses[i].street + "</span>, ";
			}
			if(current_addresses[i].zip != null){
				option += current_addresses[i].zip + " ";
			}
			option += current_addresses[i].city;
			if (current_addresses[i].streetLine && (current_addresses[i].street.length == 0 || current_addresses[i].city.length == 0)){
				option = current_addresses[i].streetLine;
			}
			listbox.addOption(option, i, false);
		}
		if(!i && popup_noResult){
			alert(popup_noResult);
		}
		if(i && $('addr_circle_D'))
			$('addr_circle_D').src = "imgs/circle_D_orange.gif";
	}catch(e){}
}

function buildAddress(street, zip, no){
	var addr = "";
	addr += $F(street);
	if($F(no).length > 0){
		addr += " , " + $(no).value;
	}
	if($F(zip).length == 5){
		addr += " , " + $(zip).value;
	}
	$('complete_address').value = addr;
}

function getAddresses(country_fld, city_fld, street, doClean, listbox){
	if(typeof listbox == "undefined"){
		listbox = addressCities_listbox;
	}
	try{
		if($('search_address_img').src.indexOf('search_address_gray.gif') > 0 || $('search_address_button').src.indexOf('search_address_gray.gif') > 0){
			return false;
		}
	}catch(e){}
	var streetEl = $(street),
		city = $(city_fld),
		pars = ""
	;

	if(!streetEl){
		pars = "country=" + $F(country_fld) + "&address=" + $F(city) + "&city=";
	}else{
		if(!$F(streetEl) && !$F(city_fld)){
			alert(pupoup_address);
			return false;
		}
		if($('_spinner_addr')){
			Element.show('_spinner_addr');
		}
		var country = $(country_fld);
		if(country && city){
			pars = 'country=' + $F(country_fld) + '&city=' + $F(city_fld) + '&address=' + $F(street);
		}else{
			var split1 = $F("city").split(" - "),
				split2 = split1[1].split(":")
			;
			pars = "country=" + split2[0] + "&city=" + split1[0] + "&address=" + $F(street);
		}
	}
	listbox.reset();
	current_addresses = new Object();
	$("_spinner_addr").show();
	new Ajax.Request("addresses.do",{
		method: 'post',
		parameters: pars,
		onFailure: function(originalRequest) {
			handleError(originalRequest);
		},
		evalScripts : false,
		onComplete: function(transport) {
			try{
				var res = transport.responseText;
				$('addresses_obj').value = res;
				current_addresses = eval(res);
				updateCurrentAddresses(listbox);
				var spinner = $('_spinner_addr'),
					as = $("address_search_spinner")
				;
				spinner && spinner.hide();
				as && as.hide();
			}catch(e){
				alert(e)
			}
		}
	});
	return false;
}

function updateCurrentHotels(){
	try{
		for(var i = 0, l = current_hotels.length; i < l; i++){
			var option = "";
			if(current_hotels[i].name) {
				option += "<span style='font-weight: bold;'>" + current_hotels[i].name + "</span>, ";
			}
			if(current_hotels[i].zip){
				option += current_hotels[i].zip + " ";
			}
			if(current_hotels[i].city != null){
				option += current_hotels[i].city + " ";
			}
			hotels_listbox.addOption(option, i, false);
		}
		if(!i){
			alert(popup_noResult);
		}
	}catch(e){}
}

function getHotels(cityAndCountryElement, name) {
	var cityAndCountry = $F(cityAndCountryElement);
	if(!cityAndCountry || !name){
		return false;
	}
	var split1 = cityAndCountry.split(" - "),
		city = split1[0],
		split2 = split1[1].split(":"),
		country = split2[0],
		pars = 'country=' + country + "&city=" + city + "&name=" + name
	;
	hotels_listbox.reset();
	current_hotels = new Object();

	$("get_hotels_spinner").show();
	new Ajax.Request("hotels2.do",{
		method: 'post',
		parameters: pars,
		onFailure: function(originalRequest) {
			handleError(originalRequest);
		},
		evalScripts : false,
		onComplete: function(transport) {
			var res = transport.responseText;
			current_hotels = eval(res);
			updateCurrentHotels();
			$("get_hotels_spinner").hide();
		}
	});
	return false;
}
function getWindowContent(originalRequest, type){
	if(originalRequest.responseText != -1){
		var htmlresponse = originalRequest.responseXML.getElementsByTagName("city"),
			cityObj
		;
		for(var a = 0, l = htmlresponse.length; a < l; a++){
			if(htmlresponse[a].getAttribute('id') != null && htmlresponse[a].getAttribute('id') != undefined){
				cityObj = new city(htmlresponse[a].getAttribute('id'), htmlresponse[a].getAttribute('name'))
				cityObj.latitude = htmlresponse[a].getAttribute('latitude');
				cityObj.longitude = htmlresponse[a].getAttribute('longitude');
				cityObj.hotels = htmlresponse[a].getAttribute('n_hotels');
				cityObj.country = htmlresponse[a].getAttribute('country');
				cityObj.key = htmlresponse[a].getAttribute('key');

				if(!cityObj.latitude && !cityObj.longitude){
					cityObj.title = "Coordinate non disponibili";
				}

				var cityText = "<span title='" + cityObj.title + "' style='font-weight: bold;'>" + cityObj.name + "</span> - " + cityObj.country + "";
				if(cityObj.key && cityObj.key && cityObj.key != 'undefined' && cityObj.key != cityObj.name){
					cityText += " (" + cityObj.key + ")";
				}

				if(typeof label_hotel != "undefined" && label_hotel){
					cityText += " :" + cityObj.hotels + " " + label_hotel;
				}else{
					cityText += " :" + cityObj.hotels + " " + default_label_hotel;
				}
				type == "key" && cities_listbox.addOption(cityText, cityObj.id, false);
				if(type == "country"){
					cities2_listbox.addOption(cityText, cityObj.id, false);
					$('city_circle_A').src = "imgs/circle_A_gray.gif";
					$('city_circle_B').src = "imgs/circle_B_gray.gif";
				}
				cities[cityObj.id] = cityObj;
			}
		}
		type == "key" && ($('city_circle_B').src = 'imgs/circle_B_orange.gif');
		type == "country" && ($('city_circle_B2').src = "imgs/circle_B_orange.gif");
	}else{
		alert(popup_noCities);
	}
	_showSpinner(false);
	return;
}

function handleError(or){
	var rt = or.responseText;
	alert('Error sending request. \n Service temporary unavailable.\n' + rt);
	alert(pupup_errorSendingRequest + "\n" + rt);
	return;
}
function onSelectCityFunction(e, type){
	var idCity = e.getSelectedValues();
	if(idCity.size() == 1) {
		Form.Element.enable('max_distance_' + type);
	}else{
		Form.Element.disable('max_distance_' + type);
	}
	return;
}
function onSelectAddressFunction(){
	var idAddress = addressCities_listbox.getSelectedIndex();
	try{
		Form.Element.enable('max_distance_address');
	}catch(e){}
	return;
}

function onSelectHotelFunction(){
	var idHotel = hotels_listbox.getSelectedIndex();
	return;
}

function onSelectAddressForFilterFunction(listbox){
	if(typeof listbox == "undefined"){
		listbox = addressCities_listbox;
	}
	var idAddress = listbox.getSelectedIndex(),
		addressObj = current_addresses[idAddress]
	;
	if(typeof idAddress == "undefined"  || !idAddress || idAddress < 0){
		return;
	}
	if(addressObj && !addressObj.coordinates.latitude && !addressObj.coordinates.longitude){
		return;
	}
	$('latitude').value = addressObj.coordinates.latitude;
	$('longitude').value = addressObj.coordinates.longitude;
	$('addresses_idx').value = idAddress;
	$('sorting').value = 'DISTANCE';
	$('az').value = 'ASC';
	updateResultList();
	return;
}

function setSelectedCityDescription(idCity){
	if(idCity){
		var cityObj = cities[idCity];
		$('cityDescr').value = cityObj.name;
	}else{
		$('cityDescr').value = "";
	}
	return;
}

function resetCity(){
	cities_listbox.reset();
	cities = {};
}

function changeCountry(e){
	resetCity2();
	$('_src2').value = '';
	refreshCenterFromCountry(e.id);
	getCities('country', e.id);
}

function resetCity2(){
	cities2_listbox.reset();
	var cities2 = {};
	$('city_circle_B2').src = "imgs/circle_B_gray.gif";
}

function resetHotels(){
	hotels_listbox.reset();
	current_hotels = {};
}
function checkForm(){
	if(!($('idCity').value.indexOf(',') > 0)){
		updateWaitText();
	}else{
		$('waitspacer').style.height = "15px";
	}
	if(typeof cities2_listbox != "undefined" && cities2_listbox.getSelectedValues()){
		var vals = cities2_listbox.getSelectedValues();
		$('idCity').value = vals;
		if (vals.size() == 1) {
			$('latitude').value = cities[vals[0]].latitude;
			$('longitude').value = cities[vals[0]].longitude;
		}else{
			$('latitude').value = '';
			$('longitude').value = '';
		}
		$('addresses_idx').value = '';
		$('id_hotel').value = '';
		return true;
	}else if(typeof addressCities_listbox != "undefined" && addressCities_listbox && addressCities_listbox.selected.length > 0 && addressCities_listbox.getSelectedIndex() != null && addressCities_listbox.getSelectedIndex() != undefined
		&& addressCities_listbox.getSelectedIndex() >= 0){
		$('latitude').value = current_addresses[addressCities_listbox.getSelectedIndex()].coordinates.latitude;
		$('longitude').value = current_addresses[addressCities_listbox.getSelectedIndex()].coordinates.longitude;
		$('addresses_idx').value = addressCities_listbox.getSelectedIndex();
//		$('idCity').value = '';
		$('id_hotel').value = '';
		return true;
	}else if(typeof(hotels_listbox) != "undefined" && hotels_listbox != null && hotels_listbox.selected.length > 0 && hotels_listbox.getSelectedIndex() != null && hotels_listbox.getSelectedIndex() != undefined
		&& hotels_listbox.getSelectedIndex() >= 0) {
		$('id_hotel').value = current_hotels[hotels_listbox.getSelectedIndex()].index;
//		$('latitude').value = '';
//		$('longitude').value = '';
		$('addresses_idx').value = '';
		$('idCity').value = '';
		return true;
	} else if($('idCity').value != ""){
		return true;
	}
	return false;
}

function checkSearchType(){
	if ($('searchtype_all').checked){
		changeHomeSearchType(1);
	}else{
		changeHomeSearchType(0);
	}
}

function changeHomeSearchType(type){
	if(type == 0){
		for(var i = 0, l = _elementIds_to_disable.length; i < l; i++){
      try{
			$(_elementIds_to_disable[i]).enable();
      }catch(Exception){}
		}
		for (i = 0, l = _elementIds_to_hide.length; i < l; i++){
      try{
			Element.show(_elementIds_to_hide[i]);
      }catch(Exception){}
		}
		$('searchtype_all').checked = false;
		$('withAvailability').value = "Y";
	}else{
		if(typeof closeCalendar != "undefined") {
			closeCalendar();
		}
		for (i = 0, l = _elementIds_to_disable.length; i < l; i++){
      try{
			$(_elementIds_to_disable[i]).disable();
      }catch(Exception){}
		}
		for (i = 0, l = _elementIds_to_hide.length; i < l; i++){
      try{
        Element.hide(_elementIds_to_hide[i]);
        }catch(Exception){}
		}
		$('searchtype_all').checked = true;
		$('withAvailability').value = "N";
	}
}

function switchSearchTab(id_to_show, containerdiv) {
	var forms = new Array('city_search_fields', 'address_search_fields', 'hotel_search_fields'),
		show_come_description = false
	;
	if(id_to_show == 'hotel_search_fields'){
		$('additional_wait').innerHTML = "";
	}

	for(var i = 0, l = forms.length; i < l; i++){
		$('tab' + (i + 1)).className = id_to_show == forms[i] ? 'tab-orange' : 'tab-gray';
	}
	var url = 'templates/';
	if(id_to_show == "city_search_fields"){
		url += "searchByCity.jsp?isTab=true";
		show_come_description = true;
	}else if(id_to_show == "address_search_fields"){
		url += "searchByAddress.jsp";
	}else if(id_to_show == "hotel_search_fields"){
		url += "searchByHotel.jsp";
	}
	new Ajax.Updater(containerdiv, url, {method: 'get', evalScripts : true});

	for(i = 0, l = forms.length; i < l; i++){
		$('tab' + (i + 1)).className = id_to_show == forms[i] ? 'tab-orange' : 'tab-gray';
	}
	try{
		if(show_come_description){
			Element.show('come_description');
		}else{
			Element.hide('come_description');
		}
	}catch(e){}
	return;
	cities = {};
	cities_listbox.reset();

	current_addresses = {};
	addressCities_listbox.reset();
	current_hotels = {};
	hotels_listbox.reset();
	resetSearchLetters();
}

var disabledElements = null;

function onAfterLoadTab(id_to_show, buttonLabel){
	if(typeof buttonLabel != "undefined") {
		var button = $("verifica");
		button && (button.innerHTML = buttonLabel);
	}

	if(id_to_show == "city_search_fields"){
		disabledElements = ["max_distance_city"];
	}else if(id_to_show == "address_search_fields"){
		disabledElements = ["max_distance_address", "custom_address"];
	}else if(id_to_show == "hotel_search_fields"){
		disabledElements = ["hotel_name"];
		(typeof Autocompleter != "undefined") && LoadJS("js/controls.js");
		typeof Effect == "undefined" && LoadJS("js/effects.js");
	}
	if(disabledElements){
		for(var i = disabledElements.length - 1; i >= 0; i--){
			if(!$(disabledElements[i])){
				setTimeout("onAfterLoadTab('" + id_to_show + "')", 200);
				return;
			}
			$(disabledElements[i]).disabled = true;
		}
	}

	if(id_to_show == "hotel_search_fields"){
		current_hotels = {};
		hotels_listbox.reset();
	}
	startAutocompleter(id_to_show);

	var d = 
	{ searchtype_all   : $('searchtype_all')
	, outboundDay      : $('outboundDay')
	, outboundMonthYear: $('outboundMonthYear')
	, returnDay        : $('returnDay')
	, returnMonthYear  : $('returnMonthYear')
	, adults           : $('adults')
	, children         : $('children')
	, rooms            : $('rooms')
	, idCurrency       : $('idCurrency')
	};

	var searchAll         = d.searchtype_all    ? d.searchtype_all.checked          : false,
		outboundDay       = d.outboundDay       ? d.outboundDay.selectedIndex       : 0,
		outboundMonthYear = d.outboundMonthYear ? d.outboundMonthYear.selectedIndex : 0,
		returnDay         = d.returnDay         ? d.returnDay.selectedIndex         : 0,
		returnMonthYear   = d.returnMonthYear   ? d.returnMonthYear.selectedIndex   : 0,
		adults            = d.adults            ? d.adults.selectedIndex            : 0,
		children          = d.children          ? d.children.selectedIndex          : 0,
		rooms             = d.rooms             ? d.rooms.selectedIndex             : 0,
		idCurrency        = d.idCurrency        ? d.idCurrency.selectedIndex        : 0
	;
	Form.reset('search_form');
	if (d.searchtype_all)     { d.searchtype_all.checked           = searchAll;         }
	if (d.outboundDay)        { d.outboundDay.selectedIndex        = outboundDay;       }
	if (d.outboundMonthYear)  { d.outboundMonthYear.selectedIndex  = outboundMonthYear; }
	if (d.returnDay)          { d.returnDay.selectedIndex          = returnDay;         }
	if (d.returnMonthYear)    { d.returnMonthYear.selectedIndex    = returnMonthYear;   }
	if (d.adults)             { d.adults.selectedIndex             = adults;            }
	if (d.children)           { d.children.selectedIndex           = children;          }
	if (d.rooms)              { d.rooms.selectedIndex              = rooms;             }
	if (d.idCurrency)         { d.idCurrency.selectedIndex         = idCurrency;        }
}

function resetSearchLetters(){}

function startAutocompleter(id_to_show){
	if(!$("city_auto_complete")) {
		setTimeout("startAutocompleter('" + id_to_show + "')", 200);
		return;
	}
	new Ajax.Autocompleter('city', 'city_auto_complete', 'AutoCompletion?language=' + languageCode,{
		minChars: 3,
		indicator: "city_auto_complete_spinner",
		afterUpdateElement: function(text, li){
			idCity = document.getElementById("idCity");
			longitude = document.getElementById("longitude");
			latitude = document.getElementById("latitude");
			var tempStr = li.id,
				arrayCodes = tempStr.split(":")
			;
			idCity.value = arrayCodes[0];
			latitude.value = arrayCodes[1];
			longitude.value = arrayCodes[2];
			enableElements();
		},
		onShow: function(element, update){
			// Fix 090505 - angelo@exmachina.ch
			// In IE8 evaluted sizes are computed on visible elements only.
			// Set display *before* to clone the position.
			update.setStyle({display:"inline"});
			if(!update.style.position || update.style.position == 'absolute'){
				update.style.position = 'absolute';
				Position.clone(element, update, {
					setHeight: false,
					offsetTop: element.offsetHeight
				});
			}
		},
		onHide:  function(element, update) {
			update.setStyle({display:"none"});
		}
	});
}

function enableElements(){
	if(disabledElements != null){
		for(var i = disabledElements.length - 1; i >= 0; i--){
			var el = $(disabledElements[i]);
			if(!el) {
				setTimeout("enableElements()", 200);
			}else{
				el.disabled = false;
			}
		}
	}
}

function trim(s) {
	return rtrim(ltrim(s));
}

function ltrim(s) {
	var l = 0;
	while(l < s.length && s[l] == ' ') {
		l++;
	}
	return s.substring(l, s.length);
}

function rtrim(s) {
	var r = s.length - 1;
	while (r > 0 && s[r] == ' ') {
		r -= 1;
	}
	return s.substring(0, r + 1);
}
