var _hotel_labels = {};
var _inited = false;

var _toggleHotel = function () {

	var _checkbox = this,
	_hotel_id = this.attr('value'),
	_hotel_name = this.attr('label'),
	_input = $('#link-drop-hotels-input'),
	_hotels = _input.val() ? _input.val().split('-') : new Array();

	_hotel_labels[_hotel_id] = _hotel_name;

	if (_checkbox.filter(':checked').length) {
		if ($.inArray(_hotel_id, _hotels) === -1)
			_hotels.push(_hotel_id);
	} else {
		_pos = $.inArray(_hotel_id, _hotels);
		if (_pos !== -1)
			_hotels.splice(_pos, 1);
	}

	_input.val(_hotels.join('-'));

	var _container = $('#toursearch-select-hotel-list .hotels-list').html('').hide();
	_html = '';
	$.each(_hotels, function(_i, _v) {
		_html += '<div style="margin: 0; padding: 0;"><a href="#" class="remove-selected-hotel" value="' + _v + '">(x)</a>' + _hotel_labels[_v] + '</div>';
	});
	if (_html) {
		_container.show();
	}
	_container.html(_html);
};

function _initToursearchForm() {

	var _orderToVar = ['asc', 'desc'],
	_orderByVar = ['departure', 'price', 'duration', 'meals', 'rate', 'name'],
	_orderTo = 0,
	_orderBy = 1;

	var _setActive = function() {
		var _text = this.text();
		this.html('<strong><i></i>' + _text + '</strong>').closest('li').addClass('b-poplist__item_cur');
	};

	var _getRoomsize = function(_v) {

		var _adult = $('#link-drop-roomsize-adult').attr('value'), _children = $('#link-drop-roomsize-children').attr('value');

		var roomsizes = {
			'1-0': 15,
			'2-0': 14,
			'3-0': 23,
			'1-1': 18,
			'1-2': 19,
			'2-1': 20,
			'2-2': 21,
			'3-1': 27,
			'3-2': 31
		};

		return roomsizes[parseInt(_adult) + '-' + parseInt(_children)];
	}


	var _today_date = new Date(), _today_date_label = _today_date.getFullYear() + '-' + (_today_date.getMonth() + 1) + '-' + _today_date.getDate();
	_max_date = new Date();
	_max_date.setFullYear(_max_date.getFullYear() + 1);
	_max_date_label = _max_date.getFullYear() + '-' + (_max_date.getMonth() + 1) + '-' + _max_date.getDate();
	var _region_labels = {};

	$('#tour_search_short, #tour_search').toursearch({

		'elements': {

			'link-drop-to': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _value_link = $(_ev.target).closest('li');
					if ($(_value_link).hasClass('headline')) {
						_ev.preventDefault();
						_ev.stopPropagation();
						return;
					}
					if (_value_link.length == 0) {return;}

					var _t = _value_link.text(), _v = _value_link.attr('value'), _ch = this.attr('val') !== _t;
					_sv(_t, _v);
					if (_ch) {$('#link-drop-regions').select_regions('loadRegions', _v);}
					_h();
				}
			},
			'link-drop-from': {
				'onContentBodyClick': function(_ev, _sv, _h) {

					var _li = $(_ev.target).closest('li'), _link = _li.addClass('check'),
					_links = _link.siblings('li').removeClass('check');
					if (!_li.length) {
						return;
					}

					if ($('#tour_search').length && _link.attr('value')!=$('#tour_search').toursearch('getValue','link-drop-from')) {
						reloadCountries(_link.attr('value'));
					}

					_sv(_link.text(), _link.attr('value'));
					_h();
				},
				'getContentHolder': function() {return this.find('ul').eq(0);}
			},
			'link-drop-departure-from': {
				'setValue': function(_text, _value) {
					this.parent().find('a.selected').html(_text);
					$('#departure-from-input').val(_value);
				},
				'onPopupBodyClick': function(_ev, _sv, _h) {if ($(_ev.target).filter('li, a.calendar_close, a.calendar_close i, a.selected, a.selected strong').length) {_h();}}
			},
			'link-drop-departure-to': {
				'setValue': function(_text, _value) {
					this.parent().find('a.selected').html(_text);
					$('#departure-to-input').val(_value);
				},
				'onPopupBodyClick': function(_ev, _sv, _h) {if ($(_ev.target).filter('li, a.calendar_close, a.calendar_close i, a.selected, a.selected strong').length) {_h();}}
			},
			'link-drop-len-from': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _link = $(_ev.target).closest('li'),
					_v = _link.attr('value');
					if (!_link.length) {return;}
					_sv(_link.text(), _v);_h();
					if ($('#tour_search_short, #tour_search').toursearch('getValue', 'link-drop-len-to') < _v) {$('#tour_search_short, #tour_search').toursearch('setValue', 'link-drop-len-to', _v, _v);}
				}
			},
			'link-drop-len-to': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _link = $(_ev.target).closest('li');
					_v = _link.attr('value');
					if (!_link.length) {return;}
					_sv(_link.text(), _v);_h();
					if ($('#tour_search_short, #tour_search').toursearch('getValue', 'link-drop-len-from') > _v) {$('#tour_search_short, #tour_search').toursearch('setValue', 'link-drop-len-from', _v, _v);}
				}
			},
			'link-drop-class': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _li = $(_ev.target).closest('li'),
					_v = _li.attr('value');

					if (!_v || _v == '10' || _v == '12' || _v == '1') {
						$('#hotel-class-and-better-checkbox').hide();
					} else {
						$('#hotel-class-and-better-checkbox').show();
					}
					if (!_li.length) {return;}
					_sv(_li.html(), _v);_h();
				},
				'setValue': function(_t, _v) {this.parent().find('a.selected').html('<strong>' + _t + '</strong>').end().find('input:hidden').val(_v);},
				'getContentHolder': function() {return this.find('ul').eq(0);}
			},
			'link-drop-meals': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _li = $(_ev.target).closest('li'),
					_v = _li.attr('value');
					if (!_v || _v == '6') {
						$('#hotel-meals-and-better-checkbox').hide();
					} else {
						$('#hotel-meals-and-better-checkbox').show();
					}
					if (!_li.length) {return;}
					_sv(_li.html(), _v);_h();
				},
				'getContentHolder': function() {return this.find('ul').eq(0);}
			},
			/**
			 * используется на сокращенной форме на странице отеля
			 */
			'link-drop-room-size': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _li = $(_ev.target).closest('li'),
					_v = _li.attr('value');
					if (!_li) {return;}
					var _t = _li.text().replace(/(\d+)/g, "<strong>$1</strong>");
					_sv(_t, _v);_h();
				},
				'setValue': function(_t, _v) {this.parent().find('a.selected').html(_t).end().find('input:hidden').val(_v);},
				'getContentHolder': function() {return this.find('ul').eq(0);}
			},
			'link-drop-room-1-child-age': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _li = $(_ev.target).closest('li'),
					_lis = _li.siblings('li').removeClass('check'),
					_v = _li.attr('value'),
					_label = _getNumerableStringRu(parseInt(_v, 10), ' год', 'года', 'лет');
					_li.addClass('check');
					$('#room-1-child-label').html(_label);
					_sv(_v, _v);_h();
				},
				'getContentHolder': function() {return this.find('ul').eq(0);},
				'setValue': function(_t, _v) {
					var _parent = this.parent(),
					_links = _parent.find('a.selected');
					$('#room-size-1-child').children('input:hidden').val(_v);
					_links.children('strong').html(_t);
				}
			},
			'link-drop-room-1-of-2-children-age': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _li = $(_ev.target).closest('li'),
					_lis = _li.siblings('li').removeClass('check'),
					_v = _li.attr('value');
					_li.addClass('check');
					_sv(_v, _v);_h();
				},
				'getContentHolder': function() {return this.find('ul').eq(0);},
				'setValue': function(_t, _v) {
					var _parent = this.parent(),
					_links = _parent.find('a.selected');
					//$('#room-size-2-children').children('input:hidden[name="Ch1"]').val(_v);
					_links.children('strong').html(_t);
				}
			},
			'link-drop-room-2-of-2-children-age': {
				'onContentBodyClick': function(_ev, _sv, _h) {
					var _li = $(_ev.target).closest('li'),
					_lis = _li.siblings('li').removeClass('check'),
					_v = _li.attr('value'),
					_label = _getNumerableStringRu(parseInt(_v, 10), ' год', 'года', 'лет');
					_li.addClass('check');
					$('#room-2-children-label').html(_label);
					_sv(_v, _v);_h();
				},
				'getContentHolder': function() {return this.find('ul').eq(0);},
				'setValue': function(_t, _v) {
					var _parent = this.parent(),
					_links = _parent.find('a.selected');
					//$('#room-size-2-children').children('input:hidden[name="Ch2"]').val(_v);
					_links.children('strong').html(_t);
				}
			}
		}
	});

	var hoverIn = function(_element, _parityDate) {

		if (_element.hasClass(this.options.disabledClass)) {
			return;
		}

		var e = _element.closest('.calendar').find('.month');

		$('li.'+this.options.intermediateClass, e).removeClass(this.options.intermediateClass);
		$('li.'+this.options.parityDateClass, e).removeClass(this.options.parityDateClass);
		$('li.'+this.options.activeDateClass, e).removeClass(this.options.activeDateClass);



		var _selectedDate = this._strToDate(_element.attr('date')),
			_currentDate = this.options._current_date,
			_startDate = null, _endDate = null,
			_days_elements = _element.closest('.calendar').find('.month').find('li[date]'),
			_days_diff = 0, _offset = 0,
			_class = '', _alt_class = '',
			_months = this.element.find('.month'),
			_left_month_element = _months.eq(0),
			_right_month_element = _months.eq(1);

		if (_currentDate < _parityDate && _selectedDate <= _parityDate) {
			_startDate = _selectedDate;
			_endDate = _parityDate;

			_class = this.options.activeDateClass;
			_alt_class = this.options.parityDateClass;
		} else if (_currentDate > _parityDate && _selectedDate >= _parityDate) {
			_startDate = _parityDate;
			_endDate = _selectedDate;

			_class = this.options.parityDateClass;
			_alt_class = this.options.activeDateClass;
		} else {
			return;
		}

		var show_start = true, show_end = true;
		if (_startDate.getMonth() < (_left_month_element.attr('month') - 1)) {
			_startDate = new _startDate.constructor(_startDate); //clone

			_startDate.setMonth(_left_month_element.attr('month') - 1);
			_startDate.setDate(1);

			show_start = false;
		}

		if (_endDate.getMonth() > (_right_month_element.attr('month') - 1)) {
			_endDate = new _startDate.constructor(_endDate); //clone

			_endDate.setMonth(_right_month_element.attr('month') - 1);
			_endDate.setDate(this._getLastDayOfMonth(_endDate) - 1);

			show_end = false;
		}

		var _startDateStr = _startDate.getFullYear() + "-" + (_startDate.getMonth()+1) + "-" + _startDate.getDate(),
			_endDateStr = _endDate.getFullYear() + "-" + (_endDate.getMonth()+1) + "-" + _endDate.getDate(),
			_startDateElement = _days_elements.filter("[date='"+_startDateStr+"']"),
			_endDateElement = _days_elements.filter("[date='"+_endDateStr+"']");

		_days_diff = (_endDate - _startDate) / (1000 * 24 * 3600);
		_offset = _startDate.getDate() -1;

		if (_days_diff && _startDateElement.closest('.month').attr('month') == _endDateElement.closest('.month').attr('month')
					   && _left_month_element.attr('month') != _endDateElement.closest('.month').attr('month')) {

			_offset += _left_month_element.find('li[date]').length;
		}

		if (show_start) {
			_days_elements.eq(_offset).addClass(_class);
		}

		while (_days_diff>= 0) {

			_days_elements.eq(_offset++).addClass(this.options.intermediateClass);
			_days_diff--;
		}

		if (show_end) {
			_days_elements.eq(_offset - 1).addClass(_alt_class);
		}
	};

	var hoverOut = function(_div) {

		if (_div.is(':visible')) {

			var e = this.element.find('.month');

			$('li.'+this.options.intermediateClass, e).removeClass(this.options.intermediateClass);
			$('li.'+this.options.parityDateClass, e).removeClass(this.options.parityDateClass);
			$('li.'+this.options.activeDateClass, e).removeClass(this.options.activeDateClass);

			this._redrawSelected();
		}
	};

	$('#link-drop-departure-start-calendar').calendar({
		onSelect: function(_date) {
			var _year = _date.getFullYear(), _month = _date.getMonth() + 1, _day = _date.getDate(), _label = '<strong>с ' + _day + ' ' + _monthLabelsShortRp[_month - 1] + '</strong>', _value = _day + '.' + _month + '.' + _year;
			$('#link-drop-departure-end-calendar').calendar('setParityDate', _value).calendar('moveDateUp', _value);
			$('#tour_search_short, #tour_search').toursearch('setValue', 'link-drop-departure-from', _label, _value);
		},
		onHoverIn: hoverIn,
		onHoverOut: hoverOut,
		currentDate: $('#departure-from-input').val(),
		minDate: _today_date_label,
		maxDate: _max_date_label,
		disabledClass: 'none',
		todayClass: 'current_date',
		activeDateClass: 'from_date',
		parityDateClass: 'to_date',
		intermediateClass: 'selected_dates',
		daysPlate: '<span>Пн</span><span>Вт</span><span>Ср</span><span>Чт</span><span>Пт</span><span class="day_off">Сб</span><span class="day_off">Вс</span>',
		parityDate: $('#departure-to-input').val()
	});

	$('#link-drop-departure-end-calendar').calendar({
		onSelect: function(_date) {
			var _year = _date.getFullYear(), _month = _date.getMonth() + 1, _day = _date.getDate(), _label = '<strong>по ' + _day + ' ' + _monthLabelsShortRp[_month - 1] + '</strong>', _value = _day + '.' + _month + '.' + _year;
			$('#link-drop-departure-start-calendar').calendar('setParityDate', _value).calendar('moveDateDown', _value);
			$('#tour_search_short, #tour_search').toursearch('setValue', 'link-drop-departure-to', _label, _value);
		},
		onHoverIn: hoverIn,
		onHoverOut: hoverOut,
		currentDate: $('#departure-to-input').val(),
		minDate: _today_date_label,
		maxDate: _max_date_label,
		disabledClass: 'none',
		todayClass: 'current_date',
		activeDateClass: 'to_date',
		parityDateClass: 'from_date',
		intermediateClass: 'selected_dates',
		daysPlate: '<span>Пн</span><span>Вт</span><span>Ср</span><span>Чт</span><span>Пт</span><span class="day_off">Сб</span><span class="day_off">Вс</span>',
		parityDate: $('#departure-from-input').val()
	});

