searchForms = {
	buildNum: 0,
	list: [],
	container: null,
	initialized: false,
	preloadScripts: true,
	selectmenuOptions: {
		style:'dropdown', 
		maxHeight: 100, 
		transferClasses: true
	},
	initForm: function(){
		
		switch($('#currSearchType').text())
		{
			case '11':
			case '5':
				searchForms.tour.init();
				break;
				
			case '7':
				searchForms.flight.init();
				break;
				
			default:
				searchForms.hotel.init();
		}
	},
	init: function(){
		if(searchForms.initialized)
		{
			return;
		}
		searchForms.initialized = true;
		searchForms.buildNum = $('#buildNum').text();
		searchForms.container = $('#sidebar .form-container');
		if(searchForms.preloadScripts)
		{
			switch($('#currSearchType').text())
			{
				case '11':
				case '5':
					
					$.ajax({
						url: addBuildNumToPath('/misc/js/lib/jquery/rangeSlider.js'), 
						type: 'GET',
						cache: true,
						ifModified: true,
						dataType: 'script',
						async: true,
						success: function(){
							
						}
					});
					$.ajax({
						url: addBuildNumToPath('/misc/js/search/form/tour.js'), 
						type: 'GET',
						cache: true,
						ifModified: true,
						dataType: 'script',
						async: true,
						success: function(){
							searchForms.initForm();
						}
					});
					
					break;
					
				case '7':
					$.ajax({
						url: addBuildNumToPath('/misc/js/search/form/flight.js'), 
						type: 'GET',
						cache: true,
						ifModified: true,
						dataType: 'script',
						async: true,
						success: function(){
							searchForms.initForm();
						}
					});
					break;
					
				default:
					$.ajax({
						url: addBuildNumToPath('/misc/js/search/form/hotel.js'), 
						type: 'GET',
						cache: true,
						ifModified: true,
						dataType: 'script',
						async: true,
						success: function(){
							searchForms.initForm();
						}
					});
			}
		}
		else
		{
			searchForms.initForm();
		}
		$('form.search-form').bind('submit', function(){
			$(this).find(':submit').button('disable');
		});
	},
	hotel: {
		
	},
	tour: {
		
	},
	flight: {
		
	}
}

