
;(function($) {

	$.widget("ui.tourSearchForm", {

		init_helper: function() {
			var hide = function() {
				// hide and adjust height
				$('#tsf-helper').slideUp(200, function() {
					//$('#tsf').height($('#tsf').height()-30+'px')
				})
			}
	
			for(var name in this.controls) {
				if (!this.controls.hasOwnProperty(name)) continue
	
				this.controls[name].bind("select", hide)
			}
	
		},
	
	
		init_Co: function() {
	
			var city = this.controls.city
	        var Co = this.controls.Co = $('#Co').CoSelect({sendRequestPrefix:'/tour/',sendRequestPostfix:'.php'})
	
			// load current options
	        //Co.CoSelect('loadOptions', {url:'countries', data:{city: city.stringSelect('get')}}, values.Co)

	        //  bind to city change
	        city.bind("select", function(e, newCityValue) {
	            // try to keep old country value
	            var oldCoValue = Co.CoSelect('get')
	
	            Co.CoSelect(
					'loadOptions',
					{url:'countries', data:{city: newCityValue}}
				)
				
	
				//alert(Co.CoSelect('getPendingValue').toSource())
				if (!Co.CoSelect('hasPendingValue')) {
					Co.CoSelect('setPendingValue', oldCoValue)
				}
	        });
		},
	
	
		init_city: function() {
	        this.controls.city = $('#city').stringSelect({options: formDefaults.city, sendRequestPrefix:'/tour/',sendRequestPostfix:'.php'})
		},
	
		init_Me: function(values) {
			this.controls.Me = $('#Me').stringCheckbox({options: formDefaults.Me, empty_title:'Любое', selectedValues: values.Me})
		},
	
		init_MeB: function(values) {
	
			this.controls.MeB = $('#MeB').checkboxSimple({checked: values.MeB === undefined ? 1 : +values.MeB})
	
			$('#Me').bind("select", function(e,values) {
				//console.log(values)
				$('#MeB-ctrl')[(values && values.length==1 && values[0]!=6) ? 'show':'hide']()
			})
		},
	
	
		/* must be initialized before AlCa, because triggers on AlCa selected value */
		init_AlCaB: function(values) {
	
			this.controls.AlCaB = $('#AlCaB').checkboxSimple({checked: values.AlCaB === undefined ? 1 : +values.AlCaB})
	
			$('#AlCa').bind("select", function(e,value) {
				$('#AlCaB-ctrl')[(value==1 || value==0 || value==10) ? 'hide':'show']()
			})
		},
	
		init_AlCa: function(values) {
			this.controls.AlCa = $('#AlCa').stringSelect({options: formDefaults.AlCa, selectedValue: values.AlCa})
		},
	
		init_Len: function(values) {
			// create days options list
			var options = {}
			for(var i=2; i<=21; i++) {
				options[i] = i
			}
			options = { data: options }
	
	
			// create controls
			var len_begin = this.controls.len_begin = $('#len_begin').stringSelect({options: options, selectedValue: values.len_begin})
			var len_end = this.controls.len_end = $('#len_end').stringSelect({options: options, selectedValue: values.len_end})
	
			// bind checkers begin/end
	        len_begin.bind("select", function(e, begin) {
	
	            var end = len_end.stringSelect('get')
	
				if (begin > end) {
					len_end.stringSelect('set', begin)
				}
	        });
	
	        len_end.bind("select", function(e, end) {
	            var begin = len_begin.stringSelect('get')
	
				if (begin > end) {
					len_begin.stringSelect('set', end)
				}
	        });
	
			function updateLenDays(days) {
				var word
				switch(days) {
				case 1:
					word='ночь'
					break
				case 2:
				case 3:
				case 4:
					word='ночи'
					break
				default:
					word='ночей'
				}
				$('#tsf-days').html(word)
			}
	
			$('#len_end').bind('select', function(e,days) {updateLenDays(days)})
			updateLenDays(len_end.stringSelect('get'))
	
	
		},
	
		init_RoSi: function(values) {
	
			var RoSi = this.controls.RoSi = $('#RoSi').RoSiSelect({options: formDefaults.RoSi, selectedValue: values.RoSi})
	
			RoSi.bind("select", function(e, value) {
	
				// at least one child => show Ch1
				if ($.inArray(value, [20,21,18,19,27,31]) != -1) {
					$('#Ch1-ctrl').show()
				} else {
					$('#Ch1-ctrl').hide()
				}
				// 2 children
				if ($.inArray(value, [21,19,31]) != -1) {
					$('#Ch2-ctrl').show()
				} else {
					$('#Ch2-ctrl').hide()
				}
				updateChYearOpt() // update years after children hide/show
	
			})
	
	
			var yearOpts = {}
			for(var i=1; i<=14; i++) {
				yearOpts[i] = i
			}
			yearOpts = { data: yearOpts }
	
			function updateChYearOpt(){
				var target
	
				if ($('#Ch1-ctrl').isShow()) target = Ch1
				if ($('#Ch2-ctrl').isShow()) target = Ch2
	
				if (!target) return
	
				var year = +target.stringSelect('get')
	
				var word
				switch(year) {
				case 1:
					word='год'
					break
				case 2:
				case 3:
				case 4:
					word='года'
					break
				default:
					word='лет'
				}
				$('#ChYear').html(word)
			}
			values.Ch1 && $('#Ch1-ctrl').show()
			values.Ch2 && $('#Ch2-ctrl').show()
	
	
			var Ch1 = this.controls.Ch1 = $('#Ch1').stringSelect({options: yearOpts, selectedValue: values.Ch1})
			var Ch2 = this.controls.Ch2 = $('#Ch2').stringSelect({options: yearOpts, selectedValue: values.Ch2})
	
			$('#Ch1').bind('select', updateChYearOpt)
			$('#Ch2').bind('select', updateChYearOpt)
			updateChYearOpt()
	
		},
	
	
		init_Pr: function(values) {
	
			/* switch "Any Price" / input fields mode */
			function PrAny(on) {
				$('#PrAny')[on ? 'show' : 'hide']()
				$('#Pr')[on ? 'hide' : 'show']()
			}
	
			var PrF = this.controls.PrF = $('#PrF').stringInput({value: values.PrF})
			var PrT = this.controls.PrT = $('#PrT').stringInput({value: values.PrT})
	
			// click on "any price" shows chooser
			$('#PrAny').click(function() {
				PrAny(false)
				//$('#PrF').stringInput('showInput')
				$('#PrT').stringInput('showInput').stringInput('focus')
			})
	
			$('#PrClear').click(function() {
				$('#PrT').stringInput('set', null)
				$('#PrF').stringInput('set', null)
			})
	
			// select shows "any price" if no choice
			function onSelect() {
				if (!PrF.stringInput('get').length && !PrF.stringInput('hasInputFocus') && !PrT.stringInput('get').length && !PrT.stringInput('hasInputFocus') ) {
					PrAny(true)
					$('#PrClear').hide()
				} else {
					$('#PrClear').show()
				}
			}
	
			this.controls.PrF.bind('select', function() { setTimeout(onSelect, 0) })
			this.controls.PrT.bind('select', function() { setTimeout(onSelect, 0) })
	
			// show widget
			if (values.PrF && values.PrF.length || values.PrT && values.PrT.length) {
				PrAny(false)
				$('#PrClear').show()
			}
	
		},
	
	
		init_Da: function(values) {
			var DaF = this.controls.DaF = $('#DaF').stringDateInput({value: values.DaF})
			var DaT = this.controls.DaT = $('#DaT').stringDateInput({value: values.DaT})
	
	
			DaF.bind("select", function(e, begin) {
	            var end = DaT.stringDateInput('get')
	      			if (begin > end) {
	      				var newEnd = new Date(begin.getFullYear(), begin.getMonth(), begin.getDate() + 3)
	      				DaT.stringDateInput('set', newEnd)
	      			}
	        });
	
			DaT.bind("select", function(e, end) {
	            var begin = DaF.stringDateInput('get')
	      			if (begin > end) {
	      				var newBegin = new Date(end.getFullYear(), end.getMonth(), end.getDate() - 3)
	      				DaF.stringDateInput('set', newBegin)
	      			}
	        });
		},
	
		init_Re: function() {
	
			var Co = this.controls.Co
			var city = this.controls.city
			var Re = this.controls.Re = $('#Re').stringCheckbox({empty_title:'Любой',sendRequestPrefix:'/tour/',sendRequestPostfix:'.php'})

			
			// load current options
	        /*Re.stringCheckbox('loadOptions',
				{url:'regions', data:{city: city.stringSelect('get'), country: Co.CoSelect('get')}}, this.tsf.Re
			)*/
	
			//  bind to country change
	        Co.bind("select", function(e, newCoValue, oldCoValue) {
	            // try to keep old country value
	            var oldReValues = Re.stringCheckbox('get')
	            if (!Re.lastCo) Re.lastCo = {}
				Re.lastCo[oldCoValue] = oldReValues
	
	            Re.stringCheckbox('loadOptions',
					{url:'regions', data:{city: city.stringSelect('get'), country: newCoValue}})
					
				//console.log("Co.bind trigger, country:%d pendingValues:%s",newCoValue, Re.lastCo[newCoValue])
	
				if (!Re.stringCheckbox('hasPendingValues')) {
					var pv = Re.lastCo[newCoValue]
					if (!pv) {
						//главный регион
						if (newCoValue==74) pv = [1169,285,284]
						if (newCoValue==26) pv = [1181,844,809,601,201,199,105,193,200,1180]
						if (newCoValue==37) pv = [403]
						if (newCoValue==35) pv = [328]
					}
					Re.stringCheckbox('setPendingValues', pv)
				}
	        });
	
		},
	
		hotelChooseType: function() {
			if (!$('#hotel-choose-name-tab').isShow()) return
			$('#hotel-choose-name-tab').hide()
			$('#hotel-choose-name').removeClass('hotel-tab-chooser-selected')
			$('#hotel-choose-type-tab').show()
			$('#hotel-choose-type').addClass('hotel-tab-chooser-selected')
		},
	
		hotelChooseName: function() {
			if ($('#hotel-choose-name-tab').isShow()) return
			$('#hotel-choose-type-tab').hide()
			$('#hotel-choose-type').removeClass('hotel-tab-chooser-selected')
			$('#hotel-choose-name-tab').show()
			$('#hotel-choose-name').addClass('hotel-tab-chooser-selected')
		},
	
		init_Hotels: function(values) {
			globalControls = this.controls;
			var self = this
	
			var hotelFilter = $('#hotel-filter').modalHotels({width: 700})
			var Als = this.controls.Als = $('#hotel-choose-name-tab').selectedHotels()
	
			/**
			 * show type hide name
			*/
			$('#hotel-choose-type').click(function() {
				self.hotelChooseType()
			})
	
			/**
			 * add hotels from modal to selected
			*/
			hotelFilter.bind('select', function(e, accept, values) {
				if (accept) {
					Als.selectedHotels('set', values)
				}
			})
	
	
	
			/**
			 * open name chooser from regions
			*/
			$('#hotel-choose-name').click(function() {
				self.hotelChooseName()
			})
	
			/**
			 * add hotels button opens window to adds/remove values
			 */
			
			$('#hotel-choose-name-add').click(function() {
				var values = Als.selectedHotels('get')
				hotelFilter.modalHotels('show', [values, globalControls])
			})
	
			/**
			 * add hotels button opens window to adds/remove values
			 */
			$('#hotel-choose-favorite-add').hotelFavoriteAdd()
	
	
			/**
			 * Set values
			 */
	
			if (values.Als) {
				this.hotelChooseName()
				Als.selectedHotels('loadHotels', values.Als)
			}
	
			/**
			 * country change saves allocations in tab and changes hotel choice
			*/
			this.controls.Co.one("ready", function() {
			self.controls.Co.bind("select", function(e, newCoValue, oldCoValue) {
	            // try to keep old country value
	            var oldAlsValues = Als.selectedHotels('get')
	
				// save state (on/off and values for country)
				if (!Als.lastCo) Als.lastCo = {}
				Als.lastCo[oldCoValue] = {show: Als.isShow(), values: oldAlsValues }
	
				Als.selectedHotels('clear')
	
				var newState = Als.lastCo[newCoValue]
				if (newState) {
					if (newState.show) {
						self.hotelChooseName()
					} else {
						self.hotelChooseType()
					}
					Als.selectedHotels('set', newState.values)
				} else {
					self.hotelChooseType()
				}
	
	
	        })});
	
		},
	
	
	
		getParams: function() {
			var params = {}
	
			if (this.controls.Spo) {
				this.controls.Spo[0].getParams(params)
			}
			if (this.controls.SpoFull && $('#SpoFull-ctrl').isShow()) {
				// only spo
				if (this.controls.SpoFull.checkboxSimple('get')) {
					return params
				}
			}
	
			var ls = ['city','RoSi','Co','len_begin','len_end','DaF','DaT','PrF','PrT','Me','MeB','Re']
	
			for(var i=0; i<ls.length;i++) {
				var ctrl = this.controls[ls[i]][0]
				ctrl.getParams(params)
			}
	
			if ($('#Ch1-ctrl').isShow()) {
				this.controls.Ch1[0].getParams(params)
			}
			if ($('#Ch2-ctrl').isShow()) {
				this.controls.Ch2[0].getParams(params)
			}
	
	
			// FIXME: replace by overridden serialize call
	
			if ($('#hotel-choose-name-tab').isShow()) {
				this.controls.Als[0].getParams(params)
			} else {
				this.controls.AlCa[0].getParams(params)
				this.controls.AlCaB[0].getParams(params)
			}
			//console.log(params)
	
			return params
	
		},
	
	
	
		search: function() {
	
			var tsr = $('#tsr')
			if (tsr.length) {
				tsr.searchTourList('hideNav')
				tsr.searchTourList('setTsfParams', this.getParams())
				tsr.searchTourList('search', {page:1})
			} else {
				window.location.href = '/tour/#tsf='+makeQuery(this.getParams())+';tsr=page=1'
			}
		},
	
	
		init_tsr: function() {
			$('#tsr').searchTourList()
			if (parseHash().tsr) {
				$('#tsr').searchTourList('setTsfParams', this.tsf)
				$('#tsr').searchTourList('search')
				// search call changes #hash, but I don't want it to affect history
				// because init_tsr search is nested call
				onHistoryChange.reset()
			}
		},
	
	
		init_tsf: function() {
			var tsf = this.tsf = parseQuery(parseHash().tsf || this._getData('last_tsf'))

			var tsf2 = parseHash().tsf2
			if (tsf2) {
	
				// only keep these in new tsf
				var keep = ['city','Co','DaF','DaT','len_begin','len_end','RoSi']
	
				var tsfNew = {}
				for(var i=0;i<keep.length;i++) {
					var p = keep[i]
					if (this.tsf[p]) tsfNew[p] = this.tsf[p]
				}
	
				// override variables with tsf2
				tsf2 = parseQuery(tsf2)
				for(var p in tsf2) {
					if (!tsf2.hasOwnProperty(p)) continue
					tsfNew[p] = tsf2[p]
				}
	
				this.tsf = tsfNew
			}
	
	
	
		},
		
		_init: function() {
			this.init.apply(this, arguments)

		},
		
		init: function() {
	
	    /**
	       * read tour search form params from #tsf=
	       */
		this.init_tsf()
	    var values = this.tsf

	    this.controls = {}
	    this.init_city()
	    this.init_Co()
	    this.init_Re()

	    this.controls.city.stringSelect('set', values.city) // trigger loaders
	    this.controls.Co.CoSelect('setPendingValue', values.Co)
	
	    this.controls.Re.stringCheckbox('setPendingValues', values.Re)

	
	    this.init_MeB(values)
	    this.init_Me(values)
	    this.init_Len(values)
	    this.init_Pr(values)
	    this.init_Da(values)
	    this.init_RoSi(values)
	    this.init_AlCaB(values)
	    this.init_AlCa(values)
	    this.init_Hotels(values)
	    
	
		if ($(document.body).hasClass('is-manager')) {
			this.controls.Delete = $('#tsf-delete').tsfDelete()
			this.controls.Spo = $('#Spo').stringInput({value: values.Spo}).show()
			this.controls.SpoFull = $('#SpoFull').checkboxSimple({checked: values.SpoFull === undefined ? 1 : values.SpoFull})
	
			this.controls.Spo.bind('select', function(e) {
	
				var value = +$('#Spo').stringInput('get')
				if (value) {
					$('#SpoFull-ctrl').show()
				} else {
					$('#SpoFull-ctrl').hide()
				}
	
			})
		}
	
	
	    var self = this
	
	    $('#tsf .submit-btn').click(function() {
	      self.search()
	    })
	
	
	    this.loading_observer = setInterval( function(){
	      if($("a:contains('Загрузка')",'#tsf').length==0){
	        $('#tsf #tsf-struct').removeClass('loading');
			self.init_helper()
			self.init_tsr()
	        clearInterval(self.loading_observer);
	      }else{
//	        console.log('%s, loading...', $("a:contains('Загрузка')",'#tsf').eq(0).attr('id'));
	      }
	    }, 500);
	
	  }// *** end of init() ***
	
	});
})(jQuery);