//	$('#tour_search_short-find, #tour_search_short-find-plus').click(function(_ev) { _ev.preventDefault(); $('#tour_search_short').submit(); })

	/* кнопка "любая стоимость", по нажатии на которую выскакивают 2 поля */
	$('#hotel-select-costs-float-link').click(function() {
		$(this).hide();
		$('#hotel-select-costs-float-div').show();
		$('#hotel-select-costs-input-to').focus();//morphText('setFocus');
	});


	/* скрывающиеся инпуты для ограничения стоимости */
	(function(){
		var _morph_text_timeout = null,
		_clearToVal = function() {
			$('#hotel-select-costs-input-to').val('');//morphText('setValue', '');
		},
		_clearFromVal = function() {
			$('#hotel-select-costs-input-from').val('');//morphText('setValue', '');
		};


		$('#hotel-select-costs-input-from, #hotel-select-costs-input-to').blur(function(_ev) {

			if(isNaN(parseInt($(this).val(), 10)))
			{
				$(this).val('');
			}

			if ($(this).filter('#hotel-select-costs-input-from').length) {

				if ($(this).val() && parseInt($(this).val(), 10) > parseInt($('#hotel-select-costs-input-to').val(), 10)) {

					_clearToVal();
				}
			} else {

				if ($(this).val() && parseInt($(this).val(), 10) < parseInt($('#hotel-select-costs-input-from').val(), 10)) {

					_clearFromVal();
				}
			}
			_morph_text_timeout = window.setTimeout(function() {
				if (!$('#hotel-select-costs-input-from').val() && !$('#hotel-select-costs-input-to').val() && !$('#hotel-select-costs-float-locked').filter(':visible').length) {
					$('#hotel-select-costs-float-div').hide();
					$('#hotel-select-costs-float-link').show();
				}
			}, 200);
		}).click(function(_ev) {

			window.clearTimeout(_morph_text_timeout);
		}).keydown(function(_ev) {

			var _kc = _ev.keyCode;if ((_kc < 48 || _kc > 57) && (_kc < 96 || _kc > 105) && (_kc < 37 || _kc > 40) && (_kc != 9 && _kc != 8)) {_ev.preventDefault();}
		});
	})();

	/* кнопка "очистить" для полей со стоимостью */
	$('#hotel-select-costs-clear-button').click(function(_ev) {
		_ev.stopPropagation();_ev.preventDefault();
		$('#hotel-select-costs-input-from, #hotel-select-costs-input-to').val('');//morphText('setValue', '');
		$('#hotel-select-costs-float-div').hide();
		$('#hotel-select-costs-float-link').show();
	});

	/* кнопка выбора типа комнаты */
	$('#link-drop-room-size-ext').roomsize({
		'singleChildRoom': '#room-size-1-child',
		'doubleChildrenRoom': '#room-size-2-children',
		'parentSet': '#tour_search_short .set1'
	});

	/* подсказка по еде*/
	var _hotel_meals_help_div = $('#hotel-meals-help-div');
	$('#hotel-meals-list-ul').find('li').mouseover(function(_ev) {
		_hotel_meals_help_div.html($(this).attr('title'));
	});

	/* обработка формы для основного подбора*/
	if ($('#tour_search').length) {

		/* сворачивалка для зеленой плашки */
		$('#tour_help, #tour_search a').click(function() {$('#tour_help').fadeOut('slow');});
		
		(function() {

			var _state = 'ready',
			_page = 1,
			_url = '',
			_skipReloadOnHashChange = false;

		
			$('#link-drop-regions').select_regions({
				'loadRegionsUrl': '/ajax/loadRegions/',
				'onRegionsLoaded': function(_res) {
					$('#select_concrete_hotel').select_hotel_dialog('reloadRegions', _res);
				},
				'regionLabelHolder': '#extend-regions-list-div',
				'onRegionSelect': function(_element) {
					var _checkbox = _element.find(':checkbox');
	
					if (_checkbox.attr('checked')) {
						_checkbox.attr('checked_attr', '1');
					} else {
						_checkbox.removeAttr('checked_attr');
					}
				},
				'onRegionChange': function() {
					_page = 1;
					$('#select_concrete_hotel').select_hotel_dialog('clearSelectedHotels');
					$('#select_concrete_hotel').select_hotel_dialog('updateRegions', $('#regions-ul').html());
				}
			});
			
			var _favorites_help = $("#help-you-have-no-favorite-hotels .help3span").contents()[0].nodeValue;
			$('#select_concrete_hotel').select_hotel_dialog({
				'tint': '#select_hotel_tint',
				'dialog': '#select_hotel',
				'whatIsFavoriteHotelPopup': '#help-what-are-favorite-hotels',
				'whatIsFavoriteHotelLink': '#link-what-are-favorite-hotels',
				'showFavoritesOnly': '#link-show-me-only-favorite-hotels',
				'youHaveNoFavoritesPopup': '#help-you-have-no-favorite-hotels',
				'showAllHotels': '#link-show-me-all-hotels',
				'showAllHotelsLi': '#show-country-hotel-li',
				'regionsFilter': '#select-hotel-filter-regions',
				'classFilter': '#select-hotel-filter-class',
				'howToSelectHotelsPopup': '#help-how-to-select-hotels',
				'regionsList': '#select-hotel-regions-list',
				'hotelsList': '#hotel-list-ul',
				'reloadHotels': function(_country, _c) {
					var self = this,
					   _ppad_name = $("#find-hotel-country-list li[value="+_country+"]").attr("ppad_name"),
					   _help = $("#help-you-have-no-favorite-hotels .help3span span"),
					   _favorites_help = "У вас пока нет любимых отелей.";
					
					this.html('<div class="wait">Загрузка отелей...</div>');
					$.ajax({
						'url': '/ajax/loadDialogHotels/' + _country + '/',
						'success': function(_res) {
							if (_res !== undefined) {

								self.html(_res);

								$('#select_concrete_hotel').select_hotel_dialog('clearFilters');
								$('#select_concrete_hotel').select_hotel_dialog('updateRegions', $('#regions-ul').html());
															
								if (_ppad_name && $('#user-has-favorites').length > 0) {
									_help.text(_favorites_help.substring(0, _favorites_help.length-1) + " " + _ppad_name + ".");
								} else if ($('#user-has-favorites').length > 0) {
									_help.text("У вас пока нет любимых отелей в этой стране.");
								}

								_c();
							}
						},
						'timeout': 60000
					});
				},
				'reloadRegions': function(_res) {
					
					$('#select_concrete_hotel').select_hotel_dialog('reloadHotels', $('#find-hotel-country-input').val());

					var self = this;

					$(self.options.regionsList).html(_res);

					self.updateRegions();
				},
				'updateRegions': function() {
					var self = this,
						_o = self.options;
						_list = $(self.options.regionsList);
					var _checked = _list.find(':checkbox[checked_attr]');

					if (_checked.length) {
						self._regions = {};
						

						_checked.each(function(index, element) {

							$(element).attr('checked', 'checked');
							
							var s_regions = $(element).attr('value').split('-');
						
							$(s_regions).each(function(k, _s_reg){
								
								self._regions[_s_reg] = true;
							});
						});

						$(_o.regionsFilter).find('a.selected').html('<strong> ' + _getNumerableStringRu(_checked.length, 'Выбран ', 'Выбрано ', 'Выбрано ') + _checked.length + _getNumerableStringRu(_checked.length, ' курорт', ' курорта', ' курортов') + ' </strong>');
					}
				},
				'hotelListBlock': '#hotel-label-list-block',
				'applyButton': '#apply-and-close',
				'onHotelSelect': function(_id, _name, _index) {

					$('#link-drop-regions').select_regions('clearSelectedRegions');
					$('#clear-selected-hotels-and-select-by-class').show();
					$('#select-hotel-class').hide();

					if (!$('#hotel-select-costs-float-locked').filter(':visible').length) {
						$('#hotel-select-costs-float-link').hide();

						$('#hotel-select-costs-input-from').val('');
						$('#hotel-select-costs-input-to').val('');
						$('#hotel-select-costs-float-div').hide();
						

						$('#hotel-select-costs-float-locked').show();
					}
					_page = 1;
				},
				'onListClear': function() {
					$('#clear-selected-hotels-and-select-by-class').hide();
					$('#select-hotel-class').show();

					if ($.isEmptyObject(this._selectedHotels)) {
						if (!$('#hotel-select-costs-input-from').val() && !$('#hotel-select-costs-input-to').val() && !$('#hotel-select-costs-float-locked').filter(':visible').length) {

							$('#hotel-select-costs-float-locked').hide();
							$('#hotel-select-costs-float-link').show();
						}
					}

				}
			});
			
	
			$('#select_concrete_hotel_form_link').click(function(_ev) {
				_ev.preventDefault();
				$('#select_concrete_hotel').trigger('click');
			});
	
			$('#clear-selected-hotels-form-link').click(function(_ev) {
				_ev.preventDefault();
				$('#select_concrete_hotel').select_hotel_dialog('clearSelectedHotels');
			});

			$('#tour_search').toursearch('onChange', function() {_page = 1;});

			if ($.History.getHash()) {

				var _res = /page=(\d+)/i.exec($.History.getHash());
				if (_res === null || _res === undefined) {
					
					_page  = 1;
				} else if ((_res.length == 2) && (_res[1] !== undefined) && parseInt(_res[1], 10)) {

					_page = parseInt(_res[1], 10);
				}
			}

			$('a.next_page', $('#tour_results')).live('click', function(_ev) {

				_page++;
				$('#toursearch-form-submit').trigger('click');
			});

			$('a.prev_page', $('#tour_results')).live('click', function(_ev) {

				if (_page > 1) {

					_page--;
					$('#toursearch-form-submit').trigger('click');
				}
			});

			var _loadResults = function() {

				if (_state == 'ready') {

					_state = 'loading';

					$('#tour_results, #tour_timeout, #tour_unavailable, #tour_whait, #tour_whait2').hide();

					if ($('#tour_whait').length) {

						$('#tour_whait').show();
					} else {

						$('#tour_whait2').show();
					}


					$.ajax({
						'url': '/tour/searchTour/' + _url,
						'type': 'GET',
						'cache': true,
						'dataType': 'html',
						'error': function(_xhr, _status, _err) {
							if (_status == 'timeout') {

								$('#tour_timeout').show();
							} else {

								$('#tour_unavailable').show();
							}
						},
						'success': function(_res) {
							$('#tour_results').html(_res).show();
							$('#legal_info').hide();
							//tour_loader_init();
						},
						'complete': function() {
							$('#tour_whait').remove();
							$('#tour_whait2').hide();
							_state = 'ready';
						},
						'timeout': 20000
					});
				}
			};
			
			var _p = $('#tour_search').parent(), _isForeignForm = _p.attr('foreign-form') ? true : false,
			_foreignFormAction = _p.attr('action');
			
			if (_isForeignForm) {
			
				$('#select_concrete_hotel').select_hotel_dialog('reloadHotels', $('#find-hotel-country-input').val(), true);
			} else {
				
				$('#select_concrete_hotel').select_hotel_dialog('reloadHotels', $('#find-hotel-country-input').val());
			}
			
			$('#toursearch-form-submit').click(function(_ev) {

				_ev.preventDefault();

				_skipReloadOnHashChange = true;

				var _hash = '',
				_tsf = '',
				_tsr = '',
				_regions_val = $('#link-drop-regions').select_regions('getSelectedRegions'),
				_hotels_val = $('#select_concrete_hotel').select_hotel_dialog('getSelectedHotels'),
				_roomsize = $('#link-drop-room-size-ext').roomsize('getValue');

				$('#tour_search').find('input:hidden, input:checkbox').each(function(_i, _el) {

					_el = $(_el);

					if (_el.attr('name')) {

						_tsf += _tsf ? '&' : '';
						var _val;
						_val = (_el.filter(':checkbox').length) ? (_el[0].checked ? '1' : '')  : (_el.val() === '0' ? '' : _el.val());
						_tsf += _el.attr('name') + '=' + _val;
					}
				});

				_tsf += _roomsize;

				if(isNaN(parseInt($('#hotel-select-costs-input-from').val(), 10)))
				{
					$('#hotel-select-costs-input-from').val('');
				}

				if(isNaN(parseInt($('#hotel-select-costs-input-to').val(), 10)))
				{
					$('#hotel-select-costs-input-to').val('');
				}

				_tsf += '&PrF=' + $('#hotel-select-costs-input-from').val();
				_tsf += '&PrT=' + $('#hotel-select-costs-input-to').val();

				if (_regions_val) {

					_tsf += '&Re=' + _regions_val;

				} else if (_hotels_val) {

					_tsf += '&Als=' + _hotels_val;
				}

				_tsf = 'tsf=' + _tsf;
				_tsr = 'tsr=Page=' + _page + '&Items=10&orderBy=price';

				_hash = '#' + _tsf + ';' + _tsr;
				_url = '?' + _tsf + '&&' + _tsr;
				
				if (!_isForeignForm) {
				
					$.History.setHash(_hash);

					_loadResults();
				} else {
				
					window.location.href = (_foreignFormAction + _hash);
				}
			});

			$.History.bind(function(_hash) {

				if (!_skipReloadOnHashChange) {

					document.location.reload(true);

					return;
				}

				_skipReloadOnHashChange = false;

				_loadResults();
			});
		})();
	}

	/* обработка формы для подбора на странице отеля */
	if ($('#tour_search_short').length) {

		(function() {

			var _state = 'ready',
					_offset = 0,
					_limit =13,
					_url = '',
					_skipReloadOnHashChange = false,
					_toursearch_link=$('#toursearch-full-link').attr('href');

			var _formatParams=function() {
				var _hash = '',
						_tsf = '',
						_tsr = '',
						_roomsize = $('#link-drop-room-size-ext').roomsize('getValue');

				$('#tour_search_short').find('input:hidden, input:checkbox').each(function(_i, _el) {

					_el = $(_el);

					if (_el.attr('name')) {

						_tsf += _tsf ? '&' : '';
						var _val;
						_val = (_el.filter(':checkbox').length) ? (_el[0].checked ? '1' : '') : (_el.val() === '0' ? '' : _el.val());
						_tsf += _el.attr('name') + '=' + _val;
					}
				});

				_tsf += _roomsize;

				_tsf = 'tsf=' + _tsf;
				_tsr = 'tsr=tours_offset=' + _offset + '&tours_limit=' + _limit;
				return {tsf: _tsf, tsr: _tsr}
			}

			var _onChange=function() {
				_offset=0;
				var _params=_formatParams();
				var _tsf=_params['tsf'],
					_tsr='tsr=Page=1&Items=10&orderBy=price'

				var _hash=TourToolbox.setHashDataVariable('Als','',_tsf + ';' + _tsr);

				$('#toursearch-full-link').attr('href', _toursearch_link + '#/' + _hash + '/');
			}

			_onChange();

			$('#tour_search_short').toursearch('onChange', function() {_onChange()});

			$('#link-drop-room-size-ext').roomsize('onChange', function() {_onChange()});

			if ($.History.getHash()) {
				_offset=TourToolbox.getHashVariable('offset');
			}

			$('a.next_page', $('#tour_results')).live('click', function(_ev) {

				_offset=parseInt(_offset)+parseInt(_limit);
				$('#toursearch-form-submit').trigger('click');
			});

			$('a.prev_page', $('#tour_results')).live('click', function(_ev) {

				if (_offset >0) {

					_offset=parseInt(_offset)-parseInt(_limit);
					$('#toursearch-form-submit').trigger('click');
				}
			});

			var _loadResults = function() {

				if (_state == 'ready') {

					_state = 'loading';

					$('#tour_results, #tour_timeout, #tour_unavailable').hide();

					$('#tour_whait').show();


					$.ajax({
						'url': '/tour/loadHotelTours/' + _url,
						'type': 'GET',
						'cache': true,
						'dataType': 'html',
						'error': function(_xhr, _status, _err) {
							if (_status == 'timeout') {

								$('#tour_timeout').show();
							} else {

								$('#tour_unavailable').show();
							}
						},
						'success': function(_res) {
							$('#tour_results').html(_res).show();
							$('#legal_info').hide();
						},
						'complete': function() {
							$('#tour_whait').hide();
							_state = 'ready';
						},
						'timeout': 20000
					});
				}
			};

			$('#toursearch-form-submit').click(function(_ev) {

				_ev.preventDefault();

				var _params=_formatParams();
				var _tsf=_params['tsf'],
					_tsr=_params['tsr'];


				var _hash = '#' + _tsf + ';' + _tsr;
					_url = '?' + _tsf + ';' + _tsr;

				_skipReloadOnHashChange=true;
				$.History.setHash(_hash);
				_loadResults();
			});

			$.History.bind(function(_hash) {

				if (!_skipReloadOnHashChange) {

					document.location.reload(true);

					return;
				}

				_skipReloadOnHashChange = false;

				_loadResults();
			});
		})();
	}
}