function initSearchForm() {
	$('#currencySelector').change(function(){
		$('.changeCurrency').text($(this).val());
		return false;
	});
	
	var _numberItem = $('.changeNumber');
	var _nText = _numberItem.text();
	if ($('.changeNumber').is(':visible'))
	{
		if ($('#searchFormTourAdultCount').length)
		{
			changeNumber(parseInt($('#searchFormTourAdultCount').val()) + parseInt($('#searchFormTourChildCount').val()));
		}else{
			changeNumber($('#sffPassengersCount, #sfhPassengersCount').val());
		}
	};
	
	function changeNumber(_number){
		if (_number > 1) {
			if (_nText.indexOf('пассажира') != -1) 
			{
				_numberItem.text(_number+' пассажиров');
			}
			else if (_nText.indexOf('туриста') != -1)
			{
				_numberItem.text(_number+' туристов');
			}
		}else{
			_numberItem.text(_nText);
		}
	};
	$('#sffPassengersCount, #sfhPassengersCount, #searchFormTourAdultCount, #searchFormTourChildCount').change(function(){
		if (this.id == 'searchFormTourAdultCount' || this.id == 'searchFormTourChildCount')
		{
			changeNumber(parseInt($('#searchFormTourAdultCount').val()) + parseInt($('#searchFormTourChildCount').val()));
		}
		else changeNumber($(this).val());
		return false;
	});
	$('#sfhAdvancedSearchLink').click(function(){
		changeNumber($('#sfhPassengersCount').val());
		return false;
	});
	$('#searchFormTourAdvancedSearchLink').click(function(){
		changeNumber(parseInt($('#searchFormTourAdultCount').val()) + parseInt($('#searchFormTourChildCount').val()));
		return false;
	});
	
	var _prices = $('.prices');
	_prices.find('input').each(function(){
		$(this).attr('data-name', this.name);
	});
	if (_prices.is(':visible')) {
		var _sliderInited = true;
		initPriceSlider();
	} else {
		var _sliderInited = false;
		_prices.find('input').each(function(){
			this.name = '';
		});
	}
	
	
	$('.choose-price a').click(function(){
		if ($(this).hasClass('open')){
			$(this).removeClass('open')
			_prices
				.slideUp()
				.find('input').each(function(){
					this.name = '';
				});
		} else {
			$(this).addClass('open')
			_prices
				.slideDown()
				.find('input').each(function(){
					this.name = $(this).attr('data-name');
				});
			if (!_sliderInited){
				_sliderInited = true;
				initPriceSlider();
			}
		}
		return false;
	});


	searchForms.init();
	
	var aShowBlockLocationSelect = $('#a_show_block_location_select');
	var aShowBlockLocationInput = $('#a_show_block_location_input');
	var blockLocationSelect = $('#block_location_select');
	var blockLocationInput = $('#block_location_input');
	var selectorCity = $('#selector_city');
	var selectorCountry = $('#selector_country');
	var hotelSearchFormAutocompleteCountryCode = $('#hotelSearchFormAutocompleteCountryCode');
	var hotelSearchFormAutocompleteCityId = $('#hotelSearchFormAutocompleteCityId');
	
	aShowBlockLocationSelect.click(function() {
		$('#hotelSearchFormAutocompleteList').hide();
		var acCountryCode = hotelSearchFormAutocompleteCountryCode.val();
		var acCityId = hotelSearchFormAutocompleteCityId.val();
		
		clearCities();
		
		if (acCountryCode) {
			selectorCountry.val(acCountryCode);
			loadCities(acCountryCode, acCityId);
		}

		blockLocationInput.hide();
		blockLocationSelect.fadeIn();
		
		return false;
	});
	
	aShowBlockLocationInput.click(function() {
		var hotelSearchFormAutocompleteInput = $('#hotelSearchFormAutocompleteInput');
		
		if (selectorCity.val() && selectorCountry.val()) {
			hotelSearchFormAutocompleteInput.val(selectorCity.find('option[value="' + selectorCity.val() + '"]').text() + ', ' + selectorCountry.find('option[value="' + selectorCountry.val() + '"]').text());
		}
		
		blockLocationSelect.hide();
		blockLocationInput.fadeIn();

		return false;
	});
	
	selectorCountry.change(function() {
		var countryCode = $(this).val();
		if (countryCode) {
			$('#ct').val('');
		} else {
			$('#cn').val('');
			$('#ct').val('');
			hotelSearchFormAutocompleteCountryCode.val('');
		}
		loadCities(countryCode);
	});
	
	selectorCity.change(function() {
		var countryCode = selectorCountry.val();
		var cityId = $(this).val();
		
		$('#cn').val(countryCode);
		$('#ct').val(cityId);
		hotelSearchFormAutocompleteCountryCode.val(countryCode);
		hotelSearchFormAutocompleteCityId.val(cityId);
		searchForms.hotel.loadGeoLocations();
	});
	
	function loadCities(countryCode, defCityId) {
		if (countryCode) {
			var data = {cc: countryCode, buildNum: searchForms.buildNum, language: $('#currentLanguage').text()};
			if (location.href.match(/nocache=/i)) {
				data.nocache = 1;
			}
			$.ajax({
				async   : true,
				type    : "GET",
				url     : "/a_ajax/location.getCountryCities",
				dataType: "json",
				data    : data,
				success : function(data) {
					selectorCity.children().not(':first').remove();
					for (var i in data) {
						var option = $('<option></option>').val(data[i].id).text(data[i].name);
						if (defCityId && defCityId == data[i].id) {
							option.attr('selected', 'selected');
						}
						option.appendTo(selectorCity);
					}
					selectorCity.removeAttr('disabled');
				}
			});
		} else {
			clearCities();
		}
		searchForms.hotel.loadGeoLocations();
	}
	
	function clearCities() {
		selectorCity.val('').attr('disabled', 'disabled').children().not(':first').remove();
	}
	
	$('#sfhStars, #sftStars').tmstars();
	
	$('input.datepicker').each(function(){
		dateInput = $(this);
		var date;
		var currentDate = new Date();
		
		dateInput.click(function(){
			date = $(this).val();
		});
		
		dateInput.blur(function(){
			_this = $(this);
			var flag = true;
			var val = _this.val();
			var mas = val.split('.');
			if(mas.length == 3){
				if(mas[2].length > 4 || mas[2] < currentDate.getFullYear()){
					_this.val(date);
					flag = false;
				} else if (mas[1].length > 2 || mas[1] <= currentDate.getMonth() || mas[2] < 13) {
					_this.val(date);
					flag = false;
				}
				if(flag){
					var newDate = new Date();
					var year = mas[2];
					var month = mas[1].toString();
					var dayCount = new Date(year, month, 0).getDate();
					if(mas[0] <= 0 || mas[0] > dayCount){
						_this.val(date);
						flag = false;
					}
				}
			} else {
				_this.val(date);
			}
		});
	});
	//formNav();
	var handleNights = handleMinMax($('select[name="nf"]'), $('select[name="nt"]'), 0)
	handleNights.init();
	var handleStars = handleMinMax($('#sftStars1, #sfhStars1'), $('#sftStars2, #sfhStars2'), 0)
	handleStars.init();
}
function initPriceSlider(){
	var _slider = $('#slider');
	var _inpMin = $('[name="pf"]');
	var _inpMax = $('[name="pt"]');
	var _more = $('.slider .right');
	var _less = $('.slider .left');
	var slider = rangeSlider({
		element: _slider,
		bounds: {
			min: parseInt(_slider.attr('min'), 10),
			max:  parseInt(_slider.attr('max'), 10)
		},
		defaultValues: {
			min:  parseInt(_slider.attr('defmin'), 10), 
			max:  parseInt(_slider.attr('defmax'), 10)
		},
		//name: 'classSorter',
		step: 500,
		changing: function(ui){
			_inpMin.val(ui.values.min);
			_inpMax.val(ui.values.max);
		},
		changed: function(ui){
		}
	});
	slider._create();
	_inpMin.val(_slider.attr('defmin')).blur(function(){
		slider.min(this.value);
	});
	_inpMax.val(_slider.attr('defmax')).blur(function(){
		slider.max(this.value);
	});
	_more.click(function(){
		slider.max(slider.ui.values.max + slider.options.step);
		return false;
	});
	_less.click(function(){
		slider.min(slider.ui.values.min - slider.options.step);
		return false;
	});
}
/*
function formNav(){
	$('.form-nav li').click(function(){
		$('.form-nav li').removeClass('active');
		$(this).addClass('active').find('input').attr('checked', true);
		document.location.href = $(this).attr('rel');
	});
}
*/

function handleMinMax(min, max, minDif){
	return {
		init: function(){
			var _maxV = 0;
			max.find('option').each(function(){
				if (this.value*1 > _maxV) _maxV = this.value*1;
			});
			min.change(function(){
				if (this.value*1 > max.val()*1-minDif) {
					if (this.value*1  > _maxV) max.val(_maxV);
					else max.val(this.value*1 + minDif);
				}
			});
			max.change(function(){
				if (this.value*1 < min.val()*1+minDif) {
					if (this.value*1 < 1) min.val(1);
					else min.val(this.value*1 - minDif);
				}
			});
		}
	}
}
function handleMinMax1(min, max, minDif){
	return {
		init: function(){
			var _maxV = 0;
			max.find('option').each(function(){
				if (this.value*1 > _maxV) _maxV = this.value*1;
			});
			//var _ndif = max.val()*1 - min.val()*1;
			min.change(function(){
				if (this.value*1 > max.val()*1-minDif) {
					if (this.value*1 + _ndif > _maxV) max.val(_maxV);
					else max.val(this.value*1 + _ndif);
				}
				//_ndif = max.val()*1 - min.val()*1;
			});
			max.change(function(){
				if (this.value*1 < min.val()*1+minDif) {
					if (this.value*1 - _ndif < 1) min.val(1);
					else min.val(this.value*1 - _ndif);
				}
				//_ndif = max.val()*1 - min.val()*1;
			});
		}
	}
}
$(document).ready(initSearchForm);