function reloadForm(_c) {

	// short form
	if ($('#toursearch-form-short-div').length) {
		$('#toursearch-form-short-div').sleep();

		$.ajax({
			'url': '/tour/reloadForm/',
			'data': {'hash': $.History.getHash(),'short_form':1,'ti_id': TourToolbox.getHashVariable('Als')},
			'cache': false,
			'success': function(_res) {

				$('#toursearch-form-short-div').wakeup().html(_res);

				if (typeof(_c) == 'function') {

					_c.call(document);
				}
			}
		});
	}
	// long form
	else if ($('#toursearch-form-div').length) {
		$('#toursearch-form-div').sleep();

		$.ajax({
			'url': '/tour/reloadForm/',
			'data': {'hash': $.History.getHash()},
			'cache': false,
			'success': function(_res) {

				$('#toursearch-form-div').wakeup().children('div').eq(0).html(_res);

				if (typeof(_c) == 'function') {

					_c.call(document);
				}
			}
		});
	}
}

function reloadCountries (_city) {
	var _cur_country=$('#tour_search').toursearch('getValue',['link-drop-to']);
	$('#link-drop-to').closest('.set').sleep();
	$.ajax({
		url: "/ajax/loadCountries/",
		data: {country_ti_id: _cur_country , city_ti_id: _city},
		dateType: 'JSON',
		type: 'GET',
		cache: true,
		success: function (_data) {
			$('#link-drop-to').next().find('ul.scroll').html(_data['list'])
			if (_data['country_id']!=undefined) {
				$('#tour_search').toursearch('setValue','link-drop-to',_data['country_name']);
				$('#find-hotel-country-input').val(_data['country_id']);
				$("#link-drop-regions").select_regions('loadRegions',_data['country_id']);
			}
		},
		complete: function () {
			$('#link-drop-to').closest('.set').wakeup();
		}
	});
}

(function() {
	var _inited = false;


	$(function(){

		if (_inited) {
			return;
		}

		if ($.History.getHash()) {
			reloadForm(function() {
				_initToursearchForm.call(document);
				_inited = true;
				$('#link-drop-regions').select_regions('refreshValues');
				$('#toursearch-form-submit').trigger('click');
				$('#select_concrete_hotel').select_hotel_dialog('updateRegions', $('#regions-ul').html());
			})
		} else {
			_initToursearchForm.call(document);
			_inited = true;
			if ($('#link-drop-regions').length) {
				$('#link-drop-regions').select_regions('refreshValues');
			}
			if ($('#select_concrete_hotel').length) {
				$('#select_concrete_hotel').select_hotel_dialog('updateRegions', $('#regions-ul').html());
			}
		}
	});
})();

function tour_loader_hotel_init() {
	$('#toursearch-form-submit').trigger('click');
}

function tour_loader_init(_options) {
	$("#tour_results").tourresult('destroy');
	$("#tour_results").tourresult(_options);

}

function load_hotel_tours_ex_01() {
	$('#tour_results .not_all em').click(function(){
		$.scrollTo('#tour_search_short', 'normal');
	});
}