function rangeSlider(options) {
	return {
		options: options,
		_values: null,

		// Created elements
		bar: null,
		leftHandle: null,
		rightHandle: null,
		innerBar: null,
		container: null,
		arrows: null,
		changing: function(){},
		changed: function(){},

		// Scroll management
		lastWheel : 0,
		lastScroll: 0,
		scrollCount: 0,

		_create: function(){
			$.extend({
				bounds: {min:0, max:10},
				defaultValues: {min:2, max:7},
				wheelMode: null,
				wheelSpeed: 4,
				arrows: false,
				step: 0.1,
				valueLabels: "", // 'show'
				formatter: function(value){
					return value;
				}
			}, this.options);
			this.round = this.options.step.toString().split('.')[1] ? this.options.step.toString().split('.')[1].length : 0;

			this._values = this.options.defaultValues;
			this.arrows = {left:null, right:null};
			this.changing = {min:false, max:false};
			this.changed = {min:false, max:false};
			this.f = false;

			this.leftHandle = $("<div class='ui-rangeSlider-handle  ui-rangeSlider-leftHandle' />")
				.bind('mousedown', $.proxy(this._mousedown, this))
				.css("position", "absolute");
			this.rightHandle = $("<div class='ui-rangeSlider-handle ui-rangeSlider-rightHandle' />")
				.bind('mousedown', $.proxy(this._mousedown, this))
				.css("position", "absolute");

			this.innerBar = $("<div class='ui-rangeSlider-innerBar' />")
				.css("position", "absolute")
				.css("top", 0)
				.css("left", 0);

			this.container = $("<div class='ui-rangeSlider-container' />")
				.css("position", "absolute");

			this.bar = $("<div class='ui-rangeSlider-bar' />").css("position", "absolute");


			$(document).bind('mousemove', $.proxy(this._mousemove, this))
			//			.bind('mouseup', $.proxy(this._mouseup, this));
			//document.addEventListener('mouseup', $.proxy(this._mouseup, this))
			if (window.addEventListener) {document.addEventListener('mouseup', $.proxy(this._mouseup, this));}
			else if (window.attachEvent && !window.opera) {document.attachEvent("onmouseup", $.proxy(this._mouseup, this));}

			this.container
				.append(this.leftHandle)
				.append(this.rightHandle)
				.append(this.innerBar)
				.append(this.bar);

			this.element = this.options.element
				.append(this.container)
				//.append(this.arrows.left)
				//.append(this.arrows.right)
				.addClass("ui-rangeSlider");

			if (this.element.css("position") != "absolute"){
				this.element.css("position", "relative");
			}
			this._initWidth();
			this.ui = {};
			this.ui.values = {};
			this.ui.values.min = this.options.defaultValues.min;
			this.ui.values.max = this.options.defaultValues.max;
			this.ui.valuesLast = {
				min : this.ui.values.min,
				max : this.ui.values.max
			};
			this.leftHandle.css('left', this._getPos(this.options.defaultValues.min)).text(this.options.valueLabels ? this.options.formatter(this.ui.values.min): '');
			this.rightHandle.css('left', this._getPos(this.options.defaultValues.max)).text(this.options.valueLabels ? this.options.formatter(this.ui.values.max) : '');
			this._setBar();
		},

		_mousedown: function(e){
			this.activeHandle = $(e.target);
			this.f = true;
			this._m = this.activeHandle.hasClass('ui-rangeSlider-leftHandle') ? 'min' : 'max';
			return false;
		},

		_mousemove: function(e){
			if (this.f){
				if (this._m == 'min'){
					var _minBound = 0;
					var _maxBound = this.rightHandle.position().left - 2*this.rightHandle.outerWidth(true);
				} else {
					var _minBound = this.leftHandle.position().left + 2*this.rightHandle.outerWidth(true);
					var _maxBound = this.container.width();
				}
				var _l = e.pageX - this.container.offset().left;
				if (_l < _minBound) _l = _minBound;
				else if (_l > _maxBound) _l = _maxBound;
				this.ui.values[this._m] = this._getValues(_l);
				
				this.activeHandle.css('left',_l);
				this.activeHandle.text(this.options.valueLabels ? this.options.formatter(this._getValues(_l)) : '');
				this._setBar();
				if (typeof this.options.changing == 'function') this.options.changing(this.ui);
			}
			return false;
		},

		_mouseup: function(){
			if (this.f){
				this.f = false;
				if (this.ui.valuesLast[this._m] != this.ui.values[this._m]){
					this.ui.valuesLast[this._m] = this.ui.values[this._m];
					this.options.changed(this.ui);
				}
				return false;
			}
			
		},

		adjust: function(_v){
			return (Math.round(_v/this.options.step)*this.options.step).toFixed(this.round);
		},

		_initWidth: function(){
			this.container.css({width: this.element.width() - this.leftHandle.outerWidth()/* - this.rightHandle.outerWidth()*/,
								marginLeft: this.leftHandle.outerWidth()/2});
			this.innerBar.css({
				"width": this.container.width() - this.innerBar.outerWidth() + this.innerBar.width(),
				"marginLeft": -this.leftHandle.outerWidth()/2
			});
			this.leftHandle.css("marginLeft", -this.leftHandle.outerWidth()/2);
			this.rightHandle.css("marginLeft", -this.rightHandle.outerWidth()/2);
		},

		_getValues: function(_l){
			return this.adjust(_l/this.container.width()*(this.options.bounds.max - this.options.bounds.min) + this.options.bounds.min)*1;
		},

		_getPos: function(_v){
			return (_v - this.options.bounds.min)*this.container.width()/(this.options.bounds.max - this.options.bounds.min);
		},

		min: function(min){
			if (min < this.options.bounds['min']) min = this.options.bounds['min'];
			if (min > this.ui.values.max)  min = this.ui.values.max;
			this._setValue('min', min);
			this._initChangeEvent();
		},

		max: function(max){
			if (max > this.options.bounds['max']) max = this.options.bounds['max'];
			if (max < this.ui.values.min)  max = this.ui.values.min;
			this._setValue('max', max);
			this._initChangeEvent();
		},
		
		values: function(min, max){
			if (min != undefined && max != undefined){
				if (min < this.options.bounds[min]) min = this.options.bounds[min];
				if (max > this.options.bounds[max]) max = this.options.bounds[max];
				
				if (min > max)  min = max;
				
				this._setValue('min', min);
				this._setValue('max', max);
				this._initChangeEvent();
			}else{
				if (min != undefined) this.min(min);
				if (max != undefined) this.max(max);
			}
		},
		
		_setValue: function (m, val){
			var _handle = (m == 'min') ? this.leftHandle : this.rightHandle;
			this.ui.values[m] = val;
			this.ui.valuesLast[m] = val;
			_handle.css('left', this._getPos(val)).text(this.options.valueLabels ? this.options.formatter(val) : '');
			this._setBar();
		},
		_initChangeEvent: function(){
			if (typeof this.options.changing == 'function') this.options.changing(this.ui);
			this.options.changed(this.ui);
		},

		_setBar: function(){
			this.bar.css({left: this.leftHandle.position().left,
					width: this.rightHandle.position().left - this.leftHandle.position().left
			});
		}
	}
}